llvm_backend.cpp 445 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208
  1. #include "llvm_backend.hpp"
  2. #include "llvm_abi.cpp"
  3. #include "llvm_backend_opt.cpp"
  4. gb_global lbAddr lb_global_type_info_data = {};
  5. gb_global lbAddr lb_global_type_info_member_types = {};
  6. gb_global lbAddr lb_global_type_info_member_names = {};
  7. gb_global lbAddr lb_global_type_info_member_offsets = {};
  8. gb_global lbAddr lb_global_type_info_member_usings = {};
  9. gb_global lbAddr lb_global_type_info_member_tags = {};
  10. gb_global isize lb_global_type_info_data_index = 0;
  11. gb_global isize lb_global_type_info_member_types_index = 0;
  12. gb_global isize lb_global_type_info_member_names_index = 0;
  13. gb_global isize lb_global_type_info_member_offsets_index = 0;
  14. gb_global isize lb_global_type_info_member_usings_index = 0;
  15. gb_global isize lb_global_type_info_member_tags_index = 0;
  16. struct lbLoopData {
  17. lbAddr idx_addr;
  18. lbValue idx;
  19. lbBlock *body;
  20. lbBlock *done;
  21. lbBlock *loop;
  22. };
  23. struct lbCompoundLitElemTempData {
  24. Ast * expr;
  25. lbValue value;
  26. i32 elem_index;
  27. lbValue gep;
  28. };
  29. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  30. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  31. LLVMValueRef llvm_zero(lbModule *m) {
  32. return LLVMConstInt(lb_type(m, t_int), 0, false);
  33. }
  34. LLVMValueRef llvm_one(lbModule *m) {
  35. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  36. }
  37. lbValue lb_zero(lbModule *m, Type *t) {
  38. lbValue v = {};
  39. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  40. v.type = t;
  41. return v;
  42. }
  43. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  44. lbValue v = lb_find_or_add_entity_string(m, str);
  45. unsigned indices[1] = {0};
  46. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  47. }
  48. bool lb_is_instr_terminating(LLVMValueRef instr) {
  49. if (instr != nullptr) {
  50. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  51. switch (op) {
  52. case LLVMRet:
  53. case LLVMBr:
  54. case LLVMSwitch:
  55. case LLVMIndirectBr:
  56. case LLVMInvoke:
  57. case LLVMUnreachable:
  58. case LLVMCallBr:
  59. return true;
  60. }
  61. }
  62. return false;
  63. }
  64. lbAddr lb_addr(lbValue addr) {
  65. lbAddr v = {lbAddr_Default, addr};
  66. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  67. GB_ASSERT(is_type_pointer(addr.type));
  68. v.kind = lbAddr_RelativePointer;
  69. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  70. GB_ASSERT(is_type_pointer(addr.type));
  71. v.kind = lbAddr_RelativeSlice;
  72. }
  73. return v;
  74. }
  75. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  76. lbAddr v = {lbAddr_Map, addr};
  77. v.map.key = map_key;
  78. v.map.type = map_type;
  79. v.map.result = map_result;
  80. return v;
  81. }
  82. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  83. lbAddr v = {lbAddr_SoaVariable, addr};
  84. v.soa.index = index;
  85. v.soa.index_expr = index_expr;
  86. return v;
  87. }
  88. Type *lb_addr_type(lbAddr const &addr) {
  89. if (addr.addr.value == nullptr) {
  90. return nullptr;
  91. }
  92. if (addr.kind == lbAddr_Map) {
  93. Type *t = base_type(addr.map.type);
  94. GB_ASSERT(is_type_map(t));
  95. return t->Map.value;
  96. }
  97. return type_deref(addr.addr.type);
  98. }
  99. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  100. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  101. }
  102. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  103. if (addr.addr.value == nullptr) {
  104. GB_PANIC("Illegal addr -> nullptr");
  105. return {};
  106. }
  107. switch (addr.kind) {
  108. case lbAddr_Map: {
  109. Type *map_type = base_type(addr.map.type);
  110. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  111. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  112. auto args = array_make<lbValue>(permanent_allocator(), 2);
  113. args[0] = h;
  114. args[1] = key;
  115. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  116. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  117. }
  118. case lbAddr_RelativePointer: {
  119. Type *rel_ptr = base_type(lb_addr_type(addr));
  120. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  121. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  122. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  123. offset = lb_emit_load(p, offset);
  124. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  125. offset = lb_emit_conv(p, offset, t_i64);
  126. }
  127. offset = lb_emit_conv(p, offset, t_uintptr);
  128. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  129. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  130. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  131. // NOTE(bill): nil check
  132. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  133. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  134. return final_ptr;
  135. }
  136. case lbAddr_SoaVariable: {
  137. // TODO(bill): FIX THIS HACK
  138. return lb_address_from_load(p, lb_addr_load(p, addr));
  139. }
  140. case lbAddr_Context:
  141. GB_PANIC("lbAddr_Context should be handled elsewhere");
  142. }
  143. return addr.addr;
  144. }
  145. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  146. lbAddr addr = lb_build_addr(p, expr);
  147. return lb_addr_get_ptr(p, addr);
  148. }
  149. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  150. if (build_context.no_bounds_check) {
  151. return;
  152. }
  153. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  154. return;
  155. }
  156. index = lb_emit_conv(p, index, t_int);
  157. len = lb_emit_conv(p, len, t_int);
  158. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  159. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  160. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  161. auto args = array_make<lbValue>(permanent_allocator(), 5);
  162. args[0] = file;
  163. args[1] = line;
  164. args[2] = column;
  165. args[3] = index;
  166. args[4] = len;
  167. lb_emit_runtime_call(p, "bounds_check_error", args);
  168. }
  169. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  170. if (build_context.no_bounds_check) {
  171. return;
  172. }
  173. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  174. return;
  175. }
  176. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  177. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  178. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  179. high = lb_emit_conv(p, high, t_int);
  180. if (!lower_value_used) {
  181. auto args = array_make<lbValue>(permanent_allocator(), 5);
  182. args[0] = file;
  183. args[1] = line;
  184. args[2] = column;
  185. args[3] = high;
  186. args[4] = len;
  187. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  188. } else {
  189. // No need to convert unless used
  190. low = lb_emit_conv(p, low, t_int);
  191. auto args = array_make<lbValue>(permanent_allocator(), 6);
  192. args[0] = file;
  193. args[1] = line;
  194. args[2] = column;
  195. args[3] = low;
  196. args[4] = high;
  197. args[5] = len;
  198. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  199. }
  200. }
  201. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  202. if (addr.addr.value == nullptr) {
  203. return;
  204. }
  205. GB_ASSERT(value.type != nullptr);
  206. if (is_type_untyped_undef(value.type)) {
  207. Type *t = lb_addr_type(addr);
  208. value.type = t;
  209. value.value = LLVMGetUndef(lb_type(p->module, t));
  210. } else if (is_type_untyped_nil(value.type)) {
  211. Type *t = lb_addr_type(addr);
  212. value.type = t;
  213. value.value = LLVMConstNull(lb_type(p->module, t));
  214. }
  215. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  216. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  217. }
  218. if (addr.kind == lbAddr_RelativePointer) {
  219. Type *rel_ptr = base_type(lb_addr_type(addr));
  220. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  221. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  222. GB_ASSERT(is_type_pointer(addr.addr.type));
  223. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  224. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  225. lbValue offset = {};
  226. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  227. offset.type = t_uintptr;
  228. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  229. offset = lb_emit_conv(p, offset, t_i64);
  230. }
  231. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  232. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  233. offset = lb_emit_select(p,
  234. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  235. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  236. offset
  237. );
  238. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  239. return;
  240. } else if (addr.kind == lbAddr_RelativeSlice) {
  241. Type *rel_ptr = base_type(lb_addr_type(addr));
  242. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  243. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  244. GB_ASSERT(is_type_pointer(addr.addr.type));
  245. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  246. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  247. lbValue offset = {};
  248. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  249. offset.type = t_uintptr;
  250. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  251. offset = lb_emit_conv(p, offset, t_i64);
  252. }
  253. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  254. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  255. offset = lb_emit_select(p,
  256. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  257. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  258. offset
  259. );
  260. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  261. lbValue len = lb_slice_len(p, value);
  262. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  263. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  264. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  265. return;
  266. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  267. lbValue ptr = addr.addr;
  268. lbValue index = addr.index_set.index;
  269. Ast *node = addr.index_set.node;
  270. ast_node(ce, CallExpr, node);
  271. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  272. proc_type = base_type(proc_type);
  273. GB_ASSERT(is_type_proc(proc_type));
  274. TypeProc *pt = &proc_type->Proc;
  275. isize arg_count = 3;
  276. isize param_count = 0;
  277. if (pt->params) {
  278. GB_ASSERT(pt->params->kind == Type_Tuple);
  279. param_count = pt->params->Tuple.variables.count;
  280. }
  281. auto args = array_make<lbValue>(permanent_allocator(), gb_max(arg_count, param_count));
  282. args[0] = ptr;
  283. args[1] = index;
  284. args[2] = value;
  285. isize arg_index = arg_count;
  286. if (arg_count < param_count) {
  287. lbModule *m = p->module;
  288. String proc_name = {};
  289. if (p->entity != nullptr) {
  290. proc_name = p->entity->token.string;
  291. }
  292. TokenPos pos = ast_token(ce->proc).pos;
  293. TypeTuple *param_tuple = &pt->params->Tuple;
  294. isize end = cast(isize)param_count;
  295. while (arg_index < end) {
  296. Entity *e = param_tuple->variables[arg_index];
  297. GB_ASSERT(e->kind == Entity_Variable);
  298. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  299. }
  300. }
  301. Entity *e = entity_from_expr(ce->proc);
  302. GB_ASSERT(e != nullptr);
  303. GB_ASSERT(is_type_polymorphic(e->type));
  304. {
  305. lbValue *found = nullptr;
  306. if (p->module != e->code_gen_module) {
  307. gb_mutex_lock(&p->module->mutex);
  308. }
  309. GB_ASSERT(e->code_gen_module != nullptr);
  310. found = map_get(&e->code_gen_module->values, hash_entity(e));
  311. if (p->module != e->code_gen_module) {
  312. gb_mutex_unlock(&p->module->mutex);
  313. }
  314. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  315. lb_emit_call(p, *found, args);
  316. }
  317. return;
  318. } else if (addr.kind == lbAddr_Map) {
  319. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  320. return;
  321. } else if (addr.kind == lbAddr_Context) {
  322. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  323. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  324. lb_addr_store(p, next_addr, old);
  325. lb_push_context_onto_stack(p, next_addr);
  326. lbValue next = lb_addr_get_ptr(p, next_addr);
  327. if (addr.ctx.sel.index.count > 0) {
  328. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  329. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  330. lb_emit_store(p, lhs, rhs);
  331. } else {
  332. lbValue lhs = next;
  333. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  334. lb_emit_store(p, lhs, rhs);
  335. }
  336. return;
  337. } else if (addr.kind == lbAddr_SoaVariable) {
  338. Type *t = type_deref(addr.addr.type);
  339. t = base_type(t);
  340. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  341. Type *elem_type = t->Struct.soa_elem;
  342. value = lb_emit_conv(p, value, elem_type);
  343. elem_type = base_type(elem_type);
  344. lbValue index = addr.soa.index;
  345. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  346. Type *t = base_type(type_deref(addr.addr.type));
  347. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  348. lbValue len = lb_soa_struct_len(p, addr.addr);
  349. if (addr.soa.index_expr != nullptr) {
  350. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  351. }
  352. }
  353. isize field_count = 0;
  354. switch (elem_type->kind) {
  355. case Type_Struct:
  356. field_count = elem_type->Struct.fields.count;
  357. break;
  358. case Type_Array:
  359. field_count = elem_type->Array.count;
  360. break;
  361. }
  362. for (isize i = 0; i < field_count; i++) {
  363. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  364. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  365. if (t->Struct.soa_kind == StructSoa_Fixed) {
  366. dst = lb_emit_array_ep(p, dst, index);
  367. lb_emit_store(p, dst, src);
  368. } else {
  369. lbValue field = lb_emit_load(p, dst);
  370. dst = lb_emit_ptr_offset(p, field, index);
  371. lb_emit_store(p, dst, src);
  372. }
  373. }
  374. return;
  375. }
  376. GB_ASSERT(value.value != nullptr);
  377. value = lb_emit_conv(p, value, lb_addr_type(addr));
  378. // if (lb_is_const_or_global(value)) {
  379. // // NOTE(bill): Just bypass the actual storage and set the initializer
  380. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  381. // LLVMValueRef dst = addr.addr.value;
  382. // LLVMValueRef src = value.value;
  383. // LLVMSetInitializer(dst, src);
  384. // return;
  385. // }
  386. // }
  387. lb_emit_store(p, addr.addr, value);
  388. }
  389. void lb_const_store(lbValue ptr, lbValue value) {
  390. GB_ASSERT(lb_is_const(ptr));
  391. GB_ASSERT(lb_is_const(value));
  392. GB_ASSERT(is_type_pointer(ptr.type));
  393. LLVMSetInitializer(ptr.value, value.value);
  394. }
  395. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  396. GB_ASSERT(value.value != nullptr);
  397. Type *a = type_deref(ptr.type);
  398. if (is_type_boolean(a)) {
  399. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  400. value = lb_emit_conv(p, value, a);
  401. }
  402. Type *ca = core_type(a);
  403. if (ca->kind == Type_Basic) {
  404. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  405. }
  406. if (is_type_proc(a)) {
  407. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  408. // stored as regular pointer with no procedure information
  409. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  410. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  411. LLVMBuildStore(p->builder, v, ptr.value);
  412. } else {
  413. Type *ca = core_type(a);
  414. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  415. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  416. } else {
  417. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  418. }
  419. LLVMBuildStore(p->builder, value.value, ptr.value);
  420. }
  421. }
  422. LLVMTypeRef llvm_addr_type(lbValue addr_val) {
  423. return LLVMGetElementType(LLVMTypeOf(addr_val.value));
  424. }
  425. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  426. lbModule *m = p->module;
  427. GB_ASSERT(value.value != nullptr);
  428. GB_ASSERT(is_type_pointer(value.type));
  429. Type *t = type_deref(value.type);
  430. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  431. return lbValue{v, t};
  432. }
  433. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  434. GB_ASSERT(addr.addr.value != nullptr);
  435. if (addr.kind == lbAddr_RelativePointer) {
  436. Type *rel_ptr = base_type(lb_addr_type(addr));
  437. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  438. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  439. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  440. offset = lb_emit_load(p, offset);
  441. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  442. offset = lb_emit_conv(p, offset, t_i64);
  443. }
  444. offset = lb_emit_conv(p, offset, t_uintptr);
  445. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  446. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  447. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  448. // NOTE(bill): nil check
  449. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  450. lbValue final_ptr = {};
  451. final_ptr.type = absolute_ptr.type;
  452. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  453. return lb_emit_load(p, final_ptr);
  454. } else if (addr.kind == lbAddr_RelativeSlice) {
  455. Type *rel_ptr = base_type(lb_addr_type(addr));
  456. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  457. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  458. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  459. lbValue offset = lb_emit_load(p, offset_ptr);
  460. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  461. offset = lb_emit_conv(p, offset, t_i64);
  462. }
  463. offset = lb_emit_conv(p, offset, t_uintptr);
  464. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  465. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  466. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  467. Type *slice_elem = slice_type->Slice.elem;
  468. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  469. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  470. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  471. // NOTE(bill): nil check
  472. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  473. lbValue data = {};
  474. data.type = absolute_ptr.type;
  475. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  476. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  477. len = lb_emit_conv(p, len, t_int);
  478. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  479. lb_fill_slice(p, slice, data, len);
  480. return lb_addr_load(p, slice);
  481. } else if (addr.kind == lbAddr_Map) {
  482. Type *map_type = base_type(addr.map.type);
  483. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  484. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  485. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  486. auto args = array_make<lbValue>(permanent_allocator(), 2);
  487. args[0] = h;
  488. args[1] = key;
  489. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  490. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  491. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  492. lbBlock *then = lb_create_block(p, "map.get.then");
  493. lbBlock *done = lb_create_block(p, "map.get.done");
  494. lb_emit_if(p, ok, then, done);
  495. lb_start_block(p, then);
  496. {
  497. // TODO(bill): mem copy it instead?
  498. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  499. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  500. lb_emit_store(p, gep0, lb_emit_load(p, value));
  501. }
  502. lb_emit_jump(p, done);
  503. lb_start_block(p, done);
  504. if (is_type_tuple(addr.map.result)) {
  505. return lb_addr_load(p, v);
  506. } else {
  507. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  508. return lb_emit_load(p, single);
  509. }
  510. } else if (addr.kind == lbAddr_Context) {
  511. lbValue a = addr.addr;
  512. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  513. if (addr.ctx.sel.index.count > 0) {
  514. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  515. return lb_emit_load(p, b);
  516. } else {
  517. return lb_emit_load(p, a);
  518. }
  519. } else if (addr.kind == lbAddr_SoaVariable) {
  520. Type *t = type_deref(addr.addr.type);
  521. t = base_type(t);
  522. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  523. Type *elem = t->Struct.soa_elem;
  524. lbValue len = {};
  525. if (t->Struct.soa_kind == StructSoa_Fixed) {
  526. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  527. } else {
  528. lbValue v = lb_emit_load(p, addr.addr);
  529. len = lb_soa_struct_len(p, v);
  530. }
  531. lbAddr res = lb_add_local_generated(p, elem, true);
  532. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  533. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  534. }
  535. if (t->Struct.soa_kind == StructSoa_Fixed) {
  536. for_array(i, t->Struct.fields) {
  537. Entity *field = t->Struct.fields[i];
  538. Type *base_type = field->type;
  539. GB_ASSERT(base_type->kind == Type_Array);
  540. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  541. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  542. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  543. lbValue src = lb_emit_load(p, src_ptr);
  544. lb_emit_store(p, dst, src);
  545. }
  546. } else {
  547. isize field_count = t->Struct.fields.count;
  548. if (t->Struct.soa_kind == StructSoa_Slice) {
  549. field_count -= 1;
  550. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  551. field_count -= 3;
  552. }
  553. for (isize i = 0; i < field_count; i++) {
  554. Entity *field = t->Struct.fields[i];
  555. Type *base_type = field->type;
  556. GB_ASSERT(base_type->kind == Type_Pointer);
  557. Type *elem = base_type->Pointer.elem;
  558. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  559. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  560. lbValue src = lb_emit_load(p, src_ptr);
  561. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  562. src = lb_emit_load(p, src);
  563. lb_emit_store(p, dst, src);
  564. }
  565. }
  566. return lb_addr_load(p, res);
  567. }
  568. if (is_type_proc(addr.addr.type)) {
  569. return addr.addr;
  570. }
  571. return lb_emit_load(p, addr.addr);
  572. }
  573. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  574. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  575. }
  576. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  577. Type *t = u.type;
  578. GB_ASSERT_MSG(is_type_pointer(t) &&
  579. is_type_union(type_deref(t)), "%s", type_to_string(t));
  580. Type *ut = type_deref(t);
  581. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  582. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  583. GB_ASSERT(type_size_of(ut) > 0);
  584. Type *tag_type = union_tag_type(ut);
  585. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  586. unsigned element_count = LLVMCountStructElementTypes(uvt);
  587. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  588. lbValue tag_ptr = {};
  589. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  590. tag_ptr.type = alloc_type_pointer(tag_type);
  591. return tag_ptr;
  592. }
  593. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  594. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  595. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  596. return lb_emit_load(p, tag_ptr);
  597. }
  598. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  599. Type *t = type_deref(parent.type);
  600. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  601. // No tag needed!
  602. } else {
  603. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  604. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  605. }
  606. }
  607. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  608. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  609. lb_emit_store(p, underlying, variant);
  610. lb_emit_store_union_variant_tag(p, parent, variant_type);
  611. }
  612. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  613. unsigned field_count = LLVMCountStructElementTypes(src);
  614. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  615. LLVMGetStructElementTypes(src, fields);
  616. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  617. }
  618. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  619. switch (alignment) {
  620. case 1:
  621. return LLVMArrayType(lb_type(m, t_u8), 0);
  622. case 2:
  623. return LLVMArrayType(lb_type(m, t_u16), 0);
  624. case 4:
  625. return LLVMArrayType(lb_type(m, t_u32), 0);
  626. case 8:
  627. return LLVMArrayType(lb_type(m, t_u64), 0);
  628. case 16:
  629. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  630. default:
  631. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  632. break;
  633. }
  634. return nullptr;
  635. }
  636. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  637. if (!elem_type_can_be_constant(elem_type)) {
  638. return false;
  639. }
  640. if (elem->kind == Ast_FieldValue) {
  641. elem = elem->FieldValue.value;
  642. }
  643. TypeAndValue tav = type_and_value_of_expr(elem);
  644. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  645. return tav.value.kind != ExactValue_Invalid;
  646. }
  647. String lb_mangle_name(lbModule *m, Entity *e) {
  648. String name = e->token.string;
  649. AstPackage *pkg = e->pkg;
  650. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  651. String pkgn = pkg->name;
  652. GB_ASSERT(!rune_is_digit(pkgn[0]));
  653. if (pkgn == "llvm") {
  654. pkgn = str_lit("llvm$");
  655. }
  656. isize max_len = pkgn.len + 1 + name.len + 1;
  657. bool require_suffix_id = is_type_polymorphic(e->type, true);
  658. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  659. require_suffix_id = true;
  660. } else if (is_blank_ident(e->token)) {
  661. require_suffix_id = true;
  662. }if (e->flags & EntityFlag_NotExported) {
  663. require_suffix_id = true;
  664. }
  665. if (require_suffix_id) {
  666. max_len += 21;
  667. }
  668. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  669. isize new_name_len = gb_snprintf(
  670. new_name, max_len,
  671. "%.*s.%.*s", LIT(pkgn), LIT(name)
  672. );
  673. if (require_suffix_id) {
  674. char *str = new_name + new_name_len-1;
  675. isize len = max_len-new_name_len;
  676. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  677. new_name_len += extra-1;
  678. }
  679. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  680. return mangled_name;
  681. }
  682. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  683. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  684. // and as a result, the declaration does not have time to determine what it should be
  685. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  686. if (e->TypeName.ir_mangled_name.len != 0) {
  687. return e->TypeName.ir_mangled_name;
  688. }
  689. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  690. if (p == nullptr) {
  691. Entity *proc = nullptr;
  692. if (e->parent_proc_decl != nullptr) {
  693. proc = e->parent_proc_decl->entity;
  694. } else {
  695. Scope *scope = e->scope;
  696. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  697. scope = scope->parent;
  698. }
  699. GB_ASSERT(scope != nullptr);
  700. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  701. proc = scope->procedure_entity;
  702. }
  703. GB_ASSERT(proc->kind == Entity_Procedure);
  704. if (proc->code_gen_procedure != nullptr) {
  705. p = proc->code_gen_procedure;
  706. }
  707. }
  708. // NOTE(bill): Generate a new name
  709. // parent_proc.name-guid
  710. String ts_name = e->token.string;
  711. if (p != nullptr) {
  712. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  713. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  714. u32 guid = ++p->module->nested_type_name_guid;
  715. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  716. String name = make_string(cast(u8 *)name_text, name_len-1);
  717. e->TypeName.ir_mangled_name = name;
  718. return name;
  719. } else {
  720. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  721. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  722. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  723. static u32 guid = 0;
  724. guid += 1;
  725. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  726. String name = make_string(cast(u8 *)name_text, name_len-1);
  727. e->TypeName.ir_mangled_name = name;
  728. return name;
  729. }
  730. }
  731. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  732. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  733. return e->TypeName.ir_mangled_name;
  734. }
  735. GB_ASSERT(e != nullptr);
  736. if (e->pkg == nullptr) {
  737. return e->token.string;
  738. }
  739. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  740. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  741. }
  742. String name = {};
  743. bool no_name_mangle = false;
  744. if (e->kind == Entity_Variable) {
  745. bool is_foreign = e->Variable.is_foreign;
  746. bool is_export = e->Variable.is_export;
  747. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  748. if (e->Variable.link_name.len > 0) {
  749. return e->Variable.link_name;
  750. }
  751. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  752. return e->Procedure.link_name;
  753. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  754. no_name_mangle = true;
  755. }
  756. if (!no_name_mangle) {
  757. name = lb_mangle_name(m, e);
  758. }
  759. if (name.len == 0) {
  760. name = e->token.string;
  761. }
  762. if (e->kind == Entity_TypeName) {
  763. e->TypeName.ir_mangled_name = name;
  764. } else if (e->kind == Entity_Procedure) {
  765. e->Procedure.link_name = name;
  766. }
  767. return name;
  768. }
  769. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  770. Type *original_type = type;
  771. LLVMContextRef ctx = m->ctx;
  772. i64 size = type_size_of(type); // Check size
  773. GB_ASSERT(type != t_invalid);
  774. switch (type->kind) {
  775. case Type_Basic:
  776. switch (type->Basic.kind) {
  777. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  778. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  779. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  780. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  781. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  782. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  783. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  784. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  785. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  786. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  787. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  788. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  789. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  790. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  791. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  792. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  793. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  794. case Basic_f16: return LLVMHalfTypeInContext(ctx);
  795. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  796. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  797. case Basic_f16le: return LLVMHalfTypeInContext(ctx);
  798. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  799. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  800. case Basic_f16be: return LLVMHalfTypeInContext(ctx);
  801. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  802. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  803. case Basic_complex32:
  804. {
  805. char const *name = "..complex32";
  806. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  807. if (type != nullptr) {
  808. return type;
  809. }
  810. type = LLVMStructCreateNamed(ctx, name);
  811. LLVMTypeRef fields[2] = {
  812. lb_type(m, t_f16),
  813. lb_type(m, t_f16),
  814. };
  815. LLVMStructSetBody(type, fields, 2, false);
  816. return type;
  817. }
  818. case Basic_complex64:
  819. {
  820. char const *name = "..complex64";
  821. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  822. if (type != nullptr) {
  823. return type;
  824. }
  825. type = LLVMStructCreateNamed(ctx, name);
  826. LLVMTypeRef fields[2] = {
  827. lb_type(m, t_f32),
  828. lb_type(m, t_f32),
  829. };
  830. LLVMStructSetBody(type, fields, 2, false);
  831. return type;
  832. }
  833. case Basic_complex128:
  834. {
  835. char const *name = "..complex128";
  836. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  837. if (type != nullptr) {
  838. return type;
  839. }
  840. type = LLVMStructCreateNamed(ctx, name);
  841. LLVMTypeRef fields[2] = {
  842. lb_type(m, t_f64),
  843. lb_type(m, t_f64),
  844. };
  845. LLVMStructSetBody(type, fields, 2, false);
  846. return type;
  847. }
  848. case Basic_quaternion64:
  849. {
  850. char const *name = "..quaternion64";
  851. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  852. if (type != nullptr) {
  853. return type;
  854. }
  855. type = LLVMStructCreateNamed(ctx, name);
  856. LLVMTypeRef fields[4] = {
  857. lb_type(m, t_f16),
  858. lb_type(m, t_f16),
  859. lb_type(m, t_f16),
  860. lb_type(m, t_f16),
  861. };
  862. LLVMStructSetBody(type, fields, 4, false);
  863. return type;
  864. }
  865. case Basic_quaternion128:
  866. {
  867. char const *name = "..quaternion128";
  868. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  869. if (type != nullptr) {
  870. return type;
  871. }
  872. type = LLVMStructCreateNamed(ctx, name);
  873. LLVMTypeRef fields[4] = {
  874. lb_type(m, t_f32),
  875. lb_type(m, t_f32),
  876. lb_type(m, t_f32),
  877. lb_type(m, t_f32),
  878. };
  879. LLVMStructSetBody(type, fields, 4, false);
  880. return type;
  881. }
  882. case Basic_quaternion256:
  883. {
  884. char const *name = "..quaternion256";
  885. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  886. if (type != nullptr) {
  887. return type;
  888. }
  889. type = LLVMStructCreateNamed(ctx, name);
  890. LLVMTypeRef fields[4] = {
  891. lb_type(m, t_f64),
  892. lb_type(m, t_f64),
  893. lb_type(m, t_f64),
  894. lb_type(m, t_f64),
  895. };
  896. LLVMStructSetBody(type, fields, 4, false);
  897. return type;
  898. }
  899. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  900. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  901. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  902. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  903. case Basic_string:
  904. {
  905. char const *name = "..string";
  906. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  907. if (type != nullptr) {
  908. return type;
  909. }
  910. type = LLVMStructCreateNamed(ctx, name);
  911. LLVMTypeRef fields[2] = {
  912. LLVMPointerType(lb_type(m, t_u8), 0),
  913. lb_type(m, t_int),
  914. };
  915. LLVMStructSetBody(type, fields, 2, false);
  916. return type;
  917. }
  918. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  919. case Basic_any:
  920. {
  921. char const *name = "..any";
  922. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  923. if (type != nullptr) {
  924. return type;
  925. }
  926. type = LLVMStructCreateNamed(ctx, name);
  927. LLVMTypeRef fields[2] = {
  928. lb_type(m, t_rawptr),
  929. lb_type(m, t_typeid),
  930. };
  931. LLVMStructSetBody(type, fields, 2, false);
  932. return type;
  933. }
  934. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  935. // Endian Specific Types
  936. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  937. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  938. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  939. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  940. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  941. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  942. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  943. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  944. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  945. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  946. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  947. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  948. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  949. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  950. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  951. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  952. // Untyped types
  953. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  954. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  955. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  956. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  957. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  958. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  959. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  960. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  961. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  962. }
  963. break;
  964. case Type_Named:
  965. {
  966. Type *base = base_type(type->Named.base);
  967. switch (base->kind) {
  968. case Type_Basic:
  969. return lb_type_internal(m, base);
  970. case Type_Named:
  971. case Type_Generic:
  972. GB_PANIC("INVALID TYPE");
  973. break;
  974. case Type_Pointer:
  975. case Type_Array:
  976. case Type_EnumeratedArray:
  977. case Type_Slice:
  978. case Type_DynamicArray:
  979. case Type_Map:
  980. case Type_Enum:
  981. case Type_BitSet:
  982. case Type_SimdVector:
  983. return lb_type_internal(m, base);
  984. // TODO(bill): Deal with this correctly. Can this be named?
  985. case Type_Proc:
  986. return lb_type_internal(m, base);
  987. case Type_Tuple:
  988. return lb_type_internal(m, base);
  989. }
  990. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  991. if (found) {
  992. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  993. if (kind == LLVMStructTypeKind) {
  994. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  995. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  996. if (llvm_type != nullptr) {
  997. return llvm_type;
  998. }
  999. llvm_type = LLVMStructCreateNamed(ctx, name);
  1000. map_set(&m->types, hash_type(type), llvm_type);
  1001. lb_clone_struct_type(llvm_type, *found);
  1002. return llvm_type;
  1003. }
  1004. }
  1005. switch (base->kind) {
  1006. case Type_Struct:
  1007. case Type_Union:
  1008. {
  1009. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1010. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1011. if (llvm_type != nullptr) {
  1012. return llvm_type;
  1013. }
  1014. llvm_type = LLVMStructCreateNamed(ctx, name);
  1015. map_set(&m->types, hash_type(type), llvm_type);
  1016. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1017. return llvm_type;
  1018. }
  1019. }
  1020. return lb_type_internal(m, base);
  1021. }
  1022. case Type_Pointer:
  1023. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1024. case Type_Array: {
  1025. m->internal_type_level -= 1;
  1026. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1027. m->internal_type_level += 1;
  1028. return t;
  1029. }
  1030. case Type_EnumeratedArray: {
  1031. m->internal_type_level -= 1;
  1032. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1033. m->internal_type_level += 1;
  1034. return t;
  1035. }
  1036. case Type_Slice:
  1037. {
  1038. LLVMTypeRef fields[2] = {
  1039. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1040. lb_type(m, t_int), // len
  1041. };
  1042. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1043. }
  1044. break;
  1045. case Type_DynamicArray:
  1046. {
  1047. LLVMTypeRef fields[4] = {
  1048. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1049. lb_type(m, t_int), // len
  1050. lb_type(m, t_int), // cap
  1051. lb_type(m, t_allocator), // allocator
  1052. };
  1053. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1054. }
  1055. break;
  1056. case Type_Map:
  1057. return lb_type(m, type->Map.internal_type);
  1058. case Type_Struct:
  1059. {
  1060. if (type->Struct.is_raw_union) {
  1061. unsigned field_count = 2;
  1062. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1063. i64 alignment = type_align_of(type);
  1064. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1065. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1066. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1067. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1068. }
  1069. isize offset = 0;
  1070. if (type->Struct.custom_align > 0) {
  1071. offset = 1;
  1072. }
  1073. m->internal_type_level += 1;
  1074. defer (m->internal_type_level -= 1);
  1075. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1076. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1077. for_array(i, type->Struct.fields) {
  1078. Entity *field = type->Struct.fields[i];
  1079. fields[i+offset] = lb_type(m, field->type);
  1080. }
  1081. if (type->Struct.custom_align > 0) {
  1082. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1083. }
  1084. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1085. }
  1086. break;
  1087. case Type_Union:
  1088. if (type->Union.variants.count == 0) {
  1089. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1090. } else {
  1091. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1092. // LLVM takes the first element's alignment as the entire alignment (like C)
  1093. i64 align = type_align_of(type);
  1094. i64 size = type_size_of(type);
  1095. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1096. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1097. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1098. }
  1099. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1100. LLVMTypeRef fields[3] = {};
  1101. unsigned field_count = 1;
  1102. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1103. if (is_type_union_maybe_pointer(type)) {
  1104. field_count += 1;
  1105. fields[1] = lb_type(m, type->Union.variants[0]);
  1106. } else {
  1107. field_count += 2;
  1108. if (block_size == align) {
  1109. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1110. } else {
  1111. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1112. }
  1113. fields[2] = lb_type(m, union_tag_type(type));
  1114. }
  1115. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1116. }
  1117. break;
  1118. case Type_Enum:
  1119. return lb_type(m, base_enum_type(type));
  1120. case Type_Tuple:
  1121. if (type->Tuple.variables.count == 1) {
  1122. return lb_type(m, type->Tuple.variables[0]->type);
  1123. } else {
  1124. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1125. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1126. for_array(i, type->Tuple.variables) {
  1127. Entity *field = type->Tuple.variables[i];
  1128. LLVMTypeRef param_type = nullptr;
  1129. param_type = lb_type(m, field->type);
  1130. fields[i] = param_type;
  1131. }
  1132. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1133. }
  1134. case Type_Proc:
  1135. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1136. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1137. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1138. } else {
  1139. unsigned param_count = 0;
  1140. if (type->Proc.calling_convention == ProcCC_Odin) {
  1141. param_count += 1;
  1142. }
  1143. if (type->Proc.param_count != 0) {
  1144. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1145. for_array(i, type->Proc.params->Tuple.variables) {
  1146. Entity *e = type->Proc.params->Tuple.variables[i];
  1147. if (e->kind != Entity_Variable) {
  1148. continue;
  1149. }
  1150. if (e->flags & EntityFlag_CVarArg) {
  1151. continue;
  1152. }
  1153. param_count += 1;
  1154. }
  1155. }
  1156. m->internal_type_level += 1;
  1157. defer (m->internal_type_level -= 1);
  1158. LLVMTypeRef ret = nullptr;
  1159. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1160. if (type->Proc.result_count != 0) {
  1161. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1162. ret = lb_type(m, single_ret);
  1163. if (ret != nullptr) {
  1164. if (is_type_boolean(single_ret) &&
  1165. is_calling_convention_none(type->Proc.calling_convention) &&
  1166. type_size_of(single_ret) <= 1) {
  1167. ret = LLVMInt1TypeInContext(m->ctx);
  1168. }
  1169. }
  1170. }
  1171. isize param_index = 0;
  1172. if (type->Proc.param_count != 0) {
  1173. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1174. for_array(i, type->Proc.params->Tuple.variables) {
  1175. Entity *e = type->Proc.params->Tuple.variables[i];
  1176. if (e->kind != Entity_Variable) {
  1177. continue;
  1178. }
  1179. if (e->flags & EntityFlag_CVarArg) {
  1180. continue;
  1181. }
  1182. Type *e_type = reduce_tuple_to_single_type(e->type);
  1183. LLVMTypeRef param_type = nullptr;
  1184. if (is_type_boolean(e_type) &&
  1185. type_size_of(e_type) <= 1) {
  1186. param_type = LLVMInt1TypeInContext(m->ctx);
  1187. } else {
  1188. if (is_type_proc(e_type)) {
  1189. param_type = lb_type(m, t_rawptr);
  1190. } else {
  1191. param_type = lb_type(m, e_type);
  1192. }
  1193. }
  1194. params[param_index++] = param_type;
  1195. }
  1196. }
  1197. if (param_index < param_count) {
  1198. params[param_index++] = lb_type(m, t_rawptr);
  1199. // params[param_index++] = lb_type(m, t_context_ptr);
  1200. }
  1201. GB_ASSERT(param_index == param_count);
  1202. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1203. map_set(&m->function_type_map, hash_type(type), ft);
  1204. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1205. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1206. // LLVMTypeRef new_ret = LLVMGetReturnType(new_abi_fn_type);
  1207. // LLVMTypeRef old_ret = LLVMGetReturnType(old_abi_fn_type);
  1208. // unsigned new_count = LLVMCountParamTypes(new_abi_fn_type);
  1209. // unsigned old_count = LLVMCountParamTypes(old_abi_fn_type);
  1210. // GB_ASSERT_MSG(new_count == old_count, "%u %u, %s %s", new_count, old_count, LLVMPrintTypeToString(new_abi_fn_type), LLVMPrintTypeToString(old_abi_fn_type));
  1211. return new_abi_fn_ptr_type;
  1212. }
  1213. break;
  1214. case Type_BitSet:
  1215. {
  1216. Type *ut = bit_set_to_int(type);
  1217. return lb_type(m, ut);
  1218. }
  1219. case Type_SimdVector:
  1220. if (type->SimdVector.is_x86_mmx) {
  1221. return LLVMX86MMXTypeInContext(ctx);
  1222. }
  1223. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1224. case Type_RelativePointer:
  1225. return lb_type_internal(m, type->RelativePointer.base_integer);
  1226. case Type_RelativeSlice:
  1227. {
  1228. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1229. unsigned field_count = 2;
  1230. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1231. fields[0] = base_integer;
  1232. fields[1] = base_integer;
  1233. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1234. }
  1235. }
  1236. GB_PANIC("Invalid type %s", type_to_string(type));
  1237. return LLVMInt32TypeInContext(ctx);
  1238. }
  1239. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1240. type = default_type(type);
  1241. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1242. if (found) {
  1243. return *found;
  1244. }
  1245. LLVMTypeRef llvm_type = nullptr;
  1246. m->internal_type_level += 1;
  1247. llvm_type = lb_type_internal(m, type);
  1248. m->internal_type_level -= 1;
  1249. if (m->internal_type_level == 0) {
  1250. map_set(&m->types, hash_type(type), llvm_type);
  1251. if (is_type_named(type)) {
  1252. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1253. }
  1254. }
  1255. return llvm_type;
  1256. }
  1257. LLVMMetadataRef lb_get_llvm_metadata(lbModule *m, void *key) {
  1258. if (key == nullptr) {
  1259. return nullptr;
  1260. }
  1261. auto found = map_get(&m->debug_values, hash_pointer(key));
  1262. if (found) {
  1263. return *found;
  1264. }
  1265. return nullptr;
  1266. }
  1267. void lb_set_llvm_metadata(lbModule *m, void *key, LLVMMetadataRef value) {
  1268. if (key != nullptr) {
  1269. map_set(&m->debug_values, hash_pointer(key), value);
  1270. }
  1271. }
  1272. LLVMMetadataRef lb_get_llvm_file_metadata_from_node(lbModule *m, Ast *node) {
  1273. if (node == nullptr) {
  1274. return nullptr;
  1275. }
  1276. return lb_get_llvm_metadata(m, node->file);
  1277. }
  1278. LLVMMetadataRef lb_get_current_debug_scope(lbProcedure *p) {
  1279. GB_ASSERT_MSG(p->debug_info != nullptr, "missing debug information for %.*s", LIT(p->name));
  1280. for (isize i = p->scope_stack.count-1; i >= 0; i--) {
  1281. Scope *s = p->scope_stack[i];
  1282. LLVMMetadataRef md = lb_get_llvm_metadata(p->module, s);
  1283. if (md) {
  1284. return md;
  1285. }
  1286. }
  1287. return p->debug_info;
  1288. }
  1289. LLVMMetadataRef lb_debug_location_from_token_pos(lbProcedure *p, TokenPos pos) {
  1290. LLVMMetadataRef scope = lb_get_current_debug_scope(p);
  1291. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  1292. return LLVMDIBuilderCreateDebugLocation(p->module->ctx, cast(unsigned)pos.line, cast(unsigned)pos.column, scope, nullptr);
  1293. }
  1294. LLVMMetadataRef lb_debug_location_from_ast(lbProcedure *p, Ast *node) {
  1295. GB_ASSERT(node != nullptr);
  1296. return lb_debug_location_from_token_pos(p, ast_token(node).pos);
  1297. }
  1298. LLVMMetadataRef lb_debug_type_internal_proc(lbModule *m, Type *type) {
  1299. Type *original_type = type;
  1300. LLVMContextRef ctx = m->ctx;
  1301. i64 size = type_size_of(type); // Check size
  1302. GB_ASSERT(type != t_invalid);
  1303. unsigned const word_size = cast(unsigned)build_context.word_size;
  1304. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1305. GB_ASSERT(type->kind == Type_Proc);
  1306. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1307. unsigned parameter_count = 1;
  1308. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1309. Entity *e = type->Proc.params->Tuple.variables[i];
  1310. if (e->kind == Entity_Variable) {
  1311. parameter_count += 1;
  1312. }
  1313. }
  1314. LLVMMetadataRef *parameters = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, parameter_count);
  1315. unsigned param_index = 0;
  1316. if (type->Proc.result_count == 0) {
  1317. parameters[param_index++] = nullptr;
  1318. } else {
  1319. parameters[param_index++] = lb_debug_type(m, type->Proc.results);
  1320. }
  1321. LLVMMetadataRef parent_scope = nullptr;
  1322. LLVMMetadataRef scope = nullptr;
  1323. LLVMMetadataRef file = nullptr;
  1324. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1325. Entity *e = type->Proc.params->Tuple.variables[i];
  1326. if (e->kind != Entity_Variable) {
  1327. continue;
  1328. }
  1329. parameters[param_index] = lb_debug_type(m, e->type);
  1330. param_index += 1;
  1331. }
  1332. LLVMDIFlags flags = LLVMDIFlagZero;
  1333. if (type->Proc.diverging) {
  1334. flags = LLVMDIFlagNoReturn;
  1335. }
  1336. return LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, parameters, parameter_count, flags);
  1337. }
  1338. LLVMMetadataRef lb_debug_struct_field(lbModule *m, String const &name, Type *type, u64 offset_in_bits) {
  1339. unsigned field_line = 1;
  1340. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1341. AstPackage *pkg = m->info->runtime_package;
  1342. GB_ASSERT(pkg->files.count != 0);
  1343. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1344. LLVMMetadataRef scope = file;
  1345. return LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1346. 8*cast(u64)type_size_of(type), 8*cast(u32)type_align_of(type), offset_in_bits,
  1347. field_flags, lb_debug_type(m, type)
  1348. );
  1349. }
  1350. LLVMMetadataRef lb_debug_basic_struct(lbModule *m, String const &name, u64 size_in_bits, u32 align_in_bits, LLVMMetadataRef *elements, unsigned element_count) {
  1351. AstPackage *pkg = m->info->runtime_package;
  1352. GB_ASSERT(pkg->files.count != 0);
  1353. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1354. LLVMMetadataRef scope = file;
  1355. 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);
  1356. }
  1357. LLVMMetadataRef lb_debug_type_basic_type(lbModule *m, String const &name, u64 size_in_bits, LLVMDWARFTypeEncoding encoding, LLVMDIFlags flags = LLVMDIFlagZero) {
  1358. LLVMMetadataRef basic_type = LLVMDIBuilderCreateBasicType(m->debug_builder, cast(char const *)name.text, name.len, size_in_bits, encoding, flags);
  1359. #if 1
  1360. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, basic_type, cast(char const *)name.text, name.len, nullptr, 0, nullptr, cast(u32)size_in_bits);
  1361. return final_decl;
  1362. #else
  1363. return basic_type;
  1364. #endif
  1365. }
  1366. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1367. Type *original_type = type;
  1368. LLVMContextRef ctx = m->ctx;
  1369. i64 size = type_size_of(type); // Check size
  1370. GB_ASSERT(type != t_invalid);
  1371. unsigned const word_size = cast(unsigned)build_context.word_size;
  1372. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1373. switch (type->kind) {
  1374. case Type_Basic:
  1375. switch (type->Basic.kind) {
  1376. case Basic_llvm_bool: return lb_debug_type_basic_type(m, str_lit("llvm bool"), 1, LLVMDWARFTypeEncoding_Boolean);
  1377. case Basic_bool: return lb_debug_type_basic_type(m, str_lit("bool"), 8, LLVMDWARFTypeEncoding_Boolean);
  1378. case Basic_b8: return lb_debug_type_basic_type(m, str_lit("b8"), 8, LLVMDWARFTypeEncoding_Boolean);
  1379. case Basic_b16: return lb_debug_type_basic_type(m, str_lit("b16"), 16, LLVMDWARFTypeEncoding_Boolean);
  1380. case Basic_b32: return lb_debug_type_basic_type(m, str_lit("b32"), 32, LLVMDWARFTypeEncoding_Boolean);
  1381. case Basic_b64: return lb_debug_type_basic_type(m, str_lit("b64"), 64, LLVMDWARFTypeEncoding_Boolean);
  1382. case Basic_i8: return lb_debug_type_basic_type(m, str_lit("i8"), 8, LLVMDWARFTypeEncoding_Signed);
  1383. case Basic_u8: return lb_debug_type_basic_type(m, str_lit("u8"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1384. case Basic_i16: return lb_debug_type_basic_type(m, str_lit("i16"), 16, LLVMDWARFTypeEncoding_Signed);
  1385. case Basic_u16: return lb_debug_type_basic_type(m, str_lit("u16"), 16, LLVMDWARFTypeEncoding_Unsigned);
  1386. case Basic_i32: return lb_debug_type_basic_type(m, str_lit("i32"), 32, LLVMDWARFTypeEncoding_Signed);
  1387. case Basic_u32: return lb_debug_type_basic_type(m, str_lit("u32"), 32, LLVMDWARFTypeEncoding_Unsigned);
  1388. case Basic_i64: return lb_debug_type_basic_type(m, str_lit("i64"), 64, LLVMDWARFTypeEncoding_Signed);
  1389. case Basic_u64: return lb_debug_type_basic_type(m, str_lit("u64"), 64, LLVMDWARFTypeEncoding_Unsigned);
  1390. case Basic_i128: return lb_debug_type_basic_type(m, str_lit("i128"), 128, LLVMDWARFTypeEncoding_Signed);
  1391. case Basic_u128: return lb_debug_type_basic_type(m, str_lit("u128"), 128, LLVMDWARFTypeEncoding_Unsigned);
  1392. case Basic_rune: return lb_debug_type_basic_type(m, str_lit("rune"), 32, LLVMDWARFTypeEncoding_Utf);
  1393. case Basic_f16: return lb_debug_type_basic_type(m, str_lit("f16"), 16, LLVMDWARFTypeEncoding_Float);
  1394. case Basic_f32: return lb_debug_type_basic_type(m, str_lit("f32"), 32, LLVMDWARFTypeEncoding_Float);
  1395. case Basic_f64: return lb_debug_type_basic_type(m, str_lit("f64"), 64, LLVMDWARFTypeEncoding_Float);
  1396. case Basic_int: return lb_debug_type_basic_type(m, str_lit("int"), word_bits, LLVMDWARFTypeEncoding_Signed);
  1397. case Basic_uint: return lb_debug_type_basic_type(m, str_lit("uint"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1398. case Basic_uintptr: return lb_debug_type_basic_type(m, str_lit("uintptr"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1399. case Basic_typeid:
  1400. return lb_debug_type_basic_type(m, str_lit("typeid"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1401. // Endian Specific Types
  1402. case Basic_i16le: return lb_debug_type_basic_type(m, str_lit("i16le"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1403. case Basic_u16le: return lb_debug_type_basic_type(m, str_lit("u16le"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1404. case Basic_i32le: return lb_debug_type_basic_type(m, str_lit("i32le"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1405. case Basic_u32le: return lb_debug_type_basic_type(m, str_lit("u32le"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1406. case Basic_i64le: return lb_debug_type_basic_type(m, str_lit("i64le"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1407. case Basic_u64le: return lb_debug_type_basic_type(m, str_lit("u64le"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1408. case Basic_i128le: return lb_debug_type_basic_type(m, str_lit("i128le"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1409. case Basic_u128le: return lb_debug_type_basic_type(m, str_lit("u128le"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1410. case Basic_f16le: return lb_debug_type_basic_type(m, str_lit("f16le"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1411. case Basic_f32le: return lb_debug_type_basic_type(m, str_lit("f32le"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1412. case Basic_f64le: return lb_debug_type_basic_type(m, str_lit("f64le"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1413. case Basic_i16be: return lb_debug_type_basic_type(m, str_lit("i16be"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1414. case Basic_u16be: return lb_debug_type_basic_type(m, str_lit("u16be"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1415. case Basic_i32be: return lb_debug_type_basic_type(m, str_lit("i32be"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1416. case Basic_u32be: return lb_debug_type_basic_type(m, str_lit("u32be"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1417. case Basic_i64be: return lb_debug_type_basic_type(m, str_lit("i64be"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1418. case Basic_u64be: return lb_debug_type_basic_type(m, str_lit("u64be"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1419. case Basic_i128be: return lb_debug_type_basic_type(m, str_lit("i128be"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1420. case Basic_u128be: return lb_debug_type_basic_type(m, str_lit("u128be"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1421. case Basic_f16be: return lb_debug_type_basic_type(m, str_lit("f16be"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1422. case Basic_f32be: return lb_debug_type_basic_type(m, str_lit("f32be"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1423. case Basic_f64be: return lb_debug_type_basic_type(m, str_lit("f64be"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1424. case Basic_complex32:
  1425. {
  1426. LLVMMetadataRef elements[2] = {};
  1427. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f16, 0);
  1428. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 4);
  1429. return lb_debug_basic_struct(m, str_lit("complex32"), 64, 32, elements, gb_count_of(elements));
  1430. }
  1431. case Basic_complex64:
  1432. {
  1433. LLVMMetadataRef elements[2] = {};
  1434. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f32, 0);
  1435. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 4);
  1436. return lb_debug_basic_struct(m, str_lit("complex64"), 64, 32, elements, gb_count_of(elements));
  1437. }
  1438. case Basic_complex128:
  1439. {
  1440. LLVMMetadataRef elements[2] = {};
  1441. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f64, 0);
  1442. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 8);
  1443. return lb_debug_basic_struct(m, str_lit("complex128"), 128, 64, elements, gb_count_of(elements));
  1444. }
  1445. case Basic_quaternion64:
  1446. {
  1447. LLVMMetadataRef elements[4] = {};
  1448. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 0);
  1449. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f16, 4);
  1450. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f16, 8);
  1451. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f16, 12);
  1452. return lb_debug_basic_struct(m, str_lit("quaternion64"), 128, 32, elements, gb_count_of(elements));
  1453. }
  1454. case Basic_quaternion128:
  1455. {
  1456. LLVMMetadataRef elements[4] = {};
  1457. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 0);
  1458. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f32, 4);
  1459. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f32, 8);
  1460. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f32, 12);
  1461. return lb_debug_basic_struct(m, str_lit("quaternion128"), 128, 32, elements, gb_count_of(elements));
  1462. }
  1463. case Basic_quaternion256:
  1464. {
  1465. LLVMMetadataRef elements[4] = {};
  1466. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 0);
  1467. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f64, 8);
  1468. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f64, 16);
  1469. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f64, 24);
  1470. return lb_debug_basic_struct(m, str_lit("quaternion256"), 256, 32, elements, gb_count_of(elements));
  1471. }
  1472. case Basic_rawptr:
  1473. {
  1474. LLVMMetadataRef void_type = lb_debug_type_basic_type(m, str_lit("void"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1475. return LLVMDIBuilderCreatePointerType(m->debug_builder, void_type, word_bits, word_bits, LLVMDWARFTypeEncoding_Address, "rawptr", 6);
  1476. }
  1477. case Basic_string:
  1478. {
  1479. LLVMMetadataRef elements[2] = {};
  1480. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_u8_ptr, 0);
  1481. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, word_bits);
  1482. return lb_debug_basic_struct(m, str_lit("string"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1483. }
  1484. case Basic_cstring:
  1485. {
  1486. LLVMMetadataRef char_type = lb_debug_type_basic_type(m, str_lit("char"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1487. return LLVMDIBuilderCreatePointerType(m->debug_builder, char_type, word_bits, word_bits, 0, "cstring", 7);
  1488. }
  1489. case Basic_any:
  1490. {
  1491. LLVMMetadataRef elements[2] = {};
  1492. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_rawptr, 0);
  1493. elements[1] = lb_debug_struct_field(m, str_lit("id"), t_typeid, word_bits);
  1494. return lb_debug_basic_struct(m, str_lit("any"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1495. }
  1496. // Untyped types
  1497. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1498. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1499. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1500. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1501. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1502. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1503. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1504. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1505. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1506. default: GB_PANIC("Basic Unhandled"); break;
  1507. }
  1508. break;
  1509. case Type_Named:
  1510. GB_PANIC("Type_Named should be handled in lb_debug_type separately");
  1511. case Type_Pointer:
  1512. return LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, type->Pointer.elem), word_bits, word_bits, 0, nullptr, 0);
  1513. case Type_Array:
  1514. return LLVMDIBuilderCreateArrayType(m->debug_builder,
  1515. type->Array.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->Array.elem), nullptr, 0);
  1516. case Type_EnumeratedArray: {
  1517. LLVMMetadataRef array_type = LLVMDIBuilderCreateArrayType(m->debug_builder,
  1518. type->EnumeratedArray.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->EnumeratedArray.elem), nullptr, 0);
  1519. gbString name = type_to_string(type, temporary_allocator());
  1520. return LLVMDIBuilderCreateTypedef(m->debug_builder, array_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1521. }
  1522. case Type_Struct:
  1523. case Type_Union:
  1524. case Type_Slice:
  1525. case Type_DynamicArray:
  1526. case Type_Map:
  1527. case Type_BitSet:
  1528. {
  1529. unsigned tag = DW_TAG_structure_type;
  1530. if (is_type_raw_union(type) || is_type_union(type)) {
  1531. tag = DW_TAG_union_type;
  1532. }
  1533. u64 size_in_bits = cast(u64)(8*type_size_of(type));
  1534. u32 align_in_bits = cast(u32)(8*type_size_of(type));
  1535. LLVMDIFlags flags = LLVMDIFlagZero;
  1536. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1537. m->debug_builder, tag, "", 0, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1538. );
  1539. lbIncompleteDebugType idt = {};
  1540. idt.type = type;
  1541. idt.metadata = temp_forward_decl;
  1542. array_add(&m->debug_incomplete_types, idt);
  1543. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1544. return temp_forward_decl;
  1545. }
  1546. case Type_Enum:
  1547. {
  1548. LLVMMetadataRef scope = nullptr;
  1549. LLVMMetadataRef file = nullptr;
  1550. unsigned line = 0;
  1551. unsigned element_count = cast(unsigned)type->Enum.fields.count;
  1552. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1553. Type *bt = base_enum_type(type);
  1554. LLVMBool is_unsigned = is_type_unsigned(bt);
  1555. for (unsigned i = 0; i < element_count; i++) {
  1556. Entity *f = type->Enum.fields[i];
  1557. GB_ASSERT(f->kind == Entity_Constant);
  1558. String name = f->token.string;
  1559. i64 value = exact_value_to_i64(f->Constant.value);
  1560. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1561. }
  1562. LLVMMetadataRef class_type = lb_debug_type(m, bt);
  1563. 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);
  1564. }
  1565. case Type_Tuple:
  1566. if (type->Tuple.variables.count == 1) {
  1567. return lb_debug_type(m, type->Tuple.variables[0]->type);
  1568. } else {
  1569. type_set_offsets(type);
  1570. LLVMMetadataRef parent_scope = nullptr;
  1571. LLVMMetadataRef scope = nullptr;
  1572. LLVMMetadataRef file = nullptr;
  1573. unsigned line = 0;
  1574. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1575. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1576. LLVMDIFlags flags = LLVMDIFlagZero;
  1577. unsigned element_count = cast(unsigned)type->Tuple.variables.count;
  1578. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1579. for (unsigned i = 0; i < element_count; i++) {
  1580. Entity *f = type->Tuple.variables[i];
  1581. GB_ASSERT(f->kind == Entity_Variable);
  1582. String name = f->token.string;
  1583. unsigned field_line = 0;
  1584. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1585. u64 offset_in_bits = 8*cast(u64)type->Tuple.offsets[i];
  1586. elements[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1587. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type), offset_in_bits,
  1588. field_flags, lb_debug_type(m, f->type)
  1589. );
  1590. }
  1591. return LLVMDIBuilderCreateStructType(m->debug_builder, parent_scope, "", 0, file, line,
  1592. size_in_bits, align_in_bits, flags,
  1593. nullptr, elements, element_count, 0, nullptr,
  1594. "", 0
  1595. );
  1596. }
  1597. case Type_Proc:
  1598. {
  1599. LLVMMetadataRef proc_underlying_type = lb_debug_type_internal_proc(m, type);
  1600. LLVMMetadataRef pointer_type = LLVMDIBuilderCreatePointerType(m->debug_builder, proc_underlying_type, word_bits, word_bits, 0, nullptr, 0);
  1601. gbString name = type_to_string(type, temporary_allocator());
  1602. return LLVMDIBuilderCreateTypedef(m->debug_builder, pointer_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1603. }
  1604. break;
  1605. case Type_SimdVector:
  1606. if (type->SimdVector.is_x86_mmx) {
  1607. return LLVMDIBuilderCreateVectorType(m->debug_builder, 2, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, t_f64), nullptr, 0);
  1608. }
  1609. 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);
  1610. case Type_RelativePointer: {
  1611. LLVMMetadataRef base_integer = lb_debug_type(m, type->RelativePointer.base_integer);
  1612. gbString name = type_to_string(type, temporary_allocator());
  1613. return LLVMDIBuilderCreateTypedef(m->debug_builder, base_integer, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1614. }
  1615. case Type_RelativeSlice:
  1616. {
  1617. unsigned element_count = 0;
  1618. LLVMMetadataRef elements[2] = {};
  1619. Type *base_integer = type->RelativeSlice.base_integer;
  1620. elements[0] = lb_debug_struct_field(m, str_lit("data_offset"), base_integer, 0);
  1621. elements[1] = lb_debug_struct_field(m, str_lit("len"), base_integer, 8*type_size_of(base_integer));
  1622. gbString name = type_to_string(type, temporary_allocator());
  1623. 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);
  1624. }
  1625. }
  1626. GB_PANIC("Invalid type %s", type_to_string(type));
  1627. return nullptr;
  1628. }
  1629. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1630. GB_ASSERT(type != nullptr);
  1631. LLVMMetadataRef found = lb_get_llvm_metadata(m, type);
  1632. if (found != nullptr) {
  1633. return found;
  1634. }
  1635. if (type->kind == Type_Named) {
  1636. LLVMMetadataRef file = nullptr;
  1637. unsigned line = 0;
  1638. LLVMMetadataRef scope = nullptr;
  1639. if (type->Named.type_name != nullptr) {
  1640. Entity *e = type->Named.type_name;
  1641. scope = lb_get_llvm_metadata(m, e->scope);
  1642. if (scope != nullptr) {
  1643. file = LLVMDIScopeGetFile(scope);
  1644. }
  1645. line = cast(unsigned)e->token.pos.line;
  1646. }
  1647. // TODO(bill): location data for Type_Named
  1648. u64 size_in_bits = 8*type_size_of(type);
  1649. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1650. String name = type->Named.name;
  1651. char const *name_text = cast(char const *)name.text;
  1652. size_t name_len = cast(size_t)name.len;
  1653. unsigned tag = DW_TAG_structure_type;
  1654. if (is_type_raw_union(type) || is_type_union(type)) {
  1655. tag = DW_TAG_union_type;
  1656. }
  1657. LLVMDIFlags flags = LLVMDIFlagZero;
  1658. Type *bt = base_type(type->Named.base);
  1659. lbIncompleteDebugType idt = {};
  1660. idt.type = type;
  1661. switch (bt->kind) {
  1662. case Type_Enum:
  1663. {
  1664. LLVMMetadataRef scope = nullptr;
  1665. LLVMMetadataRef file = nullptr;
  1666. unsigned line = 0;
  1667. unsigned element_count = cast(unsigned)bt->Enum.fields.count;
  1668. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1669. Type *ct = base_enum_type(type);
  1670. LLVMBool is_unsigned = is_type_unsigned(ct);
  1671. for (unsigned i = 0; i < element_count; i++) {
  1672. Entity *f = bt->Enum.fields[i];
  1673. GB_ASSERT(f->kind == Entity_Constant);
  1674. String name = f->token.string;
  1675. i64 value = exact_value_to_i64(f->Constant.value);
  1676. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1677. }
  1678. LLVMMetadataRef class_type = lb_debug_type(m, ct);
  1679. 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);
  1680. }
  1681. case Type_Basic:
  1682. case Type_Pointer:
  1683. case Type_Array:
  1684. case Type_EnumeratedArray:
  1685. case Type_Tuple:
  1686. case Type_Proc:
  1687. case Type_SimdVector:
  1688. case Type_RelativePointer:
  1689. case Type_RelativeSlice:
  1690. {
  1691. LLVMMetadataRef debug_bt = lb_debug_type(m, bt);
  1692. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, debug_bt, name_text, name_len, file, line, scope, align_in_bits);
  1693. lb_set_llvm_metadata(m, type, final_decl);
  1694. return final_decl;
  1695. }
  1696. case Type_Slice:
  1697. case Type_DynamicArray:
  1698. case Type_Map:
  1699. case Type_Struct:
  1700. case Type_Union:
  1701. case Type_BitSet:
  1702. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1703. m->debug_builder, tag, name_text, name_len, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1704. );
  1705. idt.metadata = temp_forward_decl;
  1706. array_add(&m->debug_incomplete_types, idt);
  1707. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1708. return temp_forward_decl;
  1709. }
  1710. }
  1711. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1712. lb_set_llvm_metadata(m, type, dt);
  1713. return dt;
  1714. }
  1715. void lb_debug_complete_types(lbModule *m) {
  1716. unsigned const word_size = cast(unsigned)build_context.word_size;
  1717. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1718. for_array(debug_incomplete_type_index, m->debug_incomplete_types) {
  1719. auto const &idt = m->debug_incomplete_types[debug_incomplete_type_index];
  1720. GB_ASSERT(idt.type != nullptr);
  1721. GB_ASSERT(idt.metadata != nullptr);
  1722. Type *t = idt.type;
  1723. Type *bt = base_type(t);
  1724. LLVMMetadataRef parent_scope = nullptr;
  1725. LLVMMetadataRef file = nullptr;
  1726. unsigned line_number = 0;
  1727. u64 size_in_bits = 8*type_size_of(t);
  1728. u32 align_in_bits = cast(u32)(8*type_align_of(t));
  1729. LLVMDIFlags flags = LLVMDIFlagZero;
  1730. LLVMMetadataRef derived_from = nullptr;
  1731. LLVMMetadataRef *elements = nullptr;
  1732. unsigned element_count = 0;
  1733. unsigned runtime_lang = 0; // Objective-C runtime version
  1734. char const *unique_id = "";
  1735. LLVMMetadataRef vtable_holder = nullptr;
  1736. size_t unique_id_len = 0;
  1737. LLVMMetadataRef record_scope = nullptr;
  1738. switch (bt->kind) {
  1739. case Type_Slice:
  1740. case Type_DynamicArray:
  1741. case Type_Map:
  1742. case Type_Struct:
  1743. case Type_Union:
  1744. case Type_BitSet: {
  1745. bool is_union = is_type_raw_union(bt) || is_type_union(bt);
  1746. String name = str_lit("<anonymous-struct>");
  1747. if (t->kind == Type_Named) {
  1748. name = t->Named.name;
  1749. if (t->Named.type_name && t->Named.type_name->pkg && t->Named.type_name->pkg->name.len != 0) {
  1750. name = concatenate3_strings(temporary_allocator(), t->Named.type_name->pkg->name, str_lit("."), t->Named.name);
  1751. }
  1752. LLVMMetadataRef file = nullptr;
  1753. unsigned line = 0;
  1754. LLVMMetadataRef file_scope = nullptr;
  1755. if (t->Named.type_name != nullptr) {
  1756. Entity *e = t->Named.type_name;
  1757. file_scope = lb_get_llvm_metadata(m, e->scope);
  1758. if (file_scope != nullptr) {
  1759. file = LLVMDIScopeGetFile(file_scope);
  1760. }
  1761. line = cast(unsigned)e->token.pos.line;
  1762. }
  1763. // TODO(bill): location data for Type_Named
  1764. } else {
  1765. name = make_string_c(type_to_string(t, temporary_allocator()));
  1766. }
  1767. switch (bt->kind) {
  1768. case Type_Slice:
  1769. element_count = 2;
  1770. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1771. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->Slice.elem), 0*word_bits);
  1772. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1773. break;
  1774. case Type_DynamicArray:
  1775. element_count = 4;
  1776. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1777. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->DynamicArray.elem), 0*word_bits);
  1778. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1779. elements[2] = lb_debug_struct_field(m, str_lit("cap"), t_int, 2*word_bits);
  1780. elements[3] = lb_debug_struct_field(m, str_lit("allocator"), t_allocator, 3*word_bits);
  1781. break;
  1782. case Type_Map:
  1783. bt = bt->Map.internal_type;
  1784. /*fallthrough*/
  1785. case Type_Struct:
  1786. if (file == nullptr) {
  1787. if (bt->Struct.node) {
  1788. file = lb_get_llvm_metadata(m, bt->Struct.node->file);
  1789. line_number = cast(unsigned)ast_token(bt->Struct.node).pos.line;
  1790. }
  1791. }
  1792. type_set_offsets(bt);
  1793. {
  1794. isize element_offset = 0;
  1795. record_scope = lb_get_llvm_metadata(m, bt->Struct.scope);
  1796. switch (bt->Struct.soa_kind) {
  1797. case StructSoa_Slice: element_offset = 1; break;
  1798. case StructSoa_Dynamic: element_offset = 3; break;
  1799. }
  1800. element_count = cast(unsigned)(bt->Struct.fields.count + element_offset);
  1801. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1802. switch (bt->Struct.soa_kind) {
  1803. case StructSoa_Slice:
  1804. elements[0] = LLVMDIBuilderCreateMemberType(
  1805. m->debug_builder, record_scope,
  1806. ".len", 4,
  1807. file, 0,
  1808. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1809. 8*type_size_of(bt)-word_bits,
  1810. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1811. );
  1812. break;
  1813. case StructSoa_Dynamic:
  1814. elements[0] = LLVMDIBuilderCreateMemberType(
  1815. m->debug_builder, record_scope,
  1816. ".len", 4,
  1817. file, 0,
  1818. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1819. 8*type_size_of(bt)-word_bits + 0*word_bits,
  1820. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1821. );
  1822. elements[1] = LLVMDIBuilderCreateMemberType(
  1823. m->debug_builder, record_scope,
  1824. ".cap", 4,
  1825. file, 0,
  1826. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1827. 8*type_size_of(bt)-word_bits + 1*word_bits,
  1828. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1829. );
  1830. elements[3] = LLVMDIBuilderCreateMemberType(
  1831. m->debug_builder, record_scope,
  1832. ".allocator", 12,
  1833. file, 0,
  1834. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1835. 8*type_size_of(bt)-word_bits + 2*word_bits,
  1836. LLVMDIFlagZero, lb_debug_type(m, t_allocator)
  1837. );
  1838. break;
  1839. }
  1840. for_array(j, bt->Struct.fields) {
  1841. Entity *f = bt->Struct.fields[j];
  1842. String fname = f->token.string;
  1843. unsigned field_line = 0;
  1844. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1845. u64 offset_in_bits = 8*cast(u64)bt->Struct.offsets[j];
  1846. elements[element_offset+j] = LLVMDIBuilderCreateMemberType(
  1847. m->debug_builder, record_scope,
  1848. cast(char const *)fname.text, cast(size_t)fname.len,
  1849. file, field_line,
  1850. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type),
  1851. offset_in_bits,
  1852. field_flags, lb_debug_type(m, f->type)
  1853. );
  1854. }
  1855. }
  1856. break;
  1857. case Type_Union:
  1858. {
  1859. if (file == nullptr) {
  1860. GB_ASSERT(bt->Union.node != nullptr);
  1861. file = lb_get_llvm_metadata(m, bt->Union.node->file);
  1862. line_number = cast(unsigned)ast_token(bt->Union.node).pos.line;
  1863. }
  1864. isize index_offset = 1;
  1865. if (is_type_union_maybe_pointer(bt)) {
  1866. index_offset = 0;
  1867. }
  1868. record_scope = lb_get_llvm_metadata(m, bt->Union.scope);
  1869. element_count = cast(unsigned)bt->Union.variants.count;
  1870. if (index_offset > 0) {
  1871. element_count += 1;
  1872. }
  1873. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1874. if (index_offset > 0) {
  1875. Type *tag_type = union_tag_type(bt);
  1876. unsigned field_line = 0;
  1877. u64 offset_in_bits = 8*cast(u64)bt->Union.variant_block_size;
  1878. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1879. elements[0] = LLVMDIBuilderCreateMemberType(
  1880. m->debug_builder, record_scope,
  1881. "tag", 3,
  1882. file, field_line,
  1883. 8*cast(u64)type_size_of(tag_type), 8*cast(u32)type_align_of(tag_type),
  1884. offset_in_bits,
  1885. field_flags, lb_debug_type(m, tag_type)
  1886. );
  1887. }
  1888. for_array(j, bt->Union.variants) {
  1889. Type *variant = bt->Union.variants[j];
  1890. unsigned field_index = cast(unsigned)(index_offset+j);
  1891. char name[16] = {};
  1892. gb_snprintf(name, gb_size_of(name), "v%u", field_index);
  1893. isize name_len = gb_strlen(name);
  1894. unsigned field_line = 0;
  1895. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1896. u64 offset_in_bits = 0;
  1897. elements[field_index] = LLVMDIBuilderCreateMemberType(
  1898. m->debug_builder, record_scope,
  1899. name, name_len,
  1900. file, field_line,
  1901. 8*cast(u64)type_size_of(variant), 8*cast(u32)type_align_of(variant),
  1902. offset_in_bits,
  1903. field_flags, lb_debug_type(m, variant)
  1904. );
  1905. }
  1906. }
  1907. break;
  1908. case Type_BitSet:
  1909. {
  1910. if (file == nullptr) {
  1911. GB_ASSERT(bt->BitSet.node != nullptr);
  1912. file = lb_get_llvm_metadata(m, bt->BitSet.node->file);
  1913. line_number = cast(unsigned)ast_token(bt->BitSet.node).pos.line;
  1914. }
  1915. LLVMMetadataRef bit_set_field_type = lb_debug_type(m, t_bool);
  1916. LLVMMetadataRef scope = file;
  1917. Type *elem = base_type(bt->BitSet.elem);
  1918. if (elem->kind == Type_Enum) {
  1919. element_count = cast(unsigned)elem->Enum.fields.count;
  1920. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1921. for_array(i, elem->Enum.fields) {
  1922. Entity *f = elem->Enum.fields[i];
  1923. GB_ASSERT(f->kind == Entity_Constant);
  1924. i64 val = exact_value_to_i64(f->Constant.value);
  1925. String name = f->token.string;
  1926. u64 offset_in_bits = cast(u64)(val - bt->BitSet.lower);
  1927. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  1928. m->debug_builder,
  1929. scope,
  1930. cast(char const *)name.text, name.len,
  1931. file, line_number,
  1932. 1,
  1933. offset_in_bits,
  1934. 0,
  1935. LLVMDIFlagZero,
  1936. bit_set_field_type
  1937. );
  1938. }
  1939. } else {
  1940. char name[32] = {};
  1941. GB_ASSERT(is_type_integer(elem));
  1942. i64 count = bt->BitSet.upper - bt->BitSet.lower + 1;
  1943. GB_ASSERT(0 <= count);
  1944. element_count = cast(unsigned)count;
  1945. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1946. for (unsigned i = 0; i < element_count; i++) {
  1947. u64 offset_in_bits = i;
  1948. i64 val = bt->BitSet.lower + cast(i64)i;
  1949. gb_snprintf(name, gb_count_of(name), "%lld", val);
  1950. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  1951. m->debug_builder,
  1952. scope,
  1953. name, gb_strlen(name),
  1954. file, line_number,
  1955. 1,
  1956. offset_in_bits,
  1957. 0,
  1958. LLVMDIFlagZero,
  1959. bit_set_field_type
  1960. );
  1961. }
  1962. }
  1963. }
  1964. }
  1965. LLVMMetadataRef final_metadata = nullptr;
  1966. if (is_union) {
  1967. final_metadata = LLVMDIBuilderCreateUnionType(
  1968. m->debug_builder,
  1969. parent_scope,
  1970. cast(char const *)name.text, cast(size_t)name.len,
  1971. file, line_number,
  1972. size_in_bits, align_in_bits,
  1973. flags,
  1974. elements, element_count,
  1975. runtime_lang,
  1976. unique_id, unique_id_len
  1977. );
  1978. } else {
  1979. final_metadata = LLVMDIBuilderCreateStructType(
  1980. m->debug_builder,
  1981. parent_scope,
  1982. cast(char const *)name.text, cast(size_t)name.len,
  1983. file, line_number,
  1984. size_in_bits, align_in_bits,
  1985. flags,
  1986. derived_from,
  1987. elements, element_count,
  1988. runtime_lang,
  1989. vtable_holder,
  1990. unique_id, unique_id_len
  1991. );
  1992. }
  1993. LLVMMetadataReplaceAllUsesWith(idt.metadata, final_metadata);
  1994. lb_set_llvm_metadata(m, idt.type, final_metadata);
  1995. } break;
  1996. default:
  1997. GB_PANIC("invalid incomplete debug type");
  1998. break;
  1999. }
  2000. }
  2001. array_clear(&m->debug_incomplete_types);
  2002. }
  2003. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  2004. if (e != nullptr) {
  2005. map_set(&m->values, hash_entity(e), val);
  2006. }
  2007. }
  2008. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  2009. if (name.len > 0) {
  2010. string_map_set(&m->members, name, val);
  2011. }
  2012. }
  2013. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  2014. string_map_set(&m->members, key, val);
  2015. }
  2016. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  2017. if (p->entity != nullptr) {
  2018. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  2019. }
  2020. string_map_set(&m->procedures, p->name, p);
  2021. }
  2022. LLVMValueRef llvm_const_cast(LLVMValueRef val, LLVMTypeRef dst) {
  2023. LLVMTypeRef src = LLVMTypeOf(val);
  2024. if (src == dst) {
  2025. return val;
  2026. }
  2027. if (LLVMIsNull(val)) {
  2028. return LLVMConstNull(dst);
  2029. }
  2030. GB_ASSERT(LLVMSizeOf(dst) == LLVMSizeOf(src));
  2031. LLVMTypeKind kind = LLVMGetTypeKind(dst);
  2032. switch (kind) {
  2033. case LLVMPointerTypeKind:
  2034. return LLVMConstPointerCast(val, dst);
  2035. case LLVMStructTypeKind:
  2036. return LLVMConstBitCast(val, dst);
  2037. default:
  2038. GB_PANIC("Unhandled const cast %s to %s", LLVMPrintTypeToString(src), LLVMPrintTypeToString(dst));
  2039. }
  2040. return val;
  2041. }
  2042. LLVMValueRef llvm_const_named_struct(LLVMTypeRef t, LLVMValueRef *values, isize value_count_) {
  2043. unsigned value_count = cast(unsigned)value_count_;
  2044. unsigned elem_count = LLVMCountStructElementTypes(t);
  2045. GB_ASSERT(value_count == elem_count);
  2046. for (unsigned i = 0; i < elem_count; i++) {
  2047. LLVMTypeRef elem_type = LLVMStructGetTypeAtIndex(t, i);
  2048. values[i] = llvm_const_cast(values[i], elem_type);
  2049. }
  2050. return LLVMConstNamedStruct(t, values, value_count);
  2051. }
  2052. LLVMValueRef llvm_const_array(LLVMTypeRef elem_type, LLVMValueRef *values, isize value_count_) {
  2053. unsigned value_count = cast(unsigned)value_count_;
  2054. for (unsigned i = 0; i < value_count; i++) {
  2055. values[i] = llvm_const_cast(values[i], elem_type);
  2056. }
  2057. return LLVMConstArray(elem_type, values, value_count);
  2058. }
  2059. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  2060. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  2061. LLVMValueRef values[2] = {
  2062. str_elem.value,
  2063. str_len.value,
  2064. };
  2065. lbValue res = {};
  2066. res.type = t_string;
  2067. res.value = llvm_const_named_struct(lb_type(p->module, t_string), values, gb_count_of(values));
  2068. return res;
  2069. } else {
  2070. lbAddr res = lb_add_local_generated(p, t_string, false);
  2071. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  2072. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  2073. return lb_addr_load(p, res);
  2074. }
  2075. }
  2076. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  2077. String s = make_string_c(name);
  2078. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2079. // and the current LLVM C API does not expose this functionality yet.
  2080. // It is better to ignore the attributes for the time being
  2081. if (s == "byval") {
  2082. return nullptr;
  2083. } else if (s == "byref") {
  2084. return nullptr;
  2085. } else if (s == "preallocated") {
  2086. return nullptr;
  2087. } else if (s == "sret") {
  2088. return nullptr;
  2089. }
  2090. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2091. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2092. return LLVMCreateEnumAttribute(ctx, kind, value);
  2093. }
  2094. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  2095. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  2096. GB_ASSERT(attr != nullptr);
  2097. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  2098. }
  2099. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  2100. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  2101. }
  2102. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  2103. if (p->abi_function_type != nullptr) {
  2104. return;
  2105. }
  2106. auto hash = hash_type(p->type);
  2107. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  2108. if (ft_found == nullptr) {
  2109. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  2110. ft_found = map_get(&m->function_type_map, hash);
  2111. }
  2112. GB_ASSERT(ft_found != nullptr);
  2113. p->abi_function_type = *ft_found;
  2114. GB_ASSERT(p->abi_function_type != nullptr);
  2115. }
  2116. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  2117. GB_ASSERT(entity != nullptr);
  2118. String link_name = lb_get_entity_name(m, entity);
  2119. {
  2120. StringHashKey key = string_hash_string(link_name);
  2121. lbValue *found = string_map_get(&m->members, key);
  2122. if (found) {
  2123. lb_add_entity(m, entity, *found);
  2124. lbProcedure **p_found = string_map_get(&m->procedures, key);
  2125. GB_ASSERT(p_found != nullptr);
  2126. return *p_found;
  2127. }
  2128. }
  2129. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2130. p->module = m;
  2131. entity->code_gen_module = m;
  2132. entity->code_gen_procedure = p;
  2133. p->entity = entity;
  2134. p->name = link_name;
  2135. DeclInfo *decl = entity->decl_info;
  2136. ast_node(pl, ProcLit, decl->proc_lit);
  2137. Type *pt = base_type(entity->type);
  2138. GB_ASSERT(pt->kind == Type_Proc);
  2139. set_procedure_abi_types(entity->type);
  2140. p->type = entity->type;
  2141. p->type_expr = decl->type_expr;
  2142. p->body = pl->body;
  2143. p->tags = pt->Proc.tags;
  2144. p->inlining = ProcInlining_none;
  2145. p->is_foreign = entity->Procedure.is_foreign;
  2146. p->is_export = entity->Procedure.is_export;
  2147. p->is_entry_point = false;
  2148. gbAllocator a = heap_allocator();
  2149. p->children.allocator = a;
  2150. p->params.allocator = a;
  2151. p->defer_stmts.allocator = a;
  2152. p->blocks.allocator = a;
  2153. p->branch_blocks.allocator = a;
  2154. p->context_stack.allocator = a;
  2155. p->scope_stack.allocator = a;
  2156. if (p->is_foreign) {
  2157. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  2158. }
  2159. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2160. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2161. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2162. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2163. lb_ensure_abi_function_type(m, p);
  2164. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  2165. if (false) {
  2166. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2167. // TODO(bill): Clean up this logic
  2168. if (build_context.metrics.os != TargetOs_js) {
  2169. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2170. }
  2171. LLVMSetFunctionCallConv(p->value, cc_kind);
  2172. }
  2173. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2174. // // TODO(bill): Clean up this logic
  2175. // if (build_context.metrics.os != TargetOs_js) {
  2176. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2177. // }
  2178. // LLVMSetFunctionCallConv(p->value, cc_kind);
  2179. lbValue proc_value = {p->value, p->type};
  2180. lb_add_entity(m, entity, proc_value);
  2181. lb_add_member(m, p->name, proc_value);
  2182. lb_add_procedure_value(m, p);
  2183. if (p->is_export) {
  2184. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  2185. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  2186. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  2187. if (build_context.metrics.os == TargetOs_js) {
  2188. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  2189. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  2190. }
  2191. }
  2192. if (p->is_foreign) {
  2193. if (build_context.metrics.os == TargetOs_js) {
  2194. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  2195. char const *module_name = "env";
  2196. if (entity->Procedure.foreign_library != nullptr) {
  2197. Entity *foreign_library = entity->Procedure.foreign_library;
  2198. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  2199. if (foreign_library->LibraryName.paths.count > 0) {
  2200. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  2201. }
  2202. }
  2203. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  2204. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  2205. }
  2206. }
  2207. // NOTE(bill): offset==0 is the return value
  2208. isize offset = 1;
  2209. if (pt->Proc.return_by_pointer) {
  2210. offset = 2;
  2211. }
  2212. isize parameter_index = 0;
  2213. if (pt->Proc.param_count) {
  2214. TypeTuple *params = &pt->Proc.params->Tuple;
  2215. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2216. Entity *e = params->variables[i];
  2217. Type *original_type = e->type;
  2218. Type *abi_type = pt->Proc.abi_compat_params[i];
  2219. if (e->kind != Entity_Variable) continue;
  2220. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2221. continue;
  2222. }
  2223. if (is_type_tuple(abi_type)) {
  2224. for_array(j, abi_type->Tuple.variables) {
  2225. Type *tft = abi_type->Tuple.variables[j]->type;
  2226. if (e->flags&EntityFlag_NoAlias) {
  2227. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  2228. }
  2229. }
  2230. parameter_index += abi_type->Tuple.variables.count;
  2231. } else {
  2232. if (e->flags&EntityFlag_NoAlias) {
  2233. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2234. }
  2235. parameter_index += 1;
  2236. }
  2237. }
  2238. }
  2239. if (m->debug_builder) { // Debug Information
  2240. Type *bt = base_type(p->type);
  2241. unsigned line = cast(unsigned)entity->token.pos.line;
  2242. LLVMMetadataRef scope = nullptr;
  2243. LLVMMetadataRef file = nullptr;
  2244. LLVMMetadataRef type = nullptr;
  2245. scope = p->module->debug_compile_unit;
  2246. type = lb_debug_type_internal_proc(m, bt);
  2247. if (entity->file != nullptr) {
  2248. file = lb_get_llvm_metadata(m, entity->file);
  2249. scope = file;
  2250. } else if (entity->identifier != nullptr && entity->identifier->file != nullptr) {
  2251. file = lb_get_llvm_metadata(m, entity->identifier->file);
  2252. scope = file;
  2253. } else if (entity->scope != nullptr) {
  2254. file = lb_get_llvm_metadata(m, entity->scope->file);
  2255. scope = file;
  2256. }
  2257. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  2258. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  2259. LLVMBool is_local_to_unit = false;
  2260. LLVMBool is_definition = p->body != nullptr;
  2261. unsigned scope_line = line;
  2262. u32 flags = LLVMDIFlagStaticMember;
  2263. LLVMBool is_optimized = false;
  2264. if (bt->Proc.diverging) {
  2265. flags |= LLVMDIFlagNoReturn;
  2266. }
  2267. if (p->body == nullptr) {
  2268. flags |= LLVMDIFlagPrototyped;
  2269. is_optimized = false;
  2270. }
  2271. if (p->body != nullptr) {
  2272. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  2273. cast(char const *)entity->token.string.text, entity->token.string.len,
  2274. cast(char const *)p->name.text, p->name.len,
  2275. file, line, type,
  2276. is_local_to_unit, is_definition,
  2277. scope_line, cast(LLVMDIFlags)flags, is_optimized
  2278. );
  2279. GB_ASSERT(p->debug_info != nullptr);
  2280. LLVMSetSubprogram(p->value, p->debug_info);
  2281. lb_set_llvm_metadata(m, p, p->debug_info);
  2282. }
  2283. }
  2284. return p;
  2285. }
  2286. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  2287. {
  2288. lbValue *found = string_map_get(&m->members, link_name);
  2289. GB_ASSERT(found == nullptr);
  2290. }
  2291. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2292. p->module = m;
  2293. p->name = link_name;
  2294. p->type = type;
  2295. p->type_expr = nullptr;
  2296. p->body = nullptr;
  2297. p->tags = 0;
  2298. p->inlining = ProcInlining_none;
  2299. p->is_foreign = false;
  2300. p->is_export = false;
  2301. p->is_entry_point = false;
  2302. gbAllocator a = permanent_allocator();
  2303. p->children.allocator = a;
  2304. p->params.allocator = a;
  2305. p->defer_stmts.allocator = a;
  2306. p->blocks.allocator = a;
  2307. p->branch_blocks.allocator = a;
  2308. p->context_stack.allocator = a;
  2309. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2310. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2311. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2312. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2313. Type *pt = p->type;
  2314. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2315. // TODO(bill): Clean up this logic
  2316. if (build_context.metrics.os != TargetOs_js) {
  2317. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2318. }
  2319. LLVMSetFunctionCallConv(p->value, cc_kind);
  2320. lbValue proc_value = {p->value, p->type};
  2321. lb_add_member(m, p->name, proc_value);
  2322. lb_add_procedure_value(m, p);
  2323. // NOTE(bill): offset==0 is the return value
  2324. isize offset = 1;
  2325. if (pt->Proc.return_by_pointer) {
  2326. lb_add_proc_attribute_at_index(p, 1, "sret");
  2327. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2328. offset = 2;
  2329. }
  2330. isize parameter_index = 0;
  2331. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2332. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2333. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2334. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2335. }
  2336. return p;
  2337. }
  2338. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2339. lbParamPasskind kind = lbParamPass_Value;
  2340. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2341. if (is_type_pointer(abi_type)) {
  2342. GB_ASSERT(e->kind == Entity_Variable);
  2343. Type *av = core_type(type_deref(abi_type));
  2344. if (are_types_identical(av, core_type(e->type))) {
  2345. kind = lbParamPass_Pointer;
  2346. if (e->flags&EntityFlag_Value) {
  2347. kind = lbParamPass_ConstRef;
  2348. }
  2349. } else {
  2350. kind = lbParamPass_BitCast;
  2351. }
  2352. } else if (is_type_integer(abi_type)) {
  2353. kind = lbParamPass_Integer;
  2354. } else if (abi_type == t_llvm_bool) {
  2355. kind = lbParamPass_Value;
  2356. } else if (is_type_boolean(abi_type)) {
  2357. kind = lbParamPass_Integer;
  2358. } else if (is_type_simd_vector(abi_type)) {
  2359. kind = lbParamPass_BitCast;
  2360. } else if (is_type_float(abi_type)) {
  2361. kind = lbParamPass_BitCast;
  2362. } else if (is_type_tuple(abi_type)) {
  2363. kind = lbParamPass_Tuple;
  2364. } else if (is_type_proc(abi_type)) {
  2365. kind = lbParamPass_Value;
  2366. } else {
  2367. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2368. }
  2369. }
  2370. if (kind_) *kind_ = kind;
  2371. lbValue res = {};
  2372. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2373. res.type = abi_type;
  2374. return res;
  2375. }
  2376. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  2377. lbParamPasskind kind = lbParamPass_Value;
  2378. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  2379. array_add(&p->params, v);
  2380. lbValue res = {};
  2381. switch (kind) {
  2382. case lbParamPass_Value: {
  2383. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2384. lbValue x = v;
  2385. if (abi_type == t_llvm_bool) {
  2386. x = lb_emit_conv(p, x, t_bool);
  2387. }
  2388. lb_addr_store(p, l, x);
  2389. return x;
  2390. }
  2391. case lbParamPass_Pointer:
  2392. lb_add_entity(p->module, e, v);
  2393. return lb_emit_load(p, v);
  2394. case lbParamPass_Integer: {
  2395. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2396. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  2397. lb_emit_store(p, iptr, v);
  2398. return lb_addr_load(p, l);
  2399. }
  2400. case lbParamPass_ConstRef:
  2401. lb_add_entity(p->module, e, v);
  2402. return lb_emit_load(p, v);
  2403. case lbParamPass_BitCast: {
  2404. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2405. lbValue x = lb_emit_transmute(p, v, e->type);
  2406. lb_addr_store(p, l, x);
  2407. return x;
  2408. }
  2409. case lbParamPass_Tuple: {
  2410. lbAddr l = lb_add_local(p, e->type, e, true, index);
  2411. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2412. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  2413. if (abi_type->Tuple.variables.count > 0) {
  2414. array_pop(&p->params);
  2415. }
  2416. for_array(i, abi_type->Tuple.variables) {
  2417. Type *t = abi_type->Tuple.variables[i]->type;
  2418. GB_ASSERT(!is_type_tuple(t));
  2419. lbParamPasskind elem_kind = lbParamPass_Value;
  2420. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  2421. array_add(&p->params, elem);
  2422. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2423. lb_emit_store(p, dst, elem);
  2424. }
  2425. return lb_addr_load(p, l);
  2426. }
  2427. }
  2428. GB_PANIC("Unreachable");
  2429. return {};
  2430. }
  2431. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2432. GB_ASSERT(b != nullptr);
  2433. if (!b->appended) {
  2434. b->appended = true;
  2435. LLVMAppendExistingBasicBlock(p->value, b->block);
  2436. }
  2437. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2438. p->curr_block = b;
  2439. }
  2440. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2441. LLVMContextRef ctx = p->module->ctx;
  2442. LLVMTypeRef src_type = LLVMTypeOf(val);
  2443. if (src_type == dst_type) {
  2444. return val;
  2445. }
  2446. i64 src_size = lb_sizeof(src_type);
  2447. i64 dst_size = lb_sizeof(dst_type);
  2448. i64 src_align = lb_alignof(src_type);
  2449. i64 dst_align = lb_alignof(dst_type);
  2450. if (LLVMIsALoadInst(val)) {
  2451. src_align = gb_min(src_align, LLVMGetAlignment(val));
  2452. }
  2453. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2454. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2455. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2456. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2457. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2458. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2459. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2460. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2461. }
  2462. if (src_size != dst_size) {
  2463. if ((lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2464. // Okay
  2465. } else {
  2466. goto general_end;
  2467. }
  2468. }
  2469. if (src_kind == dst_kind) {
  2470. if (src_kind == LLVMPointerTypeKind) {
  2471. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2472. } else if (src_kind == LLVMArrayTypeKind) {
  2473. // ignore
  2474. } else if (src_kind != LLVMStructTypeKind) {
  2475. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2476. }
  2477. } else {
  2478. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2479. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2480. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2481. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2482. }
  2483. }
  2484. general_end:;
  2485. // make the alignment big if necessary
  2486. if (LLVMIsALoadInst(val) && src_align < dst_align) {
  2487. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2488. if (LLVMGetInstructionOpcode(val_ptr) == LLVMAlloca) {
  2489. src_align = gb_max(LLVMGetAlignment(val_ptr), dst_align);
  2490. LLVMSetAlignment(val_ptr, cast(unsigned)src_align);
  2491. }
  2492. }
  2493. src_size = align_formula(src_size, src_align);
  2494. dst_size = align_formula(dst_size, dst_align);
  2495. if (LLVMIsALoadInst(val) && (src_size >= dst_size && src_align >= dst_align)) {
  2496. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2497. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2498. LLVMValueRef loaded_val = LLVMBuildLoad(p->builder, val_ptr, "");
  2499. // LLVMSetAlignment(loaded_val, gb_min(src_align, dst_align));
  2500. return loaded_val;
  2501. } else {
  2502. GB_ASSERT(p->decl_block != p->curr_block);
  2503. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2504. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2505. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2506. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2507. max_align = gb_max(max_align, 4);
  2508. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2509. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2510. LLVMBuildStore(p->builder, val, nptr);
  2511. return LLVMBuildLoad(p->builder, ptr, "");
  2512. }
  2513. }
  2514. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token) {
  2515. if (p->debug_info == nullptr) {
  2516. return;
  2517. }
  2518. if (type == nullptr) {
  2519. return;
  2520. }
  2521. if (type == t_invalid) {
  2522. return;
  2523. }
  2524. if (p->body == nullptr) {
  2525. return;
  2526. }
  2527. lbModule *m = p->module;
  2528. String const &name = token.string;
  2529. if (name == "" || name == "_") {
  2530. return;
  2531. }
  2532. if (lb_get_llvm_metadata(m, ptr) != nullptr) {
  2533. // Already been set
  2534. return;
  2535. }
  2536. AstFile *file = p->body->file;
  2537. LLVMMetadataRef llvm_scope = lb_get_current_debug_scope(p);
  2538. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, file);
  2539. GB_ASSERT(llvm_scope != nullptr);
  2540. if (llvm_file == nullptr) {
  2541. llvm_file = LLVMDIScopeGetFile(llvm_scope);
  2542. }
  2543. if (llvm_file == nullptr) {
  2544. return;
  2545. }
  2546. unsigned alignment_in_bits = cast(unsigned)(8*type_align_of(type));
  2547. LLVMDIFlags flags = LLVMDIFlagZero;
  2548. LLVMBool always_preserve = build_context.optimization_level == 0;
  2549. LLVMMetadataRef debug_type = lb_debug_type(m, type);
  2550. LLVMMetadataRef var_info = LLVMDIBuilderCreateAutoVariable(
  2551. m->debug_builder, llvm_scope,
  2552. cast(char const *)name.text, cast(size_t)name.len,
  2553. llvm_file, token.pos.line,
  2554. debug_type,
  2555. always_preserve, flags, alignment_in_bits
  2556. );
  2557. LLVMValueRef storage = ptr;
  2558. LLVMValueRef instr = ptr;
  2559. LLVMMetadataRef llvm_debug_loc = lb_debug_location_from_token_pos(p, token.pos);
  2560. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2561. lb_set_llvm_metadata(m, ptr, llvm_expr);
  2562. LLVMDIBuilderInsertDeclareBefore(m->debug_builder, storage, var_info, llvm_expr, llvm_debug_loc, instr);
  2563. }
  2564. void lb_add_debug_context_variable(lbProcedure *p, lbAddr const &ctx) {
  2565. if (!p->debug_info || !p->body) {
  2566. return;
  2567. }
  2568. LLVMMetadataRef loc = LLVMGetCurrentDebugLocation2(p->builder);
  2569. if (!loc) {
  2570. return;
  2571. }
  2572. TokenPos pos = {};
  2573. pos.file_id = p->body->file ? p->body->file->id : 0;
  2574. pos.line = LLVMDILocationGetLine(loc);
  2575. pos.column = LLVMDILocationGetColumn(loc);
  2576. Token token = {};
  2577. token.kind = Token_context;
  2578. token.string = str_lit("context");
  2579. token.pos = pos;
  2580. lb_add_debug_local_variable(p, ctx.addr.value, t_context, token);
  2581. }
  2582. void lb_begin_procedure_body(lbProcedure *p) {
  2583. DeclInfo *decl = decl_info_of_entity(p->entity);
  2584. if (decl != nullptr) {
  2585. for_array(i, decl->labels) {
  2586. BlockLabel bl = decl->labels[i];
  2587. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2588. array_add(&p->branch_blocks, bb);
  2589. }
  2590. }
  2591. if (p->tags != 0) {
  2592. u64 in = p->tags;
  2593. u64 out = p->module->state_flags;
  2594. if (in & ProcTag_bounds_check) {
  2595. out |= StateFlag_bounds_check;
  2596. out &= ~StateFlag_no_bounds_check;
  2597. } else if (in & ProcTag_no_bounds_check) {
  2598. out |= StateFlag_no_bounds_check;
  2599. out &= ~StateFlag_bounds_check;
  2600. }
  2601. p->module->state_flags = out;
  2602. }
  2603. p->builder = LLVMCreateBuilder();
  2604. p->decl_block = lb_create_block(p, "decls", true);
  2605. p->entry_block = lb_create_block(p, "entry", true);
  2606. lb_start_block(p, p->entry_block);
  2607. GB_ASSERT(p->type != nullptr);
  2608. lb_ensure_abi_function_type(p->module, p);
  2609. {
  2610. lbFunctionType *ft = p->abi_function_type;
  2611. unsigned param_offset = 0;
  2612. lbValue return_ptr_value = {};
  2613. if (ft->ret.kind == lbArg_Indirect) {
  2614. // NOTE(bill): this must be parameter 0
  2615. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2616. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2617. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2618. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2619. return_ptr_value.type = ptr_type;
  2620. p->return_ptr = lb_addr(return_ptr_value);
  2621. lb_add_entity(p->module, e, return_ptr_value);
  2622. param_offset += 1;
  2623. }
  2624. if (p->type->Proc.params != nullptr) {
  2625. TypeTuple *params = &p->type->Proc.params->Tuple;
  2626. unsigned param_index = 0;
  2627. for_array(i, params->variables) {
  2628. Entity *e = params->variables[i];
  2629. if (e->kind != Entity_Variable) {
  2630. continue;
  2631. }
  2632. lbArgType *arg_type = &ft->args[param_index];
  2633. if (arg_type->kind == lbArg_Ignore) {
  2634. continue;
  2635. } else if (arg_type->kind == lbArg_Direct) {
  2636. lbParamPasskind kind = lbParamPass_Value;
  2637. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2638. if (param_type != arg_type->type) {
  2639. kind = lbParamPass_BitCast;
  2640. }
  2641. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2642. value = OdinLLVMBuildTransmute(p, value, param_type);
  2643. lbValue param = {};
  2644. param.value = value;
  2645. param.type = e->type;
  2646. array_add(&p->params, param);
  2647. if (e->token.string.len != 0) {
  2648. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2649. lb_addr_store(p, l, param);
  2650. }
  2651. param_index += 1;
  2652. } else if (arg_type->kind == lbArg_Indirect) {
  2653. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2654. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2655. lbValue param = {};
  2656. param.value = value;
  2657. param.type = e->type;
  2658. array_add(&p->params, param);
  2659. lbValue ptr = {};
  2660. ptr.value = value_ptr;
  2661. ptr.type = alloc_type_pointer(e->type);
  2662. lb_add_entity(p->module, e, ptr);
  2663. param_index += 1;
  2664. }
  2665. }
  2666. }
  2667. if (p->type->Proc.has_named_results) {
  2668. GB_ASSERT(p->type->Proc.result_count > 0);
  2669. TypeTuple *results = &p->type->Proc.results->Tuple;
  2670. for_array(i, results->variables) {
  2671. Entity *e = results->variables[i];
  2672. GB_ASSERT(e->kind == Entity_Variable);
  2673. if (e->token.string != "") {
  2674. GB_ASSERT(!is_blank_ident(e->token));
  2675. lbAddr res = {};
  2676. if (return_ptr_value.value) {
  2677. lbValue ptr = return_ptr_value;
  2678. if (results->variables.count != 1) {
  2679. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2680. }
  2681. res = lb_addr(ptr);
  2682. lb_add_entity(p->module, e, ptr);
  2683. } else {
  2684. res = lb_add_local(p, e->type, e);
  2685. }
  2686. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2687. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2688. lb_addr_store(p, res, c);
  2689. }
  2690. }
  2691. }
  2692. }
  2693. }
  2694. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2695. lb_push_context_onto_stack_from_implicit_parameter(p);
  2696. }
  2697. lb_start_block(p, p->entry_block);
  2698. if (p->debug_info != nullptr) {
  2699. TokenPos pos = {};
  2700. if (p->body != nullptr) {
  2701. pos = ast_token(p->body).pos;
  2702. } else if (p->type_expr != nullptr) {
  2703. pos = ast_token(p->type_expr).pos;
  2704. } else if (p->entity != nullptr) {
  2705. pos = p->entity->token.pos;
  2706. }
  2707. if (pos.file_id != 0) {
  2708. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  2709. }
  2710. if (p->context_stack.count != 0) {
  2711. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  2712. }
  2713. }
  2714. }
  2715. void lb_end_procedure_body(lbProcedure *p) {
  2716. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2717. LLVMBuildBr(p->builder, p->entry_block->block);
  2718. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2719. // Make sure there is a "ret void" at the end of a procedure with no return type
  2720. if (p->type->Proc.result_count == 0) {
  2721. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2722. if (!lb_is_instr_terminating(instr)) {
  2723. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2724. LLVMBuildRetVoid(p->builder);
  2725. }
  2726. }
  2727. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  2728. LLVMBasicBlockRef block = nullptr;
  2729. // Make sure every block terminates, and if not, make it unreachable
  2730. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2731. LLVMValueRef instr = LLVMGetLastInstruction(block);
  2732. if (instr == nullptr) {
  2733. LLVMPositionBuilderAtEnd(p->builder, block);
  2734. LLVMBuildUnreachable(p->builder);
  2735. }
  2736. }
  2737. p->curr_block = nullptr;
  2738. p->module->state_flags = 0;
  2739. }
  2740. void lb_end_procedure(lbProcedure *p) {
  2741. LLVMDisposeBuilder(p->builder);
  2742. }
  2743. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2744. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2745. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2746. array_add(&from->succs, to);
  2747. array_add(&to->preds, from);
  2748. }
  2749. }
  2750. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2751. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2752. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2753. b->appended = false;
  2754. if (append) {
  2755. b->appended = true;
  2756. LLVMAppendExistingBasicBlock(p->value, b->block);
  2757. }
  2758. b->scope = p->curr_scope;
  2759. b->scope_index = p->scope_index;
  2760. b->preds.allocator = heap_allocator();
  2761. b->succs.allocator = heap_allocator();
  2762. array_add(&p->blocks, b);
  2763. return b;
  2764. }
  2765. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2766. if (p->curr_block == nullptr) {
  2767. return;
  2768. }
  2769. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2770. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2771. return;
  2772. }
  2773. lb_add_edge(p->curr_block, target_block);
  2774. LLVMBuildBr(p->builder, target_block->block);
  2775. p->curr_block = nullptr;
  2776. }
  2777. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2778. lbBlock *b = p->curr_block;
  2779. if (b == nullptr) {
  2780. return;
  2781. }
  2782. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2783. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2784. return;
  2785. }
  2786. lb_add_edge(b, true_block);
  2787. lb_add_edge(b, false_block);
  2788. LLVMValueRef cv = cond.value;
  2789. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2790. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2791. }
  2792. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2793. GB_ASSERT(cond != nullptr);
  2794. GB_ASSERT(true_block != nullptr);
  2795. GB_ASSERT(false_block != nullptr);
  2796. switch (cond->kind) {
  2797. case_ast_node(pe, ParenExpr, cond);
  2798. return lb_build_cond(p, pe->expr, true_block, false_block);
  2799. case_end;
  2800. case_ast_node(ue, UnaryExpr, cond);
  2801. if (ue->op.kind == Token_Not) {
  2802. return lb_build_cond(p, ue->expr, false_block, true_block);
  2803. }
  2804. case_end;
  2805. case_ast_node(be, BinaryExpr, cond);
  2806. if (be->op.kind == Token_CmpAnd) {
  2807. lbBlock *block = lb_create_block(p, "cmp.and");
  2808. lb_build_cond(p, be->left, block, false_block);
  2809. lb_start_block(p, block);
  2810. return lb_build_cond(p, be->right, true_block, false_block);
  2811. } else if (be->op.kind == Token_CmpOr) {
  2812. lbBlock *block = lb_create_block(p, "cmp.or");
  2813. lb_build_cond(p, be->left, true_block, block);
  2814. lb_start_block(p, block);
  2815. return lb_build_cond(p, be->right, true_block, false_block);
  2816. }
  2817. case_end;
  2818. }
  2819. lbValue v = lb_build_expr(p, cond);
  2820. // v = lb_emit_conv(p, v, t_bool);
  2821. v = lb_emit_conv(p, v, t_llvm_bool);
  2822. lb_emit_if(p, v, true_block, false_block);
  2823. return v;
  2824. }
  2825. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2826. GB_ASSERT(p->decl_block != p->curr_block);
  2827. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2828. char const *name = "";
  2829. if (e != nullptr) {
  2830. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2831. }
  2832. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2833. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2834. // unsigned alignment = 16; // TODO(bill): Make this configurable
  2835. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  2836. LLVMSetAlignment(ptr, alignment);
  2837. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2838. if (zero_init) {
  2839. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2840. switch (kind) {
  2841. case LLVMStructTypeKind:
  2842. case LLVMArrayTypeKind:
  2843. {
  2844. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  2845. LLVMTypeRef type_i8 = LLVMInt8TypeInContext(p->module->ctx);
  2846. LLVMTypeRef type_i32 = LLVMInt32TypeInContext(p->module->ctx);
  2847. i32 sz = cast(i32)type_size_of(type);
  2848. LLVMBuildMemSet(p->builder, ptr, LLVMConstNull(type_i8), LLVMConstInt(type_i32, sz, false), alignment);
  2849. }
  2850. break;
  2851. default:
  2852. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2853. break;
  2854. }
  2855. }
  2856. lbValue val = {};
  2857. val.value = ptr;
  2858. val.type = alloc_type_pointer(type);
  2859. if (e != nullptr) {
  2860. lb_add_entity(p->module, e, val);
  2861. lb_add_debug_local_variable(p, ptr, type, e->token);
  2862. }
  2863. return lb_addr(val);
  2864. }
  2865. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2866. return lb_add_local(p, type, nullptr, zero_init);
  2867. }
  2868. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2869. GB_ASSERT(pd->body != nullptr);
  2870. lbModule *m = p->module;
  2871. auto *min_dep_set = &m->info->minimum_dependency_set;
  2872. if (ptr_set_exists(min_dep_set, e) == false) {
  2873. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2874. return;
  2875. }
  2876. // NOTE(bill): Generate a new name
  2877. // parent.name-guid
  2878. String original_name = e->token.string;
  2879. String pd_name = original_name;
  2880. if (e->Procedure.link_name.len > 0) {
  2881. pd_name = e->Procedure.link_name;
  2882. }
  2883. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2884. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2885. i32 guid = cast(i32)p->children.count;
  2886. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2887. String name = make_string(cast(u8 *)name_text, name_len-1);
  2888. set_procedure_abi_types(e->type);
  2889. e->Procedure.link_name = name;
  2890. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2891. e->code_gen_procedure = nested_proc;
  2892. lbValue value = {};
  2893. value.value = nested_proc->value;
  2894. value.type = nested_proc->type;
  2895. lb_add_entity(m, e, value);
  2896. array_add(&p->children, nested_proc);
  2897. array_add(&m->procedures_to_generate, nested_proc);
  2898. }
  2899. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2900. if (e == nullptr) {
  2901. return;
  2902. }
  2903. GB_ASSERT(e->kind == Entity_LibraryName);
  2904. GB_ASSERT(e->flags & EntityFlag_Used);
  2905. for_array(i, e->LibraryName.paths) {
  2906. String library_path = e->LibraryName.paths[i];
  2907. if (library_path.len == 0) {
  2908. continue;
  2909. }
  2910. bool ok = true;
  2911. for_array(path_index, m->foreign_library_paths) {
  2912. String path = m->foreign_library_paths[path_index];
  2913. #if defined(GB_SYSTEM_WINDOWS)
  2914. if (str_eq_ignore_case(path, library_path)) {
  2915. #else
  2916. if (str_eq(path, library_path)) {
  2917. #endif
  2918. ok = false;
  2919. break;
  2920. }
  2921. }
  2922. if (ok) {
  2923. array_add(&m->foreign_library_paths, library_path);
  2924. }
  2925. }
  2926. }
  2927. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2928. if (vd == nullptr || vd->is_mutable) {
  2929. return;
  2930. }
  2931. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2932. static i32 global_guid = 0;
  2933. for_array(i, vd->names) {
  2934. Ast *ident = vd->names[i];
  2935. GB_ASSERT(ident->kind == Ast_Ident);
  2936. Entity *e = entity_of_node(ident);
  2937. GB_ASSERT(e != nullptr);
  2938. if (e->kind != Entity_TypeName) {
  2939. continue;
  2940. }
  2941. bool polymorphic_struct = false;
  2942. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2943. Type *bt = base_type(e->type);
  2944. if (bt->kind == Type_Struct) {
  2945. polymorphic_struct = bt->Struct.is_polymorphic;
  2946. }
  2947. }
  2948. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2949. continue;
  2950. }
  2951. if (e->TypeName.ir_mangled_name.len != 0) {
  2952. // NOTE(bill): Already set
  2953. continue;
  2954. }
  2955. lb_set_nested_type_name_ir_mangled_name(e, p);
  2956. }
  2957. for_array(i, vd->names) {
  2958. Ast *ident = vd->names[i];
  2959. GB_ASSERT(ident->kind == Ast_Ident);
  2960. Entity *e = entity_of_node(ident);
  2961. GB_ASSERT(e != nullptr);
  2962. if (e->kind != Entity_Procedure) {
  2963. continue;
  2964. }
  2965. CheckerInfo *info = p->module->info;
  2966. DeclInfo *decl = decl_info_of_entity(e);
  2967. ast_node(pl, ProcLit, decl->proc_lit);
  2968. if (pl->body != nullptr) {
  2969. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2970. if (found) {
  2971. auto procs = *found;
  2972. for_array(i, procs) {
  2973. Entity *e = procs[i];
  2974. if (!ptr_set_exists(min_dep_set, e)) {
  2975. continue;
  2976. }
  2977. DeclInfo *d = decl_info_of_entity(e);
  2978. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2979. }
  2980. } else {
  2981. lb_build_nested_proc(p, pl, e);
  2982. }
  2983. } else {
  2984. // FFI - Foreign function interace
  2985. String original_name = e->token.string;
  2986. String name = original_name;
  2987. if (e->Procedure.is_foreign) {
  2988. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2989. }
  2990. if (e->Procedure.link_name.len > 0) {
  2991. name = e->Procedure.link_name;
  2992. }
  2993. lbValue *prev_value = string_map_get(&p->module->members, name);
  2994. if (prev_value != nullptr) {
  2995. // NOTE(bill): Don't do mutliple declarations in the IR
  2996. return;
  2997. }
  2998. set_procedure_abi_types(e->type);
  2999. e->Procedure.link_name = name;
  3000. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  3001. lbValue value = {};
  3002. value.value = nested_proc->value;
  3003. value.type = nested_proc->type;
  3004. array_add(&p->module->procedures_to_generate, nested_proc);
  3005. if (p != nullptr) {
  3006. array_add(&p->children, nested_proc);
  3007. } else {
  3008. string_map_set(&p->module->members, name, value);
  3009. }
  3010. }
  3011. }
  3012. }
  3013. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  3014. for_array(i, stmts) {
  3015. Ast *stmt = stmts[i];
  3016. switch (stmt->kind) {
  3017. case_ast_node(vd, ValueDecl, stmt);
  3018. lb_build_constant_value_decl(p, vd);
  3019. case_end;
  3020. case_ast_node(fb, ForeignBlockDecl, stmt);
  3021. ast_node(block, BlockStmt, fb->body);
  3022. lb_build_stmt_list(p, block->stmts);
  3023. case_end;
  3024. }
  3025. }
  3026. for_array(i, stmts) {
  3027. lb_build_stmt(p, stmts[i]);
  3028. }
  3029. }
  3030. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  3031. GB_ASSERT(ident->kind == Ast_Ident);
  3032. Entity *e = entity_of_node(ident);
  3033. GB_ASSERT(e->kind == Entity_Label);
  3034. for_array(i, p->branch_blocks) {
  3035. lbBranchBlocks *b = &p->branch_blocks[i];
  3036. if (b->label == e->Label.node) {
  3037. return *b;
  3038. }
  3039. }
  3040. GB_PANIC("Unreachable");
  3041. lbBranchBlocks empty = {};
  3042. return empty;
  3043. }
  3044. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  3045. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  3046. tl->prev = p->target_list;
  3047. tl->break_ = break_;
  3048. tl->continue_ = continue_;
  3049. tl->fallthrough_ = fallthrough_;
  3050. p->target_list = tl;
  3051. if (label != nullptr) { // Set label blocks
  3052. GB_ASSERT(label->kind == Ast_Label);
  3053. for_array(i, p->branch_blocks) {
  3054. lbBranchBlocks *b = &p->branch_blocks[i];
  3055. GB_ASSERT(b->label != nullptr && label != nullptr);
  3056. GB_ASSERT(b->label->kind == Ast_Label);
  3057. if (b->label == label) {
  3058. b->break_ = break_;
  3059. b->continue_ = continue_;
  3060. return tl;
  3061. }
  3062. }
  3063. GB_PANIC("Unreachable");
  3064. }
  3065. return tl;
  3066. }
  3067. void lb_pop_target_list(lbProcedure *p) {
  3068. p->target_list = p->target_list->prev;
  3069. }
  3070. void lb_open_scope(lbProcedure *p, Scope *s) {
  3071. lbModule *m = p->module;
  3072. if (m->debug_builder) {
  3073. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  3074. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  3075. Token token = ast_token(s->node);
  3076. unsigned line = cast(unsigned)token.pos.line;
  3077. unsigned column = cast(unsigned)token.pos.column;
  3078. LLVMMetadataRef file = nullptr;
  3079. if (s->node->file != nullptr) {
  3080. file = lb_get_llvm_metadata(m, s->node->file);
  3081. }
  3082. LLVMMetadataRef scope = nullptr;
  3083. if (p->scope_stack.count > 0) {
  3084. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  3085. }
  3086. if (scope == nullptr) {
  3087. scope = lb_get_llvm_metadata(m, p);
  3088. }
  3089. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  3090. if (m->debug_builder) {
  3091. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  3092. file, line, column
  3093. );
  3094. lb_set_llvm_metadata(m, s, res);
  3095. }
  3096. }
  3097. }
  3098. p->scope_index += 1;
  3099. array_add(&p->scope_stack, s);
  3100. }
  3101. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  3102. lb_emit_defer_stmts(p, kind, block);
  3103. GB_ASSERT(p->scope_index > 0);
  3104. // NOTE(bill): Remove `context`s made in that scope
  3105. while (p->context_stack.count > 0) {
  3106. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  3107. if (ctx->scope_index >= p->scope_index) {
  3108. array_pop(&p->context_stack);
  3109. } else {
  3110. break;
  3111. }
  3112. }
  3113. p->scope_index -= 1;
  3114. array_pop(&p->scope_stack);
  3115. }
  3116. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  3117. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  3118. GB_ASSERT(is_type_boolean(tv.type));
  3119. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  3120. if (tv.value.value_bool) {
  3121. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  3122. } else if (ws->else_stmt) {
  3123. switch (ws->else_stmt->kind) {
  3124. case Ast_BlockStmt:
  3125. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  3126. break;
  3127. case Ast_WhenStmt:
  3128. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  3129. break;
  3130. default:
  3131. GB_PANIC("Invalid 'else' statement in 'when' statement");
  3132. break;
  3133. }
  3134. }
  3135. }
  3136. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  3137. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3138. lbModule *m = p->module;
  3139. lbValue count = {};
  3140. Type *expr_type = base_type(type_deref(expr.type));
  3141. switch (expr_type->kind) {
  3142. case Type_Array:
  3143. count = lb_const_int(m, t_int, expr_type->Array.count);
  3144. break;
  3145. }
  3146. lbValue val = {};
  3147. lbValue idx = {};
  3148. lbBlock *loop = nullptr;
  3149. lbBlock *done = nullptr;
  3150. lbBlock *body = nullptr;
  3151. lbAddr index = lb_add_local_generated(p, t_int, false);
  3152. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  3153. loop = lb_create_block(p, "for.index.loop");
  3154. lb_emit_jump(p, loop);
  3155. lb_start_block(p, loop);
  3156. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  3157. lb_addr_store(p, index, incr);
  3158. body = lb_create_block(p, "for.index.body");
  3159. done = lb_create_block(p, "for.index.done");
  3160. if (count.value == nullptr) {
  3161. GB_ASSERT(count_ptr.value != nullptr);
  3162. count = lb_emit_load(p, count_ptr);
  3163. }
  3164. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3165. lb_emit_if(p, cond, body, done);
  3166. lb_start_block(p, body);
  3167. idx = lb_addr_load(p, index);
  3168. switch (expr_type->kind) {
  3169. case Type_Array: {
  3170. if (val_type != nullptr) {
  3171. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3172. }
  3173. break;
  3174. }
  3175. case Type_EnumeratedArray: {
  3176. if (val_type != nullptr) {
  3177. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3178. // NOTE(bill): Override the idx value for the enumeration
  3179. Type *index_type = expr_type->EnumeratedArray.index;
  3180. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  3181. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  3182. }
  3183. }
  3184. break;
  3185. }
  3186. case Type_Slice: {
  3187. if (val_type != nullptr) {
  3188. lbValue elem = lb_slice_elem(p, expr);
  3189. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3190. }
  3191. break;
  3192. }
  3193. case Type_DynamicArray: {
  3194. if (val_type != nullptr) {
  3195. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  3196. elem = lb_emit_load(p, elem);
  3197. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3198. }
  3199. break;
  3200. }
  3201. case Type_Map: {
  3202. lbValue entries = lb_map_entries_ptr(p, expr);
  3203. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  3204. elem = lb_emit_load(p, elem);
  3205. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  3206. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  3207. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  3208. break;
  3209. }
  3210. case Type_Struct: {
  3211. GB_ASSERT(is_type_soa_struct(expr_type));
  3212. break;
  3213. }
  3214. default:
  3215. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  3216. break;
  3217. }
  3218. if (val_) *val_ = val;
  3219. if (idx_) *idx_ = idx;
  3220. if (loop_) *loop_ = loop;
  3221. if (done_) *done_ = done;
  3222. }
  3223. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  3224. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3225. lbModule *m = p->module;
  3226. lbValue count = lb_const_int(m, t_int, 0);
  3227. Type *expr_type = base_type(expr.type);
  3228. switch (expr_type->kind) {
  3229. case Type_Basic:
  3230. count = lb_string_len(p, expr);
  3231. break;
  3232. default:
  3233. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  3234. break;
  3235. }
  3236. lbValue val = {};
  3237. lbValue idx = {};
  3238. lbBlock *loop = nullptr;
  3239. lbBlock *done = nullptr;
  3240. lbBlock *body = nullptr;
  3241. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3242. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3243. loop = lb_create_block(p, "for.string.loop");
  3244. lb_emit_jump(p, loop);
  3245. lb_start_block(p, loop);
  3246. body = lb_create_block(p, "for.string.body");
  3247. done = lb_create_block(p, "for.string.done");
  3248. lbValue offset = lb_addr_load(p, offset_);
  3249. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  3250. lb_emit_if(p, cond, body, done);
  3251. lb_start_block(p, body);
  3252. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  3253. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  3254. auto args = array_make<lbValue>(permanent_allocator(), 1);
  3255. args[0] = lb_emit_string(p, str_elem, str_len);
  3256. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  3257. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  3258. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  3259. idx = offset;
  3260. if (val_type != nullptr) {
  3261. val = lb_emit_struct_ev(p, rune_and_len, 0);
  3262. }
  3263. if (val_) *val_ = val;
  3264. if (idx_) *idx_ = idx;
  3265. if (loop_) *loop_ = loop;
  3266. if (done_) *done_ = done;
  3267. }
  3268. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  3269. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3270. lbModule *m = p->module;
  3271. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  3272. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  3273. lbValue lower = lb_build_expr(p, node->left);
  3274. lbValue upper = {};
  3275. lbValue val = {};
  3276. lbValue idx = {};
  3277. lbBlock *loop = nullptr;
  3278. lbBlock *done = nullptr;
  3279. lbBlock *body = nullptr;
  3280. if (val_type == nullptr) {
  3281. val_type = lower.type;
  3282. }
  3283. lbAddr value = lb_add_local_generated(p, val_type, false);
  3284. lb_addr_store(p, value, lower);
  3285. lbAddr index = lb_add_local_generated(p, t_int, false);
  3286. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  3287. loop = lb_create_block(p, "for.interval.loop");
  3288. lb_emit_jump(p, loop);
  3289. lb_start_block(p, loop);
  3290. body = lb_create_block(p, "for.interval.body");
  3291. done = lb_create_block(p, "for.interval.done");
  3292. TokenKind op = Token_Lt;
  3293. switch (node->op.kind) {
  3294. case Token_Ellipsis: op = Token_LtEq; break;
  3295. case Token_RangeHalf: op = Token_Lt; break;
  3296. default: GB_PANIC("Invalid interval operator"); break;
  3297. }
  3298. upper = lb_build_expr(p, node->right);
  3299. lbValue curr_value = lb_addr_load(p, value);
  3300. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  3301. lb_emit_if(p, cond, body, done);
  3302. lb_start_block(p, body);
  3303. val = lb_addr_load(p, value);
  3304. idx = lb_addr_load(p, index);
  3305. lb_emit_increment(p, value.addr);
  3306. lb_emit_increment(p, index.addr);
  3307. if (val_) *val_ = val;
  3308. if (idx_) *idx_ = idx;
  3309. if (loop_) *loop_ = loop;
  3310. if (done_) *done_ = done;
  3311. }
  3312. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3313. lbModule *m = p->module;
  3314. Type *t = enum_type;
  3315. GB_ASSERT(is_type_enum(t));
  3316. Type *enum_ptr = alloc_type_pointer(t);
  3317. t = base_type(t);
  3318. Type *core_elem = core_type(t);
  3319. GB_ASSERT(t->kind == Type_Enum);
  3320. i64 enum_count = t->Enum.fields.count;
  3321. lbValue max_count = lb_const_int(m, t_int, enum_count);
  3322. lbValue ti = lb_type_info(m, t);
  3323. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  3324. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  3325. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  3326. lbValue values_data = lb_slice_elem(p, values);
  3327. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3328. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3329. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  3330. lb_emit_jump(p, loop);
  3331. lb_start_block(p, loop);
  3332. lbBlock *body = lb_create_block(p, "for.enum.body");
  3333. lbBlock *done = lb_create_block(p, "for.enum.done");
  3334. lbValue offset = lb_addr_load(p, offset_);
  3335. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  3336. lb_emit_if(p, cond, body, done);
  3337. lb_start_block(p, body);
  3338. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  3339. lb_emit_increment(p, offset_.addr);
  3340. lbValue val = {};
  3341. if (val_type != nullptr) {
  3342. GB_ASSERT(are_types_identical(enum_type, val_type));
  3343. if (is_type_integer(core_elem)) {
  3344. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  3345. val = lb_emit_conv(p, i, t);
  3346. } else {
  3347. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  3348. }
  3349. }
  3350. if (val_) *val_ = val;
  3351. if (idx_) *idx_ = offset;
  3352. if (loop_) *loop_ = loop;
  3353. if (done_) *done_ = done;
  3354. }
  3355. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  3356. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  3357. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  3358. lb_emit_jump(p, loop);
  3359. lb_start_block(p, loop);
  3360. lbBlock *body = lb_create_block(p, "for.tuple.body");
  3361. lbBlock *done = lb_create_block(p, "for.tuple.done");
  3362. lbValue tuple_value = lb_build_expr(p, expr);
  3363. Type *tuple = tuple_value.type;
  3364. GB_ASSERT(tuple->kind == Type_Tuple);
  3365. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  3366. i32 cond_index = tuple_count-1;
  3367. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  3368. lb_emit_if(p, cond, body, done);
  3369. lb_start_block(p, body);
  3370. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  3371. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  3372. if (loop_) *loop_ = loop;
  3373. if (done_) *done_ = done;
  3374. }
  3375. void lb_build_range_stmt_struct_soa(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3376. Ast *expr = unparen_expr(rs->expr);
  3377. TypeAndValue tav = type_and_value_of_expr(expr);
  3378. lbBlock *loop = nullptr;
  3379. lbBlock *body = nullptr;
  3380. lbBlock *done = nullptr;
  3381. lb_open_scope(p, scope);
  3382. Type *val_types[2] = {};
  3383. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3384. val_types[0] = type_of_expr(rs->vals[0]);
  3385. }
  3386. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3387. val_types[1] = type_of_expr(rs->vals[1]);
  3388. }
  3389. lbAddr array = lb_build_addr(p, expr);
  3390. if (is_type_pointer(type_deref(lb_addr_type(array)))) {
  3391. array = lb_addr(lb_addr_load(p, array));
  3392. }
  3393. lbValue count = lb_soa_struct_len(p, lb_addr_load(p, array));
  3394. lbAddr index = lb_add_local_generated(p, t_int, false);
  3395. lb_addr_store(p, index, lb_const_int(p->module, t_int, cast(u64)-1));
  3396. loop = lb_create_block(p, "for.soa.loop");
  3397. lb_emit_jump(p, loop);
  3398. lb_start_block(p, loop);
  3399. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  3400. lb_addr_store(p, index, incr);
  3401. body = lb_create_block(p, "for.soa.body");
  3402. done = lb_create_block(p, "for.soa.done");
  3403. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3404. lb_emit_if(p, cond, body, done);
  3405. lb_start_block(p, body);
  3406. if (val_types[0]) {
  3407. Entity *e = entity_of_node(rs->vals[0]);
  3408. if (e != nullptr) {
  3409. lbAddr soa_val = lb_addr_soa_variable(array.addr, lb_addr_load(p, index), nullptr);
  3410. map_set(&p->module->soa_values, hash_entity(e), soa_val);
  3411. }
  3412. }
  3413. if (val_types[1]) {
  3414. lb_store_range_stmt_val(p, rs->vals[1], lb_addr_load(p, index));
  3415. }
  3416. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3417. lb_build_stmt(p, rs->body);
  3418. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3419. lb_pop_target_list(p);
  3420. lb_emit_jump(p, loop);
  3421. lb_start_block(p, done);
  3422. }
  3423. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3424. Ast *expr = unparen_expr(rs->expr);
  3425. Type *expr_type = type_of_expr(expr);
  3426. if (expr_type != nullptr) {
  3427. Type *et = base_type(type_deref(expr_type));
  3428. if (is_type_soa_struct(et)) {
  3429. lb_build_range_stmt_struct_soa(p, rs, scope);
  3430. return;
  3431. }
  3432. }
  3433. lb_open_scope(p, scope);
  3434. Type *val0_type = nullptr;
  3435. Type *val1_type = nullptr;
  3436. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3437. val0_type = type_of_expr(rs->vals[0]);
  3438. }
  3439. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3440. val1_type = type_of_expr(rs->vals[1]);
  3441. }
  3442. if (val0_type != nullptr) {
  3443. Entity *e = entity_of_node(rs->vals[0]);
  3444. lb_add_local(p, e->type, e, true);
  3445. }
  3446. if (val1_type != nullptr) {
  3447. Entity *e = entity_of_node(rs->vals[1]);
  3448. lb_add_local(p, e->type, e, true);
  3449. }
  3450. lbValue val = {};
  3451. lbValue key = {};
  3452. lbBlock *loop = nullptr;
  3453. lbBlock *done = nullptr;
  3454. bool is_map = false;
  3455. TypeAndValue tav = type_and_value_of_expr(expr);
  3456. if (is_ast_range(expr)) {
  3457. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  3458. } else if (tav.mode == Addressing_Type) {
  3459. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3460. } else {
  3461. Type *expr_type = type_of_expr(expr);
  3462. Type *et = base_type(type_deref(expr_type));
  3463. switch (et->kind) {
  3464. case Type_Map: {
  3465. is_map = true;
  3466. lbValue map = lb_build_addr_ptr(p, expr);
  3467. if (is_type_pointer(type_deref(map.type))) {
  3468. map = lb_emit_load(p, map);
  3469. }
  3470. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3471. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3472. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3473. break;
  3474. }
  3475. case Type_Array: {
  3476. lbValue array = lb_build_addr_ptr(p, expr);
  3477. if (is_type_pointer(type_deref(array.type))) {
  3478. array = lb_emit_load(p, array);
  3479. }
  3480. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3481. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3482. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3483. break;
  3484. }
  3485. case Type_EnumeratedArray: {
  3486. lbValue array = lb_build_addr_ptr(p, expr);
  3487. if (is_type_pointer(type_deref(array.type))) {
  3488. array = lb_emit_load(p, array);
  3489. }
  3490. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3491. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3492. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3493. break;
  3494. }
  3495. case Type_DynamicArray: {
  3496. lbValue count_ptr = {};
  3497. lbValue array = lb_build_addr_ptr(p, expr);
  3498. if (is_type_pointer(type_deref(array.type))) {
  3499. array = lb_emit_load(p, array);
  3500. }
  3501. count_ptr = lb_emit_struct_ep(p, array, 1);
  3502. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3503. break;
  3504. }
  3505. case Type_Slice: {
  3506. lbValue count_ptr = {};
  3507. lbValue slice = lb_build_expr(p, expr);
  3508. if (is_type_pointer(slice.type)) {
  3509. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3510. slice = lb_emit_load(p, slice);
  3511. } else {
  3512. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3513. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3514. }
  3515. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3516. break;
  3517. }
  3518. case Type_Basic: {
  3519. lbValue string = lb_build_expr(p, expr);
  3520. if (is_type_pointer(string.type)) {
  3521. string = lb_emit_load(p, string);
  3522. }
  3523. if (is_type_untyped(expr_type)) {
  3524. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3525. lb_addr_store(p, s, string);
  3526. string = lb_addr_load(p, s);
  3527. }
  3528. Type *t = base_type(string.type);
  3529. GB_ASSERT(!is_type_cstring(t));
  3530. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3531. break;
  3532. }
  3533. case Type_Tuple:
  3534. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3535. break;
  3536. default:
  3537. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3538. break;
  3539. }
  3540. }
  3541. if (is_map) {
  3542. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], key);
  3543. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], val);
  3544. } else {
  3545. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3546. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], key);
  3547. }
  3548. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3549. lb_build_stmt(p, rs->body);
  3550. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3551. lb_pop_target_list(p);
  3552. lb_emit_jump(p, loop);
  3553. lb_start_block(p, done);
  3554. }
  3555. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs, Scope *scope) {
  3556. lbModule *m = p->module;
  3557. lb_open_scope(p, scope); // Open scope here
  3558. Type *val0_type = nullptr;
  3559. Type *val1_type = nullptr;
  3560. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3561. val0_type = type_of_expr(rs->val0);
  3562. }
  3563. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3564. val1_type = type_of_expr(rs->val1);
  3565. }
  3566. if (val0_type != nullptr) {
  3567. Entity *e = entity_of_node(rs->val0);
  3568. lb_add_local(p, e->type, e, true);
  3569. }
  3570. if (val1_type != nullptr) {
  3571. Entity *e = entity_of_node(rs->val1);
  3572. lb_add_local(p, e->type, e, true);
  3573. }
  3574. lbValue val = {};
  3575. lbValue key = {};
  3576. lbBlock *loop = nullptr;
  3577. lbBlock *done = nullptr;
  3578. Ast *expr = unparen_expr(rs->expr);
  3579. TypeAndValue tav = type_and_value_of_expr(expr);
  3580. if (is_ast_range(expr)) {
  3581. lbAddr val0_addr = {};
  3582. lbAddr val1_addr = {};
  3583. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3584. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3585. TokenKind op = expr->BinaryExpr.op.kind;
  3586. Ast *start_expr = expr->BinaryExpr.left;
  3587. Ast *end_expr = expr->BinaryExpr.right;
  3588. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3589. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3590. ExactValue start = start_expr->tav.value;
  3591. ExactValue end = end_expr->tav.value;
  3592. if (op == Token_Ellipsis) { // .. [start, end]
  3593. ExactValue index = exact_value_i64(0);
  3594. for (ExactValue val = start;
  3595. compare_exact_values(Token_LtEq, val, end);
  3596. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3597. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3598. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3599. lb_build_stmt(p, rs->body);
  3600. }
  3601. } else if (op == Token_RangeHalf) { // ..< [start, end)
  3602. ExactValue index = exact_value_i64(0);
  3603. for (ExactValue val = start;
  3604. compare_exact_values(Token_Lt, val, end);
  3605. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3606. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3607. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3608. lb_build_stmt(p, rs->body);
  3609. }
  3610. }
  3611. } else if (tav.mode == Addressing_Type) {
  3612. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3613. Type *et = type_deref(tav.type);
  3614. Type *bet = base_type(et);
  3615. lbAddr val0_addr = {};
  3616. lbAddr val1_addr = {};
  3617. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3618. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3619. for_array(i, bet->Enum.fields) {
  3620. Entity *field = bet->Enum.fields[i];
  3621. GB_ASSERT(field->kind == Entity_Constant);
  3622. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3623. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3624. lb_build_stmt(p, rs->body);
  3625. }
  3626. } else {
  3627. lbAddr val0_addr = {};
  3628. lbAddr val1_addr = {};
  3629. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3630. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3631. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3632. Type *t = base_type(expr->tav.type);
  3633. switch (t->kind) {
  3634. case Type_Basic:
  3635. GB_ASSERT(is_type_string(t));
  3636. {
  3637. ExactValue value = expr->tav.value;
  3638. GB_ASSERT(value.kind == ExactValue_String);
  3639. String str = value.value_string;
  3640. Rune codepoint = 0;
  3641. isize offset = 0;
  3642. do {
  3643. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3644. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3645. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3646. lb_build_stmt(p, rs->body);
  3647. offset += width;
  3648. } while (offset < str.len);
  3649. }
  3650. break;
  3651. case Type_Array:
  3652. if (t->Array.count > 0) {
  3653. lbValue val = lb_build_expr(p, expr);
  3654. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3655. for (i64 i = 0; i < t->Array.count; i++) {
  3656. if (val0_type) {
  3657. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3658. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3659. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3660. }
  3661. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3662. lb_build_stmt(p, rs->body);
  3663. }
  3664. }
  3665. break;
  3666. case Type_EnumeratedArray:
  3667. if (t->EnumeratedArray.count > 0) {
  3668. lbValue val = lb_build_expr(p, expr);
  3669. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3670. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3671. if (val0_type) {
  3672. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3673. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3674. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3675. }
  3676. if (val1_type) {
  3677. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3678. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3679. }
  3680. lb_build_stmt(p, rs->body);
  3681. }
  3682. }
  3683. break;
  3684. default:
  3685. GB_PANIC("Invalid '#unroll for' type");
  3686. break;
  3687. }
  3688. }
  3689. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3690. }
  3691. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  3692. lb_open_scope(p, scope);
  3693. if (ss->init != nullptr) {
  3694. lb_build_stmt(p, ss->init);
  3695. }
  3696. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3697. if (ss->tag != nullptr) {
  3698. tag = lb_build_expr(p, ss->tag);
  3699. }
  3700. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3701. ast_node(body, BlockStmt, ss->body);
  3702. Slice<Ast *> default_stmts = {};
  3703. lbBlock *default_fall = nullptr;
  3704. lbBlock *default_block = nullptr;
  3705. lbBlock *fall = nullptr;
  3706. isize case_count = body->stmts.count;
  3707. for_array(i, body->stmts) {
  3708. Ast *clause = body->stmts[i];
  3709. ast_node(cc, CaseClause, clause);
  3710. lbBlock *body = fall;
  3711. if (body == nullptr) {
  3712. body = lb_create_block(p, "switch.case.body");
  3713. }
  3714. fall = done;
  3715. if (i+1 < case_count) {
  3716. fall = lb_create_block(p, "switch.fall.body");
  3717. }
  3718. if (cc->list.count == 0) {
  3719. // default case
  3720. default_stmts = cc->stmts;
  3721. default_fall = fall;
  3722. default_block = body;
  3723. continue;
  3724. }
  3725. lbBlock *next_cond = nullptr;
  3726. for_array(j, cc->list) {
  3727. Ast *expr = unparen_expr(cc->list[j]);
  3728. next_cond = lb_create_block(p, "switch.case.next");
  3729. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3730. if (is_ast_range(expr)) {
  3731. ast_node(ie, BinaryExpr, expr);
  3732. TokenKind op = Token_Invalid;
  3733. switch (ie->op.kind) {
  3734. case Token_Ellipsis: op = Token_LtEq; break;
  3735. case Token_RangeHalf: op = Token_Lt; break;
  3736. default: GB_PANIC("Invalid interval operator"); break;
  3737. }
  3738. lbValue lhs = lb_build_expr(p, ie->left);
  3739. lbValue rhs = lb_build_expr(p, ie->right);
  3740. // TODO(bill): do short circuit here
  3741. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3742. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3743. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3744. } else {
  3745. if (expr->tav.mode == Addressing_Type) {
  3746. GB_ASSERT(is_type_typeid(tag.type));
  3747. lbValue e = lb_typeid(p->module, expr->tav.type);
  3748. e = lb_emit_conv(p, e, tag.type);
  3749. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3750. } else {
  3751. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3752. }
  3753. }
  3754. lb_emit_if(p, cond, body, next_cond);
  3755. lb_start_block(p, next_cond);
  3756. }
  3757. lb_start_block(p, body);
  3758. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3759. lb_open_scope(p, body->scope);
  3760. lb_build_stmt_list(p, cc->stmts);
  3761. lb_close_scope(p, lbDeferExit_Default, body);
  3762. lb_pop_target_list(p);
  3763. lb_emit_jump(p, done);
  3764. lb_start_block(p, next_cond);
  3765. }
  3766. if (default_block != nullptr) {
  3767. lb_emit_jump(p, default_block);
  3768. lb_start_block(p, default_block);
  3769. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3770. lb_open_scope(p, default_block->scope);
  3771. lb_build_stmt_list(p, default_stmts);
  3772. lb_close_scope(p, lbDeferExit_Default, default_block);
  3773. lb_pop_target_list(p);
  3774. }
  3775. lb_emit_jump(p, done);
  3776. lb_close_scope(p, lbDeferExit_Default, done);
  3777. lb_start_block(p, done);
  3778. }
  3779. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3780. Entity *e = implicit_entity_of_node(clause);
  3781. GB_ASSERT(e != nullptr);
  3782. if (e->flags & EntityFlag_Value) {
  3783. // by value
  3784. GB_ASSERT(are_types_identical(e->type, value.type));
  3785. lbAddr x = lb_add_local(p, e->type, e, false);
  3786. lb_addr_store(p, x, value);
  3787. } else {
  3788. // by reference
  3789. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3790. lb_add_entity(p->module, e, value);
  3791. }
  3792. }
  3793. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3794. Entity *e = entity_of_node(stmt_val);
  3795. if (e == nullptr) {
  3796. return {};
  3797. }
  3798. if ((e->flags & EntityFlag_Value) == 0) {
  3799. if (LLVMIsALoadInst(value.value)) {
  3800. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3801. lb_add_entity(p->module, e, ptr);
  3802. return lb_addr(ptr);
  3803. }
  3804. }
  3805. // by value
  3806. lbAddr addr = lb_add_local(p, e->type, e, false);
  3807. lb_addr_store(p, addr, value);
  3808. return addr;
  3809. }
  3810. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3811. ast_node(cc, CaseClause, clause);
  3812. lb_push_target_list(p, label, done, nullptr, nullptr);
  3813. lb_open_scope(p, body->scope);
  3814. lb_build_stmt_list(p, cc->stmts);
  3815. lb_close_scope(p, lbDeferExit_Default, body);
  3816. lb_pop_target_list(p);
  3817. lb_emit_jump(p, done);
  3818. }
  3819. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3820. lbModule *m = p->module;
  3821. ast_node(as, AssignStmt, ss->tag);
  3822. GB_ASSERT(as->lhs.count == 1);
  3823. GB_ASSERT(as->rhs.count == 1);
  3824. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3825. bool is_parent_ptr = is_type_pointer(parent.type);
  3826. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3827. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3828. lbValue parent_value = parent;
  3829. lbValue parent_ptr = parent;
  3830. if (!is_parent_ptr) {
  3831. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3832. }
  3833. lbValue tag_index = {};
  3834. lbValue union_data = {};
  3835. if (switch_kind == TypeSwitch_Union) {
  3836. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3837. tag_index = lb_emit_load(p, tag_ptr);
  3838. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3839. }
  3840. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3841. lb_emit_jump(p, start_block);
  3842. lb_start_block(p, start_block);
  3843. // NOTE(bill): Append this later
  3844. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3845. Ast *default_ = nullptr;
  3846. ast_node(body, BlockStmt, ss->body);
  3847. gb_local_persist i32 weird_count = 0;
  3848. for_array(i, body->stmts) {
  3849. Ast *clause = body->stmts[i];
  3850. ast_node(cc, CaseClause, clause);
  3851. if (cc->list.count == 0) {
  3852. default_ = clause;
  3853. continue;
  3854. }
  3855. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3856. lbBlock *next = nullptr;
  3857. Type *case_type = nullptr;
  3858. for_array(type_index, cc->list) {
  3859. next = lb_create_block(p, "typeswitch.next");
  3860. case_type = type_of_expr(cc->list[type_index]);
  3861. lbValue cond = {};
  3862. if (switch_kind == TypeSwitch_Union) {
  3863. Type *ut = base_type(type_deref(parent.type));
  3864. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3865. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3866. } else if (switch_kind == TypeSwitch_Any) {
  3867. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3868. lbValue case_typeid = lb_typeid(m, case_type);
  3869. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3870. }
  3871. GB_ASSERT(cond.value != nullptr);
  3872. lb_emit_if(p, cond, body, next);
  3873. lb_start_block(p, next);
  3874. }
  3875. Entity *case_entity = implicit_entity_of_node(clause);
  3876. lbValue value = parent_value;
  3877. lb_start_block(p, body);
  3878. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3879. if (cc->list.count == 1) {
  3880. lbValue data = {};
  3881. if (switch_kind == TypeSwitch_Union) {
  3882. data = union_data;
  3883. } else if (switch_kind == TypeSwitch_Any) {
  3884. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3885. data = any_data;
  3886. }
  3887. Type *ct = case_entity->type;
  3888. Type *ct_ptr = alloc_type_pointer(ct);
  3889. value = lb_emit_conv(p, data, ct_ptr);
  3890. if (!by_reference) {
  3891. value = lb_emit_load(p, value);
  3892. }
  3893. }
  3894. lb_store_type_case_implicit(p, clause, value);
  3895. lb_type_case_body(p, ss->label, clause, body, done);
  3896. lb_start_block(p, next);
  3897. }
  3898. if (default_ != nullptr) {
  3899. lb_store_type_case_implicit(p, default_, parent_value);
  3900. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3901. } else {
  3902. lb_emit_jump(p, done);
  3903. }
  3904. lb_start_block(p, done);
  3905. }
  3906. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3907. lbModule *m = p->module;
  3908. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3909. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3910. type = default_type(type);
  3911. lbValue short_circuit = {};
  3912. if (op == Token_CmpAnd) {
  3913. lb_build_cond(p, left, rhs, done);
  3914. short_circuit = lb_const_bool(m, type, false);
  3915. } else if (op == Token_CmpOr) {
  3916. lb_build_cond(p, left, done, rhs);
  3917. short_circuit = lb_const_bool(m, type, true);
  3918. }
  3919. if (rhs->preds.count == 0) {
  3920. lb_start_block(p, done);
  3921. return short_circuit;
  3922. }
  3923. if (done->preds.count == 0) {
  3924. lb_start_block(p, rhs);
  3925. return lb_build_expr(p, right);
  3926. }
  3927. Array<LLVMValueRef> incoming_values = {};
  3928. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3929. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3930. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3931. for_array(i, done->preds) {
  3932. incoming_values[i] = short_circuit.value;
  3933. incoming_blocks[i] = done->preds[i]->block;
  3934. }
  3935. lb_start_block(p, rhs);
  3936. lbValue edge = lb_build_expr(p, right);
  3937. incoming_values[done->preds.count] = edge.value;
  3938. incoming_blocks[done->preds.count] = p->curr_block->block;
  3939. lb_emit_jump(p, done);
  3940. lb_start_block(p, done);
  3941. lbValue res = {};
  3942. res.type = type;
  3943. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3944. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3945. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3946. return res;
  3947. }
  3948. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3949. Ast *prev_stmt = p->curr_stmt;
  3950. defer (p->curr_stmt = prev_stmt);
  3951. p->curr_stmt = node;
  3952. if (p->curr_block != nullptr) {
  3953. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  3954. if (lb_is_instr_terminating(last_instr)) {
  3955. return;
  3956. }
  3957. }
  3958. LLVMMetadataRef prev_debug_location = nullptr;
  3959. if (p->debug_info != nullptr) {
  3960. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  3961. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  3962. }
  3963. defer (if (prev_debug_location != nullptr) {
  3964. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  3965. });
  3966. u64 prev_state_flags = p->module->state_flags;
  3967. defer (p->module->state_flags = prev_state_flags);
  3968. if (node->state_flags != 0) {
  3969. u64 in = node->state_flags;
  3970. u64 out = p->module->state_flags;
  3971. if (in & StateFlag_bounds_check) {
  3972. out |= StateFlag_bounds_check;
  3973. out &= ~StateFlag_no_bounds_check;
  3974. } else if (in & StateFlag_no_bounds_check) {
  3975. out |= StateFlag_no_bounds_check;
  3976. out &= ~StateFlag_bounds_check;
  3977. }
  3978. p->module->state_flags = out;
  3979. }
  3980. switch (node->kind) {
  3981. case_ast_node(bs, EmptyStmt, node);
  3982. case_end;
  3983. case_ast_node(us, UsingStmt, node);
  3984. case_end;
  3985. case_ast_node(ws, WhenStmt, node);
  3986. lb_build_when_stmt(p, ws);
  3987. case_end;
  3988. case_ast_node(bs, BlockStmt, node);
  3989. lbBlock *done = nullptr;
  3990. if (bs->label != nullptr) {
  3991. done = lb_create_block(p, "block.done");
  3992. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3993. tl->is_block = true;
  3994. }
  3995. lb_open_scope(p, node->scope);
  3996. lb_build_stmt_list(p, bs->stmts);
  3997. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3998. if (done != nullptr) {
  3999. lb_emit_jump(p, done);
  4000. lb_start_block(p, done);
  4001. }
  4002. case_end;
  4003. case_ast_node(vd, ValueDecl, node);
  4004. if (!vd->is_mutable) {
  4005. return;
  4006. }
  4007. bool is_static = false;
  4008. if (vd->names.count > 0) {
  4009. Entity *e = entity_of_node(vd->names[0]);
  4010. if (e->flags & EntityFlag_Static) {
  4011. // NOTE(bill): If one of the entities is static, they all are
  4012. is_static = true;
  4013. }
  4014. }
  4015. if (is_static) {
  4016. for_array(i, vd->names) {
  4017. lbValue value = {};
  4018. if (vd->values.count > 0) {
  4019. GB_ASSERT(vd->names.count == vd->values.count);
  4020. Ast *ast_value = vd->values[i];
  4021. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  4022. ast_value->tav.mode == Addressing_Invalid);
  4023. bool allow_local = false;
  4024. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  4025. }
  4026. Ast *ident = vd->names[i];
  4027. GB_ASSERT(!is_blank_ident(ident));
  4028. Entity *e = entity_of_node(ident);
  4029. GB_ASSERT(e->flags & EntityFlag_Static);
  4030. String name = e->token.string;
  4031. String mangled_name = {};
  4032. {
  4033. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  4034. str = gb_string_appendc(str, "-");
  4035. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  4036. mangled_name.text = cast(u8 *)str;
  4037. mangled_name.len = gb_string_length(str);
  4038. }
  4039. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  4040. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  4041. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  4042. if (value.value != nullptr) {
  4043. LLVMSetInitializer(global, value.value);
  4044. } else {
  4045. }
  4046. if (e->Variable.thread_local_model != "") {
  4047. LLVMSetThreadLocal(global, true);
  4048. String m = e->Variable.thread_local_model;
  4049. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  4050. if (m == "default") {
  4051. mode = LLVMGeneralDynamicTLSModel;
  4052. } else if (m == "localdynamic") {
  4053. mode = LLVMLocalDynamicTLSModel;
  4054. } else if (m == "initialexec") {
  4055. mode = LLVMInitialExecTLSModel;
  4056. } else if (m == "localexec") {
  4057. mode = LLVMLocalExecTLSModel;
  4058. } else {
  4059. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  4060. }
  4061. LLVMSetThreadLocalMode(global, mode);
  4062. } else {
  4063. LLVMSetLinkage(global, LLVMInternalLinkage);
  4064. }
  4065. lbValue global_val = {global, alloc_type_pointer(e->type)};
  4066. lb_add_entity(p->module, e, global_val);
  4067. lb_add_member(p->module, mangled_name, global_val);
  4068. }
  4069. return;
  4070. }
  4071. if (vd->values.count == 0) { // declared and zero-initialized
  4072. for_array(i, vd->names) {
  4073. Ast *name = vd->names[i];
  4074. if (!is_blank_ident(name)) {
  4075. Entity *e = entity_of_node(name);
  4076. lb_add_local(p, e->type, e, true);
  4077. }
  4078. }
  4079. } else { // Tuple(s)
  4080. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  4081. auto inits = array_make<lbValue>(permanent_allocator(), 0, vd->names.count);
  4082. for_array(i, vd->names) {
  4083. Ast *name = vd->names[i];
  4084. lbAddr lval = {};
  4085. if (!is_blank_ident(name)) {
  4086. Entity *e = entity_of_node(name);
  4087. lval = lb_add_local(p, e->type, e, false);
  4088. }
  4089. array_add(&lvals, lval);
  4090. }
  4091. for_array(i, vd->values) {
  4092. lbValue init = lb_build_expr(p, vd->values[i]);
  4093. Type *t = init.type;
  4094. if (t->kind == Type_Tuple) {
  4095. for_array(i, t->Tuple.variables) {
  4096. Entity *e = t->Tuple.variables[i];
  4097. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4098. array_add(&inits, v);
  4099. }
  4100. } else {
  4101. array_add(&inits, init);
  4102. }
  4103. }
  4104. for_array(i, inits) {
  4105. lbAddr lval = lvals[i];
  4106. lbValue init = inits[i];
  4107. lb_addr_store(p, lval, init);
  4108. }
  4109. }
  4110. case_end;
  4111. case_ast_node(as, AssignStmt, node);
  4112. if (as->op.kind == Token_Eq) {
  4113. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  4114. for_array(i, as->lhs) {
  4115. Ast *lhs = as->lhs[i];
  4116. lbAddr lval = {};
  4117. if (!is_blank_ident(lhs)) {
  4118. lval = lb_build_addr(p, lhs);
  4119. }
  4120. array_add(&lvals, lval);
  4121. }
  4122. if (as->lhs.count == as->rhs.count) {
  4123. if (as->lhs.count == 1) {
  4124. lbAddr lval = lvals[0];
  4125. Ast *rhs = as->rhs[0];
  4126. lbValue init = lb_build_expr(p, rhs);
  4127. lb_addr_store(p, lvals[0], init);
  4128. } else {
  4129. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4130. for_array(i, as->rhs) {
  4131. lbValue init = lb_build_expr(p, as->rhs[i]);
  4132. array_add(&inits, init);
  4133. }
  4134. for_array(i, inits) {
  4135. lbAddr lval = lvals[i];
  4136. lbValue init = inits[i];
  4137. lb_addr_store(p, lval, init);
  4138. }
  4139. }
  4140. } else {
  4141. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4142. for_array(i, as->rhs) {
  4143. lbValue init = lb_build_expr(p, as->rhs[i]);
  4144. Type *t = init.type;
  4145. // TODO(bill): refactor for code reuse as this is repeated a bit
  4146. if (t->kind == Type_Tuple) {
  4147. for_array(i, t->Tuple.variables) {
  4148. Entity *e = t->Tuple.variables[i];
  4149. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4150. array_add(&inits, v);
  4151. }
  4152. } else {
  4153. array_add(&inits, init);
  4154. }
  4155. }
  4156. for_array(i, inits) {
  4157. lbAddr lval = lvals[i];
  4158. lbValue init = inits[i];
  4159. lb_addr_store(p, lval, init);
  4160. }
  4161. }
  4162. } else {
  4163. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  4164. // +=, -=, etc
  4165. i32 op = cast(i32)as->op.kind;
  4166. op += Token_Add - Token_AddEq; // Convert += to +
  4167. if (op == Token_CmpAnd || op == Token_CmpOr) {
  4168. Type *type = as->lhs[0]->tav.type;
  4169. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  4170. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4171. lb_addr_store(p, lhs, new_value);
  4172. } else {
  4173. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4174. lbValue value = lb_build_expr(p, as->rhs[0]);
  4175. lbValue old_value = lb_addr_load(p, lhs);
  4176. Type *type = old_value.type;
  4177. lbValue change = lb_emit_conv(p, value, type);
  4178. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  4179. lb_addr_store(p, lhs, new_value);
  4180. }
  4181. return;
  4182. }
  4183. case_end;
  4184. case_ast_node(es, ExprStmt, node);
  4185. lb_build_expr(p, es->expr);
  4186. case_end;
  4187. case_ast_node(ds, DeferStmt, node);
  4188. isize scope_index = p->scope_index;
  4189. lb_add_defer_node(p, scope_index, ds->stmt);
  4190. case_end;
  4191. case_ast_node(rs, ReturnStmt, node);
  4192. lbValue res = {};
  4193. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  4194. isize return_count = p->type->Proc.result_count;
  4195. isize res_count = rs->results.count;
  4196. if (return_count == 0) {
  4197. // No return values
  4198. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4199. LLVMBuildRetVoid(p->builder);
  4200. return;
  4201. } else if (return_count == 1) {
  4202. Entity *e = tuple->variables[0];
  4203. if (res_count == 0) {
  4204. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4205. GB_ASSERT(found);
  4206. res = lb_emit_load(p, *found);
  4207. } else {
  4208. res = lb_build_expr(p, rs->results[0]);
  4209. res = lb_emit_conv(p, res, e->type);
  4210. }
  4211. if (p->type->Proc.has_named_results) {
  4212. // NOTE(bill): store the named values before returning
  4213. if (e->token.string != "") {
  4214. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4215. GB_ASSERT(found != nullptr);
  4216. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  4217. }
  4218. }
  4219. } else {
  4220. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  4221. if (res_count != 0) {
  4222. for (isize res_index = 0; res_index < res_count; res_index++) {
  4223. lbValue res = lb_build_expr(p, rs->results[res_index]);
  4224. Type *t = res.type;
  4225. if (t->kind == Type_Tuple) {
  4226. for_array(i, t->Tuple.variables) {
  4227. Entity *e = t->Tuple.variables[i];
  4228. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  4229. array_add(&results, v);
  4230. }
  4231. } else {
  4232. array_add(&results, res);
  4233. }
  4234. }
  4235. } else {
  4236. for (isize res_index = 0; res_index < return_count; res_index++) {
  4237. Entity *e = tuple->variables[res_index];
  4238. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4239. GB_ASSERT(found);
  4240. lbValue res = lb_emit_load(p, *found);
  4241. array_add(&results, res);
  4242. }
  4243. }
  4244. GB_ASSERT(results.count == return_count);
  4245. if (p->type->Proc.has_named_results) {
  4246. // NOTE(bill): store the named values before returning
  4247. for_array(i, p->type->Proc.results->Tuple.variables) {
  4248. Entity *e = p->type->Proc.results->Tuple.variables[i];
  4249. if (e->kind != Entity_Variable) {
  4250. continue;
  4251. }
  4252. if (e->token.string == "") {
  4253. continue;
  4254. }
  4255. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4256. GB_ASSERT(found != nullptr);
  4257. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  4258. }
  4259. }
  4260. Type *ret_type = p->type->Proc.results;
  4261. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4262. res = lb_add_local_generated(p, ret_type, false).addr;
  4263. for_array(i, results) {
  4264. Entity *e = tuple->variables[i];
  4265. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  4266. lbValue val = lb_emit_conv(p, results[i], e->type);
  4267. lb_emit_store(p, field, val);
  4268. }
  4269. res = lb_emit_load(p, res);
  4270. }
  4271. lb_ensure_abi_function_type(p->module, p);
  4272. if (p->abi_function_type->ret.kind == lbArg_Indirect) {
  4273. if (res.value != nullptr) {
  4274. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  4275. } else {
  4276. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  4277. }
  4278. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4279. LLVMBuildRetVoid(p->builder);
  4280. } else {
  4281. LLVMValueRef ret_val = res.value;
  4282. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  4283. if (p->abi_function_type->ret.cast_type != nullptr) {
  4284. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  4285. }
  4286. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4287. LLVMBuildRet(p->builder, ret_val);
  4288. }
  4289. case_end;
  4290. case_ast_node(is, IfStmt, node);
  4291. lb_open_scope(p, node->scope); // Scope #1
  4292. if (is->init != nullptr) {
  4293. // TODO(bill): Should this have a separate block to begin with?
  4294. #if 1
  4295. lbBlock *init = lb_create_block(p, "if.init");
  4296. lb_emit_jump(p, init);
  4297. lb_start_block(p, init);
  4298. #endif
  4299. lb_build_stmt(p, is->init);
  4300. }
  4301. lbBlock *then = lb_create_block(p, "if.then");
  4302. lbBlock *done = lb_create_block(p, "if.done");
  4303. lbBlock *else_ = done;
  4304. if (is->else_stmt != nullptr) {
  4305. else_ = lb_create_block(p, "if.else");
  4306. }
  4307. lb_build_cond(p, is->cond, then, else_);
  4308. lb_start_block(p, then);
  4309. if (is->label != nullptr) {
  4310. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  4311. tl->is_block = true;
  4312. }
  4313. lb_build_stmt(p, is->body);
  4314. lb_emit_jump(p, done);
  4315. if (is->else_stmt != nullptr) {
  4316. lb_start_block(p, else_);
  4317. lb_open_scope(p, is->else_stmt->scope);
  4318. lb_build_stmt(p, is->else_stmt);
  4319. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4320. lb_emit_jump(p, done);
  4321. }
  4322. lb_start_block(p, done);
  4323. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4324. case_end;
  4325. case_ast_node(fs, ForStmt, node);
  4326. lb_open_scope(p, node->scope); // Open Scope here
  4327. if (fs->init != nullptr) {
  4328. #if 1
  4329. lbBlock *init = lb_create_block(p, "for.init");
  4330. lb_emit_jump(p, init);
  4331. lb_start_block(p, init);
  4332. #endif
  4333. lb_build_stmt(p, fs->init);
  4334. }
  4335. lbBlock *body = lb_create_block(p, "for.body");
  4336. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  4337. lbBlock *loop = body;
  4338. if (fs->cond != nullptr) {
  4339. loop = lb_create_block(p, "for.loop");
  4340. }
  4341. lbBlock *post = loop;
  4342. if (fs->post != nullptr) {
  4343. post = lb_create_block(p, "for.post");
  4344. }
  4345. lb_emit_jump(p, loop);
  4346. lb_start_block(p, loop);
  4347. if (loop != body) {
  4348. lb_build_cond(p, fs->cond, body, done);
  4349. lb_start_block(p, body);
  4350. }
  4351. lb_push_target_list(p, fs->label, done, post, nullptr);
  4352. lb_build_stmt(p, fs->body);
  4353. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4354. lb_pop_target_list(p);
  4355. lb_emit_jump(p, post);
  4356. if (fs->post != nullptr) {
  4357. lb_start_block(p, post);
  4358. lb_build_stmt(p, fs->post);
  4359. lb_emit_jump(p, loop);
  4360. }
  4361. lb_start_block(p, done);
  4362. case_end;
  4363. case_ast_node(rs, RangeStmt, node);
  4364. lb_build_range_stmt(p, rs, node->scope);
  4365. case_end;
  4366. case_ast_node(rs, InlineRangeStmt, node);
  4367. lb_build_inline_range_stmt(p, rs, node->scope);
  4368. case_end;
  4369. case_ast_node(ss, SwitchStmt, node);
  4370. lb_build_switch_stmt(p, ss, node->scope);
  4371. case_end;
  4372. case_ast_node(ss, TypeSwitchStmt, node);
  4373. lb_build_type_switch_stmt(p, ss);
  4374. case_end;
  4375. case_ast_node(bs, BranchStmt, node);
  4376. lbBlock *block = nullptr;
  4377. if (bs->label != nullptr) {
  4378. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  4379. switch (bs->token.kind) {
  4380. case Token_break: block = bb.break_; break;
  4381. case Token_continue: block = bb.continue_; break;
  4382. case Token_fallthrough:
  4383. GB_PANIC("fallthrough cannot have a label");
  4384. break;
  4385. }
  4386. } else {
  4387. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  4388. if (t->is_block) {
  4389. continue;
  4390. }
  4391. switch (bs->token.kind) {
  4392. case Token_break: block = t->break_; break;
  4393. case Token_continue: block = t->continue_; break;
  4394. case Token_fallthrough: block = t->fallthrough_; break;
  4395. }
  4396. }
  4397. }
  4398. if (block != nullptr) {
  4399. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  4400. }
  4401. lb_emit_jump(p, block);
  4402. case_end;
  4403. }
  4404. }
  4405. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  4406. cond = lb_emit_conv(p, cond, t_llvm_bool);
  4407. lbValue res = {};
  4408. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  4409. res.type = x.type;
  4410. return res;
  4411. }
  4412. lbValue lb_const_nil(lbModule *m, Type *type) {
  4413. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  4414. return lbValue{v, type};
  4415. }
  4416. lbValue lb_const_undef(lbModule *m, Type *type) {
  4417. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  4418. return lbValue{v, type};
  4419. }
  4420. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  4421. lbValue res = {};
  4422. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  4423. res.type = type;
  4424. return res;
  4425. }
  4426. lbValue lb_const_string(lbModule *m, String const &value) {
  4427. return lb_const_value(m, t_string, exact_value_string(value));
  4428. }
  4429. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  4430. lbValue res = {};
  4431. res.value = LLVMConstInt(lb_type(m, type), value, false);
  4432. res.type = type;
  4433. return res;
  4434. }
  4435. LLVMValueRef lb_const_f16(lbModule *m, f32 f, Type *type=t_f16) {
  4436. GB_ASSERT(type_size_of(type) == 2);
  4437. u16 u = f32_to_f16(f);
  4438. if (is_type_different_to_arch_endianness(type)) {
  4439. u = gb_endian_swap16(u);
  4440. }
  4441. LLVMValueRef i = LLVMConstInt(LLVMInt16TypeInContext(m->ctx), u, false);
  4442. return LLVMConstBitCast(i, lb_type(m, type));
  4443. }
  4444. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  4445. GB_ASSERT(type_size_of(type) == 4);
  4446. u32 u = bit_cast<u32>(f);
  4447. if (is_type_different_to_arch_endianness(type)) {
  4448. u = gb_endian_swap32(u);
  4449. }
  4450. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  4451. return LLVMConstBitCast(i, lb_type(m, type));
  4452. }
  4453. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4454. x = lb_emit_conv(p, x, t);
  4455. y = lb_emit_conv(p, y, t);
  4456. if (is_type_float(t)) {
  4457. i64 sz = 8*type_size_of(t);
  4458. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4459. args[0] = x;
  4460. args[1] = y;
  4461. switch (sz) {
  4462. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  4463. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  4464. }
  4465. GB_PANIC("Unknown float type");
  4466. }
  4467. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  4468. }
  4469. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4470. x = lb_emit_conv(p, x, t);
  4471. y = lb_emit_conv(p, y, t);
  4472. if (is_type_float(t)) {
  4473. i64 sz = 8*type_size_of(t);
  4474. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4475. args[0] = x;
  4476. args[1] = y;
  4477. switch (sz) {
  4478. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  4479. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  4480. }
  4481. GB_PANIC("Unknown float type");
  4482. }
  4483. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  4484. }
  4485. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  4486. lbValue z = {};
  4487. z = lb_emit_max(p, t, x, min);
  4488. z = lb_emit_min(p, t, z, max);
  4489. return z;
  4490. }
  4491. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  4492. StringHashKey key = string_hash_string(str);
  4493. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  4494. if (found != nullptr) {
  4495. return *found;
  4496. } else {
  4497. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4498. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4499. cast(char const *)str.text,
  4500. cast(unsigned)str.len,
  4501. false);
  4502. isize max_len = 7+8+1;
  4503. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  4504. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4505. len -= 1;
  4506. m->global_array_index++;
  4507. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4508. LLVMSetInitializer(global_data, data);
  4509. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4510. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4511. string_map_set(&m->const_strings, key, ptr);
  4512. return ptr;
  4513. }
  4514. }
  4515. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  4516. LLVMValueRef ptr = nullptr;
  4517. if (str.len != 0) {
  4518. ptr = lb_find_or_add_entity_string_ptr(m, str);
  4519. } else {
  4520. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4521. }
  4522. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4523. LLVMValueRef values[2] = {ptr, str_len};
  4524. lbValue res = {};
  4525. res.value = llvm_const_named_struct(lb_type(m, t_string), values, 2);
  4526. res.type = t_string;
  4527. return res;
  4528. }
  4529. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  4530. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4531. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4532. cast(char const *)str.text,
  4533. cast(unsigned)str.len,
  4534. false);
  4535. char *name = nullptr;
  4536. {
  4537. isize max_len = 7+8+1;
  4538. name = gb_alloc_array(permanent_allocator(), char, max_len);
  4539. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4540. len -= 1;
  4541. m->global_array_index++;
  4542. }
  4543. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4544. LLVMSetInitializer(global_data, data);
  4545. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4546. LLVMValueRef ptr = nullptr;
  4547. if (str.len != 0) {
  4548. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4549. } else {
  4550. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4551. }
  4552. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4553. LLVMValueRef values[2] = {ptr, len};
  4554. lbValue res = {};
  4555. res.value = llvm_const_named_struct(lb_type(m, t_u8_slice), values, 2);
  4556. res.type = t_u8_slice;
  4557. return res;
  4558. }
  4559. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4560. isize index = type_info_index(info, type, false);
  4561. if (index >= 0) {
  4562. auto *set = &info->minimum_dependency_type_info_set;
  4563. for_array(i, set->entries) {
  4564. if (set->entries[i].ptr == index) {
  4565. return i+1;
  4566. }
  4567. }
  4568. }
  4569. if (err_on_not_found) {
  4570. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  4571. }
  4572. return -1;
  4573. }
  4574. lbValue lb_typeid(lbModule *m, Type *type) {
  4575. type = default_type(type);
  4576. u64 id = cast(u64)lb_type_info_index(m->info, type);
  4577. GB_ASSERT(id >= 0);
  4578. u64 kind = Typeid_Invalid;
  4579. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4580. u64 special = 0;
  4581. u64 reserved = 0;
  4582. Type *bt = base_type(type);
  4583. TypeKind tk = bt->kind;
  4584. switch (tk) {
  4585. case Type_Basic: {
  4586. u32 flags = bt->Basic.flags;
  4587. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4588. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4589. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4590. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4591. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4592. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4593. if (flags & BasicFlag_String) kind = Typeid_String;
  4594. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4595. } break;
  4596. case Type_Pointer: kind = Typeid_Pointer; break;
  4597. case Type_Array: kind = Typeid_Array; break;
  4598. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  4599. case Type_Slice: kind = Typeid_Slice; break;
  4600. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4601. case Type_Map: kind = Typeid_Map; break;
  4602. case Type_Struct: kind = Typeid_Struct; break;
  4603. case Type_Enum: kind = Typeid_Enum; break;
  4604. case Type_Union: kind = Typeid_Union; break;
  4605. case Type_Tuple: kind = Typeid_Tuple; break;
  4606. case Type_Proc: kind = Typeid_Procedure; break;
  4607. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4608. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  4609. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  4610. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  4611. }
  4612. if (is_type_cstring(type)) {
  4613. special = 1;
  4614. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4615. special = 1;
  4616. }
  4617. u64 data = 0;
  4618. if (build_context.word_size == 4) {
  4619. GB_ASSERT(id <= (1u<<24u));
  4620. data |= (id &~ (1u<<24)) << 0u; // index
  4621. data |= (kind &~ (1u<<5)) << 24u; // kind
  4622. data |= (named &~ (1u<<1)) << 29u; // kind
  4623. data |= (special &~ (1u<<1)) << 30u; // kind
  4624. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4625. } else {
  4626. GB_ASSERT(build_context.word_size == 8);
  4627. GB_ASSERT(id <= (1ull<<56u));
  4628. data |= (id &~ (1ull<<56)) << 0ul; // index
  4629. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4630. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4631. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4632. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4633. }
  4634. lbValue res = {};
  4635. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  4636. res.type = t_typeid;
  4637. return res;
  4638. }
  4639. lbValue lb_type_info(lbModule *m, Type *type) {
  4640. type = default_type(type);
  4641. isize index = lb_type_info_index(m->info, type);
  4642. GB_ASSERT(index >= 0);
  4643. LLVMTypeRef it = lb_type(m, t_int);
  4644. LLVMValueRef indices[2] = {
  4645. LLVMConstInt(it, 0, false),
  4646. LLVMConstInt(it, index, true),
  4647. };
  4648. lbValue value = {};
  4649. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  4650. value.type = t_type_info_ptr;
  4651. return value;
  4652. }
  4653. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  4654. bool is_local = allow_local && m->curr_procedure != nullptr;
  4655. bool is_const = true;
  4656. if (is_local) {
  4657. for (isize i = 0; i < count; i++) {
  4658. GB_ASSERT(values[i] != nullptr);
  4659. if (!LLVMIsConstant(values[i])) {
  4660. is_const = false;
  4661. break;
  4662. }
  4663. }
  4664. }
  4665. if (!is_const) {
  4666. lbProcedure *p = m->curr_procedure;
  4667. GB_ASSERT(p != nullptr);
  4668. lbAddr v = lb_add_local_generated(p, type, false);
  4669. lbValue ptr = lb_addr_get_ptr(p, v);
  4670. for (isize i = 0; i < count; i++) {
  4671. lbValue elem = lb_emit_array_epi(p, ptr, i);
  4672. LLVMBuildStore(p->builder, values[i], elem.value);
  4673. }
  4674. return lb_addr_load(p, v).value;
  4675. }
  4676. return llvm_const_array(lb_type(m, elem_type), values, cast(unsigned int)count);
  4677. }
  4678. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  4679. LLVMContextRef ctx = m->ctx;
  4680. type = default_type(type);
  4681. Type *original_type = type;
  4682. lbValue res = {};
  4683. res.type = original_type;
  4684. type = core_type(type);
  4685. value = convert_exact_value_for_type(value, type);
  4686. if (value.kind == ExactValue_Typeid) {
  4687. return lb_typeid(m, value.value_typeid);
  4688. }
  4689. if (value.kind == ExactValue_Invalid) {
  4690. return lb_const_nil(m, type);
  4691. }
  4692. if (value.kind == ExactValue_Procedure) {
  4693. Ast *expr = unparen_expr(value.value_procedure);
  4694. if (expr->kind == Ast_ProcLit) {
  4695. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4696. }
  4697. Entity *e = entity_from_expr(expr);
  4698. e = strip_entity_wrapping(e);
  4699. GB_ASSERT(e != nullptr);
  4700. auto *found = map_get(&m->values, hash_entity(e));
  4701. if (found) {
  4702. return *found;
  4703. }
  4704. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  4705. }
  4706. bool is_local = allow_local && m->curr_procedure != nullptr;
  4707. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  4708. if (is_type_slice(type)) {
  4709. if (value.kind == ExactValue_String) {
  4710. GB_ASSERT(is_type_u8_slice(type));
  4711. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  4712. return res;
  4713. } else {
  4714. ast_node(cl, CompoundLit, value.value_compound);
  4715. isize count = cl->elems.count;
  4716. if (count == 0) {
  4717. return lb_const_nil(m, type);
  4718. }
  4719. count = gb_max(cl->max_count, count);
  4720. Type *elem = base_type(type)->Slice.elem;
  4721. Type *t = alloc_type_array(elem, count);
  4722. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4723. LLVMValueRef array_data = nullptr;
  4724. if (is_local) {
  4725. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4726. // its backing data on the stack
  4727. lbProcedure *p = m->curr_procedure;
  4728. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4729. LLVMTypeRef llvm_type = lb_type(m, t);
  4730. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4731. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4732. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4733. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4734. {
  4735. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4736. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4737. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4738. lbAddr slice = lb_add_local_generated(p, type, false);
  4739. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4740. return lb_addr_load(p, slice);
  4741. }
  4742. } else {
  4743. isize max_len = 7+8+1;
  4744. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  4745. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4746. m->global_array_index++;
  4747. String name = make_string(cast(u8 *)str, len-1);
  4748. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4749. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4750. LLVMSetInitializer(array_data, backing_array.value);
  4751. lbValue g = {};
  4752. g.value = array_data;
  4753. g.type = t;
  4754. lb_add_entity(m, e, g);
  4755. lb_add_member(m, name, g);
  4756. {
  4757. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4758. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4759. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4760. LLVMValueRef values[2] = {ptr, len};
  4761. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4762. return res;
  4763. }
  4764. }
  4765. }
  4766. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4767. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  4768. i64 count = type->Array.count;
  4769. Type *elem = type->Array.elem;
  4770. LLVMTypeRef et = lb_type(m, elem);
  4771. Rune rune;
  4772. isize offset = 0;
  4773. isize width = 1;
  4774. String s = value.value_string;
  4775. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4776. for (i64 i = 0; i < count && offset < s.len; i++) {
  4777. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  4778. offset += width;
  4779. elems[i] = LLVMConstInt(et, rune, true);
  4780. }
  4781. GB_ASSERT(offset == s.len);
  4782. res.value = llvm_const_array(et, elems, cast(unsigned)count);
  4783. return res;
  4784. }
  4785. GB_PANIC("HERE!\n");
  4786. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4787. cast(char const *)value.value_string.text,
  4788. cast(unsigned)value.value_string.len,
  4789. false /*DontNullTerminate*/);
  4790. res.value = data;
  4791. return res;
  4792. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  4793. GB_ASSERT(type->Array.count == value.value_string.len);
  4794. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4795. cast(char const *)value.value_string.text,
  4796. cast(unsigned)value.value_string.len,
  4797. true /*DontNullTerminate*/);
  4798. res.value = data;
  4799. return res;
  4800. } else if (is_type_array(type) &&
  4801. value.kind != ExactValue_Invalid &&
  4802. value.kind != ExactValue_String &&
  4803. value.kind != ExactValue_Compound) {
  4804. i64 count = type->Array.count;
  4805. Type *elem = type->Array.elem;
  4806. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4807. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4808. for (i64 i = 0; i < count; i++) {
  4809. elems[i] = single_elem.value;
  4810. }
  4811. res.value = llvm_const_array(lb_type(m, elem), elems, cast(unsigned)count);
  4812. return res;
  4813. }
  4814. switch (value.kind) {
  4815. case ExactValue_Invalid:
  4816. res.value = LLVMConstNull(lb_type(m, original_type));
  4817. return res;
  4818. case ExactValue_Bool:
  4819. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4820. return res;
  4821. case ExactValue_String:
  4822. {
  4823. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4824. lbValue res = {};
  4825. res.type = default_type(original_type);
  4826. if (is_type_cstring(res.type)) {
  4827. res.value = ptr;
  4828. } else {
  4829. if (value.value_string.len == 0) {
  4830. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4831. }
  4832. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4833. LLVMValueRef values[2] = {ptr, str_len};
  4834. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4835. }
  4836. return res;
  4837. }
  4838. case ExactValue_Integer:
  4839. if (is_type_pointer(type)) {
  4840. unsigned len = cast(unsigned)value.value_integer.len;
  4841. LLVMTypeRef t = lb_type(m, original_type);
  4842. if (len == 0) {
  4843. res.value = LLVMConstNull(t);
  4844. } else {
  4845. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), len, big_int_ptr(&value.value_integer));
  4846. res.value = LLVMConstIntToPtr(i, t);
  4847. }
  4848. } else {
  4849. unsigned len = cast(unsigned)value.value_integer.len;
  4850. if (len == 0) {
  4851. res.value = LLVMConstNull(lb_type(m, original_type));
  4852. } else {
  4853. u64 *words = big_int_ptr(&value.value_integer);
  4854. if (is_type_different_to_arch_endianness(type)) {
  4855. // NOTE(bill): Swap byte order for different endianness
  4856. i64 sz = type_size_of(type);
  4857. isize byte_len = gb_size_of(u64)*len;
  4858. u8 *old_bytes = cast(u8 *)words;
  4859. // TODO(bill): Use a different allocator here for a temporary allocation
  4860. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  4861. for (i64 i = 0; i < sz; i++) {
  4862. new_bytes[i] = old_bytes[sz-1-i];
  4863. }
  4864. words = cast(u64 *)new_bytes;
  4865. }
  4866. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4867. if (value.value_integer.neg) {
  4868. res.value = LLVMConstNeg(res.value);
  4869. }
  4870. }
  4871. }
  4872. return res;
  4873. case ExactValue_Float:
  4874. if (is_type_different_to_arch_endianness(type)) {
  4875. u64 u = bit_cast<u64>(value.value_float);
  4876. u = gb_endian_swap64(u);
  4877. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4878. } else {
  4879. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4880. }
  4881. return res;
  4882. case ExactValue_Complex:
  4883. {
  4884. LLVMValueRef values[2] = {};
  4885. switch (8*type_size_of(type)) {
  4886. case 32:
  4887. values[0] = lb_const_f16(m, cast(f32)value.value_complex->real);
  4888. values[1] = lb_const_f16(m, cast(f32)value.value_complex->imag);
  4889. break;
  4890. case 64:
  4891. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  4892. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  4893. break;
  4894. case 128:
  4895. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  4896. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  4897. break;
  4898. }
  4899. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4900. return res;
  4901. }
  4902. break;
  4903. case ExactValue_Quaternion:
  4904. {
  4905. LLVMValueRef values[4] = {};
  4906. switch (8*type_size_of(type)) {
  4907. case 64:
  4908. // @QuaternionLayout
  4909. values[3] = lb_const_f16(m, cast(f32)value.value_quaternion->real);
  4910. values[0] = lb_const_f16(m, cast(f32)value.value_quaternion->imag);
  4911. values[1] = lb_const_f16(m, cast(f32)value.value_quaternion->jmag);
  4912. values[2] = lb_const_f16(m, cast(f32)value.value_quaternion->kmag);
  4913. break;
  4914. case 128:
  4915. // @QuaternionLayout
  4916. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  4917. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  4918. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  4919. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  4920. break;
  4921. case 256:
  4922. // @QuaternionLayout
  4923. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  4924. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  4925. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  4926. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  4927. break;
  4928. }
  4929. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 4);
  4930. return res;
  4931. }
  4932. break;
  4933. case ExactValue_Pointer:
  4934. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4935. return res;
  4936. case ExactValue_Compound:
  4937. if (is_type_slice(type)) {
  4938. return lb_const_value(m, type, value, allow_local);
  4939. } else if (is_type_array(type)) {
  4940. ast_node(cl, CompoundLit, value.value_compound);
  4941. Type *elem_type = type->Array.elem;
  4942. isize elem_count = cl->elems.count;
  4943. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4944. return lb_const_nil(m, original_type);
  4945. }
  4946. if (cl->elems[0]->kind == Ast_FieldValue) {
  4947. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4948. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4949. isize value_index = 0;
  4950. for (i64 i = 0; i < type->Array.count; i++) {
  4951. bool found = false;
  4952. for (isize j = 0; j < elem_count; j++) {
  4953. Ast *elem = cl->elems[j];
  4954. ast_node(fv, FieldValue, elem);
  4955. if (is_ast_range(fv->field)) {
  4956. ast_node(ie, BinaryExpr, fv->field);
  4957. TypeAndValue lo_tav = ie->left->tav;
  4958. TypeAndValue hi_tav = ie->right->tav;
  4959. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4960. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4961. TokenKind op = ie->op.kind;
  4962. i64 lo = exact_value_to_i64(lo_tav.value);
  4963. i64 hi = exact_value_to_i64(hi_tav.value);
  4964. if (op == Token_Ellipsis) {
  4965. hi += 1;
  4966. }
  4967. if (lo == i) {
  4968. TypeAndValue tav = fv->value->tav;
  4969. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4970. for (i64 k = lo; k < hi; k++) {
  4971. values[value_index++] = val;
  4972. }
  4973. found = true;
  4974. i += (hi-lo-1);
  4975. break;
  4976. }
  4977. } else {
  4978. TypeAndValue index_tav = fv->field->tav;
  4979. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4980. i64 index = exact_value_to_i64(index_tav.value);
  4981. if (index == i) {
  4982. TypeAndValue tav = fv->value->tav;
  4983. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4984. values[value_index++] = val;
  4985. found = true;
  4986. break;
  4987. }
  4988. }
  4989. }
  4990. if (!found) {
  4991. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4992. }
  4993. }
  4994. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4995. return res;
  4996. } else {
  4997. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  4998. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4999. for (isize i = 0; i < elem_count; i++) {
  5000. TypeAndValue tav = cl->elems[i]->tav;
  5001. GB_ASSERT(tav.mode != Addressing_Invalid);
  5002. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5003. }
  5004. for (isize i = elem_count; i < type->Array.count; i++) {
  5005. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5006. }
  5007. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  5008. return res;
  5009. }
  5010. } else if (is_type_enumerated_array(type)) {
  5011. ast_node(cl, CompoundLit, value.value_compound);
  5012. Type *elem_type = type->EnumeratedArray.elem;
  5013. isize elem_count = cl->elems.count;
  5014. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5015. return lb_const_nil(m, original_type);
  5016. }
  5017. if (cl->elems[0]->kind == Ast_FieldValue) {
  5018. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5019. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  5020. isize value_index = 0;
  5021. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  5022. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  5023. for (i64 i = total_lo; i <= total_hi; i++) {
  5024. bool found = false;
  5025. for (isize j = 0; j < elem_count; j++) {
  5026. Ast *elem = cl->elems[j];
  5027. ast_node(fv, FieldValue, elem);
  5028. if (is_ast_range(fv->field)) {
  5029. ast_node(ie, BinaryExpr, fv->field);
  5030. TypeAndValue lo_tav = ie->left->tav;
  5031. TypeAndValue hi_tav = ie->right->tav;
  5032. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5033. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5034. TokenKind op = ie->op.kind;
  5035. i64 lo = exact_value_to_i64(lo_tav.value);
  5036. i64 hi = exact_value_to_i64(hi_tav.value);
  5037. if (op == Token_Ellipsis) {
  5038. hi += 1;
  5039. }
  5040. if (lo == i) {
  5041. TypeAndValue tav = fv->value->tav;
  5042. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5043. for (i64 k = lo; k < hi; k++) {
  5044. values[value_index++] = val;
  5045. }
  5046. found = true;
  5047. i += (hi-lo-1);
  5048. break;
  5049. }
  5050. } else {
  5051. TypeAndValue index_tav = fv->field->tav;
  5052. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5053. i64 index = exact_value_to_i64(index_tav.value);
  5054. if (index == i) {
  5055. TypeAndValue tav = fv->value->tav;
  5056. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5057. values[value_index++] = val;
  5058. found = true;
  5059. break;
  5060. }
  5061. }
  5062. }
  5063. if (!found) {
  5064. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5065. }
  5066. }
  5067. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  5068. return res;
  5069. } else {
  5070. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  5071. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  5072. for (isize i = 0; i < elem_count; i++) {
  5073. TypeAndValue tav = cl->elems[i]->tav;
  5074. GB_ASSERT(tav.mode != Addressing_Invalid);
  5075. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5076. }
  5077. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  5078. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5079. }
  5080. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  5081. return res;
  5082. }
  5083. } else if (is_type_simd_vector(type)) {
  5084. ast_node(cl, CompoundLit, value.value_compound);
  5085. Type *elem_type = type->SimdVector.elem;
  5086. isize elem_count = cl->elems.count;
  5087. if (elem_count == 0) {
  5088. return lb_const_nil(m, original_type);
  5089. }
  5090. GB_ASSERT(elem_type_can_be_constant(elem_type));
  5091. isize total_elem_count = type->SimdVector.count;
  5092. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  5093. for (isize i = 0; i < elem_count; i++) {
  5094. TypeAndValue tav = cl->elems[i]->tav;
  5095. GB_ASSERT(tav.mode != Addressing_Invalid);
  5096. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5097. }
  5098. LLVMTypeRef et = lb_type(m, elem_type);
  5099. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  5100. values[i] = LLVMConstNull(et);
  5101. }
  5102. for (isize i = 0; i< total_elem_count; i++) {
  5103. values[i] = llvm_const_cast(values[i], et);
  5104. }
  5105. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  5106. return res;
  5107. } else if (is_type_struct(type)) {
  5108. ast_node(cl, CompoundLit, value.value_compound);
  5109. if (cl->elems.count == 0) {
  5110. return lb_const_nil(m, original_type);
  5111. }
  5112. isize offset = 0;
  5113. if (type->Struct.custom_align > 0) {
  5114. offset = 1;
  5115. }
  5116. isize value_count = type->Struct.fields.count + offset;
  5117. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5118. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  5119. if (cl->elems.count > 0) {
  5120. if (cl->elems[0]->kind == Ast_FieldValue) {
  5121. isize elem_count = cl->elems.count;
  5122. for (isize i = 0; i < elem_count; i++) {
  5123. ast_node(fv, FieldValue, cl->elems[i]);
  5124. String name = fv->field->Ident.token.string;
  5125. TypeAndValue tav = fv->value->tav;
  5126. GB_ASSERT(tav.mode != Addressing_Invalid);
  5127. Selection sel = lookup_field(type, name, false);
  5128. Entity *f = type->Struct.fields[sel.index[0]];
  5129. if (elem_type_can_be_constant(f->type)) {
  5130. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  5131. visited[offset+f->Variable.field_index] = true;
  5132. }
  5133. }
  5134. } else {
  5135. for_array(i, cl->elems) {
  5136. Entity *f = type->Struct.fields[i];
  5137. TypeAndValue tav = cl->elems[i]->tav;
  5138. ExactValue val = {};
  5139. if (tav.mode != Addressing_Invalid) {
  5140. val = tav.value;
  5141. }
  5142. if (elem_type_can_be_constant(f->type)) {
  5143. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  5144. visited[offset+f->Variable.field_index] = true;
  5145. }
  5146. }
  5147. }
  5148. }
  5149. for (isize i = 0; i < type->Struct.fields.count; i++) {
  5150. if (!visited[offset+i]) {
  5151. GB_ASSERT(values[offset+i] == nullptr);
  5152. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  5153. }
  5154. }
  5155. if (type->Struct.custom_align > 0) {
  5156. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  5157. }
  5158. bool is_constant = true;
  5159. for (isize i = 0; i < value_count; i++) {
  5160. LLVMValueRef val = values[i];
  5161. if (!LLVMIsConstant(val)) {
  5162. GB_ASSERT(is_local);
  5163. GB_ASSERT(LLVMGetInstructionOpcode(val) == LLVMLoad);
  5164. is_constant = false;
  5165. }
  5166. }
  5167. if (is_constant) {
  5168. res.value = llvm_const_named_struct(lb_type(m, original_type), values, cast(unsigned)value_count);
  5169. return res;
  5170. } else {
  5171. // TODO(bill): THIS IS HACK BUT IT WORKS FOR WHAT I NEED
  5172. LLVMValueRef *old_values = values;
  5173. LLVMValueRef *new_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5174. for (isize i = 0; i < value_count; i++) {
  5175. LLVMValueRef old_value = old_values[i];
  5176. if (LLVMIsConstant(old_value)) {
  5177. new_values[i] = old_value;
  5178. } else {
  5179. new_values[i] = LLVMConstNull(LLVMTypeOf(old_value));
  5180. }
  5181. }
  5182. LLVMValueRef constant_value = llvm_const_named_struct(lb_type(m, original_type), new_values, cast(unsigned)value_count);
  5183. GB_ASSERT(is_local);
  5184. lbProcedure *p = m->curr_procedure;
  5185. lbAddr v = lb_add_local_generated(p, res.type, true);
  5186. LLVMBuildStore(p->builder, constant_value, v.addr.value);
  5187. for (isize i = 0; i < value_count; i++) {
  5188. LLVMValueRef val = old_values[i];
  5189. if (!LLVMIsConstant(val)) {
  5190. LLVMValueRef dst = LLVMBuildStructGEP(p->builder, v.addr.value, cast(unsigned)i, "");
  5191. LLVMBuildStore(p->builder, val, dst);
  5192. }
  5193. }
  5194. return lb_addr_load(p, v);
  5195. }
  5196. } else if (is_type_bit_set(type)) {
  5197. ast_node(cl, CompoundLit, value.value_compound);
  5198. if (cl->elems.count == 0) {
  5199. return lb_const_nil(m, original_type);
  5200. }
  5201. i64 sz = type_size_of(type);
  5202. if (sz == 0) {
  5203. return lb_const_nil(m, original_type);
  5204. }
  5205. u64 bits = 0;
  5206. for_array(i, cl->elems) {
  5207. Ast *e = cl->elems[i];
  5208. GB_ASSERT(e->kind != Ast_FieldValue);
  5209. TypeAndValue tav = e->tav;
  5210. if (tav.mode != Addressing_Constant) {
  5211. continue;
  5212. }
  5213. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  5214. i64 v = big_int_to_i64(&tav.value.value_integer);
  5215. i64 lower = type->BitSet.lower;
  5216. bits |= 1ull<<cast(u64)(v-lower);
  5217. }
  5218. if (is_type_different_to_arch_endianness(type)) {
  5219. i64 size = type_size_of(type);
  5220. switch (size) {
  5221. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  5222. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  5223. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  5224. }
  5225. }
  5226. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  5227. return res;
  5228. } else {
  5229. return lb_const_nil(m, original_type);
  5230. }
  5231. break;
  5232. case ExactValue_Procedure:
  5233. {
  5234. Ast *expr = value.value_procedure;
  5235. GB_ASSERT(expr != nullptr);
  5236. if (expr->kind == Ast_ProcLit) {
  5237. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5238. }
  5239. }
  5240. break;
  5241. case ExactValue_Typeid:
  5242. return lb_typeid(m, value.value_typeid);
  5243. }
  5244. return lb_const_nil(m, original_type);
  5245. }
  5246. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  5247. lbModule *m = p->module;
  5248. LLVMValueRef fields[4] = {};
  5249. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)).value;
  5250. fields[1]/*line*/ = lb_const_int(m, t_i32, pos.line).value;
  5251. fields[2]/*column*/ = lb_const_int(m, t_i32, pos.column).value;
  5252. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  5253. lbValue res = {};
  5254. res.value = llvm_const_named_struct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  5255. res.type = t_source_code_location;
  5256. return res;
  5257. }
  5258. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  5259. String proc_name = {};
  5260. if (p->entity) {
  5261. proc_name = p->entity->token.string;
  5262. }
  5263. TokenPos pos = {};
  5264. if (node) {
  5265. pos = ast_token(node).pos;
  5266. }
  5267. return lb_emit_source_code_location(p, proc_name, pos);
  5268. }
  5269. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  5270. switch (op) {
  5271. case Token_Add:
  5272. return x;
  5273. case Token_Not: // Boolean not
  5274. case Token_Xor: // Bitwise not
  5275. case Token_Sub: // Number negation
  5276. break;
  5277. case Token_Pointer:
  5278. GB_PANIC("This should be handled elsewhere");
  5279. break;
  5280. }
  5281. if (is_type_array(x.type)) {
  5282. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  5283. Type *tl = base_type(x.type);
  5284. lbValue val = lb_address_from_load_or_generate_local(p, x);
  5285. GB_ASSERT(is_type_array(type));
  5286. Type *elem_type = base_array_type(type);
  5287. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5288. lbAddr res_addr = lb_add_local_generated(p, type, false);
  5289. lbValue res = lb_addr_get_ptr(p, res_addr);
  5290. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5291. i32 count = cast(i32)tl->Array.count;
  5292. if (inline_array_arith) {
  5293. // inline
  5294. for (i32 i = 0; i < count; i++) {
  5295. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  5296. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5297. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  5298. }
  5299. } else {
  5300. auto loop_data = lb_loop_start(p, count, t_i32);
  5301. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  5302. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5303. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  5304. lb_loop_end(p, loop_data);
  5305. }
  5306. return lb_emit_load(p, res);
  5307. }
  5308. if (op == Token_Xor) {
  5309. lbValue cmp = {};
  5310. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  5311. cmp.type = x.type;
  5312. return lb_emit_conv(p, cmp, type);
  5313. }
  5314. if (op == Token_Not) {
  5315. lbValue cmp = {};
  5316. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  5317. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  5318. cmp.type = t_llvm_bool;
  5319. return lb_emit_conv(p, cmp, type);
  5320. }
  5321. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5322. Type *platform_type = integer_endian_type_to_platform_type(type);
  5323. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5324. lbValue res = {};
  5325. res.value = LLVMBuildNeg(p->builder, v.value, "");
  5326. res.type = platform_type;
  5327. return lb_emit_byte_swap(p, res, type);
  5328. }
  5329. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5330. Type *platform_type = integer_endian_type_to_platform_type(type);
  5331. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5332. lbValue res = {};
  5333. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  5334. res.type = platform_type;
  5335. return lb_emit_byte_swap(p, res, type);
  5336. }
  5337. lbValue res = {};
  5338. switch (op) {
  5339. case Token_Not: // Boolean not
  5340. case Token_Xor: // Bitwise not
  5341. res.value = LLVMBuildNot(p->builder, x.value, "");
  5342. res.type = x.type;
  5343. return res;
  5344. case Token_Sub: // Number negation
  5345. if (is_type_integer(x.type)) {
  5346. res.value = LLVMBuildNeg(p->builder, x.value, "");
  5347. } else if (is_type_float(x.type)) {
  5348. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  5349. } else if (is_type_complex(x.type)) {
  5350. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5351. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5352. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5353. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5354. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5355. return lb_addr_load(p, addr);
  5356. } else if (is_type_quaternion(x.type)) {
  5357. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5358. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5359. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  5360. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  5361. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5362. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5363. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5364. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  5365. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  5366. return lb_addr_load(p, addr);
  5367. } else {
  5368. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  5369. }
  5370. res.type = x.type;
  5371. return res;
  5372. }
  5373. return res;
  5374. }
  5375. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  5376. lbModule *m = p->module;
  5377. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  5378. lhs = lb_emit_conv(p, lhs, type);
  5379. rhs = lb_emit_conv(p, rhs, type);
  5380. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  5381. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  5382. GB_ASSERT(is_type_array(type));
  5383. Type *elem_type = base_array_type(type);
  5384. lbAddr res = lb_add_local_generated(p, type, false);
  5385. i64 count = base_type(type)->Array.count;
  5386. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5387. if (inline_array_arith) {
  5388. for (i64 i = 0; i < count; i++) {
  5389. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  5390. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  5391. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  5392. lbValue a = lb_emit_load(p, a_ptr);
  5393. lbValue b = lb_emit_load(p, b_ptr);
  5394. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5395. lb_emit_store(p, dst_ptr, c);
  5396. }
  5397. } else {
  5398. auto loop_data = lb_loop_start(p, count, t_i32);
  5399. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  5400. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  5401. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  5402. lbValue a = lb_emit_load(p, a_ptr);
  5403. lbValue b = lb_emit_load(p, b_ptr);
  5404. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5405. lb_emit_store(p, dst_ptr, c);
  5406. lb_loop_end(p, loop_data);
  5407. }
  5408. return lb_addr_load(p, res);
  5409. } else if (is_type_complex(type)) {
  5410. lhs = lb_emit_conv(p, lhs, type);
  5411. rhs = lb_emit_conv(p, rhs, type);
  5412. Type *ft = base_complex_elem_type(type);
  5413. if (op == Token_Quo) {
  5414. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5415. args[0] = lhs;
  5416. args[1] = rhs;
  5417. switch (type_size_of(ft)) {
  5418. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  5419. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  5420. default: GB_PANIC("Unknown float type"); break;
  5421. }
  5422. }
  5423. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5424. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  5425. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  5426. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  5427. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  5428. lbValue real = {};
  5429. lbValue imag = {};
  5430. switch (op) {
  5431. case Token_Add:
  5432. real = lb_emit_arith(p, Token_Add, a, c, ft);
  5433. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  5434. break;
  5435. case Token_Sub:
  5436. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  5437. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  5438. break;
  5439. case Token_Mul: {
  5440. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  5441. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  5442. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  5443. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  5444. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  5445. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  5446. break;
  5447. }
  5448. }
  5449. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  5450. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  5451. return lb_addr_load(p, res);
  5452. } else if (is_type_quaternion(type)) {
  5453. lhs = lb_emit_conv(p, lhs, type);
  5454. rhs = lb_emit_conv(p, rhs, type);
  5455. Type *ft = base_complex_elem_type(type);
  5456. if (op == Token_Add || op == Token_Sub) {
  5457. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5458. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  5459. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  5460. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  5461. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  5462. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  5463. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  5464. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  5465. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  5466. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  5467. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  5468. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  5469. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  5470. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  5471. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  5472. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  5473. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  5474. return lb_addr_load(p, res);
  5475. } else if (op == Token_Mul) {
  5476. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5477. args[0] = lhs;
  5478. args[1] = rhs;
  5479. switch (8*type_size_of(ft)) {
  5480. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  5481. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  5482. default: GB_PANIC("Unknown float type"); break;
  5483. }
  5484. } else if (op == Token_Quo) {
  5485. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5486. args[0] = lhs;
  5487. args[1] = rhs;
  5488. switch (8*type_size_of(ft)) {
  5489. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  5490. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  5491. default: GB_PANIC("Unknown float type"); break;
  5492. }
  5493. }
  5494. }
  5495. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5496. switch (op) {
  5497. case Token_AndNot:
  5498. case Token_And:
  5499. case Token_Or:
  5500. case Token_Xor:
  5501. goto handle_op;
  5502. }
  5503. Type *platform_type = integer_endian_type_to_platform_type(type);
  5504. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5505. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5506. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5507. return lb_emit_byte_swap(p, res, type);
  5508. }
  5509. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5510. Type *platform_type = integer_endian_type_to_platform_type(type);
  5511. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5512. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5513. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5514. return lb_emit_byte_swap(p, res, type);
  5515. }
  5516. handle_op:
  5517. lhs = lb_emit_conv(p, lhs, type);
  5518. rhs = lb_emit_conv(p, rhs, type);
  5519. lbValue res = {};
  5520. res.type = type;
  5521. // NOTE(bill): Bit Set Aliases for + and -
  5522. if (is_type_bit_set(type)) {
  5523. switch (op) {
  5524. case Token_Add: op = Token_Or; break;
  5525. case Token_Sub: op = Token_AndNot; break;
  5526. }
  5527. }
  5528. switch (op) {
  5529. case Token_Add:
  5530. if (is_type_float(type)) {
  5531. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  5532. return res;
  5533. }
  5534. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  5535. return res;
  5536. case Token_Sub:
  5537. if (is_type_float(type)) {
  5538. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  5539. return res;
  5540. }
  5541. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  5542. return res;
  5543. case Token_Mul:
  5544. if (is_type_float(type)) {
  5545. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  5546. return res;
  5547. }
  5548. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  5549. return res;
  5550. case Token_Quo:
  5551. if (is_type_float(type)) {
  5552. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  5553. return res;
  5554. } else if (is_type_unsigned(type)) {
  5555. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  5556. return res;
  5557. }
  5558. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  5559. return res;
  5560. case Token_Mod:
  5561. if (is_type_float(type)) {
  5562. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  5563. return res;
  5564. } else if (is_type_unsigned(type)) {
  5565. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5566. return res;
  5567. }
  5568. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5569. return res;
  5570. case Token_ModMod:
  5571. if (is_type_unsigned(type)) {
  5572. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5573. return res;
  5574. } else {
  5575. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5576. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  5577. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  5578. res.value = c;
  5579. return res;
  5580. }
  5581. case Token_And:
  5582. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  5583. return res;
  5584. case Token_Or:
  5585. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  5586. return res;
  5587. case Token_Xor:
  5588. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  5589. return res;
  5590. case Token_Shl:
  5591. {
  5592. rhs = lb_emit_conv(p, rhs, lhs.type);
  5593. LLVMValueRef lhsval = lhs.value;
  5594. LLVMValueRef bits = rhs.value;
  5595. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5596. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  5597. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  5598. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5599. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  5600. return res;
  5601. }
  5602. case Token_Shr:
  5603. {
  5604. rhs = lb_emit_conv(p, rhs, lhs.type);
  5605. LLVMValueRef lhsval = lhs.value;
  5606. LLVMValueRef bits = rhs.value;
  5607. bool is_unsigned = is_type_unsigned(type);
  5608. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5609. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  5610. if (is_unsigned) {
  5611. res.value = LLVMBuildLShr(p->builder, lhsval, bits, "");
  5612. } else {
  5613. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  5614. }
  5615. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5616. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  5617. return res;
  5618. }
  5619. case Token_AndNot:
  5620. {
  5621. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  5622. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  5623. return res;
  5624. }
  5625. break;
  5626. }
  5627. GB_PANIC("unhandled operator of lb_emit_arith");
  5628. return {};
  5629. }
  5630. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  5631. ast_node(be, BinaryExpr, expr);
  5632. TypeAndValue tv = type_and_value_of_expr(expr);
  5633. switch (be->op.kind) {
  5634. case Token_Add:
  5635. case Token_Sub:
  5636. case Token_Mul:
  5637. case Token_Quo:
  5638. case Token_Mod:
  5639. case Token_ModMod:
  5640. case Token_And:
  5641. case Token_Or:
  5642. case Token_Xor:
  5643. case Token_AndNot:
  5644. case Token_Shl:
  5645. case Token_Shr: {
  5646. Type *type = default_type(tv.type);
  5647. lbValue left = lb_build_expr(p, be->left);
  5648. lbValue right = lb_build_expr(p, be->right);
  5649. return lb_emit_arith(p, be->op.kind, left, right, type);
  5650. }
  5651. case Token_CmpEq:
  5652. case Token_NotEq:
  5653. case Token_Lt:
  5654. case Token_LtEq:
  5655. case Token_Gt:
  5656. case Token_GtEq:
  5657. {
  5658. lbValue left = {};
  5659. lbValue right = {};
  5660. if (be->left->tav.mode == Addressing_Type) {
  5661. left = lb_typeid(p->module, be->left->tav.type);
  5662. }
  5663. if (be->right->tav.mode == Addressing_Type) {
  5664. right = lb_typeid(p->module, be->right->tav.type);
  5665. }
  5666. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  5667. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  5668. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  5669. Type *type = default_type(tv.type);
  5670. return lb_emit_conv(p, cmp, type);
  5671. }
  5672. case Token_CmpAnd:
  5673. case Token_CmpOr:
  5674. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  5675. case Token_in:
  5676. case Token_not_in:
  5677. {
  5678. lbValue left = lb_build_expr(p, be->left);
  5679. Type *type = default_type(tv.type);
  5680. lbValue right = lb_build_expr(p, be->right);
  5681. Type *rt = base_type(right.type);
  5682. switch (rt->kind) {
  5683. case Type_Map:
  5684. {
  5685. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  5686. lbValue h = lb_gen_map_header(p, addr, rt);
  5687. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  5688. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5689. args[0] = h;
  5690. args[1] = key;
  5691. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  5692. if (be->op.kind == Token_in) {
  5693. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  5694. } else {
  5695. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  5696. }
  5697. }
  5698. break;
  5699. case Type_BitSet:
  5700. {
  5701. Type *key_type = rt->BitSet.elem;
  5702. GB_ASSERT(are_types_identical(left.type, key_type));
  5703. Type *it = bit_set_to_int(rt);
  5704. left = lb_emit_conv(p, left, it);
  5705. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  5706. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  5707. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  5708. bit = lb_emit_conv(p, bit, it);
  5709. lbValue old_value = lb_emit_transmute(p, right, it);
  5710. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  5711. if (be->op.kind == Token_in) {
  5712. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5713. } else {
  5714. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5715. }
  5716. }
  5717. break;
  5718. default:
  5719. GB_PANIC("Invalid 'in' type");
  5720. }
  5721. break;
  5722. }
  5723. break;
  5724. default:
  5725. GB_PANIC("Invalid binary expression");
  5726. break;
  5727. }
  5728. return {};
  5729. }
  5730. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  5731. Type *prev_src = src;
  5732. // Type *prev_dst = dst;
  5733. src = base_type(type_deref(src));
  5734. // dst = base_type(type_deref(dst));
  5735. bool src_is_ptr = src != prev_src;
  5736. // bool dst_is_ptr = dst != prev_dst;
  5737. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  5738. for_array(i, src->Struct.fields) {
  5739. Entity *f = src->Struct.fields[i];
  5740. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  5741. if (are_types_identical(dst, f->type)) {
  5742. return f->token.string;
  5743. }
  5744. if (src_is_ptr && is_type_pointer(dst)) {
  5745. if (are_types_identical(type_deref(dst), f->type)) {
  5746. return f->token.string;
  5747. }
  5748. }
  5749. if (is_type_struct(f->type)) {
  5750. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  5751. if (name.len > 0) {
  5752. return name;
  5753. }
  5754. }
  5755. }
  5756. }
  5757. return str_lit("");
  5758. }
  5759. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  5760. GB_ASSERT(is_type_pointer(value.type));
  5761. GB_ASSERT(is_type_pointer(t));
  5762. GB_ASSERT(lb_is_const(value));
  5763. lbValue res = {};
  5764. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  5765. res.type = t;
  5766. return res;
  5767. }
  5768. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  5769. lbModule *m = p->module;
  5770. t = reduce_tuple_to_single_type(t);
  5771. Type *src_type = value.type;
  5772. if (are_types_identical(t, src_type)) {
  5773. return value;
  5774. }
  5775. Type *src = core_type(src_type);
  5776. Type *dst = core_type(t);
  5777. GB_ASSERT(src != nullptr);
  5778. GB_ASSERT(dst != nullptr);
  5779. if (is_type_untyped_nil(src)) {
  5780. return lb_const_nil(m, t);
  5781. }
  5782. if (is_type_untyped_undef(src)) {
  5783. return lb_const_undef(m, t);
  5784. }
  5785. if (LLVMIsConstant(value.value)) {
  5786. if (is_type_any(dst)) {
  5787. Type *st = default_type(src_type);
  5788. lbAddr default_value = lb_add_local_generated(p, st, false);
  5789. lb_addr_store(p, default_value, value);
  5790. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  5791. lbValue id = lb_typeid(m, st);
  5792. lbAddr res = lb_add_local_generated(p, t, false);
  5793. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  5794. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  5795. lb_emit_store(p, a0, data);
  5796. lb_emit_store(p, a1, id);
  5797. return lb_addr_load(p, res);
  5798. } else if (dst->kind == Type_Basic) {
  5799. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5800. String str = lb_get_const_string(m, value);
  5801. lbValue res = {};
  5802. res.type = t;
  5803. res.value = llvm_cstring(m, str);
  5804. return res;
  5805. }
  5806. // if (is_type_float(dst)) {
  5807. // return value;
  5808. // } else if (is_type_integer(dst)) {
  5809. // return value;
  5810. // }
  5811. // ExactValue ev = value->Constant.value;
  5812. // if (is_type_float(dst)) {
  5813. // ev = exact_value_to_float(ev);
  5814. // } else if (is_type_complex(dst)) {
  5815. // ev = exact_value_to_complex(ev);
  5816. // } else if (is_type_quaternion(dst)) {
  5817. // ev = exact_value_to_quaternion(ev);
  5818. // } else if (is_type_string(dst)) {
  5819. // // Handled elsewhere
  5820. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5821. // } else if (is_type_integer(dst)) {
  5822. // ev = exact_value_to_integer(ev);
  5823. // } else if (is_type_pointer(dst)) {
  5824. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5825. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5826. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5827. // }
  5828. // return lb_const_value(p->module, t, ev);
  5829. }
  5830. }
  5831. if (are_types_identical(src, dst)) {
  5832. if (!are_types_identical(src_type, t)) {
  5833. return lb_emit_transmute(p, value, t);
  5834. }
  5835. return value;
  5836. }
  5837. // bool <-> llvm bool
  5838. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5839. lbValue res = {};
  5840. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5841. res.type = dst;
  5842. return res;
  5843. }
  5844. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5845. lbValue res = {};
  5846. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5847. res.type = dst;
  5848. return res;
  5849. }
  5850. // integer -> integer
  5851. if (is_type_integer(src) && is_type_integer(dst)) {
  5852. GB_ASSERT(src->kind == Type_Basic &&
  5853. dst->kind == Type_Basic);
  5854. i64 sz = type_size_of(default_type(src));
  5855. i64 dz = type_size_of(default_type(dst));
  5856. if (sz == dz) {
  5857. if (dz > 1 && !types_have_same_internal_endian(src, dst)) {
  5858. return lb_emit_byte_swap(p, value, t);
  5859. }
  5860. lbValue res = {};
  5861. res.value = value.value;
  5862. res.type = t;
  5863. return res;
  5864. }
  5865. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5866. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5867. value = lb_emit_byte_swap(p, value, platform_src_type);
  5868. }
  5869. LLVMOpcode op = LLVMTrunc;
  5870. if (dz < sz) {
  5871. op = LLVMTrunc;
  5872. } else if (dz == sz) {
  5873. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5874. // NOTE(bill): Copy the value just for type correctness
  5875. op = LLVMBitCast;
  5876. } else if (dz > sz) {
  5877. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5878. }
  5879. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5880. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5881. lbValue res = {};
  5882. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5883. res.type = t;
  5884. return lb_emit_byte_swap(p, res, t);
  5885. } else {
  5886. lbValue res = {};
  5887. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5888. res.type = t;
  5889. return res;
  5890. }
  5891. }
  5892. // boolean -> boolean/integer
  5893. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5894. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5895. lbValue res = {};
  5896. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5897. res.type = t;
  5898. return res;
  5899. }
  5900. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5901. return lb_emit_transmute(p, value, dst);
  5902. }
  5903. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5904. return lb_emit_transmute(p, value, dst);
  5905. }
  5906. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5907. return lb_emit_transmute(p, value, dst);
  5908. }
  5909. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5910. return lb_emit_transmute(p, value, dst);
  5911. }
  5912. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5913. lbValue c = lb_emit_conv(p, value, t_cstring);
  5914. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5915. args[0] = c;
  5916. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5917. return lb_emit_conv(p, s, dst);
  5918. }
  5919. // integer -> boolean
  5920. if (is_type_integer(src) && is_type_boolean(dst)) {
  5921. lbValue res = {};
  5922. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5923. res.type = t_llvm_bool;
  5924. return lb_emit_conv(p, res, t);
  5925. }
  5926. // float -> float
  5927. if (is_type_float(src) && is_type_float(dst)) {
  5928. i64 sz = type_size_of(src);
  5929. i64 dz = type_size_of(dst);
  5930. if (dz == sz) {
  5931. if (types_have_same_internal_endian(src, dst)) {
  5932. lbValue res = {};
  5933. res.type = t;
  5934. res.value = value.value;
  5935. return res;
  5936. } else {
  5937. return lb_emit_byte_swap(p, value, t);
  5938. }
  5939. }
  5940. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5941. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5942. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5943. lbValue res = {};
  5944. res = lb_emit_conv(p, value, platform_src_type);
  5945. res = lb_emit_conv(p, res, platform_dst_type);
  5946. if (is_type_different_to_arch_endianness(dst)) {
  5947. res = lb_emit_byte_swap(p, res, t);
  5948. }
  5949. return lb_emit_conv(p, res, t);
  5950. }
  5951. lbValue res = {};
  5952. res.type = t;
  5953. if (dz >= sz) {
  5954. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  5955. } else {
  5956. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  5957. }
  5958. return res;
  5959. }
  5960. if (is_type_complex(src) && is_type_complex(dst)) {
  5961. Type *ft = base_complex_elem_type(dst);
  5962. lbAddr gen = lb_add_local_generated(p, dst, false);
  5963. lbValue gp = lb_addr_get_ptr(p, gen);
  5964. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5965. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5966. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5967. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  5968. return lb_addr_load(p, gen);
  5969. }
  5970. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5971. // @QuaternionLayout
  5972. Type *ft = base_complex_elem_type(dst);
  5973. lbAddr gen = lb_add_local_generated(p, dst, false);
  5974. lbValue gp = lb_addr_get_ptr(p, gen);
  5975. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5976. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5977. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  5978. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  5979. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  5980. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  5981. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  5982. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  5983. return lb_addr_load(p, gen);
  5984. }
  5985. if (is_type_float(src) && is_type_complex(dst)) {
  5986. Type *ft = base_complex_elem_type(dst);
  5987. lbAddr gen = lb_add_local_generated(p, dst, true);
  5988. lbValue gp = lb_addr_get_ptr(p, gen);
  5989. lbValue real = lb_emit_conv(p, value, ft);
  5990. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5991. return lb_addr_load(p, gen);
  5992. }
  5993. if (is_type_float(src) && is_type_quaternion(dst)) {
  5994. Type *ft = base_complex_elem_type(dst);
  5995. lbAddr gen = lb_add_local_generated(p, dst, true);
  5996. lbValue gp = lb_addr_get_ptr(p, gen);
  5997. lbValue real = lb_emit_conv(p, value, ft);
  5998. // @QuaternionLayout
  5999. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6000. return lb_addr_load(p, gen);
  6001. }
  6002. if (is_type_complex(src) && is_type_quaternion(dst)) {
  6003. Type *ft = base_complex_elem_type(dst);
  6004. lbAddr gen = lb_add_local_generated(p, dst, true);
  6005. lbValue gp = lb_addr_get_ptr(p, gen);
  6006. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6007. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6008. // @QuaternionLayout
  6009. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6010. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  6011. return lb_addr_load(p, gen);
  6012. }
  6013. // float <-> integer
  6014. if (is_type_float(src) && is_type_integer(dst)) {
  6015. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6016. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6017. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6018. lbValue res = {};
  6019. res = lb_emit_conv(p, value, platform_src_type);
  6020. res = lb_emit_conv(p, res, platform_dst_type);
  6021. if (is_type_different_to_arch_endianness(dst)) {
  6022. res = lb_emit_byte_swap(p, res, t);
  6023. }
  6024. return lb_emit_conv(p, res, t);
  6025. }
  6026. lbValue res = {};
  6027. res.type = t;
  6028. if (is_type_unsigned(dst)) {
  6029. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  6030. } else {
  6031. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  6032. }
  6033. return res;
  6034. }
  6035. if (is_type_integer(src) && is_type_float(dst)) {
  6036. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6037. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6038. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6039. lbValue res = {};
  6040. res = lb_emit_conv(p, value, platform_src_type);
  6041. res = lb_emit_conv(p, res, platform_dst_type);
  6042. if (is_type_different_to_arch_endianness(dst)) {
  6043. res = lb_emit_byte_swap(p, res, t);
  6044. }
  6045. return lb_emit_conv(p, res, t);
  6046. }
  6047. lbValue res = {};
  6048. res.type = t;
  6049. if (is_type_unsigned(src)) {
  6050. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  6051. } else {
  6052. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  6053. }
  6054. return res;
  6055. }
  6056. // Pointer <-> uintptr
  6057. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6058. lbValue res = {};
  6059. res.type = t;
  6060. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6061. return res;
  6062. }
  6063. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6064. lbValue res = {};
  6065. res.type = t;
  6066. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6067. return res;
  6068. }
  6069. #if 1
  6070. if (is_type_union(dst)) {
  6071. for_array(i, dst->Union.variants) {
  6072. Type *vt = dst->Union.variants[i];
  6073. if (are_types_identical(vt, src_type)) {
  6074. lbAddr parent = lb_add_local_generated(p, t, true);
  6075. lb_emit_store_union_variant(p, parent.addr, value, vt);
  6076. return lb_addr_load(p, parent);
  6077. }
  6078. }
  6079. }
  6080. #endif
  6081. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  6082. // subtype polymorphism casting
  6083. if (check_is_assignable_to_using_subtype(src_type, t)) {
  6084. Type *st = type_deref(src_type);
  6085. Type *pst = st;
  6086. st = type_deref(st);
  6087. bool st_is_ptr = is_type_pointer(src_type);
  6088. st = base_type(st);
  6089. Type *dt = t;
  6090. bool dt_is_ptr = type_deref(dt) != dt;
  6091. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  6092. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  6093. if (field_name.len > 0) {
  6094. // NOTE(bill): It can be casted
  6095. Selection sel = lookup_field(st, field_name, false, true);
  6096. if (sel.entity != nullptr) {
  6097. if (st_is_ptr) {
  6098. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  6099. Type *rt = res.type;
  6100. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6101. res = lb_emit_load(p, res);
  6102. }
  6103. return res;
  6104. } else {
  6105. if (is_type_pointer(value.type)) {
  6106. Type *rt = value.type;
  6107. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6108. value = lb_emit_load(p, value);
  6109. } else {
  6110. value = lb_emit_deep_field_gep(p, value, sel);
  6111. return lb_emit_load(p, value);
  6112. }
  6113. }
  6114. return lb_emit_deep_field_ev(p, value, sel);
  6115. }
  6116. } else {
  6117. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  6118. }
  6119. }
  6120. }
  6121. // Pointer <-> Pointer
  6122. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6123. lbValue res = {};
  6124. res.type = t;
  6125. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6126. return res;
  6127. }
  6128. // proc <-> proc
  6129. if (is_type_proc(src) && is_type_proc(dst)) {
  6130. lbValue res = {};
  6131. res.type = t;
  6132. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6133. return res;
  6134. }
  6135. // pointer -> proc
  6136. if (is_type_pointer(src) && is_type_proc(dst)) {
  6137. lbValue res = {};
  6138. res.type = t;
  6139. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6140. return res;
  6141. }
  6142. // proc -> pointer
  6143. if (is_type_proc(src) && is_type_pointer(dst)) {
  6144. lbValue res = {};
  6145. res.type = t;
  6146. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6147. return res;
  6148. }
  6149. // []byte/[]u8 <-> string
  6150. if (is_type_u8_slice(src) && is_type_string(dst)) {
  6151. return lb_emit_transmute(p, value, t);
  6152. }
  6153. if (is_type_string(src) && is_type_u8_slice(dst)) {
  6154. return lb_emit_transmute(p, value, t);
  6155. }
  6156. if (is_type_array(dst)) {
  6157. Type *elem = dst->Array.elem;
  6158. lbValue e = lb_emit_conv(p, value, elem);
  6159. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6160. lbAddr v = lb_add_local_generated(p, t, false);
  6161. isize index_count = cast(isize)dst->Array.count;
  6162. for (isize i = 0; i < index_count; i++) {
  6163. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  6164. lb_emit_store(p, elem, e);
  6165. }
  6166. return lb_addr_load(p, v);
  6167. }
  6168. if (is_type_any(dst)) {
  6169. if (is_type_untyped_nil(src)) {
  6170. return lb_const_nil(p->module, t);
  6171. }
  6172. if (is_type_untyped_undef(src)) {
  6173. return lb_const_undef(p->module, t);
  6174. }
  6175. lbAddr result = lb_add_local_generated(p, t, true);
  6176. Type *st = default_type(src_type);
  6177. lbValue data = lb_address_from_load_or_generate_local(p, value);
  6178. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  6179. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  6180. data = lb_emit_conv(p, data, t_rawptr);
  6181. lbValue id = lb_typeid(p->module, st);
  6182. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  6183. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  6184. lb_emit_store(p, any_data, data);
  6185. lb_emit_store(p, any_id, id);
  6186. return lb_addr_load(p, result);
  6187. }
  6188. i64 src_sz = type_size_of(src);
  6189. i64 dst_sz = type_size_of(dst);
  6190. if (src_sz == dst_sz) {
  6191. // bit_set <-> integer
  6192. if (is_type_integer(src) && is_type_bit_set(dst)) {
  6193. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  6194. res.type = dst;
  6195. return res;
  6196. }
  6197. if (is_type_bit_set(src) && is_type_integer(dst)) {
  6198. lbValue bs = value;
  6199. bs.type = bit_set_to_int(src);
  6200. return lb_emit_conv(p, bs, dst);
  6201. }
  6202. // typeid <-> integer
  6203. if (is_type_integer(src) && is_type_typeid(dst)) {
  6204. return lb_emit_transmute(p, value, dst);
  6205. }
  6206. if (is_type_typeid(src) && is_type_integer(dst)) {
  6207. return lb_emit_transmute(p, value, dst);
  6208. }
  6209. }
  6210. if (is_type_untyped(src)) {
  6211. if (is_type_string(src) && is_type_string(dst)) {
  6212. lbAddr result = lb_add_local_generated(p, t, false);
  6213. lb_addr_store(p, result, value);
  6214. return lb_addr_load(p, result);
  6215. }
  6216. }
  6217. gb_printf_err("%.*s\n", LIT(p->name));
  6218. gb_printf_err("lb_emit_conv: src -> dst\n");
  6219. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  6220. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  6221. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  6222. gb_printf_err("Not Identical %p != %p\n", src, dst);
  6223. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  6224. type_to_string(src_type), type_to_string(t),
  6225. LIT(p->name));
  6226. return {};
  6227. }
  6228. bool lb_is_type_aggregate(Type *t) {
  6229. t = base_type(t);
  6230. switch (t->kind) {
  6231. case Type_Basic:
  6232. switch (t->Basic.kind) {
  6233. case Basic_string:
  6234. case Basic_any:
  6235. return true;
  6236. case Basic_complex32:
  6237. case Basic_complex64:
  6238. case Basic_complex128:
  6239. case Basic_quaternion64:
  6240. case Basic_quaternion128:
  6241. case Basic_quaternion256:
  6242. return true;
  6243. }
  6244. break;
  6245. case Type_Pointer:
  6246. return false;
  6247. case Type_Array:
  6248. case Type_Slice:
  6249. case Type_Struct:
  6250. case Type_Union:
  6251. case Type_Tuple:
  6252. case Type_DynamicArray:
  6253. case Type_Map:
  6254. case Type_SimdVector:
  6255. return true;
  6256. case Type_Named:
  6257. return lb_is_type_aggregate(t->Named.base);
  6258. }
  6259. return false;
  6260. }
  6261. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  6262. Type *src_type = value.type;
  6263. if (are_types_identical(t, src_type)) {
  6264. return value;
  6265. }
  6266. lbValue res = {};
  6267. res.type = t;
  6268. Type *src = base_type(src_type);
  6269. Type *dst = base_type(t);
  6270. lbModule *m = p->module;
  6271. i64 sz = type_size_of(src);
  6272. i64 dz = type_size_of(dst);
  6273. if (sz != dz) {
  6274. LLVMTypeRef s = lb_type(m, src);
  6275. LLVMTypeRef d = lb_type(m, dst);
  6276. i64 llvm_sz = lb_sizeof(s);
  6277. i64 llvm_dz = lb_sizeof(d);
  6278. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  6279. }
  6280. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  6281. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  6282. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6283. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6284. return res;
  6285. }
  6286. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6287. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6288. return res;
  6289. }
  6290. if (is_type_uintptr(src) && is_type_proc(dst)) {
  6291. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6292. return res;
  6293. }
  6294. if (is_type_proc(src) && is_type_uintptr(dst)) {
  6295. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6296. return res;
  6297. }
  6298. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  6299. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6300. return res;
  6301. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  6302. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6303. return res;
  6304. }
  6305. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6306. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  6307. return res;
  6308. }
  6309. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  6310. lbValue s = lb_address_from_load_or_generate_local(p, value);
  6311. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  6312. return lb_emit_load(p, d);
  6313. }
  6314. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  6315. // GB_PANIC("lb_emit_transmute");
  6316. return res;
  6317. }
  6318. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  6319. GB_ASSERT(addr.kind == lbAddr_Context);
  6320. GB_ASSERT(addr.ctx.sel.index.count == 0);
  6321. lbModule *m = p->module;
  6322. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6323. args[0] = addr.addr;
  6324. lb_emit_runtime_call(p, "__init_context", args);
  6325. }
  6326. lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  6327. Type *pt = base_type(p->type);
  6328. GB_ASSERT(pt->kind == Type_Proc);
  6329. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  6330. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  6331. e->flags |= EntityFlag_NoAlias;
  6332. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  6333. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  6334. lbValue param = {context_ptr, e->type};
  6335. lb_add_entity(p->module, e, param);
  6336. lbAddr ctx_addr = {};
  6337. ctx_addr.kind = lbAddr_Context;
  6338. ctx_addr.addr = param;
  6339. lbContextData *cd = array_add_and_get(&p->context_stack);
  6340. cd->ctx = ctx_addr;
  6341. cd->scope_index = -1;
  6342. return cd;
  6343. }
  6344. lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  6345. ctx.kind = lbAddr_Context;
  6346. lbContextData *cd = array_add_and_get(&p->context_stack);
  6347. cd->ctx = ctx;
  6348. cd->scope_index = p->scope_index;
  6349. return cd;
  6350. }
  6351. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  6352. if (p->context_stack.count > 0) {
  6353. return p->context_stack[p->context_stack.count-1].ctx;
  6354. }
  6355. Type *pt = base_type(p->type);
  6356. GB_ASSERT(pt->kind == Type_Proc);
  6357. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  6358. lbAddr c = lb_add_local_generated(p, t_context, true);
  6359. c.kind = lbAddr_Context;
  6360. lb_emit_init_context(p, c);
  6361. lb_push_context_onto_stack(p, c);
  6362. lb_add_debug_context_variable(p, c);
  6363. return c;
  6364. }
  6365. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  6366. if (LLVMIsALoadInst(value.value)) {
  6367. lbValue res = {};
  6368. res.value = LLVMGetOperand(value.value, 0);
  6369. res.type = alloc_type_pointer(value.type);
  6370. return res;
  6371. }
  6372. GB_ASSERT(is_type_typed(value.type));
  6373. lbAddr res = lb_add_local_generated(p, value.type, false);
  6374. lb_addr_store(p, res, value);
  6375. return res.addr;
  6376. }
  6377. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  6378. if (LLVMIsALoadInst(value.value)) {
  6379. lbValue res = {};
  6380. res.value = LLVMGetOperand(value.value, 0);
  6381. res.type = alloc_type_pointer(value.type);
  6382. return res;
  6383. }
  6384. GB_PANIC("lb_address_from_load");
  6385. return {};
  6386. }
  6387. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  6388. i64 type_alignment = type_align_of(new_type);
  6389. if (alignment < type_alignment) {
  6390. alignment = type_alignment;
  6391. }
  6392. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  6393. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  6394. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  6395. lb_addr_store(p, ptr, val);
  6396. // ptr.kind = lbAddr_Context;
  6397. return ptr.addr;
  6398. }
  6399. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  6400. GB_ASSERT(is_type_pointer(s.type));
  6401. Type *t = base_type(type_deref(s.type));
  6402. Type *result_type = nullptr;
  6403. if (is_type_relative_pointer(t)) {
  6404. s = lb_addr_get_ptr(p, lb_addr(s));
  6405. }
  6406. if (is_type_struct(t)) {
  6407. result_type = get_struct_field_type(t, index);
  6408. } else if (is_type_union(t)) {
  6409. GB_ASSERT(index == -1);
  6410. return lb_emit_union_tag_ptr(p, s);
  6411. } else if (is_type_tuple(t)) {
  6412. GB_ASSERT(t->Tuple.variables.count > 0);
  6413. result_type = t->Tuple.variables[index]->type;
  6414. } else if (is_type_complex(t)) {
  6415. Type *ft = base_complex_elem_type(t);
  6416. switch (index) {
  6417. case 0: result_type = ft; break;
  6418. case 1: result_type = ft; break;
  6419. }
  6420. } else if (is_type_quaternion(t)) {
  6421. Type *ft = base_complex_elem_type(t);
  6422. switch (index) {
  6423. case 0: result_type = ft; break;
  6424. case 1: result_type = ft; break;
  6425. case 2: result_type = ft; break;
  6426. case 3: result_type = ft; break;
  6427. }
  6428. } else if (is_type_slice(t)) {
  6429. switch (index) {
  6430. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6431. case 1: result_type = t_int; break;
  6432. }
  6433. } else if (is_type_string(t)) {
  6434. switch (index) {
  6435. case 0: result_type = t_u8_ptr; break;
  6436. case 1: result_type = t_int; break;
  6437. }
  6438. } else if (is_type_any(t)) {
  6439. switch (index) {
  6440. case 0: result_type = t_rawptr; break;
  6441. case 1: result_type = t_typeid; break;
  6442. }
  6443. } else if (is_type_dynamic_array(t)) {
  6444. switch (index) {
  6445. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6446. case 1: result_type = t_int; break;
  6447. case 2: result_type = t_int; break;
  6448. case 3: result_type = t_allocator; break;
  6449. }
  6450. } else if (is_type_map(t)) {
  6451. init_map_internal_types(t);
  6452. Type *itp = alloc_type_pointer(t->Map.internal_type);
  6453. s = lb_emit_transmute(p, s, itp);
  6454. Type *gst = t->Map.internal_type;
  6455. GB_ASSERT(gst->kind == Type_Struct);
  6456. switch (index) {
  6457. case 0: result_type = get_struct_field_type(gst, 0); break;
  6458. case 1: result_type = get_struct_field_type(gst, 1); break;
  6459. }
  6460. } else if (is_type_array(t)) {
  6461. return lb_emit_array_epi(p, s, index);
  6462. } else if (is_type_relative_slice(t)) {
  6463. switch (index) {
  6464. case 0: result_type = t->RelativeSlice.base_integer; break;
  6465. case 1: result_type = t->RelativeSlice.base_integer; break;
  6466. }
  6467. } else {
  6468. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  6469. }
  6470. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  6471. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6472. index += 1;
  6473. }
  6474. if (lb_is_const(s)) {
  6475. lbModule *m = p->module;
  6476. lbValue res = {};
  6477. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  6478. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6479. res.type = alloc_type_pointer(result_type);
  6480. return res;
  6481. } else {
  6482. lbValue res = {};
  6483. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  6484. res.type = alloc_type_pointer(result_type);
  6485. return res;
  6486. }
  6487. }
  6488. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  6489. if (LLVMIsALoadInst(s.value)) {
  6490. lbValue res = {};
  6491. res.value = LLVMGetOperand(s.value, 0);
  6492. res.type = alloc_type_pointer(s.type);
  6493. lbValue ptr = lb_emit_struct_ep(p, res, index);
  6494. return lb_emit_load(p, ptr);
  6495. }
  6496. Type *t = base_type(s.type);
  6497. Type *result_type = nullptr;
  6498. switch (t->kind) {
  6499. case Type_Basic:
  6500. switch (t->Basic.kind) {
  6501. case Basic_string:
  6502. switch (index) {
  6503. case 0: result_type = t_u8_ptr; break;
  6504. case 1: result_type = t_int; break;
  6505. }
  6506. break;
  6507. case Basic_any:
  6508. switch (index) {
  6509. case 0: result_type = t_rawptr; break;
  6510. case 1: result_type = t_typeid; break;
  6511. }
  6512. break;
  6513. case Basic_complex32:
  6514. case Basic_complex64:
  6515. case Basic_complex128:
  6516. {
  6517. Type *ft = base_complex_elem_type(t);
  6518. switch (index) {
  6519. case 0: result_type = ft; break;
  6520. case 1: result_type = ft; break;
  6521. }
  6522. break;
  6523. }
  6524. case Basic_quaternion64:
  6525. case Basic_quaternion128:
  6526. case Basic_quaternion256:
  6527. {
  6528. Type *ft = base_complex_elem_type(t);
  6529. switch (index) {
  6530. case 0: result_type = ft; break;
  6531. case 1: result_type = ft; break;
  6532. case 2: result_type = ft; break;
  6533. case 3: result_type = ft; break;
  6534. }
  6535. break;
  6536. }
  6537. }
  6538. break;
  6539. case Type_Struct:
  6540. result_type = get_struct_field_type(t, index);
  6541. break;
  6542. case Type_Union:
  6543. GB_ASSERT(index == -1);
  6544. // return lb_emit_union_tag_value(p, s);
  6545. GB_PANIC("lb_emit_union_tag_value");
  6546. case Type_Tuple:
  6547. GB_ASSERT(t->Tuple.variables.count > 0);
  6548. result_type = t->Tuple.variables[index]->type;
  6549. if (t->Tuple.variables.count == 1) {
  6550. return s;
  6551. }
  6552. break;
  6553. case Type_Slice:
  6554. switch (index) {
  6555. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6556. case 1: result_type = t_int; break;
  6557. }
  6558. break;
  6559. case Type_DynamicArray:
  6560. switch (index) {
  6561. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6562. case 1: result_type = t_int; break;
  6563. case 2: result_type = t_int; break;
  6564. case 3: result_type = t_allocator; break;
  6565. }
  6566. break;
  6567. case Type_Map:
  6568. {
  6569. init_map_internal_types(t);
  6570. Type *gst = t->Map.generated_struct_type;
  6571. switch (index) {
  6572. case 0: result_type = get_struct_field_type(gst, 0); break;
  6573. case 1: result_type = get_struct_field_type(gst, 1); break;
  6574. }
  6575. }
  6576. break;
  6577. case Type_Array:
  6578. result_type = t->Array.elem;
  6579. break;
  6580. default:
  6581. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  6582. break;
  6583. }
  6584. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  6585. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6586. index += 1;
  6587. }
  6588. lbValue res = {};
  6589. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  6590. res.type = result_type;
  6591. return res;
  6592. }
  6593. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  6594. GB_ASSERT(sel.index.count > 0);
  6595. Type *type = type_deref(e.type);
  6596. for_array(i, sel.index) {
  6597. i32 index = cast(i32)sel.index[i];
  6598. if (is_type_pointer(type)) {
  6599. type = type_deref(type);
  6600. e = lb_emit_load(p, e);
  6601. }
  6602. type = core_type(type);
  6603. if (is_type_quaternion(type)) {
  6604. e = lb_emit_struct_ep(p, e, index);
  6605. } else if (is_type_raw_union(type)) {
  6606. type = get_struct_field_type(type, index);
  6607. GB_ASSERT(is_type_pointer(e.type));
  6608. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  6609. } else if (is_type_struct(type)) {
  6610. type = get_struct_field_type(type, index);
  6611. e = lb_emit_struct_ep(p, e, index);
  6612. } else if (type->kind == Type_Union) {
  6613. GB_ASSERT(index == -1);
  6614. type = t_type_info_ptr;
  6615. e = lb_emit_struct_ep(p, e, index);
  6616. } else if (type->kind == Type_Tuple) {
  6617. type = type->Tuple.variables[index]->type;
  6618. e = lb_emit_struct_ep(p, e, index);
  6619. } else if (type->kind == Type_Basic) {
  6620. switch (type->Basic.kind) {
  6621. case Basic_any: {
  6622. if (index == 0) {
  6623. type = t_rawptr;
  6624. } else if (index == 1) {
  6625. type = t_type_info_ptr;
  6626. }
  6627. e = lb_emit_struct_ep(p, e, index);
  6628. break;
  6629. }
  6630. case Basic_string:
  6631. e = lb_emit_struct_ep(p, e, index);
  6632. break;
  6633. default:
  6634. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6635. break;
  6636. }
  6637. } else if (type->kind == Type_Slice) {
  6638. e = lb_emit_struct_ep(p, e, index);
  6639. } else if (type->kind == Type_DynamicArray) {
  6640. e = lb_emit_struct_ep(p, e, index);
  6641. } else if (type->kind == Type_Array) {
  6642. e = lb_emit_array_epi(p, e, index);
  6643. } else if (type->kind == Type_Map) {
  6644. e = lb_emit_struct_ep(p, e, index);
  6645. } else if (type->kind == Type_RelativePointer) {
  6646. e = lb_emit_struct_ep(p, e, index);
  6647. } else {
  6648. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6649. }
  6650. }
  6651. return e;
  6652. }
  6653. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  6654. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  6655. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  6656. return lb_emit_load(p, res);
  6657. }
  6658. void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  6659. // NOTE(bill): The prev block may defer injection before it's terminator
  6660. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  6661. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  6662. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  6663. return;
  6664. }
  6665. isize prev_context_stack_count = p->context_stack.count;
  6666. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  6667. defer (p->context_stack.count = prev_context_stack_count);
  6668. p->context_stack.count = d.context_stack_count;
  6669. lbBlock *b = lb_create_block(p, "defer");
  6670. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6671. lb_emit_jump(p, b);
  6672. }
  6673. lb_start_block(p, b);
  6674. if (d.kind == lbDefer_Node) {
  6675. lb_build_stmt(p, d.stmt);
  6676. } else if (d.kind == lbDefer_Instr) {
  6677. // NOTE(bill): Need to make a new copy
  6678. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  6679. LLVMInsertIntoBuilder(p->builder, instr);
  6680. } else if (d.kind == lbDefer_Proc) {
  6681. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  6682. }
  6683. }
  6684. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  6685. isize count = p->defer_stmts.count;
  6686. isize i = count;
  6687. while (i --> 0) {
  6688. lbDefer const &d = p->defer_stmts[i];
  6689. if (kind == lbDeferExit_Default) {
  6690. if (p->scope_index == d.scope_index &&
  6691. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  6692. lb_build_defer_stmt(p, d);
  6693. array_pop(&p->defer_stmts);
  6694. continue;
  6695. } else {
  6696. break;
  6697. }
  6698. } else if (kind == lbDeferExit_Return) {
  6699. lb_build_defer_stmt(p, d);
  6700. } else if (kind == lbDeferExit_Branch) {
  6701. GB_ASSERT(block != nullptr);
  6702. isize lower_limit = block->scope_index;
  6703. if (lower_limit < d.scope_index) {
  6704. lb_build_defer_stmt(p, d);
  6705. }
  6706. }
  6707. }
  6708. }
  6709. void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  6710. Type *pt = base_type(p->type);
  6711. GB_ASSERT(pt->kind == Type_Proc);
  6712. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6713. GB_ASSERT(p->context_stack.count != 0);
  6714. }
  6715. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6716. d->kind = lbDefer_Node;
  6717. d->scope_index = scope_index;
  6718. d->context_stack_count = p->context_stack.count;
  6719. d->block = p->curr_block;
  6720. d->stmt = stmt;
  6721. }
  6722. void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  6723. Type *pt = base_type(p->type);
  6724. GB_ASSERT(pt->kind == Type_Proc);
  6725. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6726. GB_ASSERT(p->context_stack.count != 0);
  6727. }
  6728. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6729. d->kind = lbDefer_Proc;
  6730. d->scope_index = p->scope_index;
  6731. d->block = p->curr_block;
  6732. d->context_stack_count = p->context_stack.count;
  6733. d->proc.deferred = deferred;
  6734. d->proc.result_as_args = result_as_args;
  6735. }
  6736. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  6737. Array<lbValue> array = {};
  6738. Type *t = base_type(value.type);
  6739. if (t == nullptr) {
  6740. // Do nothing
  6741. } else if (is_type_tuple(t)) {
  6742. GB_ASSERT(t->kind == Type_Tuple);
  6743. auto *rt = &t->Tuple;
  6744. if (rt->variables.count > 0) {
  6745. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  6746. for_array(i, rt->variables) {
  6747. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  6748. array[i] = elem;
  6749. }
  6750. }
  6751. } else {
  6752. array = array_make<lbValue>(permanent_allocator(), 1);
  6753. array[0] = value;
  6754. }
  6755. return array;
  6756. }
  6757. 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) {
  6758. unsigned arg_count = cast(unsigned)processed_args.count;
  6759. if (return_ptr.value != nullptr) {
  6760. arg_count += 1;
  6761. }
  6762. if (context_ptr.addr.value != nullptr) {
  6763. arg_count += 1;
  6764. }
  6765. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  6766. isize arg_index = 0;
  6767. if (return_ptr.value != nullptr) {
  6768. args[arg_index++] = return_ptr.value;
  6769. }
  6770. for_array(i, processed_args) {
  6771. lbValue arg = processed_args[i];
  6772. args[arg_index++] = arg.value;
  6773. }
  6774. if (context_ptr.addr.value != nullptr) {
  6775. LLVMValueRef cp = context_ptr.addr.value;
  6776. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  6777. args[arg_index++] = cp;
  6778. }
  6779. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  6780. GB_ASSERT(curr_block != p->decl_block->block);
  6781. {
  6782. LLVMTypeRef ftp = lb_type(p->module, value.type);
  6783. LLVMTypeRef ft = LLVMGetElementType(ftp);
  6784. LLVMValueRef fn = value.value;
  6785. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  6786. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  6787. }
  6788. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  6789. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  6790. {
  6791. unsigned param_count = LLVMCountParamTypes(fnp);
  6792. GB_ASSERT(arg_count >= param_count);
  6793. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  6794. LLVMGetParamTypes(fnp, param_types);
  6795. for (unsigned i = 0; i < param_count; i++) {
  6796. LLVMTypeRef param_type = param_types[i];
  6797. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  6798. GB_ASSERT_MSG(
  6799. arg_type == param_type,
  6800. "Parameter types do not match: %s != %s, argument: %s",
  6801. LLVMPrintTypeToString(arg_type),
  6802. LLVMPrintTypeToString(param_type),
  6803. LLVMPrintValueToString(args[i])
  6804. );
  6805. }
  6806. }
  6807. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  6808. // LLVMValueRef ret = LLVMBuildCall(p->builder, fn, args, arg_count, "");
  6809. lbValue res = {};
  6810. res.value = ret;
  6811. res.type = abi_rt;
  6812. return res;
  6813. }
  6814. }
  6815. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  6816. // LLVMMetadataRef curr_loc = LLVMGetCurrentDebugLocation2(p->builder);
  6817. // LLVMSetCurrentDebugLocation2(p->builder, nullptr);
  6818. // defer (if (curr_loc) {
  6819. // LLVMSetCurrentDebugLocation2(p->builder, curr_loc);
  6820. // });
  6821. String name = make_string_c(c_name);
  6822. AstPackage *pkg = p->module->info->runtime_package;
  6823. Entity *e = scope_lookup_current(pkg->scope, name);
  6824. lbValue *found = nullptr;
  6825. if (p->module != e->code_gen_module) {
  6826. gb_mutex_lock(&p->module->mutex);
  6827. }
  6828. GB_ASSERT(e->code_gen_module != nullptr);
  6829. found = map_get(&e->code_gen_module->values, hash_entity(e));
  6830. if (p->module != e->code_gen_module) {
  6831. gb_mutex_unlock(&p->module->mutex);
  6832. }
  6833. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  6834. return lb_emit_call(p, *found, args);
  6835. }
  6836. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  6837. lbModule *m = p->module;
  6838. Type *pt = base_type(value.type);
  6839. GB_ASSERT(pt->kind == Type_Proc);
  6840. Type *results = pt->Proc.results;
  6841. if (p->entity != nullptr) {
  6842. if (p->entity->flags & EntityFlag_Disabled) {
  6843. return {};
  6844. }
  6845. }
  6846. lbAddr context_ptr = {};
  6847. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6848. context_ptr = lb_find_or_generate_context_ptr(p);
  6849. }
  6850. defer (if (pt->Proc.diverging) {
  6851. LLVMBuildUnreachable(p->builder);
  6852. });
  6853. set_procedure_abi_types(pt);
  6854. bool is_c_vararg = pt->Proc.c_vararg;
  6855. isize param_count = pt->Proc.param_count;
  6856. if (is_c_vararg) {
  6857. GB_ASSERT(param_count-1 <= args.count);
  6858. param_count -= 1;
  6859. } else {
  6860. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  6861. }
  6862. lbValue result = {};
  6863. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  6864. {
  6865. lbFunctionType **ft_found = nullptr;
  6866. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6867. if (!ft_found) {
  6868. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  6869. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6870. }
  6871. GB_ASSERT(ft_found != nullptr);
  6872. lbFunctionType *ft = *ft_found;
  6873. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  6874. unsigned param_index = 0;
  6875. for (isize i = 0; i < param_count; i++) {
  6876. Entity *e = pt->Proc.params->Tuple.variables[i];
  6877. if (e->kind != Entity_Variable) {
  6878. continue;
  6879. }
  6880. GB_ASSERT(e->flags & EntityFlag_Param);
  6881. Type *original_type = e->type;
  6882. lbArgType *arg = &ft->args[param_index];
  6883. if (arg->kind == lbArg_Ignore) {
  6884. continue;
  6885. }
  6886. lbValue x = lb_emit_conv(p, args[i], original_type);
  6887. LLVMTypeRef xt = lb_type(p->module, x.type);
  6888. if (arg->kind == lbArg_Direct) {
  6889. LLVMTypeRef abi_type = arg->cast_type;
  6890. if (!abi_type) {
  6891. abi_type = arg->type;
  6892. }
  6893. if (xt == abi_type) {
  6894. array_add(&processed_args, x);
  6895. } else {
  6896. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  6897. array_add(&processed_args, x);
  6898. }
  6899. } else if (arg->kind == lbArg_Indirect) {
  6900. lbValue ptr = {};
  6901. if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  6902. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  6903. // i.e. `T const &` in C++
  6904. ptr = lb_address_from_load_or_generate_local(p, x);
  6905. } else {
  6906. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  6907. }
  6908. array_add(&processed_args, ptr);
  6909. }
  6910. param_index += 1;
  6911. }
  6912. if (inlining == ProcInlining_none) {
  6913. inlining = p->inlining;
  6914. }
  6915. Type *rt = reduce_tuple_to_single_type(results);
  6916. if (return_by_pointer) {
  6917. lbValue return_ptr = {};
  6918. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6919. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6920. return_ptr = p->return_ptr_hint_value;
  6921. p->return_ptr_hint_used = true;
  6922. }
  6923. }
  6924. if (return_ptr.value == nullptr) {
  6925. lbAddr r = lb_add_local_generated(p, rt, true);
  6926. return_ptr = r.addr;
  6927. }
  6928. GB_ASSERT(is_type_pointer(return_ptr.type));
  6929. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6930. result = lb_emit_load(p, return_ptr);
  6931. } else if (rt != nullptr) {
  6932. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  6933. if (ft->ret.cast_type) {
  6934. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  6935. }
  6936. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  6937. result.type = rt;
  6938. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  6939. result.type = t_llvm_bool;
  6940. }
  6941. if (!is_type_tuple(rt)) {
  6942. result = lb_emit_conv(p, result, rt);
  6943. }
  6944. } else {
  6945. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  6946. }
  6947. }
  6948. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  6949. if (found != nullptr) {
  6950. Entity *e = *found;
  6951. if (e != nullptr && entity_has_deferred_procedure(e)) {
  6952. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  6953. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  6954. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  6955. GB_ASSERT(deferred_found != nullptr);
  6956. lbValue deferred = *deferred_found;
  6957. auto in_args = args;
  6958. Array<lbValue> result_as_args = {};
  6959. switch (kind) {
  6960. case DeferredProcedure_none:
  6961. break;
  6962. case DeferredProcedure_in:
  6963. result_as_args = in_args;
  6964. break;
  6965. case DeferredProcedure_out:
  6966. result_as_args = lb_value_to_array(p, result);
  6967. break;
  6968. case DeferredProcedure_in_out:
  6969. {
  6970. auto out_args = lb_value_to_array(p, result);
  6971. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  6972. array_copy(&result_as_args, in_args, 0);
  6973. array_copy(&result_as_args, out_args, in_args.count);
  6974. }
  6975. break;
  6976. }
  6977. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  6978. }
  6979. }
  6980. return result;
  6981. }
  6982. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  6983. Type *t = s.type;
  6984. GB_ASSERT(is_type_pointer(t));
  6985. Type *st = base_type(type_deref(t));
  6986. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6987. GB_ASSERT_MSG(is_type_integer(core_type(index.type)), "%s", type_to_string(index.type));
  6988. LLVMValueRef indices[2] = {};
  6989. indices[0] = llvm_zero(p->module);
  6990. indices[1] = lb_emit_conv(p, index, t_int).value;
  6991. Type *ptr = base_array_type(st);
  6992. lbValue res = {};
  6993. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  6994. res.type = alloc_type_pointer(ptr);
  6995. return res;
  6996. }
  6997. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  6998. Type *t = s.type;
  6999. GB_ASSERT(is_type_pointer(t));
  7000. Type *st = base_type(type_deref(t));
  7001. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7002. GB_ASSERT(0 <= index);
  7003. Type *ptr = base_array_type(st);
  7004. LLVMValueRef indices[2] = {
  7005. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  7006. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  7007. };
  7008. lbValue res = {};
  7009. if (lb_is_const(s)) {
  7010. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  7011. } else {
  7012. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  7013. }
  7014. res.type = alloc_type_pointer(ptr);
  7015. return res;
  7016. }
  7017. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  7018. LLVMValueRef indices[1] = {index.value};
  7019. lbValue res = {};
  7020. res.type = ptr.type;
  7021. if (lb_is_const(ptr) && lb_is_const(index)) {
  7022. res.value = LLVMConstGEP(ptr.value, indices, 1);
  7023. } else {
  7024. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  7025. }
  7026. return res;
  7027. }
  7028. LLVMValueRef llvm_const_slice(lbModule *m, lbValue data, lbValue len) {
  7029. GB_ASSERT(is_type_pointer(data.type));
  7030. GB_ASSERT(are_types_identical(len.type, t_int));
  7031. LLVMValueRef vals[2] = {
  7032. data.value,
  7033. len.value,
  7034. };
  7035. return LLVMConstStructInContext(m->ctx, vals, gb_count_of(vals), false);
  7036. }
  7037. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  7038. Type *t = lb_addr_type(slice);
  7039. GB_ASSERT(is_type_slice(t));
  7040. lbValue ptr = lb_addr_get_ptr(p, slice);
  7041. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7042. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7043. }
  7044. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  7045. Type *t = lb_addr_type(string);
  7046. GB_ASSERT(is_type_string(t));
  7047. lbValue ptr = lb_addr_get_ptr(p, string);
  7048. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7049. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7050. }
  7051. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  7052. Type *t = base_type(string.type);
  7053. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  7054. return lb_emit_struct_ev(p, string, 0);
  7055. }
  7056. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  7057. Type *t = base_type(string.type);
  7058. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  7059. return lb_emit_struct_ev(p, string, 1);
  7060. }
  7061. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  7062. GB_ASSERT(is_type_cstring(value.type));
  7063. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7064. args[0] = lb_emit_conv(p, value, t_cstring);
  7065. return lb_emit_runtime_call(p, "cstring_len", args);
  7066. }
  7067. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  7068. Type *t = type_deref(array_ptr.type);
  7069. GB_ASSERT(is_type_array(t));
  7070. return lb_emit_struct_ep(p, array_ptr, 0);
  7071. }
  7072. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  7073. GB_ASSERT(is_type_slice(slice.type));
  7074. return lb_emit_struct_ev(p, slice, 0);
  7075. }
  7076. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  7077. GB_ASSERT(is_type_slice(slice.type));
  7078. return lb_emit_struct_ev(p, slice, 1);
  7079. }
  7080. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  7081. GB_ASSERT(is_type_dynamic_array(da.type));
  7082. return lb_emit_struct_ev(p, da, 0);
  7083. }
  7084. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  7085. GB_ASSERT(is_type_dynamic_array(da.type));
  7086. return lb_emit_struct_ev(p, da, 1);
  7087. }
  7088. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  7089. GB_ASSERT(is_type_dynamic_array(da.type));
  7090. return lb_emit_struct_ev(p, da, 2);
  7091. }
  7092. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  7093. GB_ASSERT(is_type_dynamic_array(da.type));
  7094. return lb_emit_struct_ev(p, da, 3);
  7095. }
  7096. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  7097. Type *t = base_type(value.type);
  7098. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7099. init_map_internal_types(t);
  7100. Type *gst = t->Map.generated_struct_type;
  7101. i32 index = 1;
  7102. lbValue entries = lb_emit_struct_ev(p, value, index);
  7103. return entries;
  7104. }
  7105. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  7106. Type *t = base_type(type_deref(value.type));
  7107. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7108. init_map_internal_types(t);
  7109. Type *gst = t->Map.generated_struct_type;
  7110. i32 index = 1;
  7111. lbValue entries = lb_emit_struct_ep(p, value, index);
  7112. return entries;
  7113. }
  7114. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  7115. lbValue entries = lb_map_entries(p, value);
  7116. return lb_dynamic_array_len(p, entries);
  7117. }
  7118. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  7119. lbValue entries = lb_map_entries(p, value);
  7120. return lb_dynamic_array_cap(p, entries);
  7121. }
  7122. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  7123. Type *t = base_type(value.type);
  7124. bool is_ptr = false;
  7125. if (is_type_pointer(t)) {
  7126. is_ptr = true;
  7127. t = base_type(type_deref(t));
  7128. }
  7129. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7130. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7131. }
  7132. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  7133. t->Struct.soa_kind == StructSoa_Dynamic);
  7134. isize n = 0;
  7135. Type *elem = base_type(t->Struct.soa_elem);
  7136. if (elem->kind == Type_Struct) {
  7137. n = elem->Struct.fields.count;
  7138. } else if (elem->kind == Type_Array) {
  7139. n = elem->Array.count;
  7140. } else {
  7141. GB_PANIC("Unreachable");
  7142. }
  7143. if (is_ptr) {
  7144. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7145. return lb_emit_load(p, v);
  7146. }
  7147. return lb_emit_struct_ev(p, value, cast(i32)n);
  7148. }
  7149. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  7150. Type *t = base_type(value.type);
  7151. bool is_ptr = false;
  7152. if (is_type_pointer(t)) {
  7153. is_ptr = true;
  7154. t = base_type(type_deref(t));
  7155. }
  7156. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7157. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7158. }
  7159. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  7160. isize n = 0;
  7161. Type *elem = base_type(t->Struct.soa_elem);
  7162. if (elem->kind == Type_Struct) {
  7163. n = elem->Struct.fields.count+1;
  7164. } else if (elem->kind == Type_Array) {
  7165. n = elem->Array.count+1;
  7166. } else {
  7167. GB_PANIC("Unreachable");
  7168. }
  7169. if (is_ptr) {
  7170. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7171. return lb_emit_load(p, v);
  7172. }
  7173. return lb_emit_struct_ev(p, value, cast(i32)n);
  7174. }
  7175. lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7176. GB_ASSERT(ce->args.count > 0);
  7177. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  7178. for_array(i, slices) {
  7179. Ast *arg = ce->args[i];
  7180. if (arg->kind == Ast_FieldValue) {
  7181. arg = arg->FieldValue.value;
  7182. }
  7183. slices[i] = lb_build_expr(p, arg);
  7184. }
  7185. lbValue len = lb_slice_len(p, slices[0]);
  7186. for (isize i = 1; i < slices.count; i++) {
  7187. lbValue other_len = lb_slice_len(p, slices[i]);
  7188. len = lb_emit_min(p, t_int, len, other_len);
  7189. }
  7190. GB_ASSERT(is_type_soa_struct(tv.type));
  7191. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7192. for_array(i, slices) {
  7193. lbValue src = lb_slice_elem(p, slices[i]);
  7194. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  7195. lb_emit_store(p, dst, src);
  7196. }
  7197. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  7198. lb_emit_store(p, len_dst, len);
  7199. return lb_addr_load(p, res);
  7200. }
  7201. lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7202. GB_ASSERT(ce->args.count == 1);
  7203. lbValue arg = lb_build_expr(p, ce->args[0]);
  7204. Type *t = base_type(arg.type);
  7205. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  7206. lbValue len = lb_soa_struct_len(p, arg);
  7207. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7208. if (is_type_tuple(tv.type)) {
  7209. lbValue rp = lb_addr_get_ptr(p, res);
  7210. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  7211. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  7212. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  7213. lb_fill_slice(p, dst, ptr, len);
  7214. }
  7215. } else {
  7216. GB_ASSERT(is_type_slice(tv.type));
  7217. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  7218. lb_fill_slice(p, res, ptr, len);
  7219. }
  7220. return lb_addr_load(p, res);
  7221. }
  7222. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  7223. ast_node(ce, CallExpr, expr);
  7224. switch (id) {
  7225. case BuiltinProc_DIRECTIVE: {
  7226. ast_node(bd, BasicDirective, ce->proc);
  7227. String name = bd->name;
  7228. GB_ASSERT(name == "location");
  7229. String procedure = p->entity->token.string;
  7230. TokenPos pos = ast_token(ce->proc).pos;
  7231. if (ce->args.count > 0) {
  7232. Ast *ident = unselector_expr(ce->args[0]);
  7233. GB_ASSERT(ident->kind == Ast_Ident);
  7234. Entity *e = entity_of_node(ident);
  7235. GB_ASSERT(e != nullptr);
  7236. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  7237. procedure = e->parent_proc_decl->entity->token.string;
  7238. } else {
  7239. procedure = str_lit("");
  7240. }
  7241. pos = e->token.pos;
  7242. }
  7243. return lb_emit_source_code_location(p, procedure, pos);
  7244. }
  7245. case BuiltinProc_type_info_of: {
  7246. Ast *arg = ce->args[0];
  7247. TypeAndValue tav = type_and_value_of_expr(arg);
  7248. if (tav.mode == Addressing_Type) {
  7249. Type *t = default_type(type_of_expr(arg));
  7250. return lb_type_info(p->module, t);
  7251. }
  7252. GB_ASSERT(is_type_typeid(tav.type));
  7253. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7254. args[0] = lb_build_expr(p, arg);
  7255. return lb_emit_runtime_call(p, "__type_info_of", args);
  7256. }
  7257. case BuiltinProc_typeid_of: {
  7258. Ast *arg = ce->args[0];
  7259. TypeAndValue tav = type_and_value_of_expr(arg);
  7260. GB_ASSERT(tav.mode == Addressing_Type);
  7261. Type *t = default_type(type_of_expr(arg));
  7262. return lb_typeid(p->module, t);
  7263. }
  7264. case BuiltinProc_len: {
  7265. lbValue v = lb_build_expr(p, ce->args[0]);
  7266. Type *t = base_type(v.type);
  7267. if (is_type_pointer(t)) {
  7268. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7269. v = lb_emit_load(p, v);
  7270. t = type_deref(t);
  7271. }
  7272. if (is_type_cstring(t)) {
  7273. return lb_cstring_len(p, v);
  7274. } else if (is_type_string(t)) {
  7275. return lb_string_len(p, v);
  7276. } else if (is_type_array(t)) {
  7277. GB_PANIC("Array lengths are constant");
  7278. } else if (is_type_slice(t)) {
  7279. return lb_slice_len(p, v);
  7280. } else if (is_type_dynamic_array(t)) {
  7281. return lb_dynamic_array_len(p, v);
  7282. } else if (is_type_map(t)) {
  7283. return lb_map_len(p, v);
  7284. } else if (is_type_soa_struct(t)) {
  7285. return lb_soa_struct_len(p, v);
  7286. }
  7287. GB_PANIC("Unreachable");
  7288. break;
  7289. }
  7290. case BuiltinProc_cap: {
  7291. lbValue v = lb_build_expr(p, ce->args[0]);
  7292. Type *t = base_type(v.type);
  7293. if (is_type_pointer(t)) {
  7294. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7295. v = lb_emit_load(p, v);
  7296. t = type_deref(t);
  7297. }
  7298. if (is_type_string(t)) {
  7299. GB_PANIC("Unreachable");
  7300. } else if (is_type_array(t)) {
  7301. GB_PANIC("Array lengths are constant");
  7302. } else if (is_type_slice(t)) {
  7303. return lb_slice_len(p, v);
  7304. } else if (is_type_dynamic_array(t)) {
  7305. return lb_dynamic_array_cap(p, v);
  7306. } else if (is_type_map(t)) {
  7307. return lb_map_cap(p, v);
  7308. } else if (is_type_soa_struct(t)) {
  7309. return lb_soa_struct_cap(p, v);
  7310. }
  7311. GB_PANIC("Unreachable");
  7312. break;
  7313. }
  7314. case BuiltinProc_swizzle: {
  7315. isize index_count = ce->args.count-1;
  7316. if (is_type_simd_vector(tv.type)) {
  7317. lbValue vec = lb_build_expr(p, ce->args[0]);
  7318. if (index_count == 0) {
  7319. return vec;
  7320. }
  7321. unsigned mask_len = cast(unsigned)index_count;
  7322. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  7323. for (isize i = 1; i < ce->args.count; i++) {
  7324. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7325. GB_ASSERT(is_type_integer(tv.type));
  7326. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7327. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  7328. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  7329. }
  7330. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  7331. LLVMValueRef v1 = vec.value;
  7332. LLVMValueRef v2 = vec.value;
  7333. lbValue res = {};
  7334. res.type = tv.type;
  7335. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  7336. return res;
  7337. }
  7338. lbAddr addr = lb_build_addr(p, ce->args[0]);
  7339. if (index_count == 0) {
  7340. return lb_addr_load(p, addr);
  7341. }
  7342. lbValue src = lb_addr_get_ptr(p, addr);
  7343. // TODO(bill): Should this be zeroed or not?
  7344. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  7345. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  7346. for (i32 i = 1; i < ce->args.count; i++) {
  7347. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7348. GB_ASSERT(is_type_integer(tv.type));
  7349. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7350. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  7351. i32 dst_index = i-1;
  7352. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  7353. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  7354. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  7355. }
  7356. return lb_addr_load(p, dst);
  7357. }
  7358. case BuiltinProc_complex: {
  7359. lbValue real = lb_build_expr(p, ce->args[0]);
  7360. lbValue imag = lb_build_expr(p, ce->args[1]);
  7361. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7362. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7363. Type *ft = base_complex_elem_type(tv.type);
  7364. real = lb_emit_conv(p, real, ft);
  7365. imag = lb_emit_conv(p, imag, ft);
  7366. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  7367. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  7368. return lb_emit_load(p, dst);
  7369. }
  7370. case BuiltinProc_quaternion: {
  7371. lbValue real = lb_build_expr(p, ce->args[0]);
  7372. lbValue imag = lb_build_expr(p, ce->args[1]);
  7373. lbValue jmag = lb_build_expr(p, ce->args[2]);
  7374. lbValue kmag = lb_build_expr(p, ce->args[3]);
  7375. // @QuaternionLayout
  7376. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7377. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7378. Type *ft = base_complex_elem_type(tv.type);
  7379. real = lb_emit_conv(p, real, ft);
  7380. imag = lb_emit_conv(p, imag, ft);
  7381. jmag = lb_emit_conv(p, jmag, ft);
  7382. kmag = lb_emit_conv(p, kmag, ft);
  7383. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  7384. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  7385. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  7386. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  7387. return lb_emit_load(p, dst);
  7388. }
  7389. case BuiltinProc_real: {
  7390. lbValue val = lb_build_expr(p, ce->args[0]);
  7391. if (is_type_complex(val.type)) {
  7392. lbValue real = lb_emit_struct_ev(p, val, 0);
  7393. return lb_emit_conv(p, real, tv.type);
  7394. } else if (is_type_quaternion(val.type)) {
  7395. // @QuaternionLayout
  7396. lbValue real = lb_emit_struct_ev(p, val, 3);
  7397. return lb_emit_conv(p, real, tv.type);
  7398. }
  7399. GB_PANIC("invalid type for real");
  7400. return {};
  7401. }
  7402. case BuiltinProc_imag: {
  7403. lbValue val = lb_build_expr(p, ce->args[0]);
  7404. if (is_type_complex(val.type)) {
  7405. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7406. return lb_emit_conv(p, imag, tv.type);
  7407. } else if (is_type_quaternion(val.type)) {
  7408. // @QuaternionLayout
  7409. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7410. return lb_emit_conv(p, imag, tv.type);
  7411. }
  7412. GB_PANIC("invalid type for imag");
  7413. return {};
  7414. }
  7415. case BuiltinProc_jmag: {
  7416. lbValue val = lb_build_expr(p, ce->args[0]);
  7417. if (is_type_quaternion(val.type)) {
  7418. // @QuaternionLayout
  7419. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7420. return lb_emit_conv(p, imag, tv.type);
  7421. }
  7422. GB_PANIC("invalid type for jmag");
  7423. return {};
  7424. }
  7425. case BuiltinProc_kmag: {
  7426. lbValue val = lb_build_expr(p, ce->args[0]);
  7427. if (is_type_quaternion(val.type)) {
  7428. // @QuaternionLayout
  7429. lbValue imag = lb_emit_struct_ev(p, val, 2);
  7430. return lb_emit_conv(p, imag, tv.type);
  7431. }
  7432. GB_PANIC("invalid type for kmag");
  7433. return {};
  7434. }
  7435. case BuiltinProc_conj: {
  7436. lbValue val = lb_build_expr(p, ce->args[0]);
  7437. lbValue res = {};
  7438. Type *t = val.type;
  7439. if (is_type_complex(t)) {
  7440. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7441. lbValue real = lb_emit_struct_ev(p, val, 0);
  7442. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7443. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7444. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  7445. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  7446. } else if (is_type_quaternion(t)) {
  7447. // @QuaternionLayout
  7448. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7449. lbValue real = lb_emit_struct_ev(p, val, 3);
  7450. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7451. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  7452. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  7453. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7454. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  7455. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  7456. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  7457. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  7458. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  7459. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  7460. }
  7461. return lb_emit_load(p, res);
  7462. }
  7463. case BuiltinProc_expand_to_tuple: {
  7464. lbValue val = lb_build_expr(p, ce->args[0]);
  7465. Type *t = base_type(val.type);
  7466. if (!is_type_tuple(tv.type)) {
  7467. if (t->kind == Type_Struct) {
  7468. GB_ASSERT(t->Struct.fields.count == 1);
  7469. return lb_emit_struct_ev(p, val, 0);
  7470. } else if (t->kind == Type_Array) {
  7471. GB_ASSERT(t->Array.count == 1);
  7472. return lb_emit_array_epi(p, val, 0);
  7473. } else {
  7474. GB_PANIC("Unknown type of expand_to_tuple");
  7475. }
  7476. }
  7477. GB_ASSERT(is_type_tuple(tv.type));
  7478. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  7479. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7480. if (t->kind == Type_Struct) {
  7481. for_array(src_index, t->Struct.fields) {
  7482. Entity *field = t->Struct.fields[src_index];
  7483. i32 field_index = field->Variable.field_index;
  7484. lbValue f = lb_emit_struct_ev(p, val, field_index);
  7485. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  7486. lb_emit_store(p, ep, f);
  7487. }
  7488. } else if (t->kind == Type_Array) {
  7489. // TODO(bill): Clean-up this code
  7490. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  7491. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  7492. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  7493. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  7494. lb_emit_store(p, ep, f);
  7495. }
  7496. } else {
  7497. GB_PANIC("Unknown type of expand_to_tuple");
  7498. }
  7499. return lb_emit_load(p, tuple);
  7500. }
  7501. case BuiltinProc_min: {
  7502. Type *t = type_of_expr(expr);
  7503. if (ce->args.count == 2) {
  7504. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7505. } else {
  7506. lbValue x = lb_build_expr(p, ce->args[0]);
  7507. for (isize i = 1; i < ce->args.count; i++) {
  7508. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  7509. }
  7510. return x;
  7511. }
  7512. }
  7513. case BuiltinProc_max: {
  7514. Type *t = type_of_expr(expr);
  7515. if (ce->args.count == 2) {
  7516. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7517. } else {
  7518. lbValue x = lb_build_expr(p, ce->args[0]);
  7519. for (isize i = 1; i < ce->args.count; i++) {
  7520. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  7521. }
  7522. return x;
  7523. }
  7524. }
  7525. case BuiltinProc_abs: {
  7526. lbValue x = lb_build_expr(p, ce->args[0]);
  7527. Type *t = x.type;
  7528. if (is_type_unsigned(t)) {
  7529. return x;
  7530. }
  7531. if (is_type_quaternion(t)) {
  7532. i64 sz = 8*type_size_of(t);
  7533. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7534. args[0] = x;
  7535. switch (sz) {
  7536. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  7537. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  7538. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  7539. }
  7540. GB_PANIC("Unknown complex type");
  7541. } else if (is_type_complex(t)) {
  7542. i64 sz = 8*type_size_of(t);
  7543. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7544. args[0] = x;
  7545. switch (sz) {
  7546. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  7547. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  7548. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  7549. }
  7550. GB_PANIC("Unknown complex type");
  7551. } else if (is_type_float(t)) {
  7552. i64 sz = 8*type_size_of(t);
  7553. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7554. args[0] = x;
  7555. switch (sz) {
  7556. case 16: return lb_emit_runtime_call(p, "abs_f16", args);
  7557. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  7558. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  7559. }
  7560. GB_PANIC("Unknown float type");
  7561. }
  7562. lbValue zero = lb_const_nil(p->module, t);
  7563. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  7564. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  7565. return lb_emit_select(p, cond, neg, x);
  7566. }
  7567. case BuiltinProc_clamp:
  7568. return lb_emit_clamp(p, type_of_expr(expr),
  7569. lb_build_expr(p, ce->args[0]),
  7570. lb_build_expr(p, ce->args[1]),
  7571. lb_build_expr(p, ce->args[2]));
  7572. case BuiltinProc_soa_zip:
  7573. return lb_soa_zip(p, ce, tv);
  7574. case BuiltinProc_soa_unzip:
  7575. return lb_soa_unzip(p, ce, tv);
  7576. // "Intrinsics"
  7577. case BuiltinProc_alloca:
  7578. {
  7579. lbValue sz = lb_build_expr(p, ce->args[0]);
  7580. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  7581. lbValue res = {};
  7582. res.type = t_u8_ptr;
  7583. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  7584. LLVMSetAlignment(res.value, cast(unsigned)al);
  7585. return res;
  7586. }
  7587. case BuiltinProc_cpu_relax:
  7588. if (build_context.metrics.arch == TargetArch_386 ||
  7589. build_context.metrics.arch == TargetArch_amd64) {
  7590. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7591. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7592. cast(char *)"pause", 5,
  7593. cast(char *)"", 0,
  7594. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7595. LLVMInlineAsmDialectATT
  7596. );
  7597. GB_ASSERT(the_asm != nullptr);
  7598. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7599. }
  7600. return {};
  7601. case BuiltinProc_atomic_fence:
  7602. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  7603. return {};
  7604. case BuiltinProc_atomic_fence_acq:
  7605. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  7606. return {};
  7607. case BuiltinProc_atomic_fence_rel:
  7608. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  7609. return {};
  7610. case BuiltinProc_atomic_fence_acqrel:
  7611. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  7612. return {};
  7613. case BuiltinProc_volatile_store:
  7614. case BuiltinProc_atomic_store:
  7615. case BuiltinProc_atomic_store_rel:
  7616. case BuiltinProc_atomic_store_relaxed:
  7617. case BuiltinProc_atomic_store_unordered: {
  7618. lbValue dst = lb_build_expr(p, ce->args[0]);
  7619. lbValue val = lb_build_expr(p, ce->args[1]);
  7620. val = lb_emit_conv(p, val, type_deref(dst.type));
  7621. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  7622. switch (id) {
  7623. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  7624. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7625. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  7626. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7627. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7628. }
  7629. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7630. return {};
  7631. }
  7632. case BuiltinProc_volatile_load:
  7633. case BuiltinProc_atomic_load:
  7634. case BuiltinProc_atomic_load_acq:
  7635. case BuiltinProc_atomic_load_relaxed:
  7636. case BuiltinProc_atomic_load_unordered: {
  7637. lbValue dst = lb_build_expr(p, ce->args[0]);
  7638. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  7639. switch (id) {
  7640. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  7641. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7642. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  7643. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7644. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7645. }
  7646. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7647. lbValue res = {};
  7648. res.value = instr;
  7649. res.type = type_deref(dst.type);
  7650. return res;
  7651. }
  7652. case BuiltinProc_atomic_add:
  7653. case BuiltinProc_atomic_add_acq:
  7654. case BuiltinProc_atomic_add_rel:
  7655. case BuiltinProc_atomic_add_acqrel:
  7656. case BuiltinProc_atomic_add_relaxed:
  7657. case BuiltinProc_atomic_sub:
  7658. case BuiltinProc_atomic_sub_acq:
  7659. case BuiltinProc_atomic_sub_rel:
  7660. case BuiltinProc_atomic_sub_acqrel:
  7661. case BuiltinProc_atomic_sub_relaxed:
  7662. case BuiltinProc_atomic_and:
  7663. case BuiltinProc_atomic_and_acq:
  7664. case BuiltinProc_atomic_and_rel:
  7665. case BuiltinProc_atomic_and_acqrel:
  7666. case BuiltinProc_atomic_and_relaxed:
  7667. case BuiltinProc_atomic_nand:
  7668. case BuiltinProc_atomic_nand_acq:
  7669. case BuiltinProc_atomic_nand_rel:
  7670. case BuiltinProc_atomic_nand_acqrel:
  7671. case BuiltinProc_atomic_nand_relaxed:
  7672. case BuiltinProc_atomic_or:
  7673. case BuiltinProc_atomic_or_acq:
  7674. case BuiltinProc_atomic_or_rel:
  7675. case BuiltinProc_atomic_or_acqrel:
  7676. case BuiltinProc_atomic_or_relaxed:
  7677. case BuiltinProc_atomic_xor:
  7678. case BuiltinProc_atomic_xor_acq:
  7679. case BuiltinProc_atomic_xor_rel:
  7680. case BuiltinProc_atomic_xor_acqrel:
  7681. case BuiltinProc_atomic_xor_relaxed:
  7682. case BuiltinProc_atomic_xchg:
  7683. case BuiltinProc_atomic_xchg_acq:
  7684. case BuiltinProc_atomic_xchg_rel:
  7685. case BuiltinProc_atomic_xchg_acqrel:
  7686. case BuiltinProc_atomic_xchg_relaxed: {
  7687. lbValue dst = lb_build_expr(p, ce->args[0]);
  7688. lbValue val = lb_build_expr(p, ce->args[1]);
  7689. val = lb_emit_conv(p, val, type_deref(dst.type));
  7690. LLVMAtomicRMWBinOp op = {};
  7691. LLVMAtomicOrdering ordering = {};
  7692. switch (id) {
  7693. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7694. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  7695. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  7696. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7697. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  7698. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7699. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  7700. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  7701. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7702. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  7703. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7704. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  7705. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  7706. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7707. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  7708. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7709. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  7710. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  7711. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7712. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  7713. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7714. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  7715. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  7716. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7717. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  7718. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7719. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  7720. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  7721. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7722. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  7723. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7724. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  7725. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  7726. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7727. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  7728. }
  7729. lbValue res = {};
  7730. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  7731. res.type = tv.type;
  7732. return res;
  7733. }
  7734. case BuiltinProc_atomic_cxchg:
  7735. case BuiltinProc_atomic_cxchg_acq:
  7736. case BuiltinProc_atomic_cxchg_rel:
  7737. case BuiltinProc_atomic_cxchg_acqrel:
  7738. case BuiltinProc_atomic_cxchg_relaxed:
  7739. case BuiltinProc_atomic_cxchg_failrelaxed:
  7740. case BuiltinProc_atomic_cxchg_failacq:
  7741. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  7742. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  7743. case BuiltinProc_atomic_cxchgweak:
  7744. case BuiltinProc_atomic_cxchgweak_acq:
  7745. case BuiltinProc_atomic_cxchgweak_rel:
  7746. case BuiltinProc_atomic_cxchgweak_acqrel:
  7747. case BuiltinProc_atomic_cxchgweak_relaxed:
  7748. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  7749. case BuiltinProc_atomic_cxchgweak_failacq:
  7750. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  7751. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  7752. Type *type = expr->tav.type;
  7753. lbValue address = lb_build_expr(p, ce->args[0]);
  7754. Type *elem = type_deref(address.type);
  7755. lbValue old_value = lb_build_expr(p, ce->args[1]);
  7756. lbValue new_value = lb_build_expr(p, ce->args[2]);
  7757. old_value = lb_emit_conv(p, old_value, elem);
  7758. new_value = lb_emit_conv(p, new_value, elem);
  7759. LLVMAtomicOrdering success_ordering = {};
  7760. LLVMAtomicOrdering failure_ordering = {};
  7761. LLVMBool weak = false;
  7762. switch (id) {
  7763. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7764. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7765. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7766. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7767. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7768. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7769. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  7770. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7771. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7772. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7773. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7774. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7775. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7776. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7777. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7778. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  7779. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7780. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7781. }
  7782. // TODO(bill): Figure out how to make it weak
  7783. LLVMBool single_threaded = weak;
  7784. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  7785. p->builder, address.value,
  7786. old_value.value, new_value.value,
  7787. success_ordering,
  7788. failure_ordering,
  7789. single_threaded
  7790. );
  7791. GB_ASSERT(tv.type->kind == Type_Tuple);
  7792. Type *fix_typed = alloc_type_tuple();
  7793. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  7794. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  7795. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  7796. lbValue res = {};
  7797. res.value = value;
  7798. res.type = fix_typed;
  7799. return res;
  7800. }
  7801. case BuiltinProc_type_equal_proc:
  7802. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  7803. case BuiltinProc_type_hasher_proc:
  7804. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  7805. case BuiltinProc_fixed_point_mul:
  7806. case BuiltinProc_fixed_point_div:
  7807. case BuiltinProc_fixed_point_mul_sat:
  7808. case BuiltinProc_fixed_point_div_sat:
  7809. {
  7810. bool do_bswap = is_type_different_to_arch_endianness(tv.type);
  7811. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  7812. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  7813. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  7814. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), platform_type);
  7815. char const *name = nullptr;
  7816. if (is_type_unsigned(tv.type)) {
  7817. switch (id) {
  7818. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  7819. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  7820. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  7821. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  7822. }
  7823. } else {
  7824. switch (id) {
  7825. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  7826. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  7827. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  7828. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  7829. }
  7830. }
  7831. GB_ASSERT(name != nullptr);
  7832. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  7833. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  7834. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  7835. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  7836. lbValue res = {};
  7837. LLVMValueRef args[3] = {};
  7838. args[0] = x.value;
  7839. args[1] = y.value;
  7840. args[2] = scale.value;
  7841. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  7842. res.type = platform_type;
  7843. return lb_emit_conv(p, res, tv.type);
  7844. }
  7845. }
  7846. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  7847. return {};
  7848. }
  7849. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  7850. switch (param_value.kind) {
  7851. case ParameterValue_Constant:
  7852. if (is_type_constant_type(parameter_type)) {
  7853. return lb_const_value(p->module, parameter_type, param_value.value);
  7854. } else {
  7855. ExactValue ev = param_value.value;
  7856. lbValue arg = {};
  7857. Type *type = type_of_expr(param_value.original_ast_expr);
  7858. if (type != nullptr) {
  7859. arg = lb_const_value(p->module, type, ev);
  7860. } else {
  7861. arg = lb_const_value(p->module, parameter_type, param_value.value);
  7862. }
  7863. return lb_emit_conv(p, arg, parameter_type);
  7864. }
  7865. case ParameterValue_Nil:
  7866. return lb_const_nil(p->module, parameter_type);
  7867. case ParameterValue_Location:
  7868. {
  7869. String proc_name = {};
  7870. if (p->entity != nullptr) {
  7871. proc_name = p->entity->token.string;
  7872. }
  7873. return lb_emit_source_code_location(p, proc_name, pos);
  7874. }
  7875. case ParameterValue_Value:
  7876. return lb_build_expr(p, param_value.ast_value);
  7877. }
  7878. return lb_const_nil(p->module, parameter_type);
  7879. }
  7880. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  7881. lbModule *m = p->module;
  7882. TypeAndValue tv = type_and_value_of_expr(expr);
  7883. ast_node(ce, CallExpr, expr);
  7884. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  7885. AddressingMode proc_mode = proc_tv.mode;
  7886. if (proc_mode == Addressing_Type) {
  7887. GB_ASSERT(ce->args.count == 1);
  7888. lbValue x = lb_build_expr(p, ce->args[0]);
  7889. lbValue y = lb_emit_conv(p, x, tv.type);
  7890. return y;
  7891. }
  7892. Ast *pexpr = unparen_expr(ce->proc);
  7893. if (proc_mode == Addressing_Builtin) {
  7894. Entity *e = entity_of_node(pexpr);
  7895. BuiltinProcId id = BuiltinProc_Invalid;
  7896. if (e != nullptr) {
  7897. id = cast(BuiltinProcId)e->Builtin.id;
  7898. } else {
  7899. id = BuiltinProc_DIRECTIVE;
  7900. }
  7901. return lb_build_builtin_proc(p, expr, tv, id);
  7902. }
  7903. // NOTE(bill): Regular call
  7904. lbValue value = {};
  7905. Ast *proc_expr = unparen_expr(ce->proc);
  7906. if (proc_expr->tav.mode == Addressing_Constant) {
  7907. ExactValue v = proc_expr->tav.value;
  7908. switch (v.kind) {
  7909. case ExactValue_Integer:
  7910. {
  7911. u64 u = big_int_to_u64(&v.value_integer);
  7912. lbValue x = {};
  7913. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7914. x.type = t_uintptr;
  7915. x = lb_emit_conv(p, x, t_rawptr);
  7916. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7917. break;
  7918. }
  7919. case ExactValue_Pointer:
  7920. {
  7921. u64 u = cast(u64)v.value_pointer;
  7922. lbValue x = {};
  7923. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7924. x.type = t_uintptr;
  7925. x = lb_emit_conv(p, x, t_rawptr);
  7926. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7927. break;
  7928. }
  7929. }
  7930. }
  7931. Entity *proc_entity = entity_of_node(proc_expr);
  7932. if (proc_entity != nullptr) {
  7933. if (proc_entity->flags & EntityFlag_Disabled) {
  7934. return {};
  7935. }
  7936. }
  7937. if (value.value == nullptr) {
  7938. value = lb_build_expr(p, proc_expr);
  7939. }
  7940. GB_ASSERT(value.value != nullptr);
  7941. Type *proc_type_ = base_type(value.type);
  7942. GB_ASSERT(proc_type_->kind == Type_Proc);
  7943. TypeProc *pt = &proc_type_->Proc;
  7944. set_procedure_abi_types(proc_type_);
  7945. if (is_call_expr_field_value(ce)) {
  7946. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  7947. for_array(arg_index, ce->args) {
  7948. Ast *arg = ce->args[arg_index];
  7949. ast_node(fv, FieldValue, arg);
  7950. GB_ASSERT(fv->field->kind == Ast_Ident);
  7951. String name = fv->field->Ident.token.string;
  7952. isize index = lookup_procedure_parameter(pt, name);
  7953. GB_ASSERT(index >= 0);
  7954. TypeAndValue tav = type_and_value_of_expr(fv->value);
  7955. if (tav.mode == Addressing_Type) {
  7956. args[index] = lb_const_nil(m, tav.type);
  7957. } else {
  7958. args[index] = lb_build_expr(p, fv->value);
  7959. }
  7960. }
  7961. TypeTuple *params = &pt->params->Tuple;
  7962. for (isize i = 0; i < args.count; i++) {
  7963. Entity *e = params->variables[i];
  7964. if (e->kind == Entity_TypeName) {
  7965. args[i] = lb_const_nil(m, e->type);
  7966. } else if (e->kind == Entity_Constant) {
  7967. continue;
  7968. } else {
  7969. GB_ASSERT(e->kind == Entity_Variable);
  7970. if (args[i].value == nullptr) {
  7971. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7972. } else {
  7973. args[i] = lb_emit_conv(p, args[i], e->type);
  7974. }
  7975. }
  7976. }
  7977. for (isize i = 0; i < args.count; i++) {
  7978. Entity *e = params->variables[i];
  7979. if (args[i].type == nullptr) {
  7980. continue;
  7981. } else if (is_type_untyped_nil(args[i].type)) {
  7982. args[i] = lb_const_nil(m, e->type);
  7983. } else if (is_type_untyped_undef(args[i].type)) {
  7984. args[i] = lb_const_undef(m, e->type);
  7985. }
  7986. }
  7987. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  7988. }
  7989. isize arg_index = 0;
  7990. isize arg_count = 0;
  7991. for_array(i, ce->args) {
  7992. Ast *arg = ce->args[i];
  7993. TypeAndValue tav = type_and_value_of_expr(arg);
  7994. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  7995. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  7996. Type *at = tav.type;
  7997. if (at->kind == Type_Tuple) {
  7998. arg_count += at->Tuple.variables.count;
  7999. } else {
  8000. arg_count++;
  8001. }
  8002. }
  8003. isize param_count = 0;
  8004. if (pt->params) {
  8005. GB_ASSERT(pt->params->kind == Type_Tuple);
  8006. param_count = pt->params->Tuple.variables.count;
  8007. }
  8008. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  8009. isize variadic_index = pt->variadic_index;
  8010. bool variadic = pt->variadic && variadic_index >= 0;
  8011. bool vari_expand = ce->ellipsis.pos.line != 0;
  8012. bool is_c_vararg = pt->c_vararg;
  8013. String proc_name = {};
  8014. if (p->entity != nullptr) {
  8015. proc_name = p->entity->token.string;
  8016. }
  8017. TokenPos pos = ast_token(ce->proc).pos;
  8018. TypeTuple *param_tuple = nullptr;
  8019. if (pt->params) {
  8020. GB_ASSERT(pt->params->kind == Type_Tuple);
  8021. param_tuple = &pt->params->Tuple;
  8022. }
  8023. for_array(i, ce->args) {
  8024. Ast *arg = ce->args[i];
  8025. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  8026. if (arg_tv.mode == Addressing_Type) {
  8027. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  8028. } else {
  8029. lbValue a = lb_build_expr(p, arg);
  8030. Type *at = a.type;
  8031. if (at->kind == Type_Tuple) {
  8032. for_array(i, at->Tuple.variables) {
  8033. Entity *e = at->Tuple.variables[i];
  8034. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  8035. args[arg_index++] = v;
  8036. }
  8037. } else {
  8038. args[arg_index++] = a;
  8039. }
  8040. }
  8041. }
  8042. if (param_count > 0) {
  8043. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  8044. GB_ASSERT(param_count < 1000000);
  8045. if (arg_count < param_count) {
  8046. isize end = cast(isize)param_count;
  8047. if (variadic) {
  8048. end = variadic_index;
  8049. }
  8050. while (arg_index < end) {
  8051. Entity *e = param_tuple->variables[arg_index];
  8052. GB_ASSERT(e->kind == Entity_Variable);
  8053. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8054. }
  8055. }
  8056. if (is_c_vararg) {
  8057. GB_ASSERT(variadic);
  8058. GB_ASSERT(!vari_expand);
  8059. isize i = 0;
  8060. for (; i < variadic_index; i++) {
  8061. Entity *e = param_tuple->variables[i];
  8062. if (e->kind == Entity_Variable) {
  8063. args[i] = lb_emit_conv(p, args[i], e->type);
  8064. }
  8065. }
  8066. Type *variadic_type = param_tuple->variables[i]->type;
  8067. GB_ASSERT(is_type_slice(variadic_type));
  8068. variadic_type = base_type(variadic_type)->Slice.elem;
  8069. if (!is_type_any(variadic_type)) {
  8070. for (; i < arg_count; i++) {
  8071. args[i] = lb_emit_conv(p, args[i], variadic_type);
  8072. }
  8073. } else {
  8074. for (; i < arg_count; i++) {
  8075. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  8076. }
  8077. }
  8078. } else if (variadic) {
  8079. isize i = 0;
  8080. for (; i < variadic_index; i++) {
  8081. Entity *e = param_tuple->variables[i];
  8082. if (e->kind == Entity_Variable) {
  8083. args[i] = lb_emit_conv(p, args[i], e->type);
  8084. }
  8085. }
  8086. if (!vari_expand) {
  8087. Type *variadic_type = param_tuple->variables[i]->type;
  8088. GB_ASSERT(is_type_slice(variadic_type));
  8089. variadic_type = base_type(variadic_type)->Slice.elem;
  8090. for (; i < arg_count; i++) {
  8091. args[i] = lb_emit_conv(p, args[i], variadic_type);
  8092. }
  8093. }
  8094. } else {
  8095. for (isize i = 0; i < param_count; i++) {
  8096. Entity *e = param_tuple->variables[i];
  8097. if (e->kind == Entity_Variable) {
  8098. if (args[i].value == nullptr) {
  8099. continue;
  8100. }
  8101. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  8102. args[i] = lb_emit_conv(p, args[i], e->type);
  8103. }
  8104. }
  8105. }
  8106. if (variadic && !vari_expand && !is_c_vararg) {
  8107. // variadic call argument generation
  8108. Type *slice_type = param_tuple->variables[variadic_index]->type;
  8109. Type *elem_type = base_type(slice_type)->Slice.elem;
  8110. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  8111. isize slice_len = arg_count+1 - (variadic_index+1);
  8112. if (slice_len > 0) {
  8113. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  8114. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  8115. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  8116. lb_emit_store(p, addr, args[i]);
  8117. }
  8118. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  8119. lbValue len = lb_const_int(m, t_int, slice_len);
  8120. lb_fill_slice(p, slice, base_elem, len);
  8121. }
  8122. arg_count = param_count;
  8123. args[variadic_index] = lb_addr_load(p, slice);
  8124. }
  8125. }
  8126. if (variadic && variadic_index+1 < param_count) {
  8127. for (isize i = variadic_index+1; i < param_count; i++) {
  8128. Entity *e = param_tuple->variables[i];
  8129. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8130. }
  8131. }
  8132. isize final_count = param_count;
  8133. if (is_c_vararg) {
  8134. final_count = arg_count;
  8135. }
  8136. if (param_tuple != nullptr) {
  8137. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  8138. Entity *e = param_tuple->variables[i];
  8139. if (args[i].type == nullptr) {
  8140. continue;
  8141. } else if (is_type_untyped_nil(args[i].type)) {
  8142. args[i] = lb_const_nil(m, e->type);
  8143. } else if (is_type_untyped_undef(args[i].type)) {
  8144. args[i] = lb_const_undef(m, e->type);
  8145. }
  8146. }
  8147. }
  8148. auto call_args = array_slice(args, 0, final_count);
  8149. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  8150. }
  8151. bool lb_is_const(lbValue value) {
  8152. LLVMValueRef v = value.value;
  8153. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  8154. // TODO(bill): Is this correct behaviour?
  8155. return true;
  8156. }
  8157. if (LLVMIsConstant(v)) {
  8158. return true;
  8159. }
  8160. return false;
  8161. }
  8162. bool lb_is_const_or_global(lbValue value) {
  8163. if (lb_is_const(value)) {
  8164. return true;
  8165. }
  8166. if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
  8167. LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
  8168. if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
  8169. return false;
  8170. }
  8171. LLVMTypeRef elem = LLVMGetElementType(t);
  8172. return lb_is_type_kind(elem, LLVMFunctionTypeKind);
  8173. }
  8174. return false;
  8175. }
  8176. bool lb_is_const_nil(lbValue value) {
  8177. LLVMValueRef v = value.value;
  8178. if (LLVMIsConstant(v)) {
  8179. if (LLVMIsAConstantAggregateZero(v)) {
  8180. return true;
  8181. } else if (LLVMIsAConstantPointerNull(v)) {
  8182. return true;
  8183. }
  8184. }
  8185. return false;
  8186. }
  8187. String lb_get_const_string(lbModule *m, lbValue value) {
  8188. GB_ASSERT(lb_is_const(value));
  8189. Type *t = base_type(value.type);
  8190. GB_ASSERT(are_types_identical(t, t_string));
  8191. unsigned ptr_indices[1] = {0};
  8192. unsigned len_indices[1] = {1};
  8193. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  8194. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  8195. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  8196. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  8197. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  8198. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  8199. size_t length = 0;
  8200. char const *text = LLVMGetAsString(underlying_ptr, &length);
  8201. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  8202. return make_string(cast(u8 const *)text, real_length);
  8203. }
  8204. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  8205. GB_ASSERT(is_type_pointer(addr.type));
  8206. Type *type = type_deref(addr.type);
  8207. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  8208. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  8209. }
  8210. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  8211. AstPackage *pkg = m->info->runtime_package;
  8212. Entity *e = scope_lookup_current(pkg->scope, name);
  8213. lbValue *found = nullptr;
  8214. if (m != e->code_gen_module) {
  8215. gb_mutex_lock(&m->mutex);
  8216. }
  8217. GB_ASSERT(e->code_gen_module != nullptr);
  8218. found = map_get(&e->code_gen_module->values, hash_entity(e));
  8219. if (m != e->code_gen_module) {
  8220. gb_mutex_unlock(&m->mutex);
  8221. }
  8222. GB_ASSERT(found != nullptr);
  8223. return found->value;
  8224. }
  8225. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  8226. Type *vt = core_type(value.type);
  8227. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  8228. // TODO(bill): lb_emit_byte_swap
  8229. lbValue res = {};
  8230. res.type = platform_type;
  8231. res.value = value.value;
  8232. int sz = cast(int)type_size_of(vt);
  8233. if (sz > 1) {
  8234. if (is_type_float(platform_type)) {
  8235. String name = {};
  8236. switch (sz) {
  8237. case 2: name = str_lit("bswap_f16"); break;
  8238. case 4: name = str_lit("bswap_f32"); break;
  8239. case 8: name = str_lit("bswap_f64"); break;
  8240. default: GB_PANIC("unhandled byteswap size"); break;
  8241. }
  8242. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  8243. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  8244. } else {
  8245. GB_ASSERT(is_type_integer(platform_type));
  8246. String name = {};
  8247. switch (sz) {
  8248. case 2: name = str_lit("bswap_16"); break;
  8249. case 4: name = str_lit("bswap_32"); break;
  8250. case 8: name = str_lit("bswap_64"); break;
  8251. case 16: name = str_lit("bswap_128"); break;
  8252. default: GB_PANIC("unhandled byteswap size"); break;
  8253. }
  8254. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  8255. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  8256. }
  8257. }
  8258. return res;
  8259. }
  8260. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  8261. lbLoopData data = {};
  8262. lbValue max = lb_const_int(p->module, t_int, count);
  8263. data.idx_addr = lb_add_local_generated(p, index_type, true);
  8264. data.body = lb_create_block(p, "loop.body");
  8265. data.done = lb_create_block(p, "loop.done");
  8266. data.loop = lb_create_block(p, "loop.loop");
  8267. lb_emit_jump(p, data.loop);
  8268. lb_start_block(p, data.loop);
  8269. data.idx = lb_addr_load(p, data.idx_addr);
  8270. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  8271. lb_emit_if(p, cond, data.body, data.done);
  8272. lb_start_block(p, data.body);
  8273. return data;
  8274. }
  8275. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  8276. if (data.idx_addr.addr.value != nullptr) {
  8277. lb_emit_increment(p, data.idx_addr.addr);
  8278. lb_emit_jump(p, data.loop);
  8279. lb_start_block(p, data.done);
  8280. }
  8281. }
  8282. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  8283. lbValue res = {};
  8284. res.type = t_llvm_bool;
  8285. Type *t = x.type;
  8286. if (is_type_pointer(t)) {
  8287. if (op_kind == Token_CmpEq) {
  8288. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8289. } else if (op_kind == Token_NotEq) {
  8290. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8291. }
  8292. return res;
  8293. } else if (is_type_cstring(t)) {
  8294. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  8295. if (op_kind == Token_CmpEq) {
  8296. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  8297. } else if (op_kind == Token_NotEq) {
  8298. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  8299. }
  8300. return res;
  8301. } else if (is_type_proc(t)) {
  8302. if (op_kind == Token_CmpEq) {
  8303. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8304. } else if (op_kind == Token_NotEq) {
  8305. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8306. }
  8307. return res;
  8308. } else if (is_type_any(t)) {
  8309. // TODO(bill): is this correct behaviour for nil comparison for any?
  8310. lbValue data = lb_emit_struct_ev(p, x, 0);
  8311. lbValue ti = lb_emit_struct_ev(p, x, 1);
  8312. if (op_kind == Token_CmpEq) {
  8313. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  8314. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  8315. res.value = LLVMBuildOr(p->builder, a, b, "");
  8316. return res;
  8317. } else if (op_kind == Token_NotEq) {
  8318. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  8319. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  8320. res.value = LLVMBuildAnd(p->builder, a, b, "");
  8321. return res;
  8322. }
  8323. } else if (is_type_slice(t)) {
  8324. lbValue len = lb_emit_struct_ev(p, x, 1);
  8325. if (op_kind == Token_CmpEq) {
  8326. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8327. return res;
  8328. } else if (op_kind == Token_NotEq) {
  8329. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8330. return res;
  8331. }
  8332. } else if (is_type_dynamic_array(t)) {
  8333. lbValue cap = lb_emit_struct_ev(p, x, 2);
  8334. if (op_kind == Token_CmpEq) {
  8335. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8336. return res;
  8337. } else if (op_kind == Token_NotEq) {
  8338. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8339. return res;
  8340. }
  8341. } else if (is_type_map(t)) {
  8342. lbValue cap = lb_map_cap(p, x);
  8343. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  8344. } else if (is_type_union(t)) {
  8345. if (type_size_of(t) == 0) {
  8346. if (op_kind == Token_CmpEq) {
  8347. return lb_const_bool(p->module, t_llvm_bool, true);
  8348. } else if (op_kind == Token_NotEq) {
  8349. return lb_const_bool(p->module, t_llvm_bool, false);
  8350. }
  8351. } else {
  8352. lbValue tag = lb_emit_union_tag_value(p, x);
  8353. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  8354. }
  8355. } else if (is_type_typeid(t)) {
  8356. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  8357. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  8358. } else if (is_type_soa_struct(t)) {
  8359. Type *bt = base_type(t);
  8360. if (bt->Struct.soa_kind == StructSoa_Slice) {
  8361. lbValue len = lb_soa_struct_len(p, x);
  8362. if (op_kind == Token_CmpEq) {
  8363. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8364. return res;
  8365. } else if (op_kind == Token_NotEq) {
  8366. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8367. return res;
  8368. }
  8369. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  8370. lbValue cap = lb_soa_struct_cap(p, x);
  8371. if (op_kind == Token_CmpEq) {
  8372. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8373. return res;
  8374. } else if (op_kind == Token_NotEq) {
  8375. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8376. return res;
  8377. }
  8378. }
  8379. } else if (is_type_struct(t) && type_has_nil(t)) {
  8380. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8381. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  8382. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8383. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  8384. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  8385. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  8386. return res;
  8387. }
  8388. return {};
  8389. }
  8390. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  8391. Type *original_type = type;
  8392. type = base_type(type);
  8393. GB_ASSERT(is_type_comparable(type));
  8394. Type *pt = alloc_type_pointer(type);
  8395. LLVMTypeRef ptr_type = lb_type(m, pt);
  8396. auto key = hash_type(type);
  8397. lbProcedure **found = map_get(&m->equal_procs, key);
  8398. lbProcedure *compare_proc = nullptr;
  8399. if (found) {
  8400. compare_proc = *found;
  8401. GB_ASSERT(compare_proc != nullptr);
  8402. return {compare_proc->value, compare_proc->type};
  8403. }
  8404. static u32 proc_index = 0;
  8405. char buf[16] = {};
  8406. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  8407. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8408. String proc_name = make_string_c(str);
  8409. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  8410. map_set(&m->equal_procs, key, p);
  8411. lb_begin_procedure_body(p);
  8412. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8413. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8414. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  8415. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  8416. lbValue lhs = {x, pt};
  8417. lbValue rhs = {y, pt};
  8418. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  8419. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  8420. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  8421. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  8422. lb_start_block(p, block_same_ptr);
  8423. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8424. lb_start_block(p, block_diff_ptr);
  8425. if (type->kind == Type_Struct) {
  8426. type_set_offsets(type);
  8427. lbBlock *block_false = lb_create_block(p, "bfalse");
  8428. lbValue res = lb_const_bool(m, t_bool, true);
  8429. for_array(i, type->Struct.fields) {
  8430. lbBlock *next_block = lb_create_block(p, "btrue");
  8431. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  8432. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  8433. lbValue left = lb_emit_load(p, pleft);
  8434. lbValue right = lb_emit_load(p, pright);
  8435. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8436. lb_emit_if(p, ok, next_block, block_false);
  8437. lb_emit_jump(p, next_block);
  8438. lb_start_block(p, next_block);
  8439. }
  8440. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8441. lb_start_block(p, block_false);
  8442. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  8443. } else {
  8444. lbValue left = lb_emit_load(p, lhs);
  8445. lbValue right = lb_emit_load(p, rhs);
  8446. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8447. ok = lb_emit_conv(p, ok, t_bool);
  8448. LLVMBuildRet(p->builder, ok.value);
  8449. }
  8450. lb_end_procedure_body(p);
  8451. compare_proc = p;
  8452. return {compare_proc->value, compare_proc->type};
  8453. }
  8454. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  8455. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  8456. i64 sz = type_size_of(type);
  8457. if (1 <= sz && sz <= 16) {
  8458. char name[20] = {};
  8459. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  8460. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8461. args[0] = data;
  8462. args[1] = seed;
  8463. return lb_emit_runtime_call(p, name, args);
  8464. }
  8465. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8466. args[0] = data;
  8467. args[1] = seed;
  8468. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  8469. return lb_emit_runtime_call(p, "default_hasher_n", args);
  8470. }
  8471. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  8472. Type *original_type = type;
  8473. type = core_type(type);
  8474. GB_ASSERT(is_type_valid_for_keys(type));
  8475. Type *pt = alloc_type_pointer(type);
  8476. LLVMTypeRef ptr_type = lb_type(m, pt);
  8477. auto key = hash_type(type);
  8478. lbProcedure **found = map_get(&m->hasher_procs, key);
  8479. if (found) {
  8480. GB_ASSERT(*found != nullptr);
  8481. return {(*found)->value, (*found)->type};
  8482. }
  8483. static u32 proc_index = 0;
  8484. char buf[16] = {};
  8485. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  8486. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8487. String proc_name = make_string_c(str);
  8488. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  8489. map_set(&m->hasher_procs, key, p);
  8490. lb_begin_procedure_body(p);
  8491. defer (lb_end_procedure_body(p));
  8492. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8493. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8494. lbValue data = {x, t_rawptr};
  8495. lbValue seed = {y, t_uintptr};
  8496. if (is_type_simple_compare(type)) {
  8497. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  8498. LLVMBuildRet(p->builder, res.value);
  8499. return {p->value, p->type};
  8500. }
  8501. if (type->kind == Type_Struct) {
  8502. type_set_offsets(type);
  8503. data = lb_emit_conv(p, data, t_u8_ptr);
  8504. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8505. for_array(i, type->Struct.fields) {
  8506. i64 offset = type->Struct.offsets[i];
  8507. Entity *field = type->Struct.fields[i];
  8508. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  8509. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  8510. args[0] = ptr;
  8511. args[1] = seed;
  8512. seed = lb_emit_call(p, field_hasher, args);
  8513. }
  8514. LLVMBuildRet(p->builder, seed.value);
  8515. } else if (type->kind == Type_Array) {
  8516. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  8517. lb_addr_store(p, pres, seed);
  8518. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8519. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  8520. auto loop_data = lb_loop_start(p, type->Array.count, t_i32);
  8521. data = lb_emit_conv(p, data, pt);
  8522. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8523. args[0] = ptr;
  8524. args[1] = lb_addr_load(p, pres);
  8525. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8526. lb_addr_store(p, pres, new_seed);
  8527. lb_loop_end(p, loop_data);
  8528. lbValue res = lb_addr_load(p, pres);
  8529. LLVMBuildRet(p->builder, res.value);
  8530. } else if (type->kind == Type_EnumeratedArray) {
  8531. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  8532. lb_addr_store(p, res, seed);
  8533. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8534. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  8535. auto loop_data = lb_loop_start(p, type->EnumeratedArray.count, t_i32);
  8536. data = lb_emit_conv(p, data, pt);
  8537. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8538. args[0] = ptr;
  8539. args[1] = lb_addr_load(p, res);
  8540. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8541. lb_addr_store(p, res, new_seed);
  8542. lb_loop_end(p, loop_data);
  8543. lbValue vres = lb_addr_load(p, res);
  8544. LLVMBuildRet(p->builder, vres.value);
  8545. } else if (is_type_cstring(type)) {
  8546. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8547. args[0] = data;
  8548. args[1] = seed;
  8549. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  8550. LLVMBuildRet(p->builder, res.value);
  8551. } else if (is_type_string(type)) {
  8552. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8553. args[0] = data;
  8554. args[1] = seed;
  8555. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  8556. LLVMBuildRet(p->builder, res.value);
  8557. } else {
  8558. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  8559. }
  8560. return {p->value, p->type};
  8561. }
  8562. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  8563. Type *a = core_type(left.type);
  8564. Type *b = core_type(right.type);
  8565. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  8566. lbValue nil_check = {};
  8567. if (is_type_untyped_nil(left.type)) {
  8568. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  8569. } else if (is_type_untyped_nil(right.type)) {
  8570. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  8571. }
  8572. if (nil_check.value != nullptr) {
  8573. return nil_check;
  8574. }
  8575. if (are_types_identical(a, b)) {
  8576. // NOTE(bill): No need for a conversion
  8577. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  8578. left = lb_emit_conv(p, left, right.type);
  8579. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  8580. right = lb_emit_conv(p, right, left.type);
  8581. } else {
  8582. Type *lt = left.type;
  8583. Type *rt = right.type;
  8584. // if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  8585. // Type *blt = base_type(lt);
  8586. // Type *brt = base_type(rt);
  8587. // i64 bits = gb_max(blt->BitSet.bits, brt->BitSet.bits);
  8588. // i64 bytes = bits / 8;
  8589. // switch (bytes) {
  8590. // case 1:
  8591. // left = lb_emit_conv(p, left, t_u8);
  8592. // right = lb_emit_conv(p, right, t_u8);
  8593. // break;
  8594. // case 2:
  8595. // left = lb_emit_conv(p, left, t_u16);
  8596. // right = lb_emit_conv(p, right, t_u16);
  8597. // break;
  8598. // case 4:
  8599. // left = lb_emit_conv(p, left, t_u32);
  8600. // right = lb_emit_conv(p, right, t_u32);
  8601. // break;
  8602. // case 8:
  8603. // left = lb_emit_conv(p, left, t_u64);
  8604. // right = lb_emit_conv(p, right, t_u64);
  8605. // break;
  8606. // default: GB_PANIC("Unknown integer size"); break;
  8607. // }
  8608. // }
  8609. lt = left.type;
  8610. rt = right.type;
  8611. i64 ls = type_size_of(lt);
  8612. i64 rs = type_size_of(rt);
  8613. if (ls < rs) {
  8614. left = lb_emit_conv(p, left, rt);
  8615. } else if (ls > rs) {
  8616. right = lb_emit_conv(p, right, lt);
  8617. } else {
  8618. right = lb_emit_conv(p, right, lt);
  8619. }
  8620. }
  8621. if (is_type_array(a)) {
  8622. Type *tl = base_type(a);
  8623. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  8624. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  8625. TokenKind cmp_op = Token_And;
  8626. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  8627. if (op_kind == Token_NotEq) {
  8628. res = lb_const_bool(p->module, t_llvm_bool, false);
  8629. cmp_op = Token_Or;
  8630. } else if (op_kind == Token_CmpEq) {
  8631. res = lb_const_bool(p->module, t_llvm_bool, true);
  8632. cmp_op = Token_And;
  8633. }
  8634. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  8635. i32 count = cast(i32)tl->Array.count;
  8636. if (inline_array_arith) {
  8637. // inline
  8638. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8639. lb_addr_store(p, val, res);
  8640. for (i32 i = 0; i < count; i++) {
  8641. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  8642. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  8643. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8644. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8645. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8646. }
  8647. return lb_addr_load(p, val);
  8648. } else {
  8649. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  8650. // TODO(bill): Test to see if this is actually faster!!!!
  8651. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8652. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8653. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  8654. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  8655. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  8656. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  8657. return lb_emit_conv(p, res, t_bool);
  8658. } else {
  8659. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8660. lb_addr_store(p, val, res);
  8661. auto loop_data = lb_loop_start(p, count, t_i32);
  8662. {
  8663. lbValue i = loop_data.idx;
  8664. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  8665. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  8666. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8667. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8668. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8669. }
  8670. lb_loop_end(p, loop_data);
  8671. return lb_addr_load(p, val);
  8672. }
  8673. }
  8674. }
  8675. if (is_type_struct(a) && is_type_comparable(a)) {
  8676. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  8677. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  8678. lbValue res = {};
  8679. if (is_type_simple_compare(a)) {
  8680. // TODO(bill): Test to see if this is actually faster!!!!
  8681. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8682. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8683. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8684. args[2] = lb_const_int(p->module, t_int, type_size_of(a));
  8685. res = lb_emit_runtime_call(p, "memory_equal", args);
  8686. } else {
  8687. lbValue value = lb_get_equal_proc_for_type(p->module, a);
  8688. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8689. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8690. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8691. res = lb_emit_call(p, value, args);
  8692. }
  8693. if (op_kind == Token_NotEq) {
  8694. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  8695. }
  8696. return res;
  8697. }
  8698. if (is_type_string(a)) {
  8699. if (is_type_cstring(a)) {
  8700. left = lb_emit_conv(p, left, t_string);
  8701. right = lb_emit_conv(p, right, t_string);
  8702. }
  8703. char const *runtime_procedure = nullptr;
  8704. switch (op_kind) {
  8705. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  8706. case Token_NotEq: runtime_procedure = "string_ne"; break;
  8707. case Token_Lt: runtime_procedure = "string_lt"; break;
  8708. case Token_Gt: runtime_procedure = "string_gt"; break;
  8709. case Token_LtEq: runtime_procedure = "string_le"; break;
  8710. case Token_GtEq: runtime_procedure = "string_gt"; break;
  8711. }
  8712. GB_ASSERT(runtime_procedure != nullptr);
  8713. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8714. args[0] = left;
  8715. args[1] = right;
  8716. return lb_emit_runtime_call(p, runtime_procedure, args);
  8717. }
  8718. if (is_type_complex(a)) {
  8719. char const *runtime_procedure = "";
  8720. i64 sz = 8*type_size_of(a);
  8721. switch (sz) {
  8722. case 64:
  8723. switch (op_kind) {
  8724. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  8725. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  8726. }
  8727. break;
  8728. case 128:
  8729. switch (op_kind) {
  8730. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  8731. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  8732. }
  8733. break;
  8734. }
  8735. GB_ASSERT(runtime_procedure != nullptr);
  8736. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8737. args[0] = left;
  8738. args[1] = right;
  8739. return lb_emit_runtime_call(p, runtime_procedure, args);
  8740. }
  8741. if (is_type_quaternion(a)) {
  8742. char const *runtime_procedure = "";
  8743. i64 sz = 8*type_size_of(a);
  8744. switch (sz) {
  8745. case 128:
  8746. switch (op_kind) {
  8747. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  8748. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  8749. }
  8750. break;
  8751. case 256:
  8752. switch (op_kind) {
  8753. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  8754. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  8755. }
  8756. break;
  8757. }
  8758. GB_ASSERT(runtime_procedure != nullptr);
  8759. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8760. args[0] = left;
  8761. args[1] = right;
  8762. return lb_emit_runtime_call(p, runtime_procedure, args);
  8763. }
  8764. if (is_type_bit_set(a)) {
  8765. switch (op_kind) {
  8766. case Token_Lt:
  8767. case Token_LtEq:
  8768. case Token_Gt:
  8769. case Token_GtEq:
  8770. {
  8771. Type *it = bit_set_to_int(a);
  8772. lbValue lhs = lb_emit_transmute(p, left, it);
  8773. lbValue rhs = lb_emit_transmute(p, right, it);
  8774. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  8775. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  8776. // (lhs & rhs) == lhs
  8777. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  8778. res.type = t_llvm_bool;
  8779. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  8780. // (lhs & rhs) == rhs
  8781. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  8782. res.type = t_llvm_bool;
  8783. }
  8784. // NOTE(bill): Strict subsets
  8785. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  8786. // res &~ (lhs == rhs)
  8787. lbValue eq = {};
  8788. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  8789. eq.type = t_llvm_bool;
  8790. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  8791. }
  8792. return res;
  8793. }
  8794. case Token_CmpEq:
  8795. case Token_NotEq:
  8796. {
  8797. LLVMIntPredicate pred = {};
  8798. switch (op_kind) {
  8799. case Token_CmpEq: pred = LLVMIntEQ; break;
  8800. case Token_NotEq: pred = LLVMIntNE; break;
  8801. }
  8802. lbValue res = {};
  8803. res.type = t_llvm_bool;
  8804. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8805. return res;
  8806. }
  8807. }
  8808. }
  8809. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  8810. Type *t = left.type;
  8811. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  8812. Type *platform_type = integer_endian_type_to_platform_type(t);
  8813. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  8814. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  8815. left = x;
  8816. right = y;
  8817. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  8818. Type *platform_type = integer_endian_type_to_platform_type(t);
  8819. lbValue x = lb_emit_conv(p, left, platform_type);
  8820. lbValue y = lb_emit_conv(p, right, platform_type);
  8821. left = x;
  8822. right = y;
  8823. }
  8824. }
  8825. a = core_type(left.type);
  8826. b = core_type(right.type);
  8827. lbValue res = {};
  8828. res.type = t_llvm_bool;
  8829. if (is_type_integer(a) ||
  8830. is_type_boolean(a) ||
  8831. is_type_pointer(a) ||
  8832. is_type_proc(a) ||
  8833. is_type_enum(a)) {
  8834. LLVMIntPredicate pred = {};
  8835. if (is_type_unsigned(left.type)) {
  8836. switch (op_kind) {
  8837. case Token_Gt: pred = LLVMIntUGT; break;
  8838. case Token_GtEq: pred = LLVMIntUGE; break;
  8839. case Token_Lt: pred = LLVMIntULT; break;
  8840. case Token_LtEq: pred = LLVMIntULE; break;
  8841. }
  8842. } else {
  8843. switch (op_kind) {
  8844. case Token_Gt: pred = LLVMIntSGT; break;
  8845. case Token_GtEq: pred = LLVMIntSGE; break;
  8846. case Token_Lt: pred = LLVMIntSLT; break;
  8847. case Token_LtEq: pred = LLVMIntSLE; break;
  8848. }
  8849. }
  8850. switch (op_kind) {
  8851. case Token_CmpEq: pred = LLVMIntEQ; break;
  8852. case Token_NotEq: pred = LLVMIntNE; break;
  8853. }
  8854. LLVMValueRef lhs = left.value;
  8855. LLVMValueRef rhs = right.value;
  8856. if (LLVMTypeOf(lhs) != LLVMTypeOf(rhs)) {
  8857. if (lb_is_type_kind(LLVMTypeOf(lhs), LLVMPointerTypeKind)) {
  8858. rhs = LLVMBuildPointerCast(p->builder, rhs, LLVMTypeOf(lhs), "");
  8859. }
  8860. }
  8861. res.value = LLVMBuildICmp(p->builder, pred, lhs, rhs, "");
  8862. } else if (is_type_float(a)) {
  8863. LLVMRealPredicate pred = {};
  8864. switch (op_kind) {
  8865. case Token_CmpEq: pred = LLVMRealOEQ; break;
  8866. case Token_Gt: pred = LLVMRealOGT; break;
  8867. case Token_GtEq: pred = LLVMRealOGE; break;
  8868. case Token_Lt: pred = LLVMRealOLT; break;
  8869. case Token_LtEq: pred = LLVMRealOLE; break;
  8870. case Token_NotEq: pred = LLVMRealONE; break;
  8871. }
  8872. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  8873. } else if (is_type_typeid(a)) {
  8874. LLVMIntPredicate pred = {};
  8875. switch (op_kind) {
  8876. case Token_Gt: pred = LLVMIntUGT; break;
  8877. case Token_GtEq: pred = LLVMIntUGE; break;
  8878. case Token_Lt: pred = LLVMIntULT; break;
  8879. case Token_LtEq: pred = LLVMIntULE; break;
  8880. case Token_CmpEq: pred = LLVMIntEQ; break;
  8881. case Token_NotEq: pred = LLVMIntNE; break;
  8882. }
  8883. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8884. } else {
  8885. 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)));
  8886. }
  8887. return res;
  8888. }
  8889. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  8890. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  8891. if (found != nullptr) {
  8892. lbValue value = {};
  8893. value.value = (*found)->value;
  8894. value.type = (*found)->type;
  8895. return value;
  8896. }
  8897. ast_node(pl, ProcLit, expr);
  8898. // NOTE(bill): Generate a new name
  8899. // parent$count
  8900. isize name_len = prefix_name.len + 1 + 8 + 1;
  8901. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  8902. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  8903. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  8904. String name = make_string((u8 *)name_text, name_len-1);
  8905. Type *type = type_of_expr(expr);
  8906. set_procedure_abi_types(type);
  8907. Token token = {};
  8908. token.pos = ast_token(expr).pos;
  8909. token.kind = Token_Ident;
  8910. token.string = name;
  8911. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  8912. e->file = expr->file;
  8913. e->decl_info = pl->decl;
  8914. lbProcedure *p = lb_create_procedure(m, e);
  8915. lbValue value = {};
  8916. value.value = p->value;
  8917. value.type = p->type;
  8918. array_add(&m->procedures_to_generate, p);
  8919. if (parent != nullptr) {
  8920. array_add(&parent->children, p);
  8921. } else {
  8922. string_map_set(&m->members, name, value);
  8923. }
  8924. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  8925. return value;
  8926. }
  8927. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  8928. lbModule *m = p->module;
  8929. Type *src_type = value.type;
  8930. bool is_ptr = is_type_pointer(src_type);
  8931. bool is_tuple = true;
  8932. Type *tuple = type;
  8933. if (type->kind != Type_Tuple) {
  8934. is_tuple = false;
  8935. tuple = make_optional_ok_type(type);
  8936. }
  8937. lbAddr v = lb_add_local_generated(p, tuple, true);
  8938. if (is_ptr) {
  8939. value = lb_emit_load(p, value);
  8940. }
  8941. Type *src = base_type(type_deref(src_type));
  8942. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  8943. Type *dst = tuple->Tuple.variables[0]->type;
  8944. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  8945. lbValue tag = {};
  8946. lbValue dst_tag = {};
  8947. lbValue cond = {};
  8948. lbValue data = {};
  8949. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8950. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8951. if (is_type_union_maybe_pointer(src)) {
  8952. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8953. } else {
  8954. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  8955. dst_tag = lb_const_union_tag(m, src, dst);
  8956. }
  8957. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  8958. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  8959. if (data.value != nullptr) {
  8960. GB_ASSERT(is_type_union_maybe_pointer(src));
  8961. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  8962. } else {
  8963. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  8964. }
  8965. lb_emit_if(p, cond, ok_block, end_block);
  8966. lb_start_block(p, ok_block);
  8967. if (data.value == nullptr) {
  8968. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8969. }
  8970. lb_emit_store(p, gep0, data);
  8971. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8972. lb_emit_jump(p, end_block);
  8973. lb_start_block(p, end_block);
  8974. if (!is_tuple) {
  8975. if (do_conversion_check) {
  8976. // NOTE(bill): Panic on invalid conversion
  8977. Type *dst_type = tuple->Tuple.variables[0]->type;
  8978. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8979. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8980. args[0] = ok;
  8981. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  8982. args[2] = lb_const_int(m, t_i32, pos.line);
  8983. args[3] = lb_const_int(m, t_i32, pos.column);
  8984. args[4] = lb_typeid(m, src_type);
  8985. args[5] = lb_typeid(m, dst_type);
  8986. args[6] = lb_emit_conv(p, value_, t_rawptr);
  8987. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8988. }
  8989. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  8990. }
  8991. return lb_addr_load(p, v);
  8992. }
  8993. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8994. lbModule *m = p->module;
  8995. Type *src_type = value.type;
  8996. if (is_type_pointer(src_type)) {
  8997. value = lb_emit_load(p, value);
  8998. }
  8999. bool is_tuple = true;
  9000. Type *tuple = type;
  9001. if (type->kind != Type_Tuple) {
  9002. is_tuple = false;
  9003. tuple = make_optional_ok_type(type);
  9004. }
  9005. Type *dst_type = tuple->Tuple.variables[0]->type;
  9006. lbAddr v = lb_add_local_generated(p, tuple, true);
  9007. lbValue dst_typeid = lb_typeid(m, dst_type);
  9008. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  9009. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  9010. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  9011. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  9012. lb_emit_if(p, cond, ok_block, end_block);
  9013. lb_start_block(p, ok_block);
  9014. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  9015. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  9016. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  9017. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  9018. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  9019. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  9020. lb_emit_jump(p, end_block);
  9021. lb_start_block(p, end_block);
  9022. if (!is_tuple) {
  9023. // NOTE(bill): Panic on invalid conversion
  9024. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  9025. auto args = array_make<lbValue>(permanent_allocator(), 7);
  9026. args[0] = ok;
  9027. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  9028. args[2] = lb_const_int(m, t_i32, pos.line);
  9029. args[3] = lb_const_int(m, t_i32, pos.column);
  9030. args[4] = any_typeid;
  9031. args[5] = dst_typeid;
  9032. args[6] = lb_emit_struct_ev(p, value, 0);;
  9033. lb_emit_runtime_call(p, "type_assertion_check2", args);
  9034. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  9035. }
  9036. return v;
  9037. }
  9038. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9039. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  9040. }
  9041. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  9042. lbModule *m = p->module;
  9043. u64 prev_state_flags = p->module->state_flags;
  9044. defer (p->module->state_flags = prev_state_flags);
  9045. if (expr->state_flags != 0) {
  9046. u64 in = expr->state_flags;
  9047. u64 out = p->module->state_flags;
  9048. if (in & StateFlag_bounds_check) {
  9049. out |= StateFlag_bounds_check;
  9050. out &= ~StateFlag_no_bounds_check;
  9051. } else if (in & StateFlag_no_bounds_check) {
  9052. out |= StateFlag_no_bounds_check;
  9053. out &= ~StateFlag_bounds_check;
  9054. }
  9055. p->module->state_flags = out;
  9056. }
  9057. expr = unparen_expr(expr);
  9058. TokenPos expr_pos = ast_token(expr).pos;
  9059. TypeAndValue tv = type_and_value_of_expr(expr);
  9060. 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));
  9061. if (tv.value.kind != ExactValue_Invalid) {
  9062. // NOTE(bill): Short on constant values
  9063. return lb_const_value(p->module, tv.type, tv.value);
  9064. }
  9065. #if 0
  9066. LLVMMetadataRef prev_debug_location = nullptr;
  9067. if (p->debug_info != nullptr) {
  9068. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  9069. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, expr));
  9070. }
  9071. defer (if (prev_debug_location != nullptr) {
  9072. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  9073. });
  9074. #endif
  9075. switch (expr->kind) {
  9076. case_ast_node(bl, BasicLit, expr);
  9077. TokenPos pos = bl->token.pos;
  9078. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  9079. case_end;
  9080. case_ast_node(bd, BasicDirective, expr);
  9081. TokenPos pos = bd->token.pos;
  9082. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name));
  9083. case_end;
  9084. case_ast_node(i, Implicit, expr);
  9085. return lb_addr_load(p, lb_build_addr(p, expr));
  9086. case_end;
  9087. case_ast_node(u, Undef, expr)
  9088. lbValue res = {};
  9089. if (is_type_untyped(tv.type)) {
  9090. res.value = nullptr;
  9091. res.type = t_untyped_undef;
  9092. } else {
  9093. res.value = LLVMGetUndef(lb_type(m, tv.type));
  9094. res.type = tv.type;
  9095. }
  9096. return res;
  9097. case_end;
  9098. case_ast_node(i, Ident, expr);
  9099. Entity *e = entity_from_expr(expr);
  9100. e = strip_entity_wrapping(e);
  9101. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  9102. if (e->kind == Entity_Builtin) {
  9103. Token token = ast_token(expr);
  9104. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  9105. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  9106. token_pos_to_string(token.pos));
  9107. return {};
  9108. } else if (e->kind == Entity_Nil) {
  9109. lbValue res = {};
  9110. res.value = nullptr;
  9111. res.type = e->type;
  9112. return res;
  9113. }
  9114. GB_ASSERT(e->kind != Entity_ProcGroup);
  9115. auto *found = map_get(&p->module->values, hash_entity(e));
  9116. if (found) {
  9117. auto v = *found;
  9118. // NOTE(bill): This is because pointers are already pointers in LLVM
  9119. if (is_type_proc(v.type)) {
  9120. return v;
  9121. }
  9122. return lb_emit_load(p, v);
  9123. } else if (e != nullptr && e->kind == Entity_Variable) {
  9124. return lb_addr_load(p, lb_build_addr(p, expr));
  9125. }
  9126. gb_printf_err("Error in: %s\n", token_pos_to_string(i->token.pos));
  9127. String pkg = {};
  9128. if (e->pkg) {
  9129. pkg = e->pkg->name;
  9130. }
  9131. 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);
  9132. return {};
  9133. case_end;
  9134. case_ast_node(de, DerefExpr, expr);
  9135. return lb_addr_load(p, lb_build_addr(p, expr));
  9136. case_end;
  9137. case_ast_node(se, SelectorExpr, expr);
  9138. TypeAndValue tav = type_and_value_of_expr(expr);
  9139. GB_ASSERT(tav.mode != Addressing_Invalid);
  9140. return lb_addr_load(p, lb_build_addr(p, expr));
  9141. case_end;
  9142. case_ast_node(ise, ImplicitSelectorExpr, expr);
  9143. TypeAndValue tav = type_and_value_of_expr(expr);
  9144. GB_ASSERT(tav.mode == Addressing_Constant);
  9145. return lb_const_value(p->module, tv.type, tv.value);
  9146. case_end;
  9147. case_ast_node(se, SelectorCallExpr, expr);
  9148. GB_ASSERT(se->modified_call);
  9149. TypeAndValue tav = type_and_value_of_expr(expr);
  9150. GB_ASSERT(tav.mode != Addressing_Invalid);
  9151. return lb_build_expr(p, se->call);
  9152. case_end;
  9153. case_ast_node(te, TernaryExpr, expr);
  9154. LLVMValueRef incoming_values[2] = {};
  9155. LLVMBasicBlockRef incoming_blocks[2] = {};
  9156. GB_ASSERT(te->y != nullptr);
  9157. lbBlock *then = lb_create_block(p, "if.then");
  9158. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  9159. lbBlock *else_ = lb_create_block(p, "if.else");
  9160. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  9161. lb_start_block(p, then);
  9162. Type *type = default_type(type_of_expr(expr));
  9163. lb_open_scope(p, nullptr);
  9164. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  9165. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9166. lb_emit_jump(p, done);
  9167. lb_start_block(p, else_);
  9168. lb_open_scope(p, nullptr);
  9169. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  9170. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9171. lb_emit_jump(p, done);
  9172. lb_start_block(p, done);
  9173. lbValue res = {};
  9174. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  9175. res.type = type;
  9176. GB_ASSERT(p->curr_block->preds.count >= 2);
  9177. incoming_blocks[0] = p->curr_block->preds[0]->block;
  9178. incoming_blocks[1] = p->curr_block->preds[1]->block;
  9179. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  9180. return res;
  9181. case_end;
  9182. case_ast_node(te, TernaryIfExpr, expr);
  9183. LLVMValueRef incoming_values[2] = {};
  9184. LLVMBasicBlockRef incoming_blocks[2] = {};
  9185. GB_ASSERT(te->y != nullptr);
  9186. lbBlock *then = lb_create_block(p, "if.then");
  9187. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  9188. lbBlock *else_ = lb_create_block(p, "if.else");
  9189. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  9190. lb_start_block(p, then);
  9191. Type *type = default_type(type_of_expr(expr));
  9192. lb_open_scope(p, nullptr);
  9193. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  9194. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9195. lb_emit_jump(p, done);
  9196. lb_start_block(p, else_);
  9197. lb_open_scope(p, nullptr);
  9198. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  9199. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9200. lb_emit_jump(p, done);
  9201. lb_start_block(p, done);
  9202. lbValue res = {};
  9203. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  9204. res.type = type;
  9205. GB_ASSERT(p->curr_block->preds.count >= 2);
  9206. incoming_blocks[0] = p->curr_block->preds[0]->block;
  9207. incoming_blocks[1] = p->curr_block->preds[1]->block;
  9208. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  9209. return res;
  9210. case_end;
  9211. case_ast_node(te, TernaryWhenExpr, expr);
  9212. TypeAndValue tav = type_and_value_of_expr(te->cond);
  9213. GB_ASSERT(tav.mode == Addressing_Constant);
  9214. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  9215. if (tav.value.value_bool) {
  9216. return lb_build_expr(p, te->x);
  9217. } else {
  9218. return lb_build_expr(p, te->y);
  9219. }
  9220. case_end;
  9221. case_ast_node(ta, TypeAssertion, expr);
  9222. TokenPos pos = ast_token(expr).pos;
  9223. Type *type = tv.type;
  9224. lbValue e = lb_build_expr(p, ta->expr);
  9225. Type *t = type_deref(e.type);
  9226. if (is_type_union(t)) {
  9227. return lb_emit_union_cast(p, e, type, pos);
  9228. } else if (is_type_any(t)) {
  9229. return lb_emit_any_cast(p, e, type, pos);
  9230. } else {
  9231. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  9232. }
  9233. case_end;
  9234. case_ast_node(tc, TypeCast, expr);
  9235. lbValue e = lb_build_expr(p, tc->expr);
  9236. switch (tc->token.kind) {
  9237. case Token_cast:
  9238. return lb_emit_conv(p, e, tv.type);
  9239. case Token_transmute:
  9240. return lb_emit_transmute(p, e, tv.type);
  9241. }
  9242. GB_PANIC("Invalid AST TypeCast");
  9243. case_end;
  9244. case_ast_node(ac, AutoCast, expr);
  9245. return lb_build_expr(p, ac->expr);
  9246. case_end;
  9247. case_ast_node(ue, UnaryExpr, expr);
  9248. switch (ue->op.kind) {
  9249. case Token_And: {
  9250. Ast *ue_expr = unparen_expr(ue->expr);
  9251. if (ue_expr->kind == Ast_CompoundLit) {
  9252. lbValue v = lb_build_expr(p, ue->expr);
  9253. Type *type = v.type;
  9254. lbAddr addr = {};
  9255. if (p->is_startup) {
  9256. addr = lb_add_global_generated(p->module, type, v);
  9257. } else {
  9258. addr = lb_add_local_generated(p, type, false);
  9259. }
  9260. lb_addr_store(p, addr, v);
  9261. return addr.addr;
  9262. } else if (ue_expr->kind == Ast_TypeAssertion) {
  9263. GB_ASSERT(is_type_pointer(tv.type));
  9264. ast_node(ta, TypeAssertion, ue_expr);
  9265. TokenPos pos = ast_token(expr).pos;
  9266. Type *type = type_of_expr(ue_expr);
  9267. GB_ASSERT(!is_type_tuple(type));
  9268. lbValue e = lb_build_expr(p, ta->expr);
  9269. Type *t = type_deref(e.type);
  9270. if (is_type_union(t)) {
  9271. lbValue v = e;
  9272. if (!is_type_pointer(v.type)) {
  9273. v = lb_address_from_load_or_generate_local(p, v);
  9274. }
  9275. Type *src_type = type_deref(v.type);
  9276. Type *dst_type = type;
  9277. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  9278. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  9279. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  9280. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9281. args[0] = ok;
  9282. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9283. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9284. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9285. args[4] = lb_typeid(p->module, src_type);
  9286. args[5] = lb_typeid(p->module, dst_type);
  9287. lb_emit_runtime_call(p, "type_assertion_check", args);
  9288. lbValue data_ptr = v;
  9289. return lb_emit_conv(p, data_ptr, tv.type);
  9290. } else if (is_type_any(t)) {
  9291. lbValue v = e;
  9292. if (is_type_pointer(v.type)) {
  9293. v = lb_emit_load(p, v);
  9294. }
  9295. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  9296. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  9297. lbValue id = lb_typeid(p->module, type);
  9298. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  9299. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9300. args[0] = ok;
  9301. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9302. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9303. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9304. args[4] = any_id;
  9305. args[5] = id;
  9306. lb_emit_runtime_call(p, "type_assertion_check", args);
  9307. return lb_emit_conv(p, data_ptr, tv.type);
  9308. } else {
  9309. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  9310. }
  9311. }
  9312. return lb_build_addr_ptr(p, ue->expr);
  9313. }
  9314. default:
  9315. {
  9316. lbValue v = lb_build_expr(p, ue->expr);
  9317. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  9318. }
  9319. }
  9320. case_end;
  9321. case_ast_node(be, BinaryExpr, expr);
  9322. return lb_build_binary_expr(p, expr);
  9323. case_end;
  9324. case_ast_node(pl, ProcLit, expr);
  9325. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  9326. case_end;
  9327. case_ast_node(cl, CompoundLit, expr);
  9328. return lb_addr_load(p, lb_build_addr(p, expr));
  9329. case_end;
  9330. case_ast_node(ce, CallExpr, expr);
  9331. lbValue res = lb_build_call_expr(p, expr);
  9332. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  9333. GB_ASSERT(is_type_tuple(res.type));
  9334. GB_ASSERT(res.type->Tuple.variables.count == 2);
  9335. return lb_emit_struct_ev(p, res, 0);
  9336. }
  9337. return res;
  9338. case_end;
  9339. case_ast_node(se, SliceExpr, expr);
  9340. return lb_addr_load(p, lb_build_addr(p, expr));
  9341. case_end;
  9342. case_ast_node(ie, IndexExpr, expr);
  9343. return lb_addr_load(p, lb_build_addr(p, expr));
  9344. case_end;
  9345. case_ast_node(ia, InlineAsmExpr, expr);
  9346. Type *t = type_of_expr(expr);
  9347. GB_ASSERT(is_type_asm_proc(t));
  9348. String asm_string = {};
  9349. String constraints_string = {};
  9350. TypeAndValue tav;
  9351. tav = type_and_value_of_expr(ia->asm_string);
  9352. GB_ASSERT(is_type_string(tav.type));
  9353. GB_ASSERT(tav.value.kind == ExactValue_String);
  9354. asm_string = tav.value.value_string;
  9355. tav = type_and_value_of_expr(ia->constraints_string);
  9356. GB_ASSERT(is_type_string(tav.type));
  9357. GB_ASSERT(tav.value.kind == ExactValue_String);
  9358. constraints_string = tav.value.value_string;
  9359. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  9360. switch (ia->dialect) {
  9361. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  9362. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  9363. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  9364. default: GB_PANIC("Unhandled inline asm dialect"); break;
  9365. }
  9366. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  9367. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  9368. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  9369. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  9370. ia->has_side_effects, ia->is_align_stack, dialect
  9371. );
  9372. GB_ASSERT(the_asm != nullptr);
  9373. return {the_asm, t};
  9374. case_end;
  9375. }
  9376. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  9377. return {};
  9378. }
  9379. lbAddr lb_get_soa_variable_addr(lbProcedure *p, Entity *e) {
  9380. lbAddr *found = map_get(&p->module->soa_values, hash_entity(e));
  9381. GB_ASSERT(found != nullptr);
  9382. return *found;
  9383. }
  9384. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  9385. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  9386. String name = e->token.string;
  9387. Entity *parent = e->using_parent;
  9388. Selection sel = lookup_field(parent->type, name, false);
  9389. GB_ASSERT(sel.entity != nullptr);
  9390. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  9391. lbValue v = {};
  9392. if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) {
  9393. // NOTE(bill): using SOA value (probably from for-in statement)
  9394. lbAddr parent_addr = lb_get_soa_variable_addr(p, parent);
  9395. v = lb_addr_get_ptr(p, parent_addr);
  9396. } else if (pv != nullptr) {
  9397. v = *pv;
  9398. } else {
  9399. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  9400. v = lb_build_addr_ptr(p, e->using_expr);
  9401. }
  9402. GB_ASSERT(v.value != nullptr);
  9403. GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type));
  9404. lbValue ptr = lb_emit_deep_field_gep(p, v, sel);
  9405. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  9406. return ptr;
  9407. }
  9408. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  9409. GB_ASSERT(e != nullptr);
  9410. if (e->kind == Entity_Constant) {
  9411. Type *t = default_type(type_of_expr(expr));
  9412. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  9413. lbAddr g = lb_add_global_generated(p->module, t, v);
  9414. return g;
  9415. }
  9416. lbValue v = {};
  9417. lbValue *found = map_get(&p->module->values, hash_entity(e));
  9418. if (found) {
  9419. v = *found;
  9420. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  9421. // NOTE(bill): Calculate the using variable every time
  9422. v = lb_get_using_variable(p, e);
  9423. } else if (e->flags & EntityFlag_SoaPtrField) {
  9424. return lb_get_soa_variable_addr(p, e);
  9425. }
  9426. if (v.value == nullptr) {
  9427. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  9428. LIT(p->name),
  9429. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  9430. GB_PANIC("Unknown value");
  9431. }
  9432. return lb_addr(v);
  9433. }
  9434. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  9435. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  9436. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  9437. map_type = base_type(map_type);
  9438. GB_ASSERT(map_type->kind == Type_Map);
  9439. Type *key_type = map_type->Map.key;
  9440. Type *val_type = map_type->Map.value;
  9441. // NOTE(bill): Removes unnecessary allocation if split gep
  9442. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  9443. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  9444. lb_emit_store(p, gep0, m);
  9445. i64 entry_size = type_size_of (map_type->Map.entry_type);
  9446. i64 entry_align = type_align_of (map_type->Map.entry_type);
  9447. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  9448. i64 key_size = type_size_of (map_type->Map.key);
  9449. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  9450. i64 value_size = type_size_of (map_type->Map.value);
  9451. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  9452. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  9453. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  9454. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  9455. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  9456. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  9457. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  9458. return lb_addr_load(p, h);
  9459. }
  9460. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  9461. if (true) {
  9462. return {};
  9463. }
  9464. lbValue hashed_key = {};
  9465. if (lb_is_const(key)) {
  9466. u64 hash = 0xcbf29ce484222325;
  9467. if (is_type_cstring(key_type)) {
  9468. size_t length = 0;
  9469. char const *text = LLVMGetAsString(key.value, &length);
  9470. hash = fnv64a(text, cast(isize)length);
  9471. } else if (is_type_string(key_type)) {
  9472. unsigned data_indices[] = {0};
  9473. unsigned len_indices[] = {1};
  9474. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  9475. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  9476. isize length = LLVMConstIntGetSExtValue(len);
  9477. char const *text = nullptr;
  9478. if (false && length != 0) {
  9479. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  9480. return {};
  9481. }
  9482. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  9483. size_t ulength = 0;
  9484. text = LLVMGetAsString(data, &ulength);
  9485. gb_printf_err("%td %td %s\n", length, ulength, text);
  9486. length = gb_min(length, cast(isize)ulength);
  9487. }
  9488. hash = fnv64a(text, cast(isize)length);
  9489. } else {
  9490. return {};
  9491. }
  9492. // TODO(bill): other const hash types
  9493. if (build_context.word_size == 4) {
  9494. hash &= 0xffffffffull;
  9495. }
  9496. hashed_key = lb_const_int(m, t_uintptr, hash);
  9497. }
  9498. return hashed_key;
  9499. }
  9500. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  9501. Type *hash_type = t_u64;
  9502. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  9503. lbValue vp = lb_addr_get_ptr(p, v);
  9504. Type *t = base_type(key.type);
  9505. key = lb_emit_conv(p, key, key_type);
  9506. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  9507. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  9508. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  9509. if (hashed_key.value == nullptr) {
  9510. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  9511. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9512. args[0] = key_ptr;
  9513. args[1] = lb_const_int(p->module, t_uintptr, 0);
  9514. hashed_key = lb_emit_call(p, hasher, args);
  9515. }
  9516. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  9517. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  9518. return lb_addr_load(p, v);
  9519. }
  9520. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  9521. lbValue map_key, lbValue map_value, Ast *node) {
  9522. map_type = base_type(map_type);
  9523. GB_ASSERT(map_type->kind == Type_Map);
  9524. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  9525. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  9526. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  9527. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  9528. lb_addr_store(p, value_addr, v);
  9529. auto args = array_make<lbValue>(permanent_allocator(), 4);
  9530. args[0] = h;
  9531. args[1] = key;
  9532. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  9533. args[3] = lb_emit_source_code_location(p, node);
  9534. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  9535. }
  9536. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  9537. expr = unparen_expr(expr);
  9538. switch (expr->kind) {
  9539. case_ast_node(i, Implicit, expr);
  9540. lbAddr v = {};
  9541. switch (i->kind) {
  9542. case Token_context:
  9543. v = lb_find_or_generate_context_ptr(p);
  9544. break;
  9545. }
  9546. GB_ASSERT(v.addr.value != nullptr);
  9547. return v;
  9548. case_end;
  9549. case_ast_node(i, Ident, expr);
  9550. if (is_blank_ident(expr)) {
  9551. lbAddr val = {};
  9552. return val;
  9553. }
  9554. String name = i->token.string;
  9555. Entity *e = entity_of_node(expr);
  9556. return lb_build_addr_from_entity(p, e, expr);
  9557. case_end;
  9558. case_ast_node(se, SelectorExpr, expr);
  9559. Ast *sel = unparen_expr(se->selector);
  9560. if (sel->kind == Ast_Ident) {
  9561. String selector = sel->Ident.token.string;
  9562. TypeAndValue tav = type_and_value_of_expr(se->expr);
  9563. if (tav.mode == Addressing_Invalid) {
  9564. // NOTE(bill): Imports
  9565. Entity *imp = entity_of_node(se->expr);
  9566. if (imp != nullptr) {
  9567. GB_ASSERT(imp->kind == Entity_ImportName);
  9568. }
  9569. return lb_build_addr(p, unparen_expr(se->selector));
  9570. }
  9571. Type *type = base_type(tav.type);
  9572. if (tav.mode == Addressing_Type) { // Addressing_Type
  9573. Selection sel = lookup_field(type, selector, true);
  9574. Entity *e = sel.entity;
  9575. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  9576. GB_ASSERT(e->flags & EntityFlag_TypeField);
  9577. String name = e->token.string;
  9578. /*if (name == "names") {
  9579. lbValue ti_ptr = lb_type_info(m, type);
  9580. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  9581. lbValue names_ptr = nullptr;
  9582. if (is_type_enum(type)) {
  9583. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  9584. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  9585. } else if (type->kind == Type_Struct) {
  9586. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  9587. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  9588. }
  9589. return ir_addr(names_ptr);
  9590. } else */{
  9591. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  9592. }
  9593. GB_PANIC("Unreachable");
  9594. }
  9595. Selection sel = lookup_field(type, selector, false);
  9596. GB_ASSERT(sel.entity != nullptr);
  9597. {
  9598. lbAddr addr = lb_build_addr(p, se->expr);
  9599. if (addr.kind == lbAddr_Map) {
  9600. lbValue v = lb_addr_load(p, addr);
  9601. lbValue a = lb_address_from_load_or_generate_local(p, v);
  9602. a = lb_emit_deep_field_gep(p, a, sel);
  9603. return lb_addr(a);
  9604. } else if (addr.kind == lbAddr_Context) {
  9605. GB_ASSERT(sel.index.count > 0);
  9606. if (addr.ctx.sel.index.count >= 0) {
  9607. sel = selection_combine(addr.ctx.sel, sel);
  9608. }
  9609. addr.ctx.sel = sel;
  9610. addr.kind = lbAddr_Context;
  9611. return addr;
  9612. } else if (addr.kind == lbAddr_SoaVariable) {
  9613. lbValue index = addr.soa.index;
  9614. i32 first_index = sel.index[0];
  9615. Selection sub_sel = sel;
  9616. sub_sel.index.data += 1;
  9617. sub_sel.index.count -= 1;
  9618. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  9619. Type *t = base_type(type_deref(addr.addr.type));
  9620. GB_ASSERT(is_type_soa_struct(t));
  9621. // TODO(bill): Bounds check
  9622. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  9623. lbValue len = lb_soa_struct_len(p, addr.addr);
  9624. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  9625. }
  9626. lbValue item = {};
  9627. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9628. item = lb_emit_array_ep(p, arr, index);
  9629. } else {
  9630. item = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  9631. }
  9632. if (sub_sel.index.count > 0) {
  9633. item = lb_emit_deep_field_gep(p, item, sub_sel);
  9634. }
  9635. return lb_addr(item);
  9636. }
  9637. lbValue a = lb_addr_get_ptr(p, addr);
  9638. a = lb_emit_deep_field_gep(p, a, sel);
  9639. return lb_addr(a);
  9640. }
  9641. } else {
  9642. GB_PANIC("Unsupported selector expression");
  9643. }
  9644. case_end;
  9645. case_ast_node(se, SelectorCallExpr, expr);
  9646. GB_ASSERT(se->modified_call);
  9647. TypeAndValue tav = type_and_value_of_expr(expr);
  9648. GB_ASSERT(tav.mode != Addressing_Invalid);
  9649. return lb_build_addr(p, se->call);
  9650. case_end;
  9651. case_ast_node(ta, TypeAssertion, expr);
  9652. TokenPos pos = ast_token(expr).pos;
  9653. lbValue e = lb_build_expr(p, ta->expr);
  9654. Type *t = type_deref(e.type);
  9655. if (is_type_union(t)) {
  9656. Type *type = type_of_expr(expr);
  9657. lbAddr v = lb_add_local_generated(p, type, false);
  9658. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  9659. return v;
  9660. } else if (is_type_any(t)) {
  9661. Type *type = type_of_expr(expr);
  9662. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  9663. } else {
  9664. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  9665. }
  9666. case_end;
  9667. case_ast_node(ue, UnaryExpr, expr);
  9668. switch (ue->op.kind) {
  9669. case Token_And: {
  9670. return lb_build_addr(p, ue->expr);
  9671. }
  9672. default:
  9673. GB_PANIC("Invalid unary expression for lb_build_addr");
  9674. }
  9675. case_end;
  9676. case_ast_node(be, BinaryExpr, expr);
  9677. lbValue v = lb_build_expr(p, expr);
  9678. Type *t = v.type;
  9679. if (is_type_pointer(t)) {
  9680. return lb_addr(v);
  9681. }
  9682. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  9683. case_end;
  9684. case_ast_node(ie, IndexExpr, expr);
  9685. Type *t = base_type(type_of_expr(ie->expr));
  9686. bool deref = is_type_pointer(t);
  9687. t = base_type(type_deref(t));
  9688. if (is_type_soa_struct(t)) {
  9689. // SOA STRUCTURES!!!!
  9690. lbValue val = lb_build_addr_ptr(p, ie->expr);
  9691. if (deref) {
  9692. val = lb_emit_load(p, val);
  9693. }
  9694. lbValue index = lb_build_expr(p, ie->index);
  9695. return lb_addr_soa_variable(val, index, ie->index);
  9696. }
  9697. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  9698. // SOA Structures for slices/dynamic arrays
  9699. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  9700. lbValue field = lb_build_expr(p, ie->expr);
  9701. lbValue index = lb_build_expr(p, ie->index);
  9702. if (!build_context.no_bounds_check) {
  9703. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  9704. // GB_ASSERT(LLVMIsALoadInst(field.value));
  9705. // lbValue a = {};
  9706. // a.value = LLVMGetOperand(field.value, 0);
  9707. // a.type = alloc_type_pointer(field.type);
  9708. // irInstr *b = &a->Instr;
  9709. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  9710. // lbValue base_struct = b->StructElementPtr.address;
  9711. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  9712. // lbValue len = ir_soa_struct_len(p, base_struct);
  9713. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9714. }
  9715. lbValue val = lb_emit_ptr_offset(p, field, index);
  9716. return lb_addr(val);
  9717. }
  9718. if (!is_type_indexable(t)) {
  9719. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9720. if (found != nullptr) {
  9721. if (found->kind == TypeAtomOp_index_get) {
  9722. return lb_build_addr(p, found->node);
  9723. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  9724. return lb_addr(lb_build_expr(p, found->node));
  9725. } else if (found->kind == TypeAtomOp_index_set) {
  9726. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  9727. if (deref) {
  9728. ptr = lb_emit_load(p, ptr);
  9729. }
  9730. lbAddr addr = {lbAddr_AtomOp_index_set};
  9731. addr.addr = ptr;
  9732. addr.index_set.index = lb_build_expr(p, ie->index);
  9733. addr.index_set.node = found->node;
  9734. return addr;
  9735. }
  9736. }
  9737. }
  9738. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  9739. if (is_type_map(t)) {
  9740. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  9741. if (deref) {
  9742. map_val = lb_emit_load(p, map_val);
  9743. }
  9744. lbValue key = lb_build_expr(p, ie->index);
  9745. key = lb_emit_conv(p, key, t->Map.key);
  9746. Type *result_type = type_of_expr(expr);
  9747. return lb_addr_map(map_val, key, t, result_type);
  9748. }
  9749. switch (t->kind) {
  9750. case Type_Array: {
  9751. lbValue array = {};
  9752. array = lb_build_addr_ptr(p, ie->expr);
  9753. if (deref) {
  9754. array = lb_emit_load(p, array);
  9755. }
  9756. lbValue index = lb_build_expr(p, ie->index);
  9757. index = lb_emit_conv(p, index, t_int);
  9758. lbValue elem = lb_emit_array_ep(p, array, index);
  9759. auto index_tv = type_and_value_of_expr(ie->index);
  9760. if (index_tv.mode != Addressing_Constant) {
  9761. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  9762. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9763. }
  9764. return lb_addr(elem);
  9765. }
  9766. case Type_EnumeratedArray: {
  9767. lbValue array = {};
  9768. array = lb_build_addr_ptr(p, ie->expr);
  9769. if (deref) {
  9770. array = lb_emit_load(p, array);
  9771. }
  9772. Type *index_type = t->EnumeratedArray.index;
  9773. auto index_tv = type_and_value_of_expr(ie->index);
  9774. lbValue index = {};
  9775. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  9776. if (index_tv.mode == Addressing_Constant) {
  9777. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  9778. index = lb_const_value(p->module, index_type, idx);
  9779. } else {
  9780. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9781. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  9782. }
  9783. } else {
  9784. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9785. }
  9786. lbValue elem = lb_emit_array_ep(p, array, index);
  9787. if (index_tv.mode != Addressing_Constant) {
  9788. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  9789. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9790. }
  9791. return lb_addr(elem);
  9792. }
  9793. case Type_Slice: {
  9794. lbValue slice = {};
  9795. slice = lb_build_expr(p, ie->expr);
  9796. if (deref) {
  9797. slice = lb_emit_load(p, slice);
  9798. }
  9799. lbValue elem = lb_slice_elem(p, slice);
  9800. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9801. lbValue len = lb_slice_len(p, slice);
  9802. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9803. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9804. return lb_addr(v);
  9805. }
  9806. case Type_RelativeSlice: {
  9807. lbAddr slice_addr = {};
  9808. if (deref) {
  9809. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  9810. } else {
  9811. slice_addr = lb_build_addr(p, ie->expr);
  9812. }
  9813. lbValue slice = lb_addr_load(p, slice_addr);
  9814. lbValue elem = lb_slice_elem(p, slice);
  9815. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9816. lbValue len = lb_slice_len(p, slice);
  9817. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9818. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9819. return lb_addr(v);
  9820. }
  9821. case Type_DynamicArray: {
  9822. lbValue dynamic_array = {};
  9823. dynamic_array = lb_build_expr(p, ie->expr);
  9824. if (deref) {
  9825. dynamic_array = lb_emit_load(p, dynamic_array);
  9826. }
  9827. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  9828. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  9829. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9830. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9831. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9832. return lb_addr(v);
  9833. }
  9834. case Type_Basic: { // Basic_string
  9835. lbValue str;
  9836. lbValue elem;
  9837. lbValue len;
  9838. lbValue index;
  9839. str = lb_build_expr(p, ie->expr);
  9840. if (deref) {
  9841. str = lb_emit_load(p, str);
  9842. }
  9843. elem = lb_string_elem(p, str);
  9844. len = lb_string_len(p, str);
  9845. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9846. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9847. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  9848. }
  9849. }
  9850. case_end;
  9851. case_ast_node(se, SliceExpr, expr);
  9852. lbValue low = lb_const_int(p->module, t_int, 0);
  9853. lbValue high = {};
  9854. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  9855. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  9856. bool no_indices = se->low == nullptr && se->high == nullptr;
  9857. {
  9858. Type *type = base_type(type_of_expr(se->expr));
  9859. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  9860. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  9861. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  9862. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9863. if (found) {
  9864. lbValue base = lb_build_expr(p, found->node);
  9865. Type *slice_type = base.type;
  9866. lbValue len = lb_slice_len(p, base);
  9867. if (high.value == nullptr) high = len;
  9868. if (!no_indices) {
  9869. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9870. }
  9871. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9872. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9873. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9874. lb_fill_slice(p, slice, elem, new_len);
  9875. return slice;
  9876. }
  9877. }
  9878. }
  9879. }
  9880. lbAddr addr = lb_build_addr(p, se->expr);
  9881. lbValue base = lb_addr_load(p, addr);
  9882. Type *type = base_type(base.type);
  9883. if (is_type_pointer(type)) {
  9884. type = base_type(type_deref(type));
  9885. addr = lb_addr(base);
  9886. base = lb_addr_load(p, addr);
  9887. }
  9888. switch (type->kind) {
  9889. case Type_Slice: {
  9890. Type *slice_type = type;
  9891. lbValue len = lb_slice_len(p, base);
  9892. if (high.value == nullptr) high = len;
  9893. if (!no_indices) {
  9894. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9895. }
  9896. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9897. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9898. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9899. lb_fill_slice(p, slice, elem, new_len);
  9900. return slice;
  9901. }
  9902. case Type_RelativeSlice:
  9903. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  9904. break;
  9905. case Type_DynamicArray: {
  9906. Type *elem_type = type->DynamicArray.elem;
  9907. Type *slice_type = alloc_type_slice(elem_type);
  9908. lbValue len = lb_dynamic_array_len(p, base);
  9909. if (high.value == nullptr) high = len;
  9910. if (!no_indices) {
  9911. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9912. }
  9913. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  9914. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9915. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9916. lb_fill_slice(p, slice, elem, new_len);
  9917. return slice;
  9918. }
  9919. case Type_Array: {
  9920. Type *slice_type = alloc_type_slice(type->Array.elem);
  9921. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  9922. if (high.value == nullptr) high = len;
  9923. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  9924. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  9925. if (!low_const || !high_const) {
  9926. if (!no_indices) {
  9927. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9928. }
  9929. }
  9930. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  9931. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9932. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9933. lb_fill_slice(p, slice, elem, new_len);
  9934. return slice;
  9935. }
  9936. case Type_Basic: {
  9937. GB_ASSERT(type == t_string);
  9938. lbValue len = lb_string_len(p, base);
  9939. if (high.value == nullptr) high = len;
  9940. if (!no_indices) {
  9941. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9942. }
  9943. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  9944. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9945. lbAddr str = lb_add_local_generated(p, t_string, false);
  9946. lb_fill_string(p, str, elem, new_len);
  9947. return str;
  9948. }
  9949. case Type_Struct:
  9950. if (is_type_soa_struct(type)) {
  9951. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  9952. if (high.value == nullptr) high = len;
  9953. if (!no_indices) {
  9954. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9955. }
  9956. #if 1
  9957. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  9958. if (type->Struct.soa_kind == StructSoa_Fixed) {
  9959. i32 field_count = cast(i32)type->Struct.fields.count;
  9960. for (i32 i = 0; i < field_count; i++) {
  9961. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9962. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  9963. field_src = lb_emit_array_ep(p, field_src, low);
  9964. lb_emit_store(p, field_dst, field_src);
  9965. }
  9966. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9967. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9968. lb_emit_store(p, len_dst, new_len);
  9969. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  9970. if (no_indices) {
  9971. lb_addr_store(p, dst, base);
  9972. } else {
  9973. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  9974. for (i32 i = 0; i < field_count; i++) {
  9975. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9976. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9977. field_src = lb_emit_ptr_offset(p, field_src, low);
  9978. lb_emit_store(p, field_dst, field_src);
  9979. }
  9980. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9981. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9982. lb_emit_store(p, len_dst, new_len);
  9983. }
  9984. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  9985. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  9986. for (i32 i = 0; i < field_count; i++) {
  9987. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9988. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9989. field_src = lb_emit_ptr_offset(p, field_src, low);
  9990. lb_emit_store(p, field_dst, field_src);
  9991. }
  9992. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9993. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9994. lb_emit_store(p, len_dst, new_len);
  9995. }
  9996. return dst;
  9997. #endif
  9998. }
  9999. break;
  10000. }
  10001. GB_PANIC("Unknown slicable type");
  10002. case_end;
  10003. case_ast_node(de, DerefExpr, expr);
  10004. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  10005. lbAddr addr = lb_build_addr(p, de->expr);
  10006. addr.relative.deref = true;
  10007. return addr;
  10008. }
  10009. lbValue addr = lb_build_expr(p, de->expr);
  10010. return lb_addr(addr);
  10011. case_end;
  10012. case_ast_node(ce, CallExpr, expr);
  10013. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  10014. lbValue e = lb_build_expr(p, expr);
  10015. lbAddr v = lb_add_local_generated(p, e.type, false);
  10016. lb_addr_store(p, v, e);
  10017. return v;
  10018. case_end;
  10019. case_ast_node(cl, CompoundLit, expr);
  10020. Type *type = type_of_expr(expr);
  10021. Type *bt = base_type(type);
  10022. lbAddr v = lb_add_local_generated(p, type, true);
  10023. Type *et = nullptr;
  10024. switch (bt->kind) {
  10025. case Type_Array: et = bt->Array.elem; break;
  10026. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  10027. case Type_Slice: et = bt->Slice.elem; break;
  10028. case Type_BitSet: et = bt->BitSet.elem; break;
  10029. case Type_SimdVector: et = bt->SimdVector.elem; break;
  10030. }
  10031. String proc_name = {};
  10032. if (p->entity) {
  10033. proc_name = p->entity->token.string;
  10034. }
  10035. TokenPos pos = ast_token(expr).pos;
  10036. switch (bt->kind) {
  10037. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  10038. case Type_Struct: {
  10039. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  10040. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  10041. bool is_raw_union = is_type_raw_union(bt);
  10042. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  10043. TypeStruct *st = &bt->Struct;
  10044. if (cl->elems.count > 0) {
  10045. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10046. for_array(field_index, cl->elems) {
  10047. Ast *elem = cl->elems[field_index];
  10048. lbValue field_expr = {};
  10049. Entity *field = nullptr;
  10050. isize index = field_index;
  10051. if (elem->kind == Ast_FieldValue) {
  10052. ast_node(fv, FieldValue, elem);
  10053. String name = fv->field->Ident.token.string;
  10054. Selection sel = lookup_field(bt, name, false);
  10055. index = sel.index[0];
  10056. elem = fv->value;
  10057. TypeAndValue tav = type_and_value_of_expr(elem);
  10058. } else {
  10059. TypeAndValue tav = type_and_value_of_expr(elem);
  10060. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  10061. index = sel.index[0];
  10062. }
  10063. field = st->fields[index];
  10064. Type *ft = field->type;
  10065. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  10066. continue;
  10067. }
  10068. field_expr = lb_build_expr(p, elem);
  10069. Type *fet = field_expr.type;
  10070. GB_ASSERT(fet->kind != Type_Tuple);
  10071. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  10072. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  10073. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  10074. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10075. lb_emit_store_union_variant(p, gep, field_expr, fet);
  10076. } else {
  10077. lbValue fv = lb_emit_conv(p, field_expr, ft);
  10078. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10079. lb_emit_store(p, gep, fv);
  10080. }
  10081. }
  10082. }
  10083. break;
  10084. }
  10085. case Type_Map: {
  10086. if (cl->elems.count == 0) {
  10087. break;
  10088. }
  10089. {
  10090. auto args = array_make<lbValue>(permanent_allocator(), 3);
  10091. args[0] = lb_gen_map_header(p, v.addr, type);
  10092. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  10093. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  10094. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  10095. }
  10096. for_array(field_index, cl->elems) {
  10097. Ast *elem = cl->elems[field_index];
  10098. ast_node(fv, FieldValue, elem);
  10099. lbValue key = lb_build_expr(p, fv->field);
  10100. lbValue value = lb_build_expr(p, fv->value);
  10101. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  10102. }
  10103. break;
  10104. }
  10105. case Type_Array: {
  10106. if (cl->elems.count > 0) {
  10107. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10108. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10109. // NOTE(bill): Separate value, gep, store into their own chunks
  10110. for_array(i, cl->elems) {
  10111. Ast *elem = cl->elems[i];
  10112. if (elem->kind == Ast_FieldValue) {
  10113. ast_node(fv, FieldValue, elem);
  10114. if (lb_is_elem_const(fv->value, et)) {
  10115. continue;
  10116. }
  10117. if (is_ast_range(fv->field)) {
  10118. ast_node(ie, BinaryExpr, fv->field);
  10119. TypeAndValue lo_tav = ie->left->tav;
  10120. TypeAndValue hi_tav = ie->right->tav;
  10121. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10122. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10123. TokenKind op = ie->op.kind;
  10124. i64 lo = exact_value_to_i64(lo_tav.value);
  10125. i64 hi = exact_value_to_i64(hi_tav.value);
  10126. if (op == Token_Ellipsis) {
  10127. hi += 1;
  10128. }
  10129. lbValue value = lb_build_expr(p, fv->value);
  10130. for (i64 k = lo; k < hi; k++) {
  10131. lbCompoundLitElemTempData data = {};
  10132. data.value = value;
  10133. data.elem_index = cast(i32)k;
  10134. array_add(&temp_data, data);
  10135. }
  10136. } else {
  10137. auto tav = fv->field->tav;
  10138. GB_ASSERT(tav.mode == Addressing_Constant);
  10139. i64 index = exact_value_to_i64(tav.value);
  10140. lbValue value = lb_build_expr(p, fv->value);
  10141. lbCompoundLitElemTempData data = {};
  10142. data.value = lb_emit_conv(p, value, et);
  10143. data.expr = fv->value;
  10144. data.elem_index = cast(i32)index;
  10145. array_add(&temp_data, data);
  10146. }
  10147. } else {
  10148. if (lb_is_elem_const(elem, et)) {
  10149. continue;
  10150. }
  10151. lbCompoundLitElemTempData data = {};
  10152. data.expr = elem;
  10153. data.elem_index = cast(i32)i;
  10154. array_add(&temp_data, data);
  10155. }
  10156. }
  10157. for_array(i, temp_data) {
  10158. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  10159. }
  10160. for_array(i, temp_data) {
  10161. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  10162. auto return_ptr_hint_value = p->return_ptr_hint_value;
  10163. auto return_ptr_hint_used = p->return_ptr_hint_used;
  10164. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  10165. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  10166. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  10167. lbValue field_expr = temp_data[i].value;
  10168. Ast *expr = temp_data[i].expr;
  10169. p->return_ptr_hint_value = temp_data[i].gep;
  10170. p->return_ptr_hint_ast = unparen_expr(expr);
  10171. if (field_expr.value == nullptr) {
  10172. field_expr = lb_build_expr(p, expr);
  10173. }
  10174. Type *t = field_expr.type;
  10175. GB_ASSERT(t->kind != Type_Tuple);
  10176. lbValue ev = lb_emit_conv(p, field_expr, et);
  10177. if (!p->return_ptr_hint_used) {
  10178. temp_data[i].value = ev;
  10179. }
  10180. }
  10181. for_array(i, temp_data) {
  10182. if (temp_data[i].value.value != nullptr) {
  10183. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10184. }
  10185. }
  10186. }
  10187. break;
  10188. }
  10189. case Type_EnumeratedArray: {
  10190. if (cl->elems.count > 0) {
  10191. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10192. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10193. // NOTE(bill): Separate value, gep, store into their own chunks
  10194. for_array(i, cl->elems) {
  10195. Ast *elem = cl->elems[i];
  10196. if (elem->kind == Ast_FieldValue) {
  10197. ast_node(fv, FieldValue, elem);
  10198. if (lb_is_elem_const(fv->value, et)) {
  10199. continue;
  10200. }
  10201. if (is_ast_range(fv->field)) {
  10202. ast_node(ie, BinaryExpr, fv->field);
  10203. TypeAndValue lo_tav = ie->left->tav;
  10204. TypeAndValue hi_tav = ie->right->tav;
  10205. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10206. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10207. TokenKind op = ie->op.kind;
  10208. i64 lo = exact_value_to_i64(lo_tav.value);
  10209. i64 hi = exact_value_to_i64(hi_tav.value);
  10210. if (op == Token_Ellipsis) {
  10211. hi += 1;
  10212. }
  10213. lbValue value = lb_build_expr(p, fv->value);
  10214. for (i64 k = lo; k < hi; k++) {
  10215. lbCompoundLitElemTempData data = {};
  10216. data.value = value;
  10217. data.elem_index = cast(i32)k;
  10218. array_add(&temp_data, data);
  10219. }
  10220. } else {
  10221. auto tav = fv->field->tav;
  10222. GB_ASSERT(tav.mode == Addressing_Constant);
  10223. i64 index = exact_value_to_i64(tav.value);
  10224. lbValue value = lb_build_expr(p, fv->value);
  10225. lbCompoundLitElemTempData data = {};
  10226. data.value = lb_emit_conv(p, value, et);
  10227. data.expr = fv->value;
  10228. data.elem_index = cast(i32)index;
  10229. array_add(&temp_data, data);
  10230. }
  10231. } else {
  10232. if (lb_is_elem_const(elem, et)) {
  10233. continue;
  10234. }
  10235. lbCompoundLitElemTempData data = {};
  10236. data.expr = elem;
  10237. data.elem_index = cast(i32)i;
  10238. array_add(&temp_data, data);
  10239. }
  10240. }
  10241. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  10242. for_array(i, temp_data) {
  10243. i32 index = temp_data[i].elem_index - index_offset;
  10244. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  10245. }
  10246. for_array(i, temp_data) {
  10247. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  10248. auto return_ptr_hint_value = p->return_ptr_hint_value;
  10249. auto return_ptr_hint_used = p->return_ptr_hint_used;
  10250. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  10251. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  10252. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  10253. lbValue field_expr = temp_data[i].value;
  10254. Ast *expr = temp_data[i].expr;
  10255. p->return_ptr_hint_value = temp_data[i].gep;
  10256. p->return_ptr_hint_ast = unparen_expr(expr);
  10257. if (field_expr.value == nullptr) {
  10258. field_expr = lb_build_expr(p, expr);
  10259. }
  10260. Type *t = field_expr.type;
  10261. GB_ASSERT(t->kind != Type_Tuple);
  10262. lbValue ev = lb_emit_conv(p, field_expr, et);
  10263. if (!p->return_ptr_hint_used) {
  10264. temp_data[i].value = ev;
  10265. }
  10266. }
  10267. for_array(i, temp_data) {
  10268. if (temp_data[i].value.value != nullptr) {
  10269. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10270. }
  10271. }
  10272. }
  10273. break;
  10274. }
  10275. case Type_Slice: {
  10276. if (cl->elems.count > 0) {
  10277. Type *elem_type = bt->Slice.elem;
  10278. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  10279. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  10280. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  10281. lbValue data = lb_slice_elem(p, slice);
  10282. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10283. for_array(i, cl->elems) {
  10284. Ast *elem = cl->elems[i];
  10285. if (elem->kind == Ast_FieldValue) {
  10286. ast_node(fv, FieldValue, elem);
  10287. if (lb_is_elem_const(fv->value, et)) {
  10288. continue;
  10289. }
  10290. if (is_ast_range(fv->field)) {
  10291. ast_node(ie, BinaryExpr, fv->field);
  10292. TypeAndValue lo_tav = ie->left->tav;
  10293. TypeAndValue hi_tav = ie->right->tav;
  10294. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10295. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10296. TokenKind op = ie->op.kind;
  10297. i64 lo = exact_value_to_i64(lo_tav.value);
  10298. i64 hi = exact_value_to_i64(hi_tav.value);
  10299. if (op == Token_Ellipsis) {
  10300. hi += 1;
  10301. }
  10302. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10303. for (i64 k = lo; k < hi; k++) {
  10304. lbCompoundLitElemTempData data = {};
  10305. data.value = value;
  10306. data.elem_index = cast(i32)k;
  10307. array_add(&temp_data, data);
  10308. }
  10309. } else {
  10310. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10311. i64 index = exact_value_to_i64(fv->field->tav.value);
  10312. lbValue field_expr = lb_build_expr(p, fv->value);
  10313. GB_ASSERT(!is_type_tuple(field_expr.type));
  10314. lbValue ev = lb_emit_conv(p, field_expr, et);
  10315. lbCompoundLitElemTempData data = {};
  10316. data.value = ev;
  10317. data.elem_index = cast(i32)index;
  10318. array_add(&temp_data, data);
  10319. }
  10320. } else {
  10321. if (lb_is_elem_const(elem, et)) {
  10322. continue;
  10323. }
  10324. lbValue field_expr = lb_build_expr(p, elem);
  10325. GB_ASSERT(!is_type_tuple(field_expr.type));
  10326. lbValue ev = lb_emit_conv(p, field_expr, et);
  10327. lbCompoundLitElemTempData data = {};
  10328. data.value = ev;
  10329. data.elem_index = cast(i32)i;
  10330. array_add(&temp_data, data);
  10331. }
  10332. }
  10333. for_array(i, temp_data) {
  10334. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  10335. }
  10336. for_array(i, temp_data) {
  10337. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10338. }
  10339. {
  10340. lbValue count = {};
  10341. count.type = t_int;
  10342. if (lb_is_const(slice)) {
  10343. unsigned indices[1] = {1};
  10344. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  10345. } else {
  10346. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  10347. }
  10348. lb_fill_slice(p, v, data, count);
  10349. }
  10350. }
  10351. break;
  10352. }
  10353. case Type_DynamicArray: {
  10354. if (cl->elems.count == 0) {
  10355. break;
  10356. }
  10357. Type *et = bt->DynamicArray.elem;
  10358. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  10359. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  10360. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  10361. {
  10362. auto args = array_make<lbValue>(permanent_allocator(), 5);
  10363. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  10364. args[1] = size;
  10365. args[2] = align;
  10366. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  10367. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  10368. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  10369. }
  10370. lbValue items = lb_generate_local_array(p, et, item_count);
  10371. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  10372. for_array(i, cl->elems) {
  10373. Ast *elem = cl->elems[i];
  10374. if (elem->kind == Ast_FieldValue) {
  10375. ast_node(fv, FieldValue, elem);
  10376. if (is_ast_range(fv->field)) {
  10377. ast_node(ie, BinaryExpr, fv->field);
  10378. TypeAndValue lo_tav = ie->left->tav;
  10379. TypeAndValue hi_tav = ie->right->tav;
  10380. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10381. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10382. TokenKind op = ie->op.kind;
  10383. i64 lo = exact_value_to_i64(lo_tav.value);
  10384. i64 hi = exact_value_to_i64(hi_tav.value);
  10385. if (op == Token_Ellipsis) {
  10386. hi += 1;
  10387. }
  10388. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10389. for (i64 k = lo; k < hi; k++) {
  10390. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  10391. lb_emit_store(p, ep, value);
  10392. }
  10393. } else {
  10394. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10395. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  10396. lbValue ev = lb_build_expr(p, fv->value);
  10397. lbValue value = lb_emit_conv(p, ev, et);
  10398. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  10399. lb_emit_store(p, ep, value);
  10400. }
  10401. } else {
  10402. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  10403. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  10404. lb_emit_store(p, ep, value);
  10405. }
  10406. }
  10407. {
  10408. auto args = array_make<lbValue>(permanent_allocator(), 6);
  10409. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  10410. args[1] = size;
  10411. args[2] = align;
  10412. args[3] = lb_emit_conv(p, items, t_rawptr);
  10413. args[4] = lb_const_int(p->module, t_int, item_count);
  10414. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  10415. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  10416. }
  10417. break;
  10418. }
  10419. case Type_Basic: {
  10420. GB_ASSERT(is_type_any(bt));
  10421. if (cl->elems.count > 0) {
  10422. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10423. String field_names[2] = {
  10424. str_lit("data"),
  10425. str_lit("id"),
  10426. };
  10427. Type *field_types[2] = {
  10428. t_rawptr,
  10429. t_typeid,
  10430. };
  10431. for_array(field_index, cl->elems) {
  10432. Ast *elem = cl->elems[field_index];
  10433. lbValue field_expr = {};
  10434. isize index = field_index;
  10435. if (elem->kind == Ast_FieldValue) {
  10436. ast_node(fv, FieldValue, elem);
  10437. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  10438. index = sel.index[0];
  10439. elem = fv->value;
  10440. } else {
  10441. TypeAndValue tav = type_and_value_of_expr(elem);
  10442. Selection sel = lookup_field(bt, field_names[field_index], false);
  10443. index = sel.index[0];
  10444. }
  10445. field_expr = lb_build_expr(p, elem);
  10446. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  10447. Type *ft = field_types[index];
  10448. lbValue fv = lb_emit_conv(p, field_expr, ft);
  10449. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10450. lb_emit_store(p, gep, fv);
  10451. }
  10452. }
  10453. break;
  10454. }
  10455. case Type_BitSet: {
  10456. i64 sz = type_size_of(type);
  10457. if (cl->elems.count > 0 && sz > 0) {
  10458. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10459. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  10460. for_array(i, cl->elems) {
  10461. Ast *elem = cl->elems[i];
  10462. GB_ASSERT(elem->kind != Ast_FieldValue);
  10463. if (lb_is_elem_const(elem, et)) {
  10464. continue;
  10465. }
  10466. lbValue expr = lb_build_expr(p, elem);
  10467. GB_ASSERT(expr.type->kind != Type_Tuple);
  10468. Type *it = bit_set_to_int(bt);
  10469. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  10470. lbValue e = lb_emit_conv(p, expr, it);
  10471. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  10472. e = lb_emit_arith(p, Token_Shl, one, e, it);
  10473. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  10474. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  10475. new_value = lb_emit_transmute(p, new_value, type);
  10476. lb_addr_store(p, v, new_value);
  10477. }
  10478. }
  10479. break;
  10480. }
  10481. }
  10482. return v;
  10483. case_end;
  10484. case_ast_node(tc, TypeCast, expr);
  10485. Type *type = type_of_expr(expr);
  10486. lbValue x = lb_build_expr(p, tc->expr);
  10487. lbValue e = {};
  10488. switch (tc->token.kind) {
  10489. case Token_cast:
  10490. e = lb_emit_conv(p, x, type);
  10491. break;
  10492. case Token_transmute:
  10493. e = lb_emit_transmute(p, x, type);
  10494. break;
  10495. default:
  10496. GB_PANIC("Invalid AST TypeCast");
  10497. }
  10498. lbAddr v = lb_add_local_generated(p, type, false);
  10499. lb_addr_store(p, v, e);
  10500. return v;
  10501. case_end;
  10502. case_ast_node(ac, AutoCast, expr);
  10503. return lb_build_addr(p, ac->expr);
  10504. case_end;
  10505. }
  10506. TokenPos token_pos = ast_token(expr).pos;
  10507. GB_PANIC("Unexpected address expression\n"
  10508. "\tAst: %.*s @ "
  10509. "%s\n",
  10510. LIT(ast_strings[expr->kind]),
  10511. token_pos_to_string(token_pos));
  10512. return {};
  10513. }
  10514. void lb_init_module(lbModule *m, Checker *c) {
  10515. m->info = &c->info;
  10516. m->ctx = LLVMGetGlobalContext();
  10517. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  10518. // m->debug_builder = nullptr;
  10519. if (build_context.ODIN_DEBUG) {
  10520. enum {DEBUG_METADATA_VERSION = 3};
  10521. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  10522. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  10523. switch (build_context.metrics.os) {
  10524. case TargetOs_windows:
  10525. LLVMAddModuleFlag(m->mod,
  10526. LLVMModuleFlagBehaviorWarning,
  10527. "CodeView", 8,
  10528. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true)));
  10529. break;
  10530. case TargetOs_darwin:
  10531. // NOTE(bill): Darwin only supports DWARF2 (that I know of)
  10532. LLVMAddModuleFlag(m->mod,
  10533. LLVMModuleFlagBehaviorWarning,
  10534. "Dwarf Version", 13,
  10535. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 2, true)));
  10536. break;
  10537. }
  10538. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  10539. }
  10540. m->state_flags = 0;
  10541. m->state_flags |= StateFlag_bounds_check;
  10542. gb_mutex_init(&m->mutex);
  10543. gbAllocator a = heap_allocator();
  10544. map_init(&m->types, a);
  10545. map_init(&m->llvm_types, a);
  10546. map_init(&m->values, a);
  10547. map_init(&m->soa_values, a);
  10548. string_map_init(&m->members, a);
  10549. map_init(&m->procedure_values, a);
  10550. string_map_init(&m->procedures, a);
  10551. string_map_init(&m->const_strings, a);
  10552. map_init(&m->anonymous_proc_lits, a);
  10553. map_init(&m->function_type_map, a);
  10554. map_init(&m->equal_procs, a);
  10555. map_init(&m->hasher_procs, a);
  10556. array_init(&m->procedures_to_generate, a, 0, 1024);
  10557. array_init(&m->foreign_library_paths, a, 0, 1024);
  10558. map_init(&m->debug_values, a);
  10559. array_init(&m->debug_incomplete_types, a, 0, 1024);
  10560. }
  10561. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  10562. if (global_error_collector.count != 0) {
  10563. return false;
  10564. }
  10565. isize tc = c->parser->total_token_count;
  10566. if (tc < 2) {
  10567. return false;
  10568. }
  10569. String init_fullpath = c->parser->init_fullpath;
  10570. if (build_context.out_filepath.len == 0) {
  10571. gen->output_name = remove_directory_from_path(init_fullpath);
  10572. gen->output_name = remove_extension_from_path(gen->output_name);
  10573. gen->output_name = string_trim_whitespace(gen->output_name);
  10574. if (gen->output_name.len == 0) {
  10575. gen->output_name = c->info.init_scope->pkg->name;
  10576. }
  10577. gen->output_base = gen->output_name;
  10578. } else {
  10579. gen->output_name = build_context.out_filepath;
  10580. gen->output_name = string_trim_whitespace(gen->output_name);
  10581. if (gen->output_name.len == 0) {
  10582. gen->output_name = c->info.init_scope->pkg->name;
  10583. }
  10584. isize pos = string_extension_position(gen->output_name);
  10585. if (pos < 0) {
  10586. gen->output_base = gen->output_name;
  10587. } else {
  10588. gen->output_base = substring(gen->output_name, 0, pos);
  10589. }
  10590. }
  10591. gbAllocator ha = heap_allocator();
  10592. array_init(&gen->output_object_paths, ha);
  10593. gen->output_base = path_to_full_path(ha, gen->output_base);
  10594. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  10595. output_file_path = gb_string_appendc(output_file_path, ".obj");
  10596. defer (gb_string_free(output_file_path));
  10597. gen->info = &c->info;
  10598. lb_init_module(&gen->module, c);
  10599. return true;
  10600. }
  10601. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  10602. GB_ASSERT(type != nullptr);
  10603. type = default_type(type);
  10604. isize max_len = 7+8+1;
  10605. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  10606. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  10607. m->global_generated_index++;
  10608. String name = make_string(str, len-1);
  10609. Scope *scope = nullptr;
  10610. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  10611. lbValue g = {};
  10612. g.type = alloc_type_pointer(type);
  10613. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  10614. if (value.value != nullptr) {
  10615. GB_ASSERT(LLVMIsConstant(value.value));
  10616. LLVMSetInitializer(g.value, value.value);
  10617. } else {
  10618. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  10619. }
  10620. lb_add_entity(m, e, g);
  10621. lb_add_member(m, name, g);
  10622. return lb_addr(g);
  10623. }
  10624. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  10625. AstPackage *p = m->info->runtime_package;
  10626. Entity *e = scope_lookup_current(p->scope, name);
  10627. lbValue *found = map_get(&m->values, hash_entity(e));
  10628. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  10629. lbValue value = *found;
  10630. return value;
  10631. }
  10632. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  10633. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  10634. lbValue *found = map_get(&m->values, hash_entity(e));
  10635. GB_ASSERT_MSG(found != nullptr, "Unable to find value '%.*s.%.*s'", LIT(pkg), LIT(name));
  10636. lbValue value = *found;
  10637. return value;
  10638. }
  10639. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  10640. i32 index = cast(i32)lb_type_info_index(m->info, type);
  10641. GB_ASSERT(index >= 0);
  10642. // gb_printf_err("%d %s\n", index, type_to_string(type));
  10643. LLVMValueRef indices[2] = {
  10644. LLVMConstInt(lb_type(m, t_int), 0, false),
  10645. LLVMConstInt(lb_type(m, t_int), index, false),
  10646. };
  10647. lbValue res = {};
  10648. res.type = t_type_info_ptr;
  10649. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  10650. return res;
  10651. }
  10652. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  10653. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  10654. lb_global_type_info_member_types_index += cast(i32)count;
  10655. return offset;
  10656. }
  10657. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  10658. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  10659. lb_global_type_info_member_names_index += cast(i32)count;
  10660. return offset;
  10661. }
  10662. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  10663. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  10664. lb_global_type_info_member_offsets_index += cast(i32)count;
  10665. return offset;
  10666. }
  10667. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  10668. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  10669. lb_global_type_info_member_usings_index += cast(i32)count;
  10670. return offset;
  10671. }
  10672. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  10673. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  10674. lb_global_type_info_member_tags_index += cast(i32)count;
  10675. return offset;
  10676. }
  10677. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  10678. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  10679. return lb_addr_get_ptr(p, addr);
  10680. }
  10681. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  10682. Token token = {Token_Ident};
  10683. isize name_len = prefix.len + 1 + 20;
  10684. auto suffix_id = cast(unsigned long long)id;
  10685. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  10686. gb_snprintf(text, name_len,
  10687. "%.*s-%llu", LIT(prefix), suffix_id);
  10688. text[name_len] = 0;
  10689. String s = make_string_c(text);
  10690. Type *t = alloc_type_array(elem_type, count);
  10691. lbValue g = {};
  10692. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  10693. g.type = alloc_type_pointer(t);
  10694. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  10695. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  10696. string_map_set(&m->members, s, g);
  10697. return g;
  10698. }
  10699. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  10700. lbModule *m = p->module;
  10701. LLVMContextRef ctx = m->ctx;
  10702. CheckerInfo *info = m->info;
  10703. {
  10704. // NOTE(bill): Set the type_table slice with the global backing array
  10705. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  10706. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  10707. GB_ASSERT(is_type_array(type));
  10708. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  10709. LLVMValueRef values[2] = {
  10710. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  10711. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  10712. };
  10713. LLVMValueRef slice = llvm_const_named_struct(llvm_addr_type(global_type_table), values, gb_count_of(values));
  10714. LLVMSetInitializer(global_type_table.value, slice);
  10715. }
  10716. // Useful types
  10717. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  10718. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  10719. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  10720. Type *t_type_info_flags = type_info_flags_entity->type;
  10721. i32 type_info_member_types_index = 0;
  10722. i32 type_info_member_names_index = 0;
  10723. i32 type_info_member_offsets_index = 0;
  10724. for_array(type_info_type_index, info->type_info_types) {
  10725. Type *t = info->type_info_types[type_info_type_index];
  10726. if (t == nullptr || t == t_invalid) {
  10727. continue;
  10728. }
  10729. isize entry_index = lb_type_info_index(info, t, false);
  10730. if (entry_index <= 0) {
  10731. continue;
  10732. }
  10733. lbValue tag = {};
  10734. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  10735. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  10736. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  10737. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  10738. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  10739. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  10740. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  10741. switch (t->kind) {
  10742. case Type_Named: {
  10743. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  10744. LLVMValueRef pkg_name = nullptr;
  10745. if (t->Named.type_name->pkg) {
  10746. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  10747. } else {
  10748. pkg_name = LLVMConstNull(lb_type(m, t_string));
  10749. }
  10750. String proc_name = {};
  10751. if (t->Named.type_name->parent_proc_decl) {
  10752. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  10753. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  10754. proc_name = decl->entity->token.string;
  10755. }
  10756. }
  10757. TokenPos pos = t->Named.type_name->token.pos;
  10758. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  10759. LLVMValueRef vals[4] = {
  10760. lb_const_string(p->module, t->Named.type_name->token.string).value,
  10761. lb_get_type_info_ptr(m, t->Named.base).value,
  10762. pkg_name,
  10763. loc.value
  10764. };
  10765. lbValue res = {};
  10766. res.type = type_deref(tag.type);
  10767. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10768. lb_emit_store(p, tag, res);
  10769. break;
  10770. }
  10771. case Type_Basic:
  10772. switch (t->Basic.kind) {
  10773. case Basic_bool:
  10774. case Basic_b8:
  10775. case Basic_b16:
  10776. case Basic_b32:
  10777. case Basic_b64:
  10778. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  10779. break;
  10780. case Basic_i8:
  10781. case Basic_u8:
  10782. case Basic_i16:
  10783. case Basic_u16:
  10784. case Basic_i32:
  10785. case Basic_u32:
  10786. case Basic_i64:
  10787. case Basic_u64:
  10788. case Basic_i128:
  10789. case Basic_u128:
  10790. case Basic_i16le:
  10791. case Basic_u16le:
  10792. case Basic_i32le:
  10793. case Basic_u32le:
  10794. case Basic_i64le:
  10795. case Basic_u64le:
  10796. case Basic_i128le:
  10797. case Basic_u128le:
  10798. case Basic_i16be:
  10799. case Basic_u16be:
  10800. case Basic_i32be:
  10801. case Basic_u32be:
  10802. case Basic_i64be:
  10803. case Basic_u64be:
  10804. case Basic_i128be:
  10805. case Basic_u128be:
  10806. case Basic_int:
  10807. case Basic_uint:
  10808. case Basic_uintptr: {
  10809. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  10810. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  10811. // NOTE(bill): This is matches the runtime layout
  10812. u8 endianness_value = 0;
  10813. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10814. endianness_value = 1;
  10815. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10816. endianness_value = 2;
  10817. }
  10818. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10819. LLVMValueRef vals[2] = {
  10820. is_signed.value,
  10821. endianness.value,
  10822. };
  10823. lbValue res = {};
  10824. res.type = type_deref(tag.type);
  10825. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10826. lb_emit_store(p, tag, res);
  10827. break;
  10828. }
  10829. case Basic_rune:
  10830. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  10831. break;
  10832. case Basic_f16:
  10833. case Basic_f32:
  10834. case Basic_f64:
  10835. case Basic_f16le:
  10836. case Basic_f32le:
  10837. case Basic_f64le:
  10838. case Basic_f16be:
  10839. case Basic_f32be:
  10840. case Basic_f64be:
  10841. {
  10842. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  10843. // NOTE(bill): This is matches the runtime layout
  10844. u8 endianness_value = 0;
  10845. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10846. endianness_value = 1;
  10847. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10848. endianness_value = 2;
  10849. }
  10850. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10851. LLVMValueRef vals[1] = {
  10852. endianness.value,
  10853. };
  10854. lbValue res = {};
  10855. res.type = type_deref(tag.type);
  10856. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10857. lb_emit_store(p, tag, res);
  10858. }
  10859. break;
  10860. case Basic_complex32:
  10861. case Basic_complex64:
  10862. case Basic_complex128:
  10863. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  10864. break;
  10865. case Basic_quaternion64:
  10866. case Basic_quaternion128:
  10867. case Basic_quaternion256:
  10868. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  10869. break;
  10870. case Basic_rawptr:
  10871. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10872. break;
  10873. case Basic_string:
  10874. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10875. break;
  10876. case Basic_cstring:
  10877. {
  10878. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10879. LLVMValueRef vals[1] = {
  10880. lb_const_bool(m, t_bool, true).value,
  10881. };
  10882. lbValue res = {};
  10883. res.type = type_deref(tag.type);
  10884. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10885. lb_emit_store(p, tag, res);
  10886. }
  10887. break;
  10888. case Basic_any:
  10889. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  10890. break;
  10891. case Basic_typeid:
  10892. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  10893. break;
  10894. }
  10895. break;
  10896. case Type_Pointer: {
  10897. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10898. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  10899. LLVMValueRef vals[1] = {
  10900. gep.value,
  10901. };
  10902. lbValue res = {};
  10903. res.type = type_deref(tag.type);
  10904. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10905. lb_emit_store(p, tag, res);
  10906. break;
  10907. }
  10908. case Type_Array: {
  10909. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  10910. i64 ez = type_size_of(t->Array.elem);
  10911. LLVMValueRef vals[3] = {
  10912. lb_get_type_info_ptr(m, t->Array.elem).value,
  10913. lb_const_int(m, t_int, ez).value,
  10914. lb_const_int(m, t_int, t->Array.count).value,
  10915. };
  10916. lbValue res = {};
  10917. res.type = type_deref(tag.type);
  10918. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10919. lb_emit_store(p, tag, res);
  10920. break;
  10921. }
  10922. case Type_EnumeratedArray: {
  10923. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  10924. LLVMValueRef vals[6] = {
  10925. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  10926. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  10927. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  10928. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  10929. // Unions
  10930. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10931. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10932. };
  10933. lbValue res = {};
  10934. res.type = type_deref(tag.type);
  10935. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10936. lb_emit_store(p, tag, res);
  10937. // NOTE(bill): Union assignment
  10938. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  10939. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  10940. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  10941. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  10942. lb_emit_store(p, min_value, min_v);
  10943. lb_emit_store(p, max_value, max_v);
  10944. break;
  10945. }
  10946. case Type_DynamicArray: {
  10947. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  10948. LLVMValueRef vals[2] = {
  10949. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  10950. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  10951. };
  10952. lbValue res = {};
  10953. res.type = type_deref(tag.type);
  10954. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10955. lb_emit_store(p, tag, res);
  10956. break;
  10957. }
  10958. case Type_Slice: {
  10959. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  10960. LLVMValueRef vals[2] = {
  10961. lb_get_type_info_ptr(m, t->Slice.elem).value,
  10962. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  10963. };
  10964. lbValue res = {};
  10965. res.type = type_deref(tag.type);
  10966. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10967. lb_emit_store(p, tag, res);
  10968. break;
  10969. }
  10970. case Type_Proc: {
  10971. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  10972. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10973. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10974. if (t->Proc.params != nullptr) {
  10975. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  10976. }
  10977. if (t->Proc.results != nullptr) {
  10978. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  10979. }
  10980. LLVMValueRef vals[4] = {
  10981. params,
  10982. results,
  10983. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  10984. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  10985. };
  10986. lbValue res = {};
  10987. res.type = type_deref(tag.type);
  10988. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10989. lb_emit_store(p, tag, res);
  10990. break;
  10991. }
  10992. case Type_Tuple: {
  10993. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  10994. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  10995. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  10996. for_array(i, t->Tuple.variables) {
  10997. // NOTE(bill): offset is not used for tuples
  10998. Entity *f = t->Tuple.variables[i];
  10999. lbValue index = lb_const_int(m, t_int, i);
  11000. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11001. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  11002. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  11003. if (f->token.string.len > 0) {
  11004. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  11005. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  11006. }
  11007. }
  11008. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  11009. LLVMValueRef types_slice = llvm_const_slice(m, memory_types, count);
  11010. LLVMValueRef names_slice = llvm_const_slice(m, memory_names, count);
  11011. LLVMValueRef vals[2] = {
  11012. types_slice,
  11013. names_slice,
  11014. };
  11015. lbValue res = {};
  11016. res.type = type_deref(tag.type);
  11017. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11018. lb_emit_store(p, tag, res);
  11019. break;
  11020. }
  11021. case Type_Enum:
  11022. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  11023. {
  11024. GB_ASSERT(t->Enum.base_type != nullptr);
  11025. // 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));
  11026. LLVMValueRef vals[3] = {};
  11027. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  11028. if (t->Enum.fields.count > 0) {
  11029. auto fields = t->Enum.fields;
  11030. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  11031. str_lit("$enum_names"), cast(i64)entry_index);
  11032. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  11033. str_lit("$enum_values"), cast(i64)entry_index);
  11034. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  11035. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  11036. GB_ASSERT(is_type_integer(t->Enum.base_type));
  11037. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  11038. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  11039. for_array(i, fields) {
  11040. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  11041. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  11042. }
  11043. LLVMValueRef name_init = llvm_const_array(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  11044. LLVMValueRef value_init = llvm_const_array(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  11045. LLVMSetInitializer(name_array.value, name_init);
  11046. LLVMSetInitializer(value_array.value, value_init);
  11047. lbValue v_count = lb_const_int(m, t_int, fields.count);
  11048. vals[1] = llvm_const_slice(m, lb_array_elem(p, name_array), v_count);
  11049. vals[2] = llvm_const_slice(m, lb_array_elem(p, value_array), v_count);
  11050. } else {
  11051. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  11052. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  11053. }
  11054. lbValue res = {};
  11055. res.type = type_deref(tag.type);
  11056. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11057. lb_emit_store(p, tag, res);
  11058. }
  11059. break;
  11060. case Type_Union: {
  11061. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  11062. {
  11063. LLVMValueRef vals[6] = {};
  11064. isize variant_count = gb_max(0, t->Union.variants.count);
  11065. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  11066. // NOTE(bill): Zeroth is nil so ignore it
  11067. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  11068. Type *vt = t->Union.variants[variant_index];
  11069. lbValue tip = lb_get_type_info_ptr(m, vt);
  11070. lbValue index = lb_const_int(m, t_int, variant_index);
  11071. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11072. lb_emit_store(p, type_info, lb_type_info(m, vt));
  11073. }
  11074. lbValue count = lb_const_int(m, t_int, variant_count);
  11075. vals[0] = llvm_const_slice(m, memory_types, count);
  11076. i64 tag_size = union_tag_size(t);
  11077. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  11078. if (tag_size > 0) {
  11079. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  11080. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  11081. } else {
  11082. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  11083. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11084. }
  11085. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  11086. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  11087. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  11088. lbValue res = {};
  11089. res.type = type_deref(tag.type);
  11090. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11091. lb_emit_store(p, tag, res);
  11092. }
  11093. break;
  11094. }
  11095. case Type_Struct: {
  11096. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  11097. LLVMValueRef vals[12] = {};
  11098. {
  11099. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  11100. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  11101. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  11102. vals[5] = is_packed.value;
  11103. vals[6] = is_raw_union.value;
  11104. vals[7] = is_custom_align.value;
  11105. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  11106. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  11107. }
  11108. if (t->Struct.soa_kind != StructSoa_None) {
  11109. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  11110. Type *kind_type = type_deref(kind.type);
  11111. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  11112. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  11113. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  11114. vals[9] = soa_kind.value;
  11115. vals[10] = soa_type.value;
  11116. vals[11] = soa_len.value;
  11117. }
  11118. }
  11119. isize count = t->Struct.fields.count;
  11120. if (count > 0) {
  11121. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  11122. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  11123. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  11124. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  11125. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  11126. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  11127. for (isize source_index = 0; source_index < count; source_index++) {
  11128. // TODO(bill): Order fields in source order not layout order
  11129. Entity *f = t->Struct.fields[source_index];
  11130. lbValue tip = lb_get_type_info_ptr(m, f->type);
  11131. i64 foffset = 0;
  11132. if (!t->Struct.is_raw_union) {
  11133. foffset = t->Struct.offsets[f->Variable.field_index];
  11134. }
  11135. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  11136. lbValue index = lb_const_int(m, t_int, source_index);
  11137. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11138. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  11139. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  11140. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  11141. if (f->token.string.len > 0) {
  11142. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  11143. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  11144. }
  11145. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  11146. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  11147. if (t->Struct.tags.count > 0) {
  11148. String tag_string = t->Struct.tags[source_index];
  11149. if (tag_string.len > 0) {
  11150. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  11151. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  11152. }
  11153. }
  11154. }
  11155. lbValue cv = lb_const_int(m, t_int, count);
  11156. vals[0] = llvm_const_slice(m, memory_types, cv);
  11157. vals[1] = llvm_const_slice(m, memory_names, cv);
  11158. vals[2] = llvm_const_slice(m, memory_offsets, cv);
  11159. vals[3] = llvm_const_slice(m, memory_usings, cv);
  11160. vals[4] = llvm_const_slice(m, memory_tags, cv);
  11161. }
  11162. for (isize i = 0; i < gb_count_of(vals); i++) {
  11163. if (vals[i] == nullptr) {
  11164. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  11165. }
  11166. }
  11167. lbValue res = {};
  11168. res.type = type_deref(tag.type);
  11169. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11170. lb_emit_store(p, tag, res);
  11171. break;
  11172. }
  11173. case Type_Map: {
  11174. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  11175. init_map_internal_types(t);
  11176. LLVMValueRef vals[5] = {
  11177. lb_get_type_info_ptr(m, t->Map.key).value,
  11178. lb_get_type_info_ptr(m, t->Map.value).value,
  11179. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  11180. lb_get_equal_proc_for_type(m, t->Map.key).value,
  11181. lb_get_hasher_proc_for_type(m, t->Map.key).value
  11182. };
  11183. lbValue res = {};
  11184. res.type = type_deref(tag.type);
  11185. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11186. lb_emit_store(p, tag, res);
  11187. break;
  11188. }
  11189. case Type_BitSet:
  11190. {
  11191. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  11192. GB_ASSERT(is_type_typed(t->BitSet.elem));
  11193. LLVMValueRef vals[4] = {
  11194. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  11195. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  11196. lb_const_int(m, t_i64, t->BitSet.lower).value,
  11197. lb_const_int(m, t_i64, t->BitSet.upper).value,
  11198. };
  11199. if (t->BitSet.underlying != nullptr) {
  11200. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  11201. }
  11202. lbValue res = {};
  11203. res.type = type_deref(tag.type);
  11204. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11205. lb_emit_store(p, tag, res);
  11206. }
  11207. break;
  11208. case Type_SimdVector:
  11209. {
  11210. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  11211. LLVMValueRef vals[4] = {};
  11212. if (t->SimdVector.is_x86_mmx) {
  11213. vals[3] = lb_const_bool(m, t_bool, true).value;
  11214. } else {
  11215. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  11216. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  11217. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  11218. }
  11219. lbValue res = {};
  11220. res.type = type_deref(tag.type);
  11221. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11222. lb_emit_store(p, tag, res);
  11223. }
  11224. break;
  11225. case Type_RelativePointer:
  11226. {
  11227. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  11228. LLVMValueRef vals[2] = {
  11229. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  11230. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  11231. };
  11232. lbValue res = {};
  11233. res.type = type_deref(tag.type);
  11234. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11235. lb_emit_store(p, tag, res);
  11236. }
  11237. break;
  11238. case Type_RelativeSlice:
  11239. {
  11240. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  11241. LLVMValueRef vals[2] = {
  11242. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  11243. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  11244. };
  11245. lbValue res = {};
  11246. res.type = type_deref(tag.type);
  11247. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11248. lb_emit_store(p, tag, res);
  11249. }
  11250. break;
  11251. }
  11252. if (tag.value != nullptr) {
  11253. Type *tag_type = type_deref(tag.type);
  11254. GB_ASSERT(is_type_named(tag_type));
  11255. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  11256. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  11257. } else {
  11258. if (t != t_llvm_bool) {
  11259. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  11260. }
  11261. }
  11262. }
  11263. }
  11264. void lb_generate_code(lbGenerator *gen) {
  11265. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  11266. TIME_SECTION("LLVM Initializtion");
  11267. lbModule *m = &gen->module;
  11268. LLVMModuleRef mod = gen->module.mod;
  11269. CheckerInfo *info = gen->info;
  11270. auto *min_dep_set = &info->minimum_dependency_set;
  11271. LLVMInitializeAllTargetInfos();
  11272. LLVMInitializeAllTargets();
  11273. LLVMInitializeAllTargetMCs();
  11274. LLVMInitializeAllAsmPrinters();
  11275. LLVMInitializeAllAsmParsers();
  11276. LLVMInitializeAllDisassemblers();
  11277. LLVMInitializeNativeTarget();
  11278. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  11279. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  11280. LLVMSetTarget(mod, target_triple);
  11281. LLVMTargetRef target = {};
  11282. char *llvm_error = nullptr;
  11283. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  11284. GB_ASSERT(target != nullptr);
  11285. TIME_SECTION("LLVM Create Target Machine");
  11286. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  11287. if (build_context.metrics.arch == TargetArch_wasm32) {
  11288. code_mode = LLVMCodeModelJITDefault;
  11289. }
  11290. char const *host_cpu_name = LLVMGetHostCPUName();
  11291. char const *llvm_cpu = "generic";
  11292. char const *llvm_features = "";
  11293. if (build_context.microarch.len != 0) {
  11294. if (build_context.microarch == "native") {
  11295. llvm_cpu = host_cpu_name;
  11296. } else {
  11297. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  11298. }
  11299. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  11300. llvm_features = LLVMGetHostCPUFeatures();
  11301. }
  11302. }
  11303. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  11304. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  11305. switch (build_context.optimization_level) {
  11306. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  11307. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  11308. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  11309. case 3: code_gen_level = LLVMCodeGenLevelDefault; break; // NOTE(bill): force -opt:3 to be the same as -opt:2
  11310. // case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  11311. }
  11312. // NOTE(bill): Target Machine Creation
  11313. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(
  11314. target, target_triple, llvm_cpu,
  11315. llvm_features,
  11316. code_gen_level,
  11317. LLVMRelocDefault,
  11318. code_mode);
  11319. defer (LLVMDisposeTargetMachine(target_machine));
  11320. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  11321. if (m->debug_builder) { // Debug Info
  11322. for_array(i, info->files.entries) {
  11323. AstFile *f = info->files.entries[i].value;
  11324. String fullpath = f->fullpath;
  11325. String filename = remove_directory_from_path(fullpath);
  11326. String directory = directory_from_path(fullpath);
  11327. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  11328. cast(char const *)filename.text, filename.len,
  11329. cast(char const *)directory.text, directory.len);
  11330. lb_set_llvm_metadata(m, f, res);
  11331. }
  11332. gbString producer = gb_string_make(heap_allocator(), "odin");
  11333. producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  11334. #ifdef NIGHTLY
  11335. producer = gb_string_appendc(producer, "-nightly");
  11336. #endif
  11337. #ifdef GIT_SHA
  11338. producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  11339. #endif
  11340. gbString split_name = gb_string_make(heap_allocator(), "");
  11341. LLVMBool is_optimized = build_context.optimization_level > 0;
  11342. AstFile *init_file = m->info->init_package->files[0];
  11343. if (m->info->entry_point && m->info->entry_point->identifier && m->info->entry_point->identifier->file) {
  11344. init_file = m->info->entry_point->identifier->file;
  11345. }
  11346. LLVMBool split_debug_inlining = false;
  11347. LLVMBool debug_info_for_profiling = false;
  11348. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  11349. lb_get_llvm_metadata(m, init_file),
  11350. producer, gb_string_length(producer),
  11351. is_optimized, "", 0,
  11352. 1, split_name, gb_string_length(split_name),
  11353. LLVMDWARFEmissionFull,
  11354. 0, split_debug_inlining,
  11355. debug_info_for_profiling,
  11356. "", 0, // sys_root
  11357. "", 0 // SDK
  11358. );
  11359. GB_ASSERT(m->debug_compile_unit != nullptr);
  11360. }
  11361. TIME_SECTION("LLVM Global Variables");
  11362. {
  11363. { // Add type info data
  11364. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  11365. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  11366. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  11367. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  11368. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11369. LLVMSetLinkage(g, LLVMInternalLinkage);
  11370. lbValue value = {};
  11371. value.value = g;
  11372. value.type = alloc_type_pointer(t);
  11373. lb_global_type_info_data = lb_addr(value);
  11374. }
  11375. { // Type info member buffer
  11376. // NOTE(bill): Removes need for heap allocation by making it global memory
  11377. isize count = 0;
  11378. for_array(entry_index, m->info->type_info_types) {
  11379. Type *t = m->info->type_info_types[entry_index];
  11380. isize index = lb_type_info_index(m->info, t, false);
  11381. if (index < 0) {
  11382. continue;
  11383. }
  11384. switch (t->kind) {
  11385. case Type_Union:
  11386. count += t->Union.variants.count;
  11387. break;
  11388. case Type_Struct:
  11389. count += t->Struct.fields.count;
  11390. break;
  11391. case Type_Tuple:
  11392. count += t->Tuple.variables.count;
  11393. break;
  11394. }
  11395. }
  11396. if (count > 0) {
  11397. {
  11398. char const *name = LB_TYPE_INFO_TYPES_NAME;
  11399. Type *t = alloc_type_array(t_type_info_ptr, count);
  11400. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11401. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11402. LLVMSetLinkage(g, LLVMInternalLinkage);
  11403. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  11404. }
  11405. {
  11406. char const *name = LB_TYPE_INFO_NAMES_NAME;
  11407. Type *t = alloc_type_array(t_string, count);
  11408. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11409. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11410. LLVMSetLinkage(g, LLVMInternalLinkage);
  11411. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  11412. }
  11413. {
  11414. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  11415. Type *t = alloc_type_array(t_uintptr, count);
  11416. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11417. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11418. LLVMSetLinkage(g, LLVMInternalLinkage);
  11419. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  11420. }
  11421. {
  11422. char const *name = LB_TYPE_INFO_USINGS_NAME;
  11423. Type *t = alloc_type_array(t_bool, count);
  11424. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11425. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11426. LLVMSetLinkage(g, LLVMInternalLinkage);
  11427. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  11428. }
  11429. {
  11430. char const *name = LB_TYPE_INFO_TAGS_NAME;
  11431. Type *t = alloc_type_array(t_string, count);
  11432. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11433. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11434. LLVMSetLinkage(g, LLVMInternalLinkage);
  11435. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  11436. }
  11437. }
  11438. }
  11439. }
  11440. isize global_variable_max_count = 0;
  11441. Entity *entry_point = info->entry_point;
  11442. bool has_dll_main = false;
  11443. bool has_win_main = false;
  11444. for_array(i, info->entities) {
  11445. Entity *e = info->entities[i];
  11446. String name = e->token.string;
  11447. bool is_global = e->pkg != nullptr;
  11448. if (e->kind == Entity_Variable) {
  11449. global_variable_max_count++;
  11450. } else if (e->kind == Entity_Procedure && !is_global) {
  11451. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  11452. GB_ASSERT(e == entry_point);
  11453. // entry_point = e;
  11454. }
  11455. if (e->Procedure.is_export ||
  11456. (e->Procedure.link_name.len > 0) ||
  11457. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  11458. if (!has_dll_main && name == "DllMain") {
  11459. has_dll_main = true;
  11460. } else if (!has_win_main && name == "WinMain") {
  11461. has_win_main = true;
  11462. }
  11463. }
  11464. }
  11465. }
  11466. struct GlobalVariable {
  11467. lbValue var;
  11468. lbValue init;
  11469. DeclInfo *decl;
  11470. bool is_initialized;
  11471. };
  11472. auto global_variables = array_make<GlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  11473. for_array(i, info->variable_init_order) {
  11474. DeclInfo *d = info->variable_init_order[i];
  11475. Entity *e = d->entity;
  11476. if ((e->scope->flags & ScopeFlag_File) == 0) {
  11477. continue;
  11478. }
  11479. if (!ptr_set_exists(min_dep_set, e)) {
  11480. continue;
  11481. }
  11482. DeclInfo *decl = decl_info_of_entity(e);
  11483. if (decl == nullptr) {
  11484. continue;
  11485. }
  11486. GB_ASSERT(e->kind == Entity_Variable);
  11487. bool is_foreign = e->Variable.is_foreign;
  11488. bool is_export = e->Variable.is_export;
  11489. String name = lb_get_entity_name(m, e);
  11490. lbValue g = {};
  11491. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  11492. g.type = alloc_type_pointer(e->type);
  11493. if (e->Variable.thread_local_model != "") {
  11494. LLVMSetThreadLocal(g.value, true);
  11495. String m = e->Variable.thread_local_model;
  11496. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  11497. if (m == "default") {
  11498. mode = LLVMGeneralDynamicTLSModel;
  11499. } else if (m == "localdynamic") {
  11500. mode = LLVMLocalDynamicTLSModel;
  11501. } else if (m == "initialexec") {
  11502. mode = LLVMInitialExecTLSModel;
  11503. } else if (m == "localexec") {
  11504. mode = LLVMLocalExecTLSModel;
  11505. } else {
  11506. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  11507. }
  11508. LLVMSetThreadLocalMode(g.value, mode);
  11509. }
  11510. if (is_foreign) {
  11511. LLVMSetExternallyInitialized(g.value, true);
  11512. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  11513. } else {
  11514. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  11515. }
  11516. if (is_export) {
  11517. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  11518. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  11519. }
  11520. if (e->flags & EntityFlag_Static) {
  11521. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  11522. }
  11523. GlobalVariable var = {};
  11524. var.var = g;
  11525. var.decl = decl;
  11526. if (decl->init_expr != nullptr) {
  11527. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  11528. if (!is_type_any(e->type)) {
  11529. if (tav.mode != Addressing_Invalid) {
  11530. if (tav.value.kind != ExactValue_Invalid) {
  11531. ExactValue v = tav.value;
  11532. lbValue init = lb_const_value(m, tav.type, v);
  11533. LLVMSetInitializer(g.value, init.value);
  11534. var.is_initialized = true;
  11535. }
  11536. }
  11537. }
  11538. if (!var.is_initialized &&
  11539. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  11540. var.is_initialized = true;
  11541. }
  11542. }
  11543. array_add(&global_variables, var);
  11544. lb_add_entity(m, e, g);
  11545. lb_add_member(m, name, g);
  11546. if (m->debug_builder) {
  11547. String global_name = e->token.string;
  11548. if (global_name.len != 0 && global_name != "_") {
  11549. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  11550. LLVMMetadataRef llvm_scope = llvm_file;
  11551. LLVMBool local_to_unit = e->flags & EntityFlag_Static;
  11552. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  11553. LLVMMetadataRef llvm_decl = nullptr;
  11554. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  11555. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  11556. m->debug_builder, llvm_scope,
  11557. cast(char const *)global_name.text, global_name.len,
  11558. "", 0, // linkage
  11559. llvm_file, e->token.pos.line,
  11560. lb_debug_type(m, e->type),
  11561. local_to_unit,
  11562. llvm_expr,
  11563. llvm_decl,
  11564. align_in_bits
  11565. );
  11566. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  11567. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  11568. }
  11569. }
  11570. }
  11571. TIME_SECTION("LLVM Global Procedures and Types");
  11572. for_array(i, info->entities) {
  11573. Entity *e = info->entities[i];
  11574. String name = e->token.string;
  11575. DeclInfo *decl = e->decl_info;
  11576. Scope * scope = e->scope;
  11577. if ((scope->flags & ScopeFlag_File) == 0) {
  11578. continue;
  11579. }
  11580. Scope *package_scope = scope->parent;
  11581. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  11582. switch (e->kind) {
  11583. case Entity_Variable:
  11584. // NOTE(bill): Handled above as it requires a specific load order
  11585. continue;
  11586. case Entity_ProcGroup:
  11587. continue;
  11588. case Entity_TypeName:
  11589. case Entity_Procedure:
  11590. break;
  11591. }
  11592. bool polymorphic_struct = false;
  11593. if (e->type != nullptr && e->kind == Entity_TypeName) {
  11594. Type *bt = base_type(e->type);
  11595. if (bt->kind == Type_Struct) {
  11596. polymorphic_struct = is_type_polymorphic(bt);
  11597. }
  11598. }
  11599. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  11600. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  11601. continue;
  11602. }
  11603. String mangled_name = lb_get_entity_name(m, e);
  11604. switch (e->kind) {
  11605. case Entity_TypeName:
  11606. lb_type(m, e->type);
  11607. break;
  11608. case Entity_Procedure:
  11609. {
  11610. lbProcedure *p = lb_create_procedure(m, e);
  11611. array_add(&m->procedures_to_generate, p);
  11612. }
  11613. break;
  11614. }
  11615. }
  11616. TIME_SECTION("LLVM Registry Initializtion");
  11617. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  11618. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  11619. defer (LLVMDisposePassManager(default_function_pass_manager));
  11620. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  11621. lb_populate_function_pass_manager(default_function_pass_manager, false, build_context.optimization_level);
  11622. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  11623. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  11624. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  11625. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  11626. lb_populate_function_pass_manager(default_function_pass_manager_without_memcpy, true, build_context.optimization_level);
  11627. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  11628. TIME_SECTION("LLVM Runtime Type Information Creation");
  11629. lbProcedure *startup_type_info = nullptr;
  11630. lbProcedure *startup_runtime = nullptr;
  11631. { // Startup Type Info
  11632. Type *params = alloc_type_tuple();
  11633. Type *results = alloc_type_tuple();
  11634. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11635. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  11636. p->is_startup = true;
  11637. startup_type_info = p;
  11638. lb_begin_procedure_body(p);
  11639. lb_setup_type_info_data(p);
  11640. lb_end_procedure_body(p);
  11641. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11642. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11643. LLVMDumpValue(p->value);
  11644. gb_printf_err("\n\n\n\n");
  11645. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11646. }
  11647. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11648. }
  11649. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  11650. { // Startup Runtime
  11651. Type *params = alloc_type_tuple();
  11652. Type *results = alloc_type_tuple();
  11653. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11654. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  11655. p->is_startup = true;
  11656. startup_runtime = p;
  11657. lb_begin_procedure_body(p);
  11658. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  11659. for_array(i, global_variables) {
  11660. auto *var = &global_variables[i];
  11661. if (var->is_initialized) {
  11662. continue;
  11663. }
  11664. Entity *e = var->decl->entity;
  11665. GB_ASSERT(e->kind == Entity_Variable);
  11666. if (var->decl->init_expr != nullptr) {
  11667. // gb_printf_err("%s\n", expr_to_string(var->decl->init_expr));
  11668. lbValue init = lb_build_expr(p, var->decl->init_expr);
  11669. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  11670. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  11671. if (lb_is_const_or_global(init)) {
  11672. if (!var->is_initialized) {
  11673. LLVMSetInitializer(var->var.value, init.value);
  11674. var->is_initialized = true;
  11675. continue;
  11676. }
  11677. } else {
  11678. var->init = init;
  11679. }
  11680. }
  11681. if (var->init.value != nullptr) {
  11682. GB_ASSERT(!var->is_initialized);
  11683. Type *t = type_deref(var->var.type);
  11684. if (is_type_any(t)) {
  11685. // NOTE(bill): Edge case for 'any' type
  11686. Type *var_type = default_type(var->init.type);
  11687. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  11688. lb_addr_store(p, g, var->init);
  11689. lbValue gp = lb_addr_get_ptr(p, g);
  11690. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  11691. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  11692. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  11693. lb_emit_store(p, ti, lb_type_info(m, var_type));
  11694. } else {
  11695. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  11696. LLVMTypeRef vt = LLVMGetElementType(pvt);
  11697. lbValue src0 = lb_emit_conv(p, var->init, t);
  11698. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  11699. LLVMValueRef dst = var->var.value;
  11700. LLVMBuildStore(p->builder, src, dst);
  11701. }
  11702. var->is_initialized = true;
  11703. }
  11704. }
  11705. lb_end_procedure_body(p);
  11706. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11707. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11708. LLVMDumpValue(p->value);
  11709. gb_printf_err("\n\n\n\n");
  11710. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11711. }
  11712. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11713. /*{
  11714. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  11715. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  11716. instr != last_instr;
  11717. instr = LLVMGetNextInstruction(instr)) {
  11718. if (LLVMIsAAllocaInst(instr)) {
  11719. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  11720. LLVMValueRef sz_val = LLVMSizeOf(type);
  11721. GB_ASSERT(LLVMIsConstant(sz_val));
  11722. gb_printf_err(">> 0x%p\n", sz_val);
  11723. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  11724. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  11725. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  11726. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  11727. gb_printf_err(">> %ll\n", sz);
  11728. }
  11729. }
  11730. }*/
  11731. }
  11732. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  11733. TIME_SECTION("LLVM DLL main");
  11734. Type *params = alloc_type_tuple();
  11735. Type *results = alloc_type_tuple();
  11736. String name = str_lit("main");
  11737. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  11738. name = str_lit("mainCRTStartup");
  11739. } else {
  11740. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  11741. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  11742. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  11743. }
  11744. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  11745. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  11746. Type *proc_type = alloc_type_proc(nullptr,
  11747. params, params->Tuple.variables.count,
  11748. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  11749. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  11750. p->is_startup = true;
  11751. lb_begin_procedure_body(p);
  11752. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  11753. if (build_context.command_kind == Command_test) {
  11754. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  11755. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  11756. Type *slice_type = alloc_type_slice(t_Internal_Test);
  11757. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  11758. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  11759. LLVMTypeRef lbt_Internal_Test = lb_type(m, t_Internal_Test);
  11760. LLVMValueRef indices[2] = {};
  11761. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  11762. for_array(i, m->info->testing_procedures) {
  11763. Entity *testing_proc = m->info->testing_procedures[i];
  11764. String name = testing_proc->token.string;
  11765. lbValue *found = map_get(&m->values, hash_entity(testing_proc));
  11766. GB_ASSERT(found != nullptr);
  11767. String pkg_name = {};
  11768. if (testing_proc->pkg != nullptr) {
  11769. pkg_name = testing_proc->pkg->name;
  11770. }
  11771. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  11772. lbValue v_name = lb_find_or_add_entity_string(m, name);
  11773. lbValue v_proc = *found;
  11774. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  11775. LLVMValueRef vals[3] = {};
  11776. vals[0] = v_pkg.value;
  11777. vals[1] = v_name.value;
  11778. vals[2] = v_proc.value;
  11779. GB_ASSERT(LLVMIsConstant(vals[0]));
  11780. GB_ASSERT(LLVMIsConstant(vals[1]));
  11781. GB_ASSERT(LLVMIsConstant(vals[2]));
  11782. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  11783. LLVMValueRef src = llvm_const_named_struct(lbt_Internal_Test, vals, gb_count_of(vals));
  11784. LLVMBuildStore(p->builder, src, dst);
  11785. }
  11786. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  11787. lb_fill_slice(p, all_tests_slice,
  11788. lb_array_elem(p, all_tests_array),
  11789. lb_const_int(m, t_int, m->info->testing_procedures.count));
  11790. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  11791. auto args = array_make<lbValue>(heap_allocator(), 1);
  11792. args[0] = lb_addr_load(p, all_tests_slice);
  11793. lb_emit_call(p, runner, args);
  11794. } else {
  11795. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  11796. GB_ASSERT(found != nullptr);
  11797. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  11798. }
  11799. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  11800. lb_end_procedure_body(p);
  11801. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11802. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11803. LLVMDumpValue(p->value);
  11804. gb_printf_err("\n\n\n\n");
  11805. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11806. }
  11807. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11808. }
  11809. String filepath_ll = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".ll"));
  11810. TIME_SECTION("LLVM Procedure Generation");
  11811. for_array(i, m->procedures_to_generate) {
  11812. lbProcedure *p = m->procedures_to_generate[i];
  11813. if (p->is_done) {
  11814. continue;
  11815. }
  11816. if (p->body != nullptr) { // Build Procedure
  11817. m->curr_procedure = p;
  11818. lb_begin_procedure_body(p);
  11819. lb_build_stmt(p, p->body);
  11820. lb_end_procedure_body(p);
  11821. p->is_done = true;
  11822. m->curr_procedure = nullptr;
  11823. }
  11824. lb_end_procedure(p);
  11825. // Add Flags
  11826. if (p->body != nullptr) {
  11827. if (p->name == "memcpy" || p->name == "memmove" ||
  11828. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  11829. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  11830. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  11831. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  11832. }
  11833. }
  11834. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11835. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  11836. LLVMDumpValue(p->value);
  11837. gb_printf_err("\n\n\n\n");
  11838. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11839. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11840. }
  11841. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  11842. gb_exit(1);
  11843. }
  11844. }
  11845. if (m->debug_builder != nullptr) {
  11846. TIME_SECTION("LLVM Debug Info Complete Types");
  11847. lb_debug_complete_types(m);
  11848. TIME_SECTION("LLVM Print Module to File");
  11849. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11850. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11851. gb_exit(1);
  11852. return;
  11853. }
  11854. TIME_SECTION("LLVM Debug Info Builder Finalize");
  11855. LLVMDIBuilderFinalize(m->debug_builder);
  11856. }
  11857. TIME_SECTION("LLVM Function Pass");
  11858. {
  11859. for_array(i, m->procedures_to_generate) {
  11860. lbProcedure *p = m->procedures_to_generate[i];
  11861. if (p->body != nullptr) { // Build Procedure
  11862. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  11863. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  11864. } else {
  11865. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11866. }
  11867. }
  11868. }
  11869. for_array(i, m->equal_procs.entries) {
  11870. lbProcedure *p = m->equal_procs.entries[i].value;
  11871. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11872. }
  11873. for_array(i, m->hasher_procs.entries) {
  11874. lbProcedure *p = m->hasher_procs.entries[i].value;
  11875. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11876. }
  11877. }
  11878. TIME_SECTION("LLVM Module Pass");
  11879. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  11880. defer (LLVMDisposePassManager(module_pass_manager));
  11881. lb_populate_module_pass_manager(target_machine, module_pass_manager, build_context.optimization_level);
  11882. LLVMRunPassManager(module_pass_manager, mod);
  11883. llvm_error = nullptr;
  11884. defer (LLVMDisposeMessage(llvm_error));
  11885. String filepath_obj = {};
  11886. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  11887. if (build_context.build_mode == BuildMode_Assembly) {
  11888. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".S"));
  11889. code_gen_file_type = LLVMAssemblyFile;
  11890. } else {
  11891. switch (build_context.metrics.os) {
  11892. case TargetOs_windows:
  11893. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".obj"));
  11894. break;
  11895. case TargetOs_darwin:
  11896. case TargetOs_linux:
  11897. case TargetOs_essence:
  11898. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".o"));
  11899. break;
  11900. case TargetOs_js:
  11901. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  11902. break;
  11903. }
  11904. }
  11905. if (LLVMVerifyModule(mod, LLVMReturnStatusAction, &llvm_error)) {
  11906. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  11907. if (build_context.keep_temp_files) {
  11908. TIME_SECTION("LLVM Print Module to File");
  11909. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11910. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11911. gb_exit(1);
  11912. return;
  11913. }
  11914. }
  11915. gb_exit(1);
  11916. return;
  11917. }
  11918. llvm_error = nullptr;
  11919. if (build_context.keep_temp_files) {
  11920. TIME_SECTION("LLVM Print Module to File");
  11921. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11922. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11923. gb_exit(1);
  11924. return;
  11925. }
  11926. }
  11927. TIME_SECTION("LLVM Object Generation");
  11928. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  11929. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11930. gb_exit(1);
  11931. return;
  11932. }
  11933. array_add(&gen->output_object_paths, filepath_obj);
  11934. for_array(i, m->info->required_foreign_imports_through_force) {
  11935. Entity *e = m->info->required_foreign_imports_through_force[i];
  11936. lb_add_foreign_library_path(m, e);
  11937. }
  11938. #undef TIME_SECTION
  11939. }