llvm_backend.cpp 438 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016
  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. // Basic_f16,
  795. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  796. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  797. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  798. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  799. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  800. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  801. // Basic_complex32,
  802. case Basic_complex64:
  803. {
  804. char const *name = "..complex64";
  805. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  806. if (type != nullptr) {
  807. return type;
  808. }
  809. type = LLVMStructCreateNamed(ctx, name);
  810. LLVMTypeRef fields[2] = {
  811. lb_type(m, t_f32),
  812. lb_type(m, t_f32),
  813. };
  814. LLVMStructSetBody(type, fields, 2, false);
  815. return type;
  816. }
  817. case Basic_complex128:
  818. {
  819. char const *name = "..complex128";
  820. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  821. if (type != nullptr) {
  822. return type;
  823. }
  824. type = LLVMStructCreateNamed(ctx, name);
  825. LLVMTypeRef fields[2] = {
  826. lb_type(m, t_f64),
  827. lb_type(m, t_f64),
  828. };
  829. LLVMStructSetBody(type, fields, 2, false);
  830. return type;
  831. }
  832. case Basic_quaternion128:
  833. {
  834. char const *name = "..quaternion128";
  835. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  836. if (type != nullptr) {
  837. return type;
  838. }
  839. type = LLVMStructCreateNamed(ctx, name);
  840. LLVMTypeRef fields[4] = {
  841. lb_type(m, t_f32),
  842. lb_type(m, t_f32),
  843. lb_type(m, t_f32),
  844. lb_type(m, t_f32),
  845. };
  846. LLVMStructSetBody(type, fields, 4, false);
  847. return type;
  848. }
  849. case Basic_quaternion256:
  850. {
  851. char const *name = "..quaternion256";
  852. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  853. if (type != nullptr) {
  854. return type;
  855. }
  856. type = LLVMStructCreateNamed(ctx, name);
  857. LLVMTypeRef fields[4] = {
  858. lb_type(m, t_f64),
  859. lb_type(m, t_f64),
  860. lb_type(m, t_f64),
  861. lb_type(m, t_f64),
  862. };
  863. LLVMStructSetBody(type, fields, 4, false);
  864. return type;
  865. }
  866. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  867. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  868. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  869. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  870. case Basic_string:
  871. {
  872. char const *name = "..string";
  873. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  874. if (type != nullptr) {
  875. return type;
  876. }
  877. type = LLVMStructCreateNamed(ctx, name);
  878. LLVMTypeRef fields[2] = {
  879. LLVMPointerType(lb_type(m, t_u8), 0),
  880. lb_type(m, t_int),
  881. };
  882. LLVMStructSetBody(type, fields, 2, false);
  883. return type;
  884. }
  885. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  886. case Basic_any:
  887. {
  888. char const *name = "..any";
  889. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  890. if (type != nullptr) {
  891. return type;
  892. }
  893. type = LLVMStructCreateNamed(ctx, name);
  894. LLVMTypeRef fields[2] = {
  895. lb_type(m, t_rawptr),
  896. lb_type(m, t_typeid),
  897. };
  898. LLVMStructSetBody(type, fields, 2, false);
  899. return type;
  900. }
  901. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  902. // Endian Specific Types
  903. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  904. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  905. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  906. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  907. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  908. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  909. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  910. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  911. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  912. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  913. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  914. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  915. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  916. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  917. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  918. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  919. // Untyped types
  920. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  921. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  922. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  923. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  924. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  925. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  926. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  927. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  928. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  929. }
  930. break;
  931. case Type_Named:
  932. {
  933. Type *base = base_type(type->Named.base);
  934. switch (base->kind) {
  935. case Type_Basic:
  936. return lb_type_internal(m, base);
  937. case Type_Named:
  938. case Type_Generic:
  939. GB_PANIC("INVALID TYPE");
  940. break;
  941. case Type_Pointer:
  942. case Type_Array:
  943. case Type_EnumeratedArray:
  944. case Type_Slice:
  945. case Type_DynamicArray:
  946. case Type_Map:
  947. case Type_Enum:
  948. case Type_BitSet:
  949. case Type_SimdVector:
  950. return lb_type_internal(m, base);
  951. // TODO(bill): Deal with this correctly. Can this be named?
  952. case Type_Proc:
  953. return lb_type_internal(m, base);
  954. case Type_Tuple:
  955. return lb_type_internal(m, base);
  956. }
  957. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  958. if (found) {
  959. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  960. if (kind == LLVMStructTypeKind) {
  961. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  962. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  963. if (llvm_type != nullptr) {
  964. return llvm_type;
  965. }
  966. llvm_type = LLVMStructCreateNamed(ctx, name);
  967. map_set(&m->types, hash_type(type), llvm_type);
  968. lb_clone_struct_type(llvm_type, *found);
  969. return llvm_type;
  970. }
  971. }
  972. switch (base->kind) {
  973. case Type_Struct:
  974. case Type_Union:
  975. {
  976. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  977. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  978. if (llvm_type != nullptr) {
  979. return llvm_type;
  980. }
  981. llvm_type = LLVMStructCreateNamed(ctx, name);
  982. map_set(&m->types, hash_type(type), llvm_type);
  983. lb_clone_struct_type(llvm_type, lb_type(m, base));
  984. return llvm_type;
  985. }
  986. }
  987. return lb_type_internal(m, base);
  988. }
  989. case Type_Pointer:
  990. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  991. case Type_Array: {
  992. m->internal_type_level -= 1;
  993. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  994. m->internal_type_level += 1;
  995. return t;
  996. }
  997. case Type_EnumeratedArray: {
  998. m->internal_type_level -= 1;
  999. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1000. m->internal_type_level += 1;
  1001. return t;
  1002. }
  1003. case Type_Slice:
  1004. {
  1005. LLVMTypeRef fields[2] = {
  1006. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1007. lb_type(m, t_int), // len
  1008. };
  1009. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1010. }
  1011. break;
  1012. case Type_DynamicArray:
  1013. {
  1014. LLVMTypeRef fields[4] = {
  1015. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1016. lb_type(m, t_int), // len
  1017. lb_type(m, t_int), // cap
  1018. lb_type(m, t_allocator), // allocator
  1019. };
  1020. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1021. }
  1022. break;
  1023. case Type_Map:
  1024. return lb_type(m, type->Map.internal_type);
  1025. case Type_Struct:
  1026. {
  1027. if (type->Struct.is_raw_union) {
  1028. unsigned field_count = 2;
  1029. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1030. i64 alignment = type_align_of(type);
  1031. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1032. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1033. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1034. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1035. }
  1036. isize offset = 0;
  1037. if (type->Struct.custom_align > 0) {
  1038. offset = 1;
  1039. }
  1040. m->internal_type_level += 1;
  1041. defer (m->internal_type_level -= 1);
  1042. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1043. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1044. for_array(i, type->Struct.fields) {
  1045. Entity *field = type->Struct.fields[i];
  1046. fields[i+offset] = lb_type(m, field->type);
  1047. }
  1048. if (type->Struct.custom_align > 0) {
  1049. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1050. }
  1051. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1052. }
  1053. break;
  1054. case Type_Union:
  1055. if (type->Union.variants.count == 0) {
  1056. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1057. } else {
  1058. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1059. // LLVM takes the first element's alignment as the entire alignment (like C)
  1060. i64 align = type_align_of(type);
  1061. i64 size = type_size_of(type);
  1062. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1063. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1064. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1065. }
  1066. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1067. LLVMTypeRef fields[3] = {};
  1068. unsigned field_count = 1;
  1069. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1070. if (is_type_union_maybe_pointer(type)) {
  1071. field_count += 1;
  1072. fields[1] = lb_type(m, type->Union.variants[0]);
  1073. } else {
  1074. field_count += 2;
  1075. if (block_size == align) {
  1076. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1077. } else {
  1078. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1079. }
  1080. fields[2] = lb_type(m, union_tag_type(type));
  1081. }
  1082. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1083. }
  1084. break;
  1085. case Type_Enum:
  1086. return lb_type(m, base_enum_type(type));
  1087. case Type_Tuple:
  1088. if (type->Tuple.variables.count == 1) {
  1089. return lb_type(m, type->Tuple.variables[0]->type);
  1090. } else {
  1091. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1092. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1093. for_array(i, type->Tuple.variables) {
  1094. Entity *field = type->Tuple.variables[i];
  1095. LLVMTypeRef param_type = nullptr;
  1096. param_type = lb_type(m, field->type);
  1097. fields[i] = param_type;
  1098. }
  1099. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1100. }
  1101. case Type_Proc:
  1102. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1103. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1104. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1105. } else {
  1106. unsigned param_count = 0;
  1107. if (type->Proc.calling_convention == ProcCC_Odin) {
  1108. param_count += 1;
  1109. }
  1110. if (type->Proc.param_count != 0) {
  1111. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1112. for_array(i, type->Proc.params->Tuple.variables) {
  1113. Entity *e = type->Proc.params->Tuple.variables[i];
  1114. if (e->kind != Entity_Variable) {
  1115. continue;
  1116. }
  1117. if (e->flags & EntityFlag_CVarArg) {
  1118. continue;
  1119. }
  1120. param_count += 1;
  1121. }
  1122. }
  1123. m->internal_type_level += 1;
  1124. defer (m->internal_type_level -= 1);
  1125. LLVMTypeRef ret = nullptr;
  1126. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1127. if (type->Proc.result_count != 0) {
  1128. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1129. ret = lb_type(m, single_ret);
  1130. if (ret != nullptr) {
  1131. if (is_type_boolean(single_ret) &&
  1132. is_calling_convention_none(type->Proc.calling_convention) &&
  1133. type_size_of(single_ret) <= 1) {
  1134. ret = LLVMInt1TypeInContext(m->ctx);
  1135. }
  1136. }
  1137. }
  1138. isize param_index = 0;
  1139. if (type->Proc.param_count != 0) {
  1140. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1141. for_array(i, type->Proc.params->Tuple.variables) {
  1142. Entity *e = type->Proc.params->Tuple.variables[i];
  1143. if (e->kind != Entity_Variable) {
  1144. continue;
  1145. }
  1146. if (e->flags & EntityFlag_CVarArg) {
  1147. continue;
  1148. }
  1149. Type *e_type = reduce_tuple_to_single_type(e->type);
  1150. LLVMTypeRef param_type = nullptr;
  1151. if (is_type_boolean(e_type) &&
  1152. type_size_of(e_type) <= 1) {
  1153. param_type = LLVMInt1TypeInContext(m->ctx);
  1154. } else {
  1155. if (is_type_proc(e_type)) {
  1156. param_type = lb_type(m, t_rawptr);
  1157. } else {
  1158. param_type = lb_type(m, e_type);
  1159. }
  1160. }
  1161. params[param_index++] = param_type;
  1162. }
  1163. }
  1164. if (param_index < param_count) {
  1165. params[param_index++] = lb_type(m, t_rawptr);
  1166. // params[param_index++] = lb_type(m, t_context_ptr);
  1167. }
  1168. GB_ASSERT(param_index == param_count);
  1169. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1170. map_set(&m->function_type_map, hash_type(type), ft);
  1171. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1172. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1173. // LLVMTypeRef new_ret = LLVMGetReturnType(new_abi_fn_type);
  1174. // LLVMTypeRef old_ret = LLVMGetReturnType(old_abi_fn_type);
  1175. // unsigned new_count = LLVMCountParamTypes(new_abi_fn_type);
  1176. // unsigned old_count = LLVMCountParamTypes(old_abi_fn_type);
  1177. // 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));
  1178. return new_abi_fn_ptr_type;
  1179. }
  1180. break;
  1181. case Type_BitSet:
  1182. {
  1183. Type *ut = bit_set_to_int(type);
  1184. return lb_type(m, ut);
  1185. }
  1186. case Type_SimdVector:
  1187. if (type->SimdVector.is_x86_mmx) {
  1188. return LLVMX86MMXTypeInContext(ctx);
  1189. }
  1190. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1191. case Type_RelativePointer:
  1192. return lb_type_internal(m, type->RelativePointer.base_integer);
  1193. case Type_RelativeSlice:
  1194. {
  1195. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1196. unsigned field_count = 2;
  1197. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1198. fields[0] = base_integer;
  1199. fields[1] = base_integer;
  1200. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1201. }
  1202. }
  1203. GB_PANIC("Invalid type %s", type_to_string(type));
  1204. return LLVMInt32TypeInContext(ctx);
  1205. }
  1206. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1207. type = default_type(type);
  1208. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1209. if (found) {
  1210. return *found;
  1211. }
  1212. LLVMTypeRef llvm_type = nullptr;
  1213. m->internal_type_level += 1;
  1214. llvm_type = lb_type_internal(m, type);
  1215. m->internal_type_level -= 1;
  1216. if (m->internal_type_level == 0) {
  1217. map_set(&m->types, hash_type(type), llvm_type);
  1218. if (is_type_named(type)) {
  1219. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1220. }
  1221. }
  1222. return llvm_type;
  1223. }
  1224. LLVMMetadataRef lb_get_llvm_metadata(lbModule *m, void *key) {
  1225. if (key == nullptr) {
  1226. return nullptr;
  1227. }
  1228. auto found = map_get(&m->debug_values, hash_pointer(key));
  1229. if (found) {
  1230. return *found;
  1231. }
  1232. return nullptr;
  1233. }
  1234. void lb_set_llvm_metadata(lbModule *m, void *key, LLVMMetadataRef value) {
  1235. if (key != nullptr) {
  1236. map_set(&m->debug_values, hash_pointer(key), value);
  1237. }
  1238. }
  1239. LLVMMetadataRef lb_get_llvm_file_metadata_from_node(lbModule *m, Ast *node) {
  1240. if (node == nullptr) {
  1241. return nullptr;
  1242. }
  1243. return lb_get_llvm_metadata(m, node->file);
  1244. }
  1245. LLVMMetadataRef lb_get_current_debug_scope(lbProcedure *p) {
  1246. GB_ASSERT_MSG(p->debug_info != nullptr, "missing debug information for %.*s", LIT(p->name));
  1247. for (isize i = p->scope_stack.count-1; i >= 0; i--) {
  1248. Scope *s = p->scope_stack[i];
  1249. LLVMMetadataRef md = lb_get_llvm_metadata(p->module, s);
  1250. if (md) {
  1251. return md;
  1252. }
  1253. }
  1254. return p->debug_info;
  1255. }
  1256. LLVMMetadataRef lb_debug_location_from_token_pos(lbProcedure *p, TokenPos pos) {
  1257. LLVMMetadataRef scope = lb_get_current_debug_scope(p);
  1258. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  1259. return LLVMDIBuilderCreateDebugLocation(p->module->ctx, cast(unsigned)pos.line, cast(unsigned)pos.column, scope, nullptr);
  1260. }
  1261. LLVMMetadataRef lb_debug_location_from_ast(lbProcedure *p, Ast *node) {
  1262. GB_ASSERT(node != nullptr);
  1263. return lb_debug_location_from_token_pos(p, ast_token(node).pos);
  1264. }
  1265. LLVMMetadataRef lb_debug_type_internal_proc(lbModule *m, Type *type) {
  1266. Type *original_type = type;
  1267. LLVMContextRef ctx = m->ctx;
  1268. i64 size = type_size_of(type); // Check size
  1269. GB_ASSERT(type != t_invalid);
  1270. unsigned const word_size = cast(unsigned)build_context.word_size;
  1271. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1272. GB_ASSERT(type->kind == Type_Proc);
  1273. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1274. unsigned parameter_count = 1;
  1275. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1276. Entity *e = type->Proc.params->Tuple.variables[i];
  1277. if (e->kind == Entity_Variable) {
  1278. parameter_count += 1;
  1279. }
  1280. }
  1281. LLVMMetadataRef *parameters = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, parameter_count);
  1282. unsigned param_index = 0;
  1283. if (type->Proc.result_count == 0) {
  1284. parameters[param_index++] = nullptr;
  1285. } else {
  1286. parameters[param_index++] = lb_debug_type(m, type->Proc.results);
  1287. }
  1288. LLVMMetadataRef parent_scope = nullptr;
  1289. LLVMMetadataRef scope = nullptr;
  1290. LLVMMetadataRef file = nullptr;
  1291. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1292. Entity *e = type->Proc.params->Tuple.variables[i];
  1293. if (e->kind != Entity_Variable) {
  1294. continue;
  1295. }
  1296. parameters[param_index] = lb_debug_type(m, e->type);
  1297. param_index += 1;
  1298. }
  1299. LLVMDIFlags flags = LLVMDIFlagZero;
  1300. if (type->Proc.diverging) {
  1301. flags = LLVMDIFlagNoReturn;
  1302. }
  1303. return LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, parameters, parameter_count, flags);
  1304. }
  1305. LLVMMetadataRef lb_debug_struct_field(lbModule *m, String const &name, Type *type, u64 offset_in_bits) {
  1306. unsigned field_line = 1;
  1307. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1308. AstPackage *pkg = m->info->runtime_package;
  1309. GB_ASSERT(pkg->files.count != 0);
  1310. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1311. LLVMMetadataRef scope = file;
  1312. return LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1313. 8*cast(u64)type_size_of(type), 8*cast(u32)type_align_of(type), offset_in_bits,
  1314. field_flags, lb_debug_type(m, type)
  1315. );
  1316. }
  1317. LLVMMetadataRef lb_debug_basic_struct(lbModule *m, String const &name, u64 size_in_bits, u32 align_in_bits, LLVMMetadataRef *elements, unsigned element_count) {
  1318. AstPackage *pkg = m->info->runtime_package;
  1319. GB_ASSERT(pkg->files.count != 0);
  1320. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1321. LLVMMetadataRef scope = file;
  1322. 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);
  1323. }
  1324. LLVMMetadataRef lb_debug_type_basic_type(lbModule *m, String const &name, u64 size_in_bits, LLVMDWARFTypeEncoding encoding, LLVMDIFlags flags = LLVMDIFlagZero) {
  1325. LLVMMetadataRef basic_type = LLVMDIBuilderCreateBasicType(m->debug_builder, cast(char const *)name.text, name.len, size_in_bits, encoding, flags);
  1326. #if 1
  1327. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, basic_type, cast(char const *)name.text, name.len, nullptr, 0, nullptr, cast(u32)size_in_bits);
  1328. return final_decl;
  1329. #else
  1330. return basic_type;
  1331. #endif
  1332. }
  1333. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1334. Type *original_type = type;
  1335. LLVMContextRef ctx = m->ctx;
  1336. i64 size = type_size_of(type); // Check size
  1337. GB_ASSERT(type != t_invalid);
  1338. unsigned const word_size = cast(unsigned)build_context.word_size;
  1339. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1340. switch (type->kind) {
  1341. case Type_Basic:
  1342. switch (type->Basic.kind) {
  1343. case Basic_llvm_bool: return lb_debug_type_basic_type(m, str_lit("llvm bool"), 1, LLVMDWARFTypeEncoding_Boolean);
  1344. case Basic_bool: return lb_debug_type_basic_type(m, str_lit("bool"), 8, LLVMDWARFTypeEncoding_Boolean);
  1345. case Basic_b8: return lb_debug_type_basic_type(m, str_lit("b8"), 8, LLVMDWARFTypeEncoding_Boolean);
  1346. case Basic_b16: return lb_debug_type_basic_type(m, str_lit("b16"), 16, LLVMDWARFTypeEncoding_Boolean);
  1347. case Basic_b32: return lb_debug_type_basic_type(m, str_lit("b32"), 32, LLVMDWARFTypeEncoding_Boolean);
  1348. case Basic_b64: return lb_debug_type_basic_type(m, str_lit("b64"), 64, LLVMDWARFTypeEncoding_Boolean);
  1349. case Basic_i8: return lb_debug_type_basic_type(m, str_lit("i8"), 8, LLVMDWARFTypeEncoding_Signed);
  1350. case Basic_u8: return lb_debug_type_basic_type(m, str_lit("u8"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1351. case Basic_i16: return lb_debug_type_basic_type(m, str_lit("i16"), 16, LLVMDWARFTypeEncoding_Signed);
  1352. case Basic_u16: return lb_debug_type_basic_type(m, str_lit("u16"), 16, LLVMDWARFTypeEncoding_Unsigned);
  1353. case Basic_i32: return lb_debug_type_basic_type(m, str_lit("i32"), 32, LLVMDWARFTypeEncoding_Signed);
  1354. case Basic_u32: return lb_debug_type_basic_type(m, str_lit("u32"), 32, LLVMDWARFTypeEncoding_Unsigned);
  1355. case Basic_i64: return lb_debug_type_basic_type(m, str_lit("i64"), 64, LLVMDWARFTypeEncoding_Signed);
  1356. case Basic_u64: return lb_debug_type_basic_type(m, str_lit("u64"), 64, LLVMDWARFTypeEncoding_Unsigned);
  1357. case Basic_i128: return lb_debug_type_basic_type(m, str_lit("i128"), 128, LLVMDWARFTypeEncoding_Signed);
  1358. case Basic_u128: return lb_debug_type_basic_type(m, str_lit("u128"), 128, LLVMDWARFTypeEncoding_Unsigned);
  1359. case Basic_rune: return lb_debug_type_basic_type(m, str_lit("rune"), 32, LLVMDWARFTypeEncoding_Utf);
  1360. // Basic_f16,
  1361. case Basic_f32: return lb_debug_type_basic_type(m, str_lit("f32"), 32, LLVMDWARFTypeEncoding_Float);
  1362. case Basic_f64: return lb_debug_type_basic_type(m, str_lit("f64"), 64, LLVMDWARFTypeEncoding_Float);
  1363. case Basic_int: return lb_debug_type_basic_type(m, str_lit("int"), word_bits, LLVMDWARFTypeEncoding_Signed);
  1364. case Basic_uint: return lb_debug_type_basic_type(m, str_lit("uint"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1365. case Basic_uintptr: return lb_debug_type_basic_type(m, str_lit("uintptr"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1366. case Basic_typeid:
  1367. return lb_debug_type_basic_type(m, str_lit("typeid"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1368. // Endian Specific Types
  1369. case Basic_i16le: return lb_debug_type_basic_type(m, str_lit("i16le"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1370. case Basic_u16le: return lb_debug_type_basic_type(m, str_lit("u16le"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1371. case Basic_i32le: return lb_debug_type_basic_type(m, str_lit("i32le"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1372. case Basic_u32le: return lb_debug_type_basic_type(m, str_lit("u32le"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1373. case Basic_i64le: return lb_debug_type_basic_type(m, str_lit("i64le"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1374. case Basic_u64le: return lb_debug_type_basic_type(m, str_lit("u64le"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1375. case Basic_i128le: return lb_debug_type_basic_type(m, str_lit("i128le"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1376. case Basic_u128le: return lb_debug_type_basic_type(m, str_lit("u128le"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1377. case Basic_f32le: return lb_debug_type_basic_type(m, str_lit("f32le"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1378. case Basic_f64le: return lb_debug_type_basic_type(m, str_lit("f64le"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1379. case Basic_i16be: return lb_debug_type_basic_type(m, str_lit("i16be"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1380. case Basic_u16be: return lb_debug_type_basic_type(m, str_lit("u16be"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1381. case Basic_i32be: return lb_debug_type_basic_type(m, str_lit("i32be"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1382. case Basic_u32be: return lb_debug_type_basic_type(m, str_lit("u32be"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1383. case Basic_i64be: return lb_debug_type_basic_type(m, str_lit("i64be"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1384. case Basic_u64be: return lb_debug_type_basic_type(m, str_lit("u64be"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1385. case Basic_i128be: return lb_debug_type_basic_type(m, str_lit("i128be"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1386. case Basic_u128be: return lb_debug_type_basic_type(m, str_lit("u128be"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1387. case Basic_f32be: return lb_debug_type_basic_type(m, str_lit("f32be"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1388. case Basic_f64be: return lb_debug_type_basic_type(m, str_lit("f64be"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1389. // Basic_complex32,
  1390. case Basic_complex64:
  1391. {
  1392. LLVMMetadataRef elements[2] = {};
  1393. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f32, 0);
  1394. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 4);
  1395. return lb_debug_basic_struct(m, str_lit("complex64"), 64, 32, elements, gb_count_of(elements));
  1396. }
  1397. case Basic_complex128:
  1398. {
  1399. LLVMMetadataRef elements[2] = {};
  1400. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f64, 0);
  1401. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 8);
  1402. return lb_debug_basic_struct(m, str_lit("complex128"), 128, 64, elements, gb_count_of(elements));
  1403. }
  1404. case Basic_quaternion128:
  1405. {
  1406. LLVMMetadataRef elements[4] = {};
  1407. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 0);
  1408. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f32, 4);
  1409. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f32, 8);
  1410. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f32, 12);
  1411. return lb_debug_basic_struct(m, str_lit("quaternion128"), 128, 32, elements, gb_count_of(elements));
  1412. }
  1413. case Basic_quaternion256:
  1414. {
  1415. LLVMMetadataRef elements[4] = {};
  1416. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 0);
  1417. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f64, 8);
  1418. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f64, 16);
  1419. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f64, 24);
  1420. return lb_debug_basic_struct(m, str_lit("quaternion256"), 256, 32, elements, gb_count_of(elements));
  1421. }
  1422. case Basic_rawptr:
  1423. {
  1424. LLVMMetadataRef void_type = lb_debug_type_basic_type(m, str_lit("void"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1425. return LLVMDIBuilderCreatePointerType(m->debug_builder, void_type, word_bits, word_bits, LLVMDWARFTypeEncoding_Address, "rawptr", 6);
  1426. }
  1427. case Basic_string:
  1428. {
  1429. LLVMMetadataRef elements[2] = {};
  1430. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_u8_ptr, 0);
  1431. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, word_bits);
  1432. return lb_debug_basic_struct(m, str_lit("string"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1433. }
  1434. case Basic_cstring:
  1435. {
  1436. LLVMMetadataRef char_type = lb_debug_type_basic_type(m, str_lit("char"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1437. return LLVMDIBuilderCreatePointerType(m->debug_builder, char_type, word_bits, word_bits, 0, "cstring", 7);
  1438. }
  1439. case Basic_any:
  1440. {
  1441. LLVMMetadataRef elements[2] = {};
  1442. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_rawptr, 0);
  1443. elements[1] = lb_debug_struct_field(m, str_lit("id"), t_typeid, word_bits);
  1444. return lb_debug_basic_struct(m, str_lit("any"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1445. }
  1446. // Untyped types
  1447. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1448. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1449. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1450. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1451. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1452. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1453. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1454. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1455. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1456. default: GB_PANIC("Basic Unhandled"); break;
  1457. }
  1458. break;
  1459. case Type_Named:
  1460. GB_PANIC("Type_Named should be handled in lb_debug_type separately");
  1461. case Type_Pointer:
  1462. return LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, type->Pointer.elem), word_bits, word_bits, 0, nullptr, 0);
  1463. case Type_Array:
  1464. return LLVMDIBuilderCreateArrayType(m->debug_builder,
  1465. type->Array.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->Array.elem), nullptr, 0);
  1466. case Type_EnumeratedArray: {
  1467. LLVMMetadataRef array_type = LLVMDIBuilderCreateArrayType(m->debug_builder,
  1468. type->EnumeratedArray.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->EnumeratedArray.elem), nullptr, 0);
  1469. gbString name = type_to_string(type, temporary_allocator());
  1470. return LLVMDIBuilderCreateTypedef(m->debug_builder, array_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1471. }
  1472. case Type_Struct:
  1473. case Type_Union:
  1474. case Type_Slice:
  1475. case Type_DynamicArray:
  1476. case Type_Map:
  1477. case Type_BitSet:
  1478. {
  1479. unsigned tag = DW_TAG_structure_type;
  1480. if (is_type_raw_union(type) || is_type_union(type)) {
  1481. tag = DW_TAG_union_type;
  1482. }
  1483. u64 size_in_bits = cast(u64)(8*type_size_of(type));
  1484. u32 align_in_bits = cast(u32)(8*type_size_of(type));
  1485. LLVMDIFlags flags = LLVMDIFlagZero;
  1486. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1487. m->debug_builder, tag, "", 0, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1488. );
  1489. lbIncompleteDebugType idt = {};
  1490. idt.type = type;
  1491. idt.metadata = temp_forward_decl;
  1492. array_add(&m->debug_incomplete_types, idt);
  1493. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1494. return temp_forward_decl;
  1495. }
  1496. case Type_Enum:
  1497. {
  1498. LLVMMetadataRef scope = nullptr;
  1499. LLVMMetadataRef file = nullptr;
  1500. unsigned line = 0;
  1501. unsigned element_count = cast(unsigned)type->Enum.fields.count;
  1502. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1503. Type *bt = base_enum_type(type);
  1504. LLVMBool is_unsigned = is_type_unsigned(bt);
  1505. for (unsigned i = 0; i < element_count; i++) {
  1506. Entity *f = type->Enum.fields[i];
  1507. GB_ASSERT(f->kind == Entity_Constant);
  1508. String name = f->token.string;
  1509. i64 value = exact_value_to_i64(f->Constant.value);
  1510. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1511. }
  1512. LLVMMetadataRef class_type = lb_debug_type(m, bt);
  1513. 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);
  1514. }
  1515. case Type_Tuple:
  1516. if (type->Tuple.variables.count == 1) {
  1517. return lb_debug_type(m, type->Tuple.variables[0]->type);
  1518. } else {
  1519. type_set_offsets(type);
  1520. LLVMMetadataRef parent_scope = nullptr;
  1521. LLVMMetadataRef scope = nullptr;
  1522. LLVMMetadataRef file = nullptr;
  1523. unsigned line = 0;
  1524. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1525. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1526. LLVMDIFlags flags = LLVMDIFlagZero;
  1527. unsigned element_count = cast(unsigned)type->Tuple.variables.count;
  1528. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1529. for (unsigned i = 0; i < element_count; i++) {
  1530. Entity *f = type->Tuple.variables[i];
  1531. GB_ASSERT(f->kind == Entity_Variable);
  1532. String name = f->token.string;
  1533. unsigned field_line = 0;
  1534. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1535. u64 offset_in_bits = 8*cast(u64)type->Tuple.offsets[i];
  1536. elements[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1537. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type), offset_in_bits,
  1538. field_flags, lb_debug_type(m, f->type)
  1539. );
  1540. }
  1541. return LLVMDIBuilderCreateStructType(m->debug_builder, parent_scope, "", 0, file, line,
  1542. size_in_bits, align_in_bits, flags,
  1543. nullptr, elements, element_count, 0, nullptr,
  1544. "", 0
  1545. );
  1546. }
  1547. case Type_Proc:
  1548. {
  1549. LLVMMetadataRef proc_underlying_type = lb_debug_type_internal_proc(m, type);
  1550. LLVMMetadataRef pointer_type = LLVMDIBuilderCreatePointerType(m->debug_builder, proc_underlying_type, word_bits, word_bits, 0, nullptr, 0);
  1551. gbString name = type_to_string(type, temporary_allocator());
  1552. return LLVMDIBuilderCreateTypedef(m->debug_builder, pointer_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1553. }
  1554. break;
  1555. case Type_SimdVector:
  1556. if (type->SimdVector.is_x86_mmx) {
  1557. return LLVMDIBuilderCreateVectorType(m->debug_builder, 2, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, t_f64), nullptr, 0);
  1558. }
  1559. 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);
  1560. case Type_RelativePointer: {
  1561. LLVMMetadataRef base_integer = lb_debug_type(m, type->RelativePointer.base_integer);
  1562. gbString name = type_to_string(type, temporary_allocator());
  1563. return LLVMDIBuilderCreateTypedef(m->debug_builder, base_integer, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1564. }
  1565. case Type_RelativeSlice:
  1566. {
  1567. unsigned element_count = 0;
  1568. LLVMMetadataRef elements[2] = {};
  1569. Type *base_integer = type->RelativeSlice.base_integer;
  1570. elements[0] = lb_debug_struct_field(m, str_lit("data_offset"), base_integer, 0);
  1571. elements[1] = lb_debug_struct_field(m, str_lit("len"), base_integer, 8*type_size_of(base_integer));
  1572. gbString name = type_to_string(type, temporary_allocator());
  1573. 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);
  1574. }
  1575. }
  1576. GB_PANIC("Invalid type %s", type_to_string(type));
  1577. return nullptr;
  1578. }
  1579. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1580. GB_ASSERT(type != nullptr);
  1581. LLVMMetadataRef found = lb_get_llvm_metadata(m, type);
  1582. if (found != nullptr) {
  1583. return found;
  1584. }
  1585. if (type->kind == Type_Named) {
  1586. LLVMMetadataRef file = nullptr;
  1587. unsigned line = 0;
  1588. LLVMMetadataRef scope = nullptr;
  1589. if (type->Named.type_name != nullptr) {
  1590. Entity *e = type->Named.type_name;
  1591. scope = lb_get_llvm_metadata(m, e->scope);
  1592. if (scope != nullptr) {
  1593. file = LLVMDIScopeGetFile(scope);
  1594. }
  1595. line = cast(unsigned)e->token.pos.line;
  1596. }
  1597. // TODO(bill): location data for Type_Named
  1598. u64 size_in_bits = 8*type_size_of(type);
  1599. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1600. String name = type->Named.name;
  1601. char const *name_text = cast(char const *)name.text;
  1602. size_t name_len = cast(size_t)name.len;
  1603. unsigned tag = DW_TAG_structure_type;
  1604. if (is_type_raw_union(type) || is_type_union(type)) {
  1605. tag = DW_TAG_union_type;
  1606. }
  1607. LLVMDIFlags flags = LLVMDIFlagZero;
  1608. Type *bt = base_type(type->Named.base);
  1609. lbIncompleteDebugType idt = {};
  1610. idt.type = type;
  1611. switch (bt->kind) {
  1612. case Type_Enum:
  1613. {
  1614. LLVMMetadataRef scope = nullptr;
  1615. LLVMMetadataRef file = nullptr;
  1616. unsigned line = 0;
  1617. unsigned element_count = cast(unsigned)bt->Enum.fields.count;
  1618. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1619. Type *ct = base_enum_type(type);
  1620. LLVMBool is_unsigned = is_type_unsigned(ct);
  1621. for (unsigned i = 0; i < element_count; i++) {
  1622. Entity *f = bt->Enum.fields[i];
  1623. GB_ASSERT(f->kind == Entity_Constant);
  1624. String name = f->token.string;
  1625. i64 value = exact_value_to_i64(f->Constant.value);
  1626. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1627. }
  1628. LLVMMetadataRef class_type = lb_debug_type(m, ct);
  1629. 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);
  1630. }
  1631. case Type_Basic:
  1632. case Type_Pointer:
  1633. case Type_Array:
  1634. case Type_EnumeratedArray:
  1635. case Type_Tuple:
  1636. case Type_Proc:
  1637. case Type_SimdVector:
  1638. case Type_RelativePointer:
  1639. case Type_RelativeSlice:
  1640. {
  1641. LLVMMetadataRef debug_bt = lb_debug_type(m, bt);
  1642. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, debug_bt, name_text, name_len, file, line, scope, align_in_bits);
  1643. lb_set_llvm_metadata(m, type, final_decl);
  1644. return final_decl;
  1645. }
  1646. case Type_Slice:
  1647. case Type_DynamicArray:
  1648. case Type_Map:
  1649. case Type_Struct:
  1650. case Type_Union:
  1651. case Type_BitSet:
  1652. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1653. m->debug_builder, tag, name_text, name_len, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1654. );
  1655. idt.metadata = temp_forward_decl;
  1656. array_add(&m->debug_incomplete_types, idt);
  1657. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1658. return temp_forward_decl;
  1659. }
  1660. }
  1661. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1662. lb_set_llvm_metadata(m, type, dt);
  1663. return dt;
  1664. }
  1665. void lb_debug_complete_types(lbModule *m) {
  1666. unsigned const word_size = cast(unsigned)build_context.word_size;
  1667. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1668. for_array(debug_incomplete_type_index, m->debug_incomplete_types) {
  1669. auto const &idt = m->debug_incomplete_types[debug_incomplete_type_index];
  1670. GB_ASSERT(idt.type != nullptr);
  1671. GB_ASSERT(idt.metadata != nullptr);
  1672. Type *t = idt.type;
  1673. Type *bt = base_type(t);
  1674. LLVMMetadataRef parent_scope = nullptr;
  1675. LLVMMetadataRef file = nullptr;
  1676. unsigned line_number = 0;
  1677. u64 size_in_bits = 8*type_size_of(t);
  1678. u32 align_in_bits = cast(u32)(8*type_align_of(t));
  1679. LLVMDIFlags flags = LLVMDIFlagZero;
  1680. LLVMMetadataRef derived_from = nullptr;
  1681. LLVMMetadataRef *elements = nullptr;
  1682. unsigned element_count = 0;
  1683. unsigned runtime_lang = 0; // Objective-C runtime version
  1684. char const *unique_id = "";
  1685. LLVMMetadataRef vtable_holder = nullptr;
  1686. size_t unique_id_len = 0;
  1687. LLVMMetadataRef record_scope = nullptr;
  1688. switch (bt->kind) {
  1689. case Type_Slice:
  1690. case Type_DynamicArray:
  1691. case Type_Map:
  1692. case Type_Struct:
  1693. case Type_Union:
  1694. case Type_BitSet: {
  1695. bool is_union = is_type_raw_union(bt) || is_type_union(bt);
  1696. String name = str_lit("<anonymous-struct>");
  1697. if (t->kind == Type_Named) {
  1698. name = t->Named.name;
  1699. if (t->Named.type_name && t->Named.type_name->pkg && t->Named.type_name->pkg->name.len != 0) {
  1700. name = concatenate3_strings(temporary_allocator(), t->Named.type_name->pkg->name, str_lit("."), t->Named.name);
  1701. }
  1702. LLVMMetadataRef file = nullptr;
  1703. unsigned line = 0;
  1704. LLVMMetadataRef file_scope = nullptr;
  1705. if (t->Named.type_name != nullptr) {
  1706. Entity *e = t->Named.type_name;
  1707. file_scope = lb_get_llvm_metadata(m, e->scope);
  1708. if (file_scope != nullptr) {
  1709. file = LLVMDIScopeGetFile(file_scope);
  1710. }
  1711. line = cast(unsigned)e->token.pos.line;
  1712. }
  1713. // TODO(bill): location data for Type_Named
  1714. } else {
  1715. name = make_string_c(type_to_string(t, temporary_allocator()));
  1716. }
  1717. switch (bt->kind) {
  1718. case Type_Slice:
  1719. element_count = 2;
  1720. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1721. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->Slice.elem), 0*word_bits);
  1722. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1723. break;
  1724. case Type_DynamicArray:
  1725. element_count = 4;
  1726. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1727. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->DynamicArray.elem), 0*word_bits);
  1728. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1729. elements[2] = lb_debug_struct_field(m, str_lit("cap"), t_int, 2*word_bits);
  1730. elements[3] = lb_debug_struct_field(m, str_lit("allocator"), t_allocator, 3*word_bits);
  1731. break;
  1732. case Type_Map:
  1733. bt = bt->Map.internal_type;
  1734. /*fallthrough*/
  1735. case Type_Struct:
  1736. if (file == nullptr) {
  1737. if (bt->Struct.node) {
  1738. file = lb_get_llvm_metadata(m, bt->Struct.node->file);
  1739. line_number = cast(unsigned)ast_token(bt->Struct.node).pos.line;
  1740. }
  1741. }
  1742. type_set_offsets(bt);
  1743. {
  1744. isize element_offset = 0;
  1745. record_scope = lb_get_llvm_metadata(m, bt->Struct.scope);
  1746. switch (bt->Struct.soa_kind) {
  1747. case StructSoa_Slice: element_offset = 1; break;
  1748. case StructSoa_Dynamic: element_offset = 3; break;
  1749. }
  1750. element_count = cast(unsigned)(bt->Struct.fields.count + element_offset);
  1751. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1752. switch (bt->Struct.soa_kind) {
  1753. case StructSoa_Slice:
  1754. elements[0] = LLVMDIBuilderCreateMemberType(
  1755. m->debug_builder, record_scope,
  1756. ".len", 4,
  1757. file, 0,
  1758. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1759. 8*type_size_of(bt)-word_bits,
  1760. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1761. );
  1762. break;
  1763. case StructSoa_Dynamic:
  1764. elements[0] = LLVMDIBuilderCreateMemberType(
  1765. m->debug_builder, record_scope,
  1766. ".len", 4,
  1767. file, 0,
  1768. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1769. 8*type_size_of(bt)-word_bits + 0*word_bits,
  1770. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1771. );
  1772. elements[1] = LLVMDIBuilderCreateMemberType(
  1773. m->debug_builder, record_scope,
  1774. ".cap", 4,
  1775. file, 0,
  1776. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1777. 8*type_size_of(bt)-word_bits + 1*word_bits,
  1778. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1779. );
  1780. elements[3] = LLVMDIBuilderCreateMemberType(
  1781. m->debug_builder, record_scope,
  1782. ".allocator", 12,
  1783. file, 0,
  1784. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1785. 8*type_size_of(bt)-word_bits + 2*word_bits,
  1786. LLVMDIFlagZero, lb_debug_type(m, t_allocator)
  1787. );
  1788. break;
  1789. }
  1790. for_array(j, bt->Struct.fields) {
  1791. Entity *f = bt->Struct.fields[j];
  1792. String fname = f->token.string;
  1793. unsigned field_line = 0;
  1794. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1795. u64 offset_in_bits = 8*cast(u64)bt->Struct.offsets[j];
  1796. elements[element_offset+j] = LLVMDIBuilderCreateMemberType(
  1797. m->debug_builder, record_scope,
  1798. cast(char const *)fname.text, cast(size_t)fname.len,
  1799. file, field_line,
  1800. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type),
  1801. offset_in_bits,
  1802. field_flags, lb_debug_type(m, f->type)
  1803. );
  1804. }
  1805. }
  1806. break;
  1807. case Type_Union:
  1808. {
  1809. if (file == nullptr) {
  1810. GB_ASSERT(bt->Union.node != nullptr);
  1811. file = lb_get_llvm_metadata(m, bt->Union.node->file);
  1812. line_number = cast(unsigned)ast_token(bt->Union.node).pos.line;
  1813. }
  1814. isize index_offset = 1;
  1815. if (is_type_union_maybe_pointer(bt)) {
  1816. index_offset = 0;
  1817. }
  1818. record_scope = lb_get_llvm_metadata(m, bt->Union.scope);
  1819. element_count = cast(unsigned)bt->Union.variants.count;
  1820. if (index_offset > 0) {
  1821. element_count += 1;
  1822. }
  1823. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1824. if (index_offset > 0) {
  1825. Type *tag_type = union_tag_type(bt);
  1826. unsigned field_line = 0;
  1827. u64 offset_in_bits = 8*cast(u64)bt->Union.variant_block_size;
  1828. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1829. elements[0] = LLVMDIBuilderCreateMemberType(
  1830. m->debug_builder, record_scope,
  1831. "tag", 3,
  1832. file, field_line,
  1833. 8*cast(u64)type_size_of(tag_type), 8*cast(u32)type_align_of(tag_type),
  1834. offset_in_bits,
  1835. field_flags, lb_debug_type(m, tag_type)
  1836. );
  1837. }
  1838. for_array(j, bt->Union.variants) {
  1839. Type *variant = bt->Union.variants[j];
  1840. unsigned field_index = cast(unsigned)(index_offset+j);
  1841. char name[16] = {};
  1842. gb_snprintf(name, gb_size_of(name), "v%u", field_index);
  1843. isize name_len = gb_strlen(name);
  1844. unsigned field_line = 0;
  1845. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1846. u64 offset_in_bits = 0;
  1847. elements[field_index] = LLVMDIBuilderCreateMemberType(
  1848. m->debug_builder, record_scope,
  1849. name, name_len,
  1850. file, field_line,
  1851. 8*cast(u64)type_size_of(variant), 8*cast(u32)type_align_of(variant),
  1852. offset_in_bits,
  1853. field_flags, lb_debug_type(m, variant)
  1854. );
  1855. }
  1856. }
  1857. break;
  1858. case Type_BitSet:
  1859. {
  1860. if (file == nullptr) {
  1861. GB_ASSERT(bt->BitSet.node != nullptr);
  1862. file = lb_get_llvm_metadata(m, bt->BitSet.node->file);
  1863. line_number = cast(unsigned)ast_token(bt->BitSet.node).pos.line;
  1864. }
  1865. LLVMMetadataRef bit_set_field_type = lb_debug_type(m, t_bool);
  1866. LLVMMetadataRef scope = file;
  1867. Type *elem = base_type(bt->BitSet.elem);
  1868. if (elem->kind == Type_Enum) {
  1869. element_count = cast(unsigned)elem->Enum.fields.count;
  1870. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1871. for_array(i, elem->Enum.fields) {
  1872. Entity *f = elem->Enum.fields[i];
  1873. GB_ASSERT(f->kind == Entity_Constant);
  1874. i64 val = exact_value_to_i64(f->Constant.value);
  1875. String name = f->token.string;
  1876. u64 offset_in_bits = cast(u64)(val - bt->BitSet.lower);
  1877. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  1878. m->debug_builder,
  1879. scope,
  1880. cast(char const *)name.text, name.len,
  1881. file, line_number,
  1882. 1,
  1883. offset_in_bits,
  1884. 0,
  1885. LLVMDIFlagZero,
  1886. bit_set_field_type
  1887. );
  1888. }
  1889. } else {
  1890. char name[32] = {};
  1891. GB_ASSERT(is_type_integer(elem));
  1892. i64 count = bt->BitSet.upper - bt->BitSet.lower + 1;
  1893. GB_ASSERT(0 <= count);
  1894. element_count = cast(unsigned)count;
  1895. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1896. for (unsigned i = 0; i < element_count; i++) {
  1897. u64 offset_in_bits = i;
  1898. i64 val = bt->BitSet.lower + cast(i64)i;
  1899. gb_snprintf(name, gb_count_of(name), "%lld", val);
  1900. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  1901. m->debug_builder,
  1902. scope,
  1903. name, gb_strlen(name),
  1904. file, line_number,
  1905. 1,
  1906. offset_in_bits,
  1907. 0,
  1908. LLVMDIFlagZero,
  1909. bit_set_field_type
  1910. );
  1911. }
  1912. }
  1913. }
  1914. }
  1915. LLVMMetadataRef final_metadata = nullptr;
  1916. if (is_union) {
  1917. final_metadata = LLVMDIBuilderCreateUnionType(
  1918. m->debug_builder,
  1919. parent_scope,
  1920. cast(char const *)name.text, cast(size_t)name.len,
  1921. file, line_number,
  1922. size_in_bits, align_in_bits,
  1923. flags,
  1924. elements, element_count,
  1925. runtime_lang,
  1926. unique_id, unique_id_len
  1927. );
  1928. } else {
  1929. final_metadata = LLVMDIBuilderCreateStructType(
  1930. m->debug_builder,
  1931. parent_scope,
  1932. cast(char const *)name.text, cast(size_t)name.len,
  1933. file, line_number,
  1934. size_in_bits, align_in_bits,
  1935. flags,
  1936. derived_from,
  1937. elements, element_count,
  1938. runtime_lang,
  1939. vtable_holder,
  1940. unique_id, unique_id_len
  1941. );
  1942. }
  1943. LLVMMetadataReplaceAllUsesWith(idt.metadata, final_metadata);
  1944. lb_set_llvm_metadata(m, idt.type, final_metadata);
  1945. } break;
  1946. default:
  1947. GB_PANIC("invalid incomplete debug type");
  1948. break;
  1949. }
  1950. }
  1951. array_clear(&m->debug_incomplete_types);
  1952. }
  1953. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1954. if (e != nullptr) {
  1955. map_set(&m->values, hash_entity(e), val);
  1956. }
  1957. }
  1958. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1959. if (name.len > 0) {
  1960. string_map_set(&m->members, name, val);
  1961. }
  1962. }
  1963. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1964. string_map_set(&m->members, key, val);
  1965. }
  1966. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1967. if (p->entity != nullptr) {
  1968. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1969. }
  1970. string_map_set(&m->procedures, p->name, p);
  1971. }
  1972. LLVMValueRef llvm_const_cast(LLVMValueRef val, LLVMTypeRef dst) {
  1973. LLVMTypeRef src = LLVMTypeOf(val);
  1974. if (src == dst) {
  1975. return val;
  1976. }
  1977. if (LLVMIsNull(val)) {
  1978. return LLVMConstNull(dst);
  1979. }
  1980. GB_ASSERT(LLVMSizeOf(dst) == LLVMSizeOf(src));
  1981. LLVMTypeKind kind = LLVMGetTypeKind(dst);
  1982. switch (kind) {
  1983. case LLVMPointerTypeKind:
  1984. return LLVMConstPointerCast(val, dst);
  1985. case LLVMStructTypeKind:
  1986. return LLVMConstBitCast(val, dst);
  1987. default:
  1988. GB_PANIC("Unhandled const cast %s to %s", LLVMPrintTypeToString(src), LLVMPrintTypeToString(dst));
  1989. }
  1990. return val;
  1991. }
  1992. LLVMValueRef llvm_const_named_struct(LLVMTypeRef t, LLVMValueRef *values, isize value_count_) {
  1993. unsigned value_count = cast(unsigned)value_count_;
  1994. unsigned elem_count = LLVMCountStructElementTypes(t);
  1995. GB_ASSERT(value_count == elem_count);
  1996. for (unsigned i = 0; i < elem_count; i++) {
  1997. LLVMTypeRef elem_type = LLVMStructGetTypeAtIndex(t, i);
  1998. values[i] = llvm_const_cast(values[i], elem_type);
  1999. }
  2000. return LLVMConstNamedStruct(t, values, value_count);
  2001. }
  2002. LLVMValueRef llvm_const_array(LLVMTypeRef elem_type, LLVMValueRef *values, isize value_count_) {
  2003. unsigned value_count = cast(unsigned)value_count_;
  2004. for (unsigned i = 0; i < value_count; i++) {
  2005. values[i] = llvm_const_cast(values[i], elem_type);
  2006. }
  2007. return LLVMConstArray(elem_type, values, value_count);
  2008. }
  2009. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  2010. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  2011. LLVMValueRef values[2] = {
  2012. str_elem.value,
  2013. str_len.value,
  2014. };
  2015. lbValue res = {};
  2016. res.type = t_string;
  2017. res.value = llvm_const_named_struct(lb_type(p->module, t_string), values, gb_count_of(values));
  2018. return res;
  2019. } else {
  2020. lbAddr res = lb_add_local_generated(p, t_string, false);
  2021. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  2022. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  2023. return lb_addr_load(p, res);
  2024. }
  2025. }
  2026. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  2027. String s = make_string_c(name);
  2028. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2029. // and the current LLVM C API does not expose this functionality yet.
  2030. // It is better to ignore the attributes for the time being
  2031. if (s == "byval") {
  2032. return nullptr;
  2033. } else if (s == "byref") {
  2034. return nullptr;
  2035. } else if (s == "preallocated") {
  2036. return nullptr;
  2037. } else if (s == "sret") {
  2038. return nullptr;
  2039. }
  2040. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2041. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2042. return LLVMCreateEnumAttribute(ctx, kind, value);
  2043. }
  2044. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  2045. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  2046. GB_ASSERT(attr != nullptr);
  2047. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  2048. }
  2049. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  2050. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  2051. }
  2052. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  2053. if (p->abi_function_type != nullptr) {
  2054. return;
  2055. }
  2056. auto hash = hash_type(p->type);
  2057. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  2058. if (ft_found == nullptr) {
  2059. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  2060. ft_found = map_get(&m->function_type_map, hash);
  2061. }
  2062. GB_ASSERT(ft_found != nullptr);
  2063. p->abi_function_type = *ft_found;
  2064. GB_ASSERT(p->abi_function_type != nullptr);
  2065. }
  2066. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  2067. GB_ASSERT(entity != nullptr);
  2068. String link_name = lb_get_entity_name(m, entity);
  2069. {
  2070. StringHashKey key = string_hash_string(link_name);
  2071. lbValue *found = string_map_get(&m->members, key);
  2072. if (found) {
  2073. lb_add_entity(m, entity, *found);
  2074. lbProcedure **p_found = string_map_get(&m->procedures, key);
  2075. GB_ASSERT(p_found != nullptr);
  2076. return *p_found;
  2077. }
  2078. }
  2079. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2080. p->module = m;
  2081. entity->code_gen_module = m;
  2082. entity->code_gen_procedure = p;
  2083. p->entity = entity;
  2084. p->name = link_name;
  2085. DeclInfo *decl = entity->decl_info;
  2086. ast_node(pl, ProcLit, decl->proc_lit);
  2087. Type *pt = base_type(entity->type);
  2088. GB_ASSERT(pt->kind == Type_Proc);
  2089. set_procedure_abi_types(entity->type);
  2090. p->type = entity->type;
  2091. p->type_expr = decl->type_expr;
  2092. p->body = pl->body;
  2093. p->tags = pt->Proc.tags;
  2094. p->inlining = ProcInlining_none;
  2095. p->is_foreign = entity->Procedure.is_foreign;
  2096. p->is_export = entity->Procedure.is_export;
  2097. p->is_entry_point = false;
  2098. gbAllocator a = heap_allocator();
  2099. p->children.allocator = a;
  2100. p->params.allocator = a;
  2101. p->defer_stmts.allocator = a;
  2102. p->blocks.allocator = a;
  2103. p->branch_blocks.allocator = a;
  2104. p->context_stack.allocator = a;
  2105. p->scope_stack.allocator = a;
  2106. if (p->is_foreign) {
  2107. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  2108. }
  2109. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2110. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2111. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2112. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2113. lb_ensure_abi_function_type(m, p);
  2114. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  2115. if (false) {
  2116. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2117. // TODO(bill): Clean up this logic
  2118. if (build_context.metrics.os != TargetOs_js) {
  2119. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2120. }
  2121. LLVMSetFunctionCallConv(p->value, cc_kind);
  2122. }
  2123. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2124. // // TODO(bill): Clean up this logic
  2125. // if (build_context.metrics.os != TargetOs_js) {
  2126. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2127. // }
  2128. // LLVMSetFunctionCallConv(p->value, cc_kind);
  2129. lbValue proc_value = {p->value, p->type};
  2130. lb_add_entity(m, entity, proc_value);
  2131. lb_add_member(m, p->name, proc_value);
  2132. lb_add_procedure_value(m, p);
  2133. if (p->is_export) {
  2134. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  2135. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  2136. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  2137. if (build_context.metrics.os == TargetOs_js) {
  2138. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  2139. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  2140. }
  2141. }
  2142. if (p->is_foreign) {
  2143. if (build_context.metrics.os == TargetOs_js) {
  2144. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  2145. char const *module_name = "env";
  2146. if (entity->Procedure.foreign_library != nullptr) {
  2147. Entity *foreign_library = entity->Procedure.foreign_library;
  2148. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  2149. if (foreign_library->LibraryName.paths.count > 0) {
  2150. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  2151. }
  2152. }
  2153. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  2154. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  2155. }
  2156. }
  2157. // NOTE(bill): offset==0 is the return value
  2158. isize offset = 1;
  2159. if (pt->Proc.return_by_pointer) {
  2160. offset = 2;
  2161. }
  2162. isize parameter_index = 0;
  2163. if (pt->Proc.param_count) {
  2164. TypeTuple *params = &pt->Proc.params->Tuple;
  2165. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2166. Entity *e = params->variables[i];
  2167. Type *original_type = e->type;
  2168. Type *abi_type = pt->Proc.abi_compat_params[i];
  2169. if (e->kind != Entity_Variable) continue;
  2170. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2171. continue;
  2172. }
  2173. if (is_type_tuple(abi_type)) {
  2174. for_array(j, abi_type->Tuple.variables) {
  2175. Type *tft = abi_type->Tuple.variables[j]->type;
  2176. if (e->flags&EntityFlag_NoAlias) {
  2177. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  2178. }
  2179. }
  2180. parameter_index += abi_type->Tuple.variables.count;
  2181. } else {
  2182. if (e->flags&EntityFlag_NoAlias) {
  2183. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2184. }
  2185. parameter_index += 1;
  2186. }
  2187. }
  2188. }
  2189. if (m->debug_builder) { // Debug Information
  2190. Type *bt = base_type(p->type);
  2191. unsigned line = cast(unsigned)entity->token.pos.line;
  2192. LLVMMetadataRef scope = nullptr;
  2193. LLVMMetadataRef file = nullptr;
  2194. LLVMMetadataRef type = nullptr;
  2195. scope = p->module->debug_compile_unit;
  2196. type = lb_debug_type_internal_proc(m, bt);
  2197. if (entity->file != nullptr) {
  2198. file = lb_get_llvm_metadata(m, entity->file);
  2199. scope = file;
  2200. } else if (entity->identifier != nullptr && entity->identifier->file != nullptr) {
  2201. file = lb_get_llvm_metadata(m, entity->identifier->file);
  2202. scope = file;
  2203. } else if (entity->scope != nullptr) {
  2204. file = lb_get_llvm_metadata(m, entity->scope->file);
  2205. scope = file;
  2206. }
  2207. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  2208. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  2209. LLVMBool is_local_to_unit = false;
  2210. LLVMBool is_definition = p->body != nullptr;
  2211. unsigned scope_line = line;
  2212. u32 flags = LLVMDIFlagStaticMember;
  2213. LLVMBool is_optimized = false;
  2214. if (bt->Proc.diverging) {
  2215. flags |= LLVMDIFlagNoReturn;
  2216. }
  2217. if (p->body == nullptr) {
  2218. flags |= LLVMDIFlagPrototyped;
  2219. is_optimized = false;
  2220. }
  2221. if (p->body != nullptr) {
  2222. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  2223. cast(char const *)entity->token.string.text, entity->token.string.len,
  2224. cast(char const *)p->name.text, p->name.len,
  2225. file, line, type,
  2226. is_local_to_unit, is_definition,
  2227. scope_line, cast(LLVMDIFlags)flags, is_optimized
  2228. );
  2229. GB_ASSERT(p->debug_info != nullptr);
  2230. LLVMSetSubprogram(p->value, p->debug_info);
  2231. lb_set_llvm_metadata(m, p, p->debug_info);
  2232. }
  2233. }
  2234. return p;
  2235. }
  2236. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  2237. {
  2238. lbValue *found = string_map_get(&m->members, link_name);
  2239. GB_ASSERT(found == nullptr);
  2240. }
  2241. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2242. p->module = m;
  2243. p->name = link_name;
  2244. p->type = type;
  2245. p->type_expr = nullptr;
  2246. p->body = nullptr;
  2247. p->tags = 0;
  2248. p->inlining = ProcInlining_none;
  2249. p->is_foreign = false;
  2250. p->is_export = false;
  2251. p->is_entry_point = false;
  2252. gbAllocator a = permanent_allocator();
  2253. p->children.allocator = a;
  2254. p->params.allocator = a;
  2255. p->defer_stmts.allocator = a;
  2256. p->blocks.allocator = a;
  2257. p->branch_blocks.allocator = a;
  2258. p->context_stack.allocator = a;
  2259. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2260. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2261. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2262. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2263. Type *pt = p->type;
  2264. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2265. // TODO(bill): Clean up this logic
  2266. if (build_context.metrics.os != TargetOs_js) {
  2267. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2268. }
  2269. LLVMSetFunctionCallConv(p->value, cc_kind);
  2270. lbValue proc_value = {p->value, p->type};
  2271. lb_add_member(m, p->name, proc_value);
  2272. lb_add_procedure_value(m, p);
  2273. // NOTE(bill): offset==0 is the return value
  2274. isize offset = 1;
  2275. if (pt->Proc.return_by_pointer) {
  2276. lb_add_proc_attribute_at_index(p, 1, "sret");
  2277. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2278. offset = 2;
  2279. }
  2280. isize parameter_index = 0;
  2281. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2282. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2283. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2284. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2285. }
  2286. return p;
  2287. }
  2288. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2289. lbParamPasskind kind = lbParamPass_Value;
  2290. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2291. if (is_type_pointer(abi_type)) {
  2292. GB_ASSERT(e->kind == Entity_Variable);
  2293. Type *av = core_type(type_deref(abi_type));
  2294. if (are_types_identical(av, core_type(e->type))) {
  2295. kind = lbParamPass_Pointer;
  2296. if (e->flags&EntityFlag_Value) {
  2297. kind = lbParamPass_ConstRef;
  2298. }
  2299. } else {
  2300. kind = lbParamPass_BitCast;
  2301. }
  2302. } else if (is_type_integer(abi_type)) {
  2303. kind = lbParamPass_Integer;
  2304. } else if (abi_type == t_llvm_bool) {
  2305. kind = lbParamPass_Value;
  2306. } else if (is_type_boolean(abi_type)) {
  2307. kind = lbParamPass_Integer;
  2308. } else if (is_type_simd_vector(abi_type)) {
  2309. kind = lbParamPass_BitCast;
  2310. } else if (is_type_float(abi_type)) {
  2311. kind = lbParamPass_BitCast;
  2312. } else if (is_type_tuple(abi_type)) {
  2313. kind = lbParamPass_Tuple;
  2314. } else if (is_type_proc(abi_type)) {
  2315. kind = lbParamPass_Value;
  2316. } else {
  2317. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2318. }
  2319. }
  2320. if (kind_) *kind_ = kind;
  2321. lbValue res = {};
  2322. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2323. res.type = abi_type;
  2324. return res;
  2325. }
  2326. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  2327. lbParamPasskind kind = lbParamPass_Value;
  2328. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  2329. array_add(&p->params, v);
  2330. lbValue res = {};
  2331. switch (kind) {
  2332. case lbParamPass_Value: {
  2333. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2334. lbValue x = v;
  2335. if (abi_type == t_llvm_bool) {
  2336. x = lb_emit_conv(p, x, t_bool);
  2337. }
  2338. lb_addr_store(p, l, x);
  2339. return x;
  2340. }
  2341. case lbParamPass_Pointer:
  2342. lb_add_entity(p->module, e, v);
  2343. return lb_emit_load(p, v);
  2344. case lbParamPass_Integer: {
  2345. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2346. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  2347. lb_emit_store(p, iptr, v);
  2348. return lb_addr_load(p, l);
  2349. }
  2350. case lbParamPass_ConstRef:
  2351. lb_add_entity(p->module, e, v);
  2352. return lb_emit_load(p, v);
  2353. case lbParamPass_BitCast: {
  2354. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2355. lbValue x = lb_emit_transmute(p, v, e->type);
  2356. lb_addr_store(p, l, x);
  2357. return x;
  2358. }
  2359. case lbParamPass_Tuple: {
  2360. lbAddr l = lb_add_local(p, e->type, e, true, index);
  2361. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2362. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  2363. if (abi_type->Tuple.variables.count > 0) {
  2364. array_pop(&p->params);
  2365. }
  2366. for_array(i, abi_type->Tuple.variables) {
  2367. Type *t = abi_type->Tuple.variables[i]->type;
  2368. GB_ASSERT(!is_type_tuple(t));
  2369. lbParamPasskind elem_kind = lbParamPass_Value;
  2370. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  2371. array_add(&p->params, elem);
  2372. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2373. lb_emit_store(p, dst, elem);
  2374. }
  2375. return lb_addr_load(p, l);
  2376. }
  2377. }
  2378. GB_PANIC("Unreachable");
  2379. return {};
  2380. }
  2381. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2382. GB_ASSERT(b != nullptr);
  2383. if (!b->appended) {
  2384. b->appended = true;
  2385. LLVMAppendExistingBasicBlock(p->value, b->block);
  2386. }
  2387. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2388. p->curr_block = b;
  2389. }
  2390. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2391. LLVMContextRef ctx = p->module->ctx;
  2392. LLVMTypeRef src_type = LLVMTypeOf(val);
  2393. if (src_type == dst_type) {
  2394. return val;
  2395. }
  2396. i64 src_size = lb_sizeof(src_type);
  2397. i64 dst_size = lb_sizeof(dst_type);
  2398. i64 src_align = lb_alignof(src_type);
  2399. i64 dst_align = lb_alignof(dst_type);
  2400. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2401. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2402. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2403. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2404. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2405. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2406. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2407. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2408. }
  2409. if (src_size != dst_size) {
  2410. if ((lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2411. // Okay
  2412. } else {
  2413. goto general_end;
  2414. }
  2415. }
  2416. if (src_kind == dst_kind) {
  2417. if (src_kind == LLVMPointerTypeKind) {
  2418. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2419. } else if (src_kind == LLVMArrayTypeKind) {
  2420. // ignore
  2421. } else if (src_kind != LLVMStructTypeKind) {
  2422. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2423. }
  2424. } else {
  2425. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2426. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2427. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2428. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2429. }
  2430. }
  2431. general_end:;
  2432. if (LLVMIsALoadInst(val) && src_size >= dst_size) {
  2433. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2434. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2435. LLVMValueRef loaded_val = LLVMBuildLoad(p->builder, val_ptr, "");
  2436. // LLVMSetAlignment(loaded_val, gb_min(src_align, dst_align));
  2437. return loaded_val;
  2438. } else {
  2439. GB_ASSERT(p->decl_block != p->curr_block);
  2440. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2441. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2442. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2443. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2444. max_align = gb_max(max_align, 4);
  2445. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2446. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2447. LLVMBuildStore(p->builder, val, nptr);
  2448. return LLVMBuildLoad(p->builder, ptr, "");
  2449. }
  2450. }
  2451. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token) {
  2452. if (p->debug_info == nullptr) {
  2453. return;
  2454. }
  2455. if (type == nullptr) {
  2456. return;
  2457. }
  2458. if (type == t_invalid) {
  2459. return;
  2460. }
  2461. if (p->body == nullptr) {
  2462. return;
  2463. }
  2464. lbModule *m = p->module;
  2465. String const &name = token.string;
  2466. if (name == "" || name == "_") {
  2467. return;
  2468. }
  2469. if (lb_get_llvm_metadata(m, ptr) != nullptr) {
  2470. // Already been set
  2471. return;
  2472. }
  2473. AstFile *file = p->body->file;
  2474. LLVMMetadataRef llvm_scope = lb_get_current_debug_scope(p);
  2475. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, file);
  2476. GB_ASSERT(llvm_scope != nullptr);
  2477. if (llvm_file == nullptr) {
  2478. llvm_file = LLVMDIScopeGetFile(llvm_scope);
  2479. }
  2480. if (llvm_file == nullptr) {
  2481. return;
  2482. }
  2483. unsigned alignment_in_bits = cast(unsigned)(8*type_align_of(type));
  2484. LLVMDIFlags flags = LLVMDIFlagZero;
  2485. LLVMBool always_preserve = build_context.optimization_level == 0;
  2486. LLVMMetadataRef debug_type = lb_debug_type(m, type);
  2487. LLVMMetadataRef var_info = LLVMDIBuilderCreateAutoVariable(
  2488. m->debug_builder, llvm_scope,
  2489. cast(char const *)name.text, cast(size_t)name.len,
  2490. llvm_file, token.pos.line,
  2491. debug_type,
  2492. always_preserve, flags, alignment_in_bits
  2493. );
  2494. LLVMValueRef storage = ptr;
  2495. LLVMValueRef instr = ptr;
  2496. LLVMMetadataRef llvm_debug_loc = lb_debug_location_from_token_pos(p, token.pos);
  2497. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2498. lb_set_llvm_metadata(m, ptr, llvm_expr);
  2499. LLVMDIBuilderInsertDeclareBefore(m->debug_builder, storage, var_info, llvm_expr, llvm_debug_loc, instr);
  2500. }
  2501. void lb_add_debug_context_variable(lbProcedure *p, lbAddr const &ctx) {
  2502. if (!p->debug_info || !p->body) {
  2503. return;
  2504. }
  2505. LLVMMetadataRef loc = LLVMGetCurrentDebugLocation2(p->builder);
  2506. if (!loc) {
  2507. return;
  2508. }
  2509. TokenPos pos = {};
  2510. pos.file_id = p->body->file ? p->body->file->id : 0;
  2511. pos.line = LLVMDILocationGetLine(loc);
  2512. pos.column = LLVMDILocationGetColumn(loc);
  2513. Token token = {};
  2514. token.kind = Token_context;
  2515. token.string = str_lit("context");
  2516. token.pos = pos;
  2517. lb_add_debug_local_variable(p, ctx.addr.value, t_context, token);
  2518. }
  2519. void lb_begin_procedure_body(lbProcedure *p) {
  2520. DeclInfo *decl = decl_info_of_entity(p->entity);
  2521. if (decl != nullptr) {
  2522. for_array(i, decl->labels) {
  2523. BlockLabel bl = decl->labels[i];
  2524. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2525. array_add(&p->branch_blocks, bb);
  2526. }
  2527. }
  2528. if (p->tags != 0) {
  2529. u64 in = p->tags;
  2530. u64 out = p->module->state_flags;
  2531. if (in & ProcTag_bounds_check) {
  2532. out |= StateFlag_bounds_check;
  2533. out &= ~StateFlag_no_bounds_check;
  2534. } else if (in & ProcTag_no_bounds_check) {
  2535. out |= StateFlag_no_bounds_check;
  2536. out &= ~StateFlag_bounds_check;
  2537. }
  2538. p->module->state_flags = out;
  2539. }
  2540. p->builder = LLVMCreateBuilder();
  2541. p->decl_block = lb_create_block(p, "decls", true);
  2542. p->entry_block = lb_create_block(p, "entry", true);
  2543. lb_start_block(p, p->entry_block);
  2544. GB_ASSERT(p->type != nullptr);
  2545. lb_ensure_abi_function_type(p->module, p);
  2546. {
  2547. lbFunctionType *ft = p->abi_function_type;
  2548. unsigned param_offset = 0;
  2549. lbValue return_ptr_value = {};
  2550. if (ft->ret.kind == lbArg_Indirect) {
  2551. // NOTE(bill): this must be parameter 0
  2552. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2553. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2554. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2555. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2556. return_ptr_value.type = ptr_type;
  2557. p->return_ptr = lb_addr(return_ptr_value);
  2558. lb_add_entity(p->module, e, return_ptr_value);
  2559. param_offset += 1;
  2560. }
  2561. if (p->type->Proc.params != nullptr) {
  2562. TypeTuple *params = &p->type->Proc.params->Tuple;
  2563. unsigned param_index = 0;
  2564. for_array(i, params->variables) {
  2565. Entity *e = params->variables[i];
  2566. if (e->kind != Entity_Variable) {
  2567. continue;
  2568. }
  2569. lbArgType *arg_type = &ft->args[param_index];
  2570. if (arg_type->kind == lbArg_Ignore) {
  2571. continue;
  2572. } else if (arg_type->kind == lbArg_Direct) {
  2573. lbParamPasskind kind = lbParamPass_Value;
  2574. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2575. if (param_type != arg_type->type) {
  2576. kind = lbParamPass_BitCast;
  2577. }
  2578. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2579. value = OdinLLVMBuildTransmute(p, value, param_type);
  2580. lbValue param = {};
  2581. param.value = value;
  2582. param.type = e->type;
  2583. array_add(&p->params, param);
  2584. if (e->token.string.len != 0) {
  2585. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2586. lb_addr_store(p, l, param);
  2587. }
  2588. param_index += 1;
  2589. } else if (arg_type->kind == lbArg_Indirect) {
  2590. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2591. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2592. lbValue param = {};
  2593. param.value = value;
  2594. param.type = e->type;
  2595. array_add(&p->params, param);
  2596. lbValue ptr = {};
  2597. ptr.value = value_ptr;
  2598. ptr.type = alloc_type_pointer(e->type);
  2599. lb_add_entity(p->module, e, ptr);
  2600. param_index += 1;
  2601. }
  2602. }
  2603. }
  2604. if (p->type->Proc.has_named_results) {
  2605. GB_ASSERT(p->type->Proc.result_count > 0);
  2606. TypeTuple *results = &p->type->Proc.results->Tuple;
  2607. for_array(i, results->variables) {
  2608. Entity *e = results->variables[i];
  2609. GB_ASSERT(e->kind == Entity_Variable);
  2610. if (e->token.string != "") {
  2611. GB_ASSERT(!is_blank_ident(e->token));
  2612. lbAddr res = {};
  2613. if (return_ptr_value.value) {
  2614. lbValue ptr = return_ptr_value;
  2615. if (results->variables.count != 1) {
  2616. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2617. }
  2618. res = lb_addr(ptr);
  2619. lb_add_entity(p->module, e, ptr);
  2620. } else {
  2621. res = lb_add_local(p, e->type, e);
  2622. }
  2623. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2624. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2625. lb_addr_store(p, res, c);
  2626. }
  2627. }
  2628. }
  2629. }
  2630. }
  2631. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2632. lb_push_context_onto_stack_from_implicit_parameter(p);
  2633. }
  2634. lb_start_block(p, p->entry_block);
  2635. if (p->debug_info != nullptr) {
  2636. TokenPos pos = {};
  2637. if (p->body != nullptr) {
  2638. pos = ast_token(p->body).pos;
  2639. } else if (p->type_expr != nullptr) {
  2640. pos = ast_token(p->type_expr).pos;
  2641. } else if (p->entity != nullptr) {
  2642. pos = p->entity->token.pos;
  2643. }
  2644. if (pos.file_id != 0) {
  2645. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  2646. }
  2647. if (p->context_stack.count != 0) {
  2648. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  2649. }
  2650. }
  2651. }
  2652. void lb_end_procedure_body(lbProcedure *p) {
  2653. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2654. LLVMBuildBr(p->builder, p->entry_block->block);
  2655. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2656. // Make sure there is a "ret void" at the end of a procedure with no return type
  2657. if (p->type->Proc.result_count == 0) {
  2658. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2659. if (!lb_is_instr_terminating(instr)) {
  2660. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2661. LLVMBuildRetVoid(p->builder);
  2662. }
  2663. }
  2664. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  2665. LLVMBasicBlockRef block = nullptr;
  2666. // Make sure every block terminates, and if not, make it unreachable
  2667. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2668. LLVMValueRef instr = LLVMGetLastInstruction(block);
  2669. if (instr == nullptr) {
  2670. LLVMPositionBuilderAtEnd(p->builder, block);
  2671. LLVMBuildUnreachable(p->builder);
  2672. }
  2673. }
  2674. p->curr_block = nullptr;
  2675. p->module->state_flags = 0;
  2676. }
  2677. void lb_end_procedure(lbProcedure *p) {
  2678. LLVMDisposeBuilder(p->builder);
  2679. }
  2680. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2681. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2682. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2683. array_add(&from->succs, to);
  2684. array_add(&to->preds, from);
  2685. }
  2686. }
  2687. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2688. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2689. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2690. b->appended = false;
  2691. if (append) {
  2692. b->appended = true;
  2693. LLVMAppendExistingBasicBlock(p->value, b->block);
  2694. }
  2695. b->scope = p->curr_scope;
  2696. b->scope_index = p->scope_index;
  2697. b->preds.allocator = heap_allocator();
  2698. b->succs.allocator = heap_allocator();
  2699. array_add(&p->blocks, b);
  2700. return b;
  2701. }
  2702. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2703. if (p->curr_block == nullptr) {
  2704. return;
  2705. }
  2706. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2707. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2708. return;
  2709. }
  2710. lb_add_edge(p->curr_block, target_block);
  2711. LLVMBuildBr(p->builder, target_block->block);
  2712. p->curr_block = nullptr;
  2713. }
  2714. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2715. lbBlock *b = p->curr_block;
  2716. if (b == nullptr) {
  2717. return;
  2718. }
  2719. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2720. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2721. return;
  2722. }
  2723. lb_add_edge(b, true_block);
  2724. lb_add_edge(b, false_block);
  2725. LLVMValueRef cv = cond.value;
  2726. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2727. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2728. }
  2729. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2730. GB_ASSERT(cond != nullptr);
  2731. GB_ASSERT(true_block != nullptr);
  2732. GB_ASSERT(false_block != nullptr);
  2733. switch (cond->kind) {
  2734. case_ast_node(pe, ParenExpr, cond);
  2735. return lb_build_cond(p, pe->expr, true_block, false_block);
  2736. case_end;
  2737. case_ast_node(ue, UnaryExpr, cond);
  2738. if (ue->op.kind == Token_Not) {
  2739. return lb_build_cond(p, ue->expr, false_block, true_block);
  2740. }
  2741. case_end;
  2742. case_ast_node(be, BinaryExpr, cond);
  2743. if (be->op.kind == Token_CmpAnd) {
  2744. lbBlock *block = lb_create_block(p, "cmp.and");
  2745. lb_build_cond(p, be->left, block, false_block);
  2746. lb_start_block(p, block);
  2747. return lb_build_cond(p, be->right, true_block, false_block);
  2748. } else if (be->op.kind == Token_CmpOr) {
  2749. lbBlock *block = lb_create_block(p, "cmp.or");
  2750. lb_build_cond(p, be->left, true_block, block);
  2751. lb_start_block(p, block);
  2752. return lb_build_cond(p, be->right, true_block, false_block);
  2753. }
  2754. case_end;
  2755. }
  2756. lbValue v = lb_build_expr(p, cond);
  2757. // v = lb_emit_conv(p, v, t_bool);
  2758. v = lb_emit_conv(p, v, t_llvm_bool);
  2759. lb_emit_if(p, v, true_block, false_block);
  2760. return v;
  2761. }
  2762. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2763. GB_ASSERT(p->decl_block != p->curr_block);
  2764. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2765. char const *name = "";
  2766. if (e != nullptr) {
  2767. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2768. }
  2769. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2770. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2771. // unsigned alignment = 16; // TODO(bill): Make this configurable
  2772. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  2773. LLVMSetAlignment(ptr, alignment);
  2774. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2775. if (zero_init) {
  2776. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2777. switch (kind) {
  2778. case LLVMStructTypeKind:
  2779. case LLVMArrayTypeKind:
  2780. {
  2781. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  2782. LLVMTypeRef type_i8 = LLVMInt8TypeInContext(p->module->ctx);
  2783. LLVMTypeRef type_i32 = LLVMInt32TypeInContext(p->module->ctx);
  2784. i32 sz = cast(i32)type_size_of(type);
  2785. LLVMBuildMemSet(p->builder, ptr, LLVMConstNull(type_i8), LLVMConstInt(type_i32, sz, false), alignment);
  2786. }
  2787. break;
  2788. default:
  2789. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2790. break;
  2791. }
  2792. }
  2793. lbValue val = {};
  2794. val.value = ptr;
  2795. val.type = alloc_type_pointer(type);
  2796. if (e != nullptr) {
  2797. lb_add_entity(p->module, e, val);
  2798. lb_add_debug_local_variable(p, ptr, type, e->token);
  2799. }
  2800. return lb_addr(val);
  2801. }
  2802. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2803. return lb_add_local(p, type, nullptr, zero_init);
  2804. }
  2805. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2806. GB_ASSERT(pd->body != nullptr);
  2807. lbModule *m = p->module;
  2808. auto *min_dep_set = &m->info->minimum_dependency_set;
  2809. if (ptr_set_exists(min_dep_set, e) == false) {
  2810. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2811. return;
  2812. }
  2813. // NOTE(bill): Generate a new name
  2814. // parent.name-guid
  2815. String original_name = e->token.string;
  2816. String pd_name = original_name;
  2817. if (e->Procedure.link_name.len > 0) {
  2818. pd_name = e->Procedure.link_name;
  2819. }
  2820. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2821. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2822. i32 guid = cast(i32)p->children.count;
  2823. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2824. String name = make_string(cast(u8 *)name_text, name_len-1);
  2825. set_procedure_abi_types(e->type);
  2826. e->Procedure.link_name = name;
  2827. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2828. e->code_gen_procedure = nested_proc;
  2829. lbValue value = {};
  2830. value.value = nested_proc->value;
  2831. value.type = nested_proc->type;
  2832. lb_add_entity(m, e, value);
  2833. array_add(&p->children, nested_proc);
  2834. array_add(&m->procedures_to_generate, nested_proc);
  2835. }
  2836. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2837. if (e == nullptr) {
  2838. return;
  2839. }
  2840. GB_ASSERT(e->kind == Entity_LibraryName);
  2841. GB_ASSERT(e->flags & EntityFlag_Used);
  2842. for_array(i, e->LibraryName.paths) {
  2843. String library_path = e->LibraryName.paths[i];
  2844. if (library_path.len == 0) {
  2845. continue;
  2846. }
  2847. bool ok = true;
  2848. for_array(path_index, m->foreign_library_paths) {
  2849. String path = m->foreign_library_paths[path_index];
  2850. #if defined(GB_SYSTEM_WINDOWS)
  2851. if (str_eq_ignore_case(path, library_path)) {
  2852. #else
  2853. if (str_eq(path, library_path)) {
  2854. #endif
  2855. ok = false;
  2856. break;
  2857. }
  2858. }
  2859. if (ok) {
  2860. array_add(&m->foreign_library_paths, library_path);
  2861. }
  2862. }
  2863. }
  2864. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2865. if (vd == nullptr || vd->is_mutable) {
  2866. return;
  2867. }
  2868. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2869. static i32 global_guid = 0;
  2870. for_array(i, vd->names) {
  2871. Ast *ident = vd->names[i];
  2872. GB_ASSERT(ident->kind == Ast_Ident);
  2873. Entity *e = entity_of_node(ident);
  2874. GB_ASSERT(e != nullptr);
  2875. if (e->kind != Entity_TypeName) {
  2876. continue;
  2877. }
  2878. bool polymorphic_struct = false;
  2879. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2880. Type *bt = base_type(e->type);
  2881. if (bt->kind == Type_Struct) {
  2882. polymorphic_struct = bt->Struct.is_polymorphic;
  2883. }
  2884. }
  2885. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2886. continue;
  2887. }
  2888. if (e->TypeName.ir_mangled_name.len != 0) {
  2889. // NOTE(bill): Already set
  2890. continue;
  2891. }
  2892. lb_set_nested_type_name_ir_mangled_name(e, p);
  2893. }
  2894. for_array(i, vd->names) {
  2895. Ast *ident = vd->names[i];
  2896. GB_ASSERT(ident->kind == Ast_Ident);
  2897. Entity *e = entity_of_node(ident);
  2898. GB_ASSERT(e != nullptr);
  2899. if (e->kind != Entity_Procedure) {
  2900. continue;
  2901. }
  2902. CheckerInfo *info = p->module->info;
  2903. DeclInfo *decl = decl_info_of_entity(e);
  2904. ast_node(pl, ProcLit, decl->proc_lit);
  2905. if (pl->body != nullptr) {
  2906. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2907. if (found) {
  2908. auto procs = *found;
  2909. for_array(i, procs) {
  2910. Entity *e = procs[i];
  2911. if (!ptr_set_exists(min_dep_set, e)) {
  2912. continue;
  2913. }
  2914. DeclInfo *d = decl_info_of_entity(e);
  2915. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2916. }
  2917. } else {
  2918. lb_build_nested_proc(p, pl, e);
  2919. }
  2920. } else {
  2921. // FFI - Foreign function interace
  2922. String original_name = e->token.string;
  2923. String name = original_name;
  2924. if (e->Procedure.is_foreign) {
  2925. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2926. }
  2927. if (e->Procedure.link_name.len > 0) {
  2928. name = e->Procedure.link_name;
  2929. }
  2930. lbValue *prev_value = string_map_get(&p->module->members, name);
  2931. if (prev_value != nullptr) {
  2932. // NOTE(bill): Don't do mutliple declarations in the IR
  2933. return;
  2934. }
  2935. set_procedure_abi_types(e->type);
  2936. e->Procedure.link_name = name;
  2937. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2938. lbValue value = {};
  2939. value.value = nested_proc->value;
  2940. value.type = nested_proc->type;
  2941. array_add(&p->module->procedures_to_generate, nested_proc);
  2942. if (p != nullptr) {
  2943. array_add(&p->children, nested_proc);
  2944. } else {
  2945. string_map_set(&p->module->members, name, value);
  2946. }
  2947. }
  2948. }
  2949. }
  2950. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  2951. for_array(i, stmts) {
  2952. Ast *stmt = stmts[i];
  2953. switch (stmt->kind) {
  2954. case_ast_node(vd, ValueDecl, stmt);
  2955. lb_build_constant_value_decl(p, vd);
  2956. case_end;
  2957. case_ast_node(fb, ForeignBlockDecl, stmt);
  2958. ast_node(block, BlockStmt, fb->body);
  2959. lb_build_stmt_list(p, block->stmts);
  2960. case_end;
  2961. }
  2962. }
  2963. for_array(i, stmts) {
  2964. lb_build_stmt(p, stmts[i]);
  2965. }
  2966. }
  2967. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  2968. GB_ASSERT(ident->kind == Ast_Ident);
  2969. Entity *e = entity_of_node(ident);
  2970. GB_ASSERT(e->kind == Entity_Label);
  2971. for_array(i, p->branch_blocks) {
  2972. lbBranchBlocks *b = &p->branch_blocks[i];
  2973. if (b->label == e->Label.node) {
  2974. return *b;
  2975. }
  2976. }
  2977. GB_PANIC("Unreachable");
  2978. lbBranchBlocks empty = {};
  2979. return empty;
  2980. }
  2981. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  2982. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  2983. tl->prev = p->target_list;
  2984. tl->break_ = break_;
  2985. tl->continue_ = continue_;
  2986. tl->fallthrough_ = fallthrough_;
  2987. p->target_list = tl;
  2988. if (label != nullptr) { // Set label blocks
  2989. GB_ASSERT(label->kind == Ast_Label);
  2990. for_array(i, p->branch_blocks) {
  2991. lbBranchBlocks *b = &p->branch_blocks[i];
  2992. GB_ASSERT(b->label != nullptr && label != nullptr);
  2993. GB_ASSERT(b->label->kind == Ast_Label);
  2994. if (b->label == label) {
  2995. b->break_ = break_;
  2996. b->continue_ = continue_;
  2997. return tl;
  2998. }
  2999. }
  3000. GB_PANIC("Unreachable");
  3001. }
  3002. return tl;
  3003. }
  3004. void lb_pop_target_list(lbProcedure *p) {
  3005. p->target_list = p->target_list->prev;
  3006. }
  3007. void lb_open_scope(lbProcedure *p, Scope *s) {
  3008. lbModule *m = p->module;
  3009. if (m->debug_builder) {
  3010. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  3011. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  3012. Token token = ast_token(s->node);
  3013. unsigned line = cast(unsigned)token.pos.line;
  3014. unsigned column = cast(unsigned)token.pos.column;
  3015. LLVMMetadataRef file = nullptr;
  3016. if (s->node->file != nullptr) {
  3017. file = lb_get_llvm_metadata(m, s->node->file);
  3018. }
  3019. LLVMMetadataRef scope = nullptr;
  3020. if (p->scope_stack.count > 0) {
  3021. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  3022. }
  3023. if (scope == nullptr) {
  3024. scope = lb_get_llvm_metadata(m, p);
  3025. }
  3026. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  3027. if (m->debug_builder) {
  3028. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  3029. file, line, column
  3030. );
  3031. lb_set_llvm_metadata(m, s, res);
  3032. }
  3033. }
  3034. }
  3035. p->scope_index += 1;
  3036. array_add(&p->scope_stack, s);
  3037. }
  3038. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  3039. lb_emit_defer_stmts(p, kind, block);
  3040. GB_ASSERT(p->scope_index > 0);
  3041. // NOTE(bill): Remove `context`s made in that scope
  3042. while (p->context_stack.count > 0) {
  3043. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  3044. if (ctx->scope_index >= p->scope_index) {
  3045. array_pop(&p->context_stack);
  3046. } else {
  3047. break;
  3048. }
  3049. }
  3050. p->scope_index -= 1;
  3051. array_pop(&p->scope_stack);
  3052. }
  3053. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  3054. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  3055. GB_ASSERT(is_type_boolean(tv.type));
  3056. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  3057. if (tv.value.value_bool) {
  3058. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  3059. } else if (ws->else_stmt) {
  3060. switch (ws->else_stmt->kind) {
  3061. case Ast_BlockStmt:
  3062. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  3063. break;
  3064. case Ast_WhenStmt:
  3065. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  3066. break;
  3067. default:
  3068. GB_PANIC("Invalid 'else' statement in 'when' statement");
  3069. break;
  3070. }
  3071. }
  3072. }
  3073. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  3074. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3075. lbModule *m = p->module;
  3076. lbValue count = {};
  3077. Type *expr_type = base_type(type_deref(expr.type));
  3078. switch (expr_type->kind) {
  3079. case Type_Array:
  3080. count = lb_const_int(m, t_int, expr_type->Array.count);
  3081. break;
  3082. }
  3083. lbValue val = {};
  3084. lbValue idx = {};
  3085. lbBlock *loop = nullptr;
  3086. lbBlock *done = nullptr;
  3087. lbBlock *body = nullptr;
  3088. lbAddr index = lb_add_local_generated(p, t_int, false);
  3089. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  3090. loop = lb_create_block(p, "for.index.loop");
  3091. lb_emit_jump(p, loop);
  3092. lb_start_block(p, loop);
  3093. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  3094. lb_addr_store(p, index, incr);
  3095. body = lb_create_block(p, "for.index.body");
  3096. done = lb_create_block(p, "for.index.done");
  3097. if (count.value == nullptr) {
  3098. GB_ASSERT(count_ptr.value != nullptr);
  3099. count = lb_emit_load(p, count_ptr);
  3100. }
  3101. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3102. lb_emit_if(p, cond, body, done);
  3103. lb_start_block(p, body);
  3104. idx = lb_addr_load(p, index);
  3105. switch (expr_type->kind) {
  3106. case Type_Array: {
  3107. if (val_type != nullptr) {
  3108. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3109. }
  3110. break;
  3111. }
  3112. case Type_EnumeratedArray: {
  3113. if (val_type != nullptr) {
  3114. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3115. // NOTE(bill): Override the idx value for the enumeration
  3116. Type *index_type = expr_type->EnumeratedArray.index;
  3117. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  3118. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  3119. }
  3120. }
  3121. break;
  3122. }
  3123. case Type_Slice: {
  3124. if (val_type != nullptr) {
  3125. lbValue elem = lb_slice_elem(p, expr);
  3126. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3127. }
  3128. break;
  3129. }
  3130. case Type_DynamicArray: {
  3131. if (val_type != nullptr) {
  3132. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  3133. elem = lb_emit_load(p, elem);
  3134. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3135. }
  3136. break;
  3137. }
  3138. case Type_Map: {
  3139. lbValue entries = lb_map_entries_ptr(p, expr);
  3140. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  3141. elem = lb_emit_load(p, elem);
  3142. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  3143. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  3144. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  3145. break;
  3146. }
  3147. case Type_Struct: {
  3148. GB_ASSERT(is_type_soa_struct(expr_type));
  3149. break;
  3150. }
  3151. default:
  3152. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  3153. break;
  3154. }
  3155. if (val_) *val_ = val;
  3156. if (idx_) *idx_ = idx;
  3157. if (loop_) *loop_ = loop;
  3158. if (done_) *done_ = done;
  3159. }
  3160. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  3161. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3162. lbModule *m = p->module;
  3163. lbValue count = lb_const_int(m, t_int, 0);
  3164. Type *expr_type = base_type(expr.type);
  3165. switch (expr_type->kind) {
  3166. case Type_Basic:
  3167. count = lb_string_len(p, expr);
  3168. break;
  3169. default:
  3170. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  3171. break;
  3172. }
  3173. lbValue val = {};
  3174. lbValue idx = {};
  3175. lbBlock *loop = nullptr;
  3176. lbBlock *done = nullptr;
  3177. lbBlock *body = nullptr;
  3178. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3179. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3180. loop = lb_create_block(p, "for.string.loop");
  3181. lb_emit_jump(p, loop);
  3182. lb_start_block(p, loop);
  3183. body = lb_create_block(p, "for.string.body");
  3184. done = lb_create_block(p, "for.string.done");
  3185. lbValue offset = lb_addr_load(p, offset_);
  3186. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  3187. lb_emit_if(p, cond, body, done);
  3188. lb_start_block(p, body);
  3189. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  3190. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  3191. auto args = array_make<lbValue>(permanent_allocator(), 1);
  3192. args[0] = lb_emit_string(p, str_elem, str_len);
  3193. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  3194. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  3195. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  3196. idx = offset;
  3197. if (val_type != nullptr) {
  3198. val = lb_emit_struct_ev(p, rune_and_len, 0);
  3199. }
  3200. if (val_) *val_ = val;
  3201. if (idx_) *idx_ = idx;
  3202. if (loop_) *loop_ = loop;
  3203. if (done_) *done_ = done;
  3204. }
  3205. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  3206. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3207. lbModule *m = p->module;
  3208. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  3209. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  3210. lbValue lower = lb_build_expr(p, node->left);
  3211. lbValue upper = {};
  3212. lbValue val = {};
  3213. lbValue idx = {};
  3214. lbBlock *loop = nullptr;
  3215. lbBlock *done = nullptr;
  3216. lbBlock *body = nullptr;
  3217. if (val_type == nullptr) {
  3218. val_type = lower.type;
  3219. }
  3220. lbAddr value = lb_add_local_generated(p, val_type, false);
  3221. lb_addr_store(p, value, lower);
  3222. lbAddr index = lb_add_local_generated(p, t_int, false);
  3223. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  3224. loop = lb_create_block(p, "for.interval.loop");
  3225. lb_emit_jump(p, loop);
  3226. lb_start_block(p, loop);
  3227. body = lb_create_block(p, "for.interval.body");
  3228. done = lb_create_block(p, "for.interval.done");
  3229. TokenKind op = Token_Lt;
  3230. switch (node->op.kind) {
  3231. case Token_Ellipsis: op = Token_LtEq; break;
  3232. case Token_RangeHalf: op = Token_Lt; break;
  3233. default: GB_PANIC("Invalid interval operator"); break;
  3234. }
  3235. upper = lb_build_expr(p, node->right);
  3236. lbValue curr_value = lb_addr_load(p, value);
  3237. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  3238. lb_emit_if(p, cond, body, done);
  3239. lb_start_block(p, body);
  3240. val = lb_addr_load(p, value);
  3241. idx = lb_addr_load(p, index);
  3242. lb_emit_increment(p, value.addr);
  3243. lb_emit_increment(p, index.addr);
  3244. if (val_) *val_ = val;
  3245. if (idx_) *idx_ = idx;
  3246. if (loop_) *loop_ = loop;
  3247. if (done_) *done_ = done;
  3248. }
  3249. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3250. lbModule *m = p->module;
  3251. Type *t = enum_type;
  3252. GB_ASSERT(is_type_enum(t));
  3253. Type *enum_ptr = alloc_type_pointer(t);
  3254. t = base_type(t);
  3255. Type *core_elem = core_type(t);
  3256. GB_ASSERT(t->kind == Type_Enum);
  3257. i64 enum_count = t->Enum.fields.count;
  3258. lbValue max_count = lb_const_int(m, t_int, enum_count);
  3259. lbValue ti = lb_type_info(m, t);
  3260. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  3261. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  3262. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  3263. lbValue values_data = lb_slice_elem(p, values);
  3264. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3265. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3266. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  3267. lb_emit_jump(p, loop);
  3268. lb_start_block(p, loop);
  3269. lbBlock *body = lb_create_block(p, "for.enum.body");
  3270. lbBlock *done = lb_create_block(p, "for.enum.done");
  3271. lbValue offset = lb_addr_load(p, offset_);
  3272. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  3273. lb_emit_if(p, cond, body, done);
  3274. lb_start_block(p, body);
  3275. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  3276. lb_emit_increment(p, offset_.addr);
  3277. lbValue val = {};
  3278. if (val_type != nullptr) {
  3279. GB_ASSERT(are_types_identical(enum_type, val_type));
  3280. if (is_type_integer(core_elem)) {
  3281. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  3282. val = lb_emit_conv(p, i, t);
  3283. } else {
  3284. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  3285. }
  3286. }
  3287. if (val_) *val_ = val;
  3288. if (idx_) *idx_ = offset;
  3289. if (loop_) *loop_ = loop;
  3290. if (done_) *done_ = done;
  3291. }
  3292. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  3293. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  3294. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  3295. lb_emit_jump(p, loop);
  3296. lb_start_block(p, loop);
  3297. lbBlock *body = lb_create_block(p, "for.tuple.body");
  3298. lbBlock *done = lb_create_block(p, "for.tuple.done");
  3299. lbValue tuple_value = lb_build_expr(p, expr);
  3300. Type *tuple = tuple_value.type;
  3301. GB_ASSERT(tuple->kind == Type_Tuple);
  3302. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  3303. i32 cond_index = tuple_count-1;
  3304. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  3305. lb_emit_if(p, cond, body, done);
  3306. lb_start_block(p, body);
  3307. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  3308. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  3309. if (loop_) *loop_ = loop;
  3310. if (done_) *done_ = done;
  3311. }
  3312. void lb_build_range_stmt_struct_soa(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3313. Ast *expr = unparen_expr(rs->expr);
  3314. TypeAndValue tav = type_and_value_of_expr(expr);
  3315. lbBlock *loop = nullptr;
  3316. lbBlock *body = nullptr;
  3317. lbBlock *done = nullptr;
  3318. lb_open_scope(p, scope);
  3319. Type *val_types[2] = {};
  3320. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3321. val_types[0] = type_of_expr(rs->vals[0]);
  3322. }
  3323. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3324. val_types[1] = type_of_expr(rs->vals[1]);
  3325. }
  3326. lbAddr array = lb_build_addr(p, expr);
  3327. if (is_type_pointer(type_deref(lb_addr_type(array)))) {
  3328. array = lb_addr(lb_addr_load(p, array));
  3329. }
  3330. lbValue count = lb_soa_struct_len(p, lb_addr_load(p, array));
  3331. lbAddr index = lb_add_local_generated(p, t_int, false);
  3332. lb_addr_store(p, index, lb_const_int(p->module, t_int, cast(u64)-1));
  3333. loop = lb_create_block(p, "for.soa.loop");
  3334. lb_emit_jump(p, loop);
  3335. lb_start_block(p, loop);
  3336. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  3337. lb_addr_store(p, index, incr);
  3338. body = lb_create_block(p, "for.soa.body");
  3339. done = lb_create_block(p, "for.soa.done");
  3340. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3341. lb_emit_if(p, cond, body, done);
  3342. lb_start_block(p, body);
  3343. if (val_types[0]) {
  3344. Entity *e = entity_of_node(rs->vals[0]);
  3345. if (e != nullptr) {
  3346. lbAddr soa_val = lb_addr_soa_variable(array.addr, lb_addr_load(p, index), nullptr);
  3347. map_set(&p->module->soa_values, hash_entity(e), soa_val);
  3348. }
  3349. }
  3350. if (val_types[1]) {
  3351. lb_store_range_stmt_val(p, rs->vals[1], lb_addr_load(p, index));
  3352. }
  3353. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3354. lb_build_stmt(p, rs->body);
  3355. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3356. lb_pop_target_list(p);
  3357. lb_emit_jump(p, loop);
  3358. lb_start_block(p, done);
  3359. }
  3360. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3361. Ast *expr = unparen_expr(rs->expr);
  3362. Type *expr_type = type_of_expr(expr);
  3363. if (expr_type != nullptr) {
  3364. Type *et = base_type(type_deref(expr_type));
  3365. if (is_type_soa_struct(et)) {
  3366. lb_build_range_stmt_struct_soa(p, rs, scope);
  3367. return;
  3368. }
  3369. }
  3370. lb_open_scope(p, scope);
  3371. Type *val0_type = nullptr;
  3372. Type *val1_type = nullptr;
  3373. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3374. val0_type = type_of_expr(rs->vals[0]);
  3375. }
  3376. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3377. val1_type = type_of_expr(rs->vals[1]);
  3378. }
  3379. if (val0_type != nullptr) {
  3380. Entity *e = entity_of_node(rs->vals[0]);
  3381. lb_add_local(p, e->type, e, true);
  3382. }
  3383. if (val1_type != nullptr) {
  3384. Entity *e = entity_of_node(rs->vals[1]);
  3385. lb_add_local(p, e->type, e, true);
  3386. }
  3387. lbValue val = {};
  3388. lbValue key = {};
  3389. lbBlock *loop = nullptr;
  3390. lbBlock *done = nullptr;
  3391. bool is_map = false;
  3392. TypeAndValue tav = type_and_value_of_expr(expr);
  3393. if (is_ast_range(expr)) {
  3394. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  3395. } else if (tav.mode == Addressing_Type) {
  3396. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3397. } else {
  3398. Type *expr_type = type_of_expr(expr);
  3399. Type *et = base_type(type_deref(expr_type));
  3400. switch (et->kind) {
  3401. case Type_Map: {
  3402. is_map = true;
  3403. lbValue map = lb_build_addr_ptr(p, expr);
  3404. if (is_type_pointer(type_deref(map.type))) {
  3405. map = lb_emit_load(p, map);
  3406. }
  3407. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3408. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3409. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3410. break;
  3411. }
  3412. case Type_Array: {
  3413. lbValue array = lb_build_addr_ptr(p, expr);
  3414. if (is_type_pointer(type_deref(array.type))) {
  3415. array = lb_emit_load(p, array);
  3416. }
  3417. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3418. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3419. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3420. break;
  3421. }
  3422. case Type_EnumeratedArray: {
  3423. lbValue array = lb_build_addr_ptr(p, expr);
  3424. if (is_type_pointer(type_deref(array.type))) {
  3425. array = lb_emit_load(p, array);
  3426. }
  3427. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3428. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3429. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3430. break;
  3431. }
  3432. case Type_DynamicArray: {
  3433. lbValue count_ptr = {};
  3434. lbValue array = lb_build_addr_ptr(p, expr);
  3435. if (is_type_pointer(type_deref(array.type))) {
  3436. array = lb_emit_load(p, array);
  3437. }
  3438. count_ptr = lb_emit_struct_ep(p, array, 1);
  3439. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3440. break;
  3441. }
  3442. case Type_Slice: {
  3443. lbValue count_ptr = {};
  3444. lbValue slice = lb_build_expr(p, expr);
  3445. if (is_type_pointer(slice.type)) {
  3446. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3447. slice = lb_emit_load(p, slice);
  3448. } else {
  3449. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3450. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3451. }
  3452. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3453. break;
  3454. }
  3455. case Type_Basic: {
  3456. lbValue string = lb_build_expr(p, expr);
  3457. if (is_type_pointer(string.type)) {
  3458. string = lb_emit_load(p, string);
  3459. }
  3460. if (is_type_untyped(expr_type)) {
  3461. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3462. lb_addr_store(p, s, string);
  3463. string = lb_addr_load(p, s);
  3464. }
  3465. Type *t = base_type(string.type);
  3466. GB_ASSERT(!is_type_cstring(t));
  3467. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3468. break;
  3469. }
  3470. case Type_Tuple:
  3471. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3472. break;
  3473. default:
  3474. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3475. break;
  3476. }
  3477. }
  3478. if (is_map) {
  3479. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], key);
  3480. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], val);
  3481. } else {
  3482. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3483. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], key);
  3484. }
  3485. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3486. lb_build_stmt(p, rs->body);
  3487. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3488. lb_pop_target_list(p);
  3489. lb_emit_jump(p, loop);
  3490. lb_start_block(p, done);
  3491. }
  3492. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs, Scope *scope) {
  3493. lbModule *m = p->module;
  3494. lb_open_scope(p, scope); // Open scope here
  3495. Type *val0_type = nullptr;
  3496. Type *val1_type = nullptr;
  3497. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3498. val0_type = type_of_expr(rs->val0);
  3499. }
  3500. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3501. val1_type = type_of_expr(rs->val1);
  3502. }
  3503. if (val0_type != nullptr) {
  3504. Entity *e = entity_of_node(rs->val0);
  3505. lb_add_local(p, e->type, e, true);
  3506. }
  3507. if (val1_type != nullptr) {
  3508. Entity *e = entity_of_node(rs->val1);
  3509. lb_add_local(p, e->type, e, true);
  3510. }
  3511. lbValue val = {};
  3512. lbValue key = {};
  3513. lbBlock *loop = nullptr;
  3514. lbBlock *done = nullptr;
  3515. Ast *expr = unparen_expr(rs->expr);
  3516. TypeAndValue tav = type_and_value_of_expr(expr);
  3517. if (is_ast_range(expr)) {
  3518. lbAddr val0_addr = {};
  3519. lbAddr val1_addr = {};
  3520. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3521. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3522. TokenKind op = expr->BinaryExpr.op.kind;
  3523. Ast *start_expr = expr->BinaryExpr.left;
  3524. Ast *end_expr = expr->BinaryExpr.right;
  3525. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3526. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3527. ExactValue start = start_expr->tav.value;
  3528. ExactValue end = end_expr->tav.value;
  3529. if (op == Token_Ellipsis) { // .. [start, end]
  3530. ExactValue index = exact_value_i64(0);
  3531. for (ExactValue val = start;
  3532. compare_exact_values(Token_LtEq, val, end);
  3533. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3534. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3535. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3536. lb_build_stmt(p, rs->body);
  3537. }
  3538. } else if (op == Token_RangeHalf) { // ..< [start, end)
  3539. ExactValue index = exact_value_i64(0);
  3540. for (ExactValue val = start;
  3541. compare_exact_values(Token_Lt, val, end);
  3542. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3543. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3544. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3545. lb_build_stmt(p, rs->body);
  3546. }
  3547. }
  3548. } else if (tav.mode == Addressing_Type) {
  3549. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3550. Type *et = type_deref(tav.type);
  3551. Type *bet = base_type(et);
  3552. lbAddr val0_addr = {};
  3553. lbAddr val1_addr = {};
  3554. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3555. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3556. for_array(i, bet->Enum.fields) {
  3557. Entity *field = bet->Enum.fields[i];
  3558. GB_ASSERT(field->kind == Entity_Constant);
  3559. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3560. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3561. lb_build_stmt(p, rs->body);
  3562. }
  3563. } else {
  3564. lbAddr val0_addr = {};
  3565. lbAddr val1_addr = {};
  3566. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3567. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3568. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3569. Type *t = base_type(expr->tav.type);
  3570. switch (t->kind) {
  3571. case Type_Basic:
  3572. GB_ASSERT(is_type_string(t));
  3573. {
  3574. ExactValue value = expr->tav.value;
  3575. GB_ASSERT(value.kind == ExactValue_String);
  3576. String str = value.value_string;
  3577. Rune codepoint = 0;
  3578. isize offset = 0;
  3579. do {
  3580. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3581. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3582. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3583. lb_build_stmt(p, rs->body);
  3584. offset += width;
  3585. } while (offset < str.len);
  3586. }
  3587. break;
  3588. case Type_Array:
  3589. if (t->Array.count > 0) {
  3590. lbValue val = lb_build_expr(p, expr);
  3591. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3592. for (i64 i = 0; i < t->Array.count; i++) {
  3593. if (val0_type) {
  3594. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3595. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3596. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3597. }
  3598. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3599. lb_build_stmt(p, rs->body);
  3600. }
  3601. }
  3602. break;
  3603. case Type_EnumeratedArray:
  3604. if (t->EnumeratedArray.count > 0) {
  3605. lbValue val = lb_build_expr(p, expr);
  3606. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3607. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3608. if (val0_type) {
  3609. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3610. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3611. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3612. }
  3613. if (val1_type) {
  3614. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3615. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3616. }
  3617. lb_build_stmt(p, rs->body);
  3618. }
  3619. }
  3620. break;
  3621. default:
  3622. GB_PANIC("Invalid '#unroll for' type");
  3623. break;
  3624. }
  3625. }
  3626. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3627. }
  3628. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  3629. lb_open_scope(p, scope);
  3630. if (ss->init != nullptr) {
  3631. lb_build_stmt(p, ss->init);
  3632. }
  3633. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3634. if (ss->tag != nullptr) {
  3635. tag = lb_build_expr(p, ss->tag);
  3636. }
  3637. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3638. ast_node(body, BlockStmt, ss->body);
  3639. Slice<Ast *> default_stmts = {};
  3640. lbBlock *default_fall = nullptr;
  3641. lbBlock *default_block = nullptr;
  3642. lbBlock *fall = nullptr;
  3643. isize case_count = body->stmts.count;
  3644. for_array(i, body->stmts) {
  3645. Ast *clause = body->stmts[i];
  3646. ast_node(cc, CaseClause, clause);
  3647. lbBlock *body = fall;
  3648. if (body == nullptr) {
  3649. body = lb_create_block(p, "switch.case.body");
  3650. }
  3651. fall = done;
  3652. if (i+1 < case_count) {
  3653. fall = lb_create_block(p, "switch.fall.body");
  3654. }
  3655. if (cc->list.count == 0) {
  3656. // default case
  3657. default_stmts = cc->stmts;
  3658. default_fall = fall;
  3659. default_block = body;
  3660. continue;
  3661. }
  3662. lbBlock *next_cond = nullptr;
  3663. for_array(j, cc->list) {
  3664. Ast *expr = unparen_expr(cc->list[j]);
  3665. next_cond = lb_create_block(p, "switch.case.next");
  3666. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3667. if (is_ast_range(expr)) {
  3668. ast_node(ie, BinaryExpr, expr);
  3669. TokenKind op = Token_Invalid;
  3670. switch (ie->op.kind) {
  3671. case Token_Ellipsis: op = Token_LtEq; break;
  3672. case Token_RangeHalf: op = Token_Lt; break;
  3673. default: GB_PANIC("Invalid interval operator"); break;
  3674. }
  3675. lbValue lhs = lb_build_expr(p, ie->left);
  3676. lbValue rhs = lb_build_expr(p, ie->right);
  3677. // TODO(bill): do short circuit here
  3678. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3679. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3680. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3681. } else {
  3682. if (expr->tav.mode == Addressing_Type) {
  3683. GB_ASSERT(is_type_typeid(tag.type));
  3684. lbValue e = lb_typeid(p->module, expr->tav.type);
  3685. e = lb_emit_conv(p, e, tag.type);
  3686. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3687. } else {
  3688. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3689. }
  3690. }
  3691. lb_emit_if(p, cond, body, next_cond);
  3692. lb_start_block(p, next_cond);
  3693. }
  3694. lb_start_block(p, body);
  3695. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3696. lb_open_scope(p, body->scope);
  3697. lb_build_stmt_list(p, cc->stmts);
  3698. lb_close_scope(p, lbDeferExit_Default, body);
  3699. lb_pop_target_list(p);
  3700. lb_emit_jump(p, done);
  3701. lb_start_block(p, next_cond);
  3702. }
  3703. if (default_block != nullptr) {
  3704. lb_emit_jump(p, default_block);
  3705. lb_start_block(p, default_block);
  3706. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3707. lb_open_scope(p, default_block->scope);
  3708. lb_build_stmt_list(p, default_stmts);
  3709. lb_close_scope(p, lbDeferExit_Default, default_block);
  3710. lb_pop_target_list(p);
  3711. }
  3712. lb_emit_jump(p, done);
  3713. lb_close_scope(p, lbDeferExit_Default, done);
  3714. lb_start_block(p, done);
  3715. }
  3716. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3717. Entity *e = implicit_entity_of_node(clause);
  3718. GB_ASSERT(e != nullptr);
  3719. if (e->flags & EntityFlag_Value) {
  3720. // by value
  3721. GB_ASSERT(are_types_identical(e->type, value.type));
  3722. lbAddr x = lb_add_local(p, e->type, e, false);
  3723. lb_addr_store(p, x, value);
  3724. } else {
  3725. // by reference
  3726. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3727. lb_add_entity(p->module, e, value);
  3728. }
  3729. }
  3730. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3731. Entity *e = entity_of_node(stmt_val);
  3732. if (e == nullptr) {
  3733. return {};
  3734. }
  3735. if ((e->flags & EntityFlag_Value) == 0) {
  3736. if (LLVMIsALoadInst(value.value)) {
  3737. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3738. lb_add_entity(p->module, e, ptr);
  3739. return lb_addr(ptr);
  3740. }
  3741. }
  3742. // by value
  3743. lbAddr addr = lb_add_local(p, e->type, e, false);
  3744. lb_addr_store(p, addr, value);
  3745. return addr;
  3746. }
  3747. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3748. ast_node(cc, CaseClause, clause);
  3749. lb_push_target_list(p, label, done, nullptr, nullptr);
  3750. lb_open_scope(p, body->scope);
  3751. lb_build_stmt_list(p, cc->stmts);
  3752. lb_close_scope(p, lbDeferExit_Default, body);
  3753. lb_pop_target_list(p);
  3754. lb_emit_jump(p, done);
  3755. }
  3756. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3757. lbModule *m = p->module;
  3758. ast_node(as, AssignStmt, ss->tag);
  3759. GB_ASSERT(as->lhs.count == 1);
  3760. GB_ASSERT(as->rhs.count == 1);
  3761. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3762. bool is_parent_ptr = is_type_pointer(parent.type);
  3763. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3764. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3765. lbValue parent_value = parent;
  3766. lbValue parent_ptr = parent;
  3767. if (!is_parent_ptr) {
  3768. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3769. }
  3770. lbValue tag_index = {};
  3771. lbValue union_data = {};
  3772. if (switch_kind == TypeSwitch_Union) {
  3773. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3774. tag_index = lb_emit_load(p, tag_ptr);
  3775. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3776. }
  3777. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3778. lb_emit_jump(p, start_block);
  3779. lb_start_block(p, start_block);
  3780. // NOTE(bill): Append this later
  3781. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3782. Ast *default_ = nullptr;
  3783. ast_node(body, BlockStmt, ss->body);
  3784. gb_local_persist i32 weird_count = 0;
  3785. for_array(i, body->stmts) {
  3786. Ast *clause = body->stmts[i];
  3787. ast_node(cc, CaseClause, clause);
  3788. if (cc->list.count == 0) {
  3789. default_ = clause;
  3790. continue;
  3791. }
  3792. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3793. lbBlock *next = nullptr;
  3794. Type *case_type = nullptr;
  3795. for_array(type_index, cc->list) {
  3796. next = lb_create_block(p, "typeswitch.next");
  3797. case_type = type_of_expr(cc->list[type_index]);
  3798. lbValue cond = {};
  3799. if (switch_kind == TypeSwitch_Union) {
  3800. Type *ut = base_type(type_deref(parent.type));
  3801. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3802. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3803. } else if (switch_kind == TypeSwitch_Any) {
  3804. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3805. lbValue case_typeid = lb_typeid(m, case_type);
  3806. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3807. }
  3808. GB_ASSERT(cond.value != nullptr);
  3809. lb_emit_if(p, cond, body, next);
  3810. lb_start_block(p, next);
  3811. }
  3812. Entity *case_entity = implicit_entity_of_node(clause);
  3813. lbValue value = parent_value;
  3814. lb_start_block(p, body);
  3815. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3816. if (cc->list.count == 1) {
  3817. lbValue data = {};
  3818. if (switch_kind == TypeSwitch_Union) {
  3819. data = union_data;
  3820. } else if (switch_kind == TypeSwitch_Any) {
  3821. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3822. data = any_data;
  3823. }
  3824. Type *ct = case_entity->type;
  3825. Type *ct_ptr = alloc_type_pointer(ct);
  3826. value = lb_emit_conv(p, data, ct_ptr);
  3827. if (!by_reference) {
  3828. value = lb_emit_load(p, value);
  3829. }
  3830. }
  3831. lb_store_type_case_implicit(p, clause, value);
  3832. lb_type_case_body(p, ss->label, clause, body, done);
  3833. lb_start_block(p, next);
  3834. }
  3835. if (default_ != nullptr) {
  3836. lb_store_type_case_implicit(p, default_, parent_value);
  3837. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3838. } else {
  3839. lb_emit_jump(p, done);
  3840. }
  3841. lb_start_block(p, done);
  3842. }
  3843. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3844. lbModule *m = p->module;
  3845. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3846. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3847. type = default_type(type);
  3848. lbValue short_circuit = {};
  3849. if (op == Token_CmpAnd) {
  3850. lb_build_cond(p, left, rhs, done);
  3851. short_circuit = lb_const_bool(m, type, false);
  3852. } else if (op == Token_CmpOr) {
  3853. lb_build_cond(p, left, done, rhs);
  3854. short_circuit = lb_const_bool(m, type, true);
  3855. }
  3856. if (rhs->preds.count == 0) {
  3857. lb_start_block(p, done);
  3858. return short_circuit;
  3859. }
  3860. if (done->preds.count == 0) {
  3861. lb_start_block(p, rhs);
  3862. return lb_build_expr(p, right);
  3863. }
  3864. Array<LLVMValueRef> incoming_values = {};
  3865. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3866. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3867. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3868. for_array(i, done->preds) {
  3869. incoming_values[i] = short_circuit.value;
  3870. incoming_blocks[i] = done->preds[i]->block;
  3871. }
  3872. lb_start_block(p, rhs);
  3873. lbValue edge = lb_build_expr(p, right);
  3874. incoming_values[done->preds.count] = edge.value;
  3875. incoming_blocks[done->preds.count] = p->curr_block->block;
  3876. lb_emit_jump(p, done);
  3877. lb_start_block(p, done);
  3878. lbValue res = {};
  3879. res.type = type;
  3880. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3881. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3882. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3883. return res;
  3884. }
  3885. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3886. Ast *prev_stmt = p->curr_stmt;
  3887. defer (p->curr_stmt = prev_stmt);
  3888. p->curr_stmt = node;
  3889. if (p->curr_block != nullptr) {
  3890. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  3891. if (lb_is_instr_terminating(last_instr)) {
  3892. return;
  3893. }
  3894. }
  3895. LLVMMetadataRef prev_debug_location = nullptr;
  3896. if (p->debug_info != nullptr) {
  3897. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  3898. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  3899. }
  3900. defer (if (prev_debug_location != nullptr) {
  3901. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  3902. });
  3903. u64 prev_state_flags = p->module->state_flags;
  3904. defer (p->module->state_flags = prev_state_flags);
  3905. if (node->state_flags != 0) {
  3906. u64 in = node->state_flags;
  3907. u64 out = p->module->state_flags;
  3908. if (in & StateFlag_bounds_check) {
  3909. out |= StateFlag_bounds_check;
  3910. out &= ~StateFlag_no_bounds_check;
  3911. } else if (in & StateFlag_no_bounds_check) {
  3912. out |= StateFlag_no_bounds_check;
  3913. out &= ~StateFlag_bounds_check;
  3914. }
  3915. p->module->state_flags = out;
  3916. }
  3917. switch (node->kind) {
  3918. case_ast_node(bs, EmptyStmt, node);
  3919. case_end;
  3920. case_ast_node(us, UsingStmt, node);
  3921. case_end;
  3922. case_ast_node(ws, WhenStmt, node);
  3923. lb_build_when_stmt(p, ws);
  3924. case_end;
  3925. case_ast_node(bs, BlockStmt, node);
  3926. lbBlock *done = nullptr;
  3927. if (bs->label != nullptr) {
  3928. done = lb_create_block(p, "block.done");
  3929. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3930. tl->is_block = true;
  3931. }
  3932. lb_open_scope(p, node->scope);
  3933. lb_build_stmt_list(p, bs->stmts);
  3934. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3935. if (done != nullptr) {
  3936. lb_emit_jump(p, done);
  3937. lb_start_block(p, done);
  3938. }
  3939. case_end;
  3940. case_ast_node(vd, ValueDecl, node);
  3941. if (!vd->is_mutable) {
  3942. return;
  3943. }
  3944. bool is_static = false;
  3945. if (vd->names.count > 0) {
  3946. Entity *e = entity_of_node(vd->names[0]);
  3947. if (e->flags & EntityFlag_Static) {
  3948. // NOTE(bill): If one of the entities is static, they all are
  3949. is_static = true;
  3950. }
  3951. }
  3952. if (is_static) {
  3953. for_array(i, vd->names) {
  3954. lbValue value = {};
  3955. if (vd->values.count > 0) {
  3956. GB_ASSERT(vd->names.count == vd->values.count);
  3957. Ast *ast_value = vd->values[i];
  3958. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  3959. ast_value->tav.mode == Addressing_Invalid);
  3960. bool allow_local = false;
  3961. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  3962. }
  3963. Ast *ident = vd->names[i];
  3964. GB_ASSERT(!is_blank_ident(ident));
  3965. Entity *e = entity_of_node(ident);
  3966. GB_ASSERT(e->flags & EntityFlag_Static);
  3967. String name = e->token.string;
  3968. String mangled_name = {};
  3969. {
  3970. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  3971. str = gb_string_appendc(str, "-");
  3972. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  3973. mangled_name.text = cast(u8 *)str;
  3974. mangled_name.len = gb_string_length(str);
  3975. }
  3976. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  3977. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  3978. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  3979. if (value.value != nullptr) {
  3980. LLVMSetInitializer(global, value.value);
  3981. } else {
  3982. }
  3983. if (e->Variable.thread_local_model != "") {
  3984. LLVMSetThreadLocal(global, true);
  3985. String m = e->Variable.thread_local_model;
  3986. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  3987. if (m == "default") {
  3988. mode = LLVMGeneralDynamicTLSModel;
  3989. } else if (m == "localdynamic") {
  3990. mode = LLVMLocalDynamicTLSModel;
  3991. } else if (m == "initialexec") {
  3992. mode = LLVMInitialExecTLSModel;
  3993. } else if (m == "localexec") {
  3994. mode = LLVMLocalExecTLSModel;
  3995. } else {
  3996. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  3997. }
  3998. LLVMSetThreadLocalMode(global, mode);
  3999. } else {
  4000. LLVMSetLinkage(global, LLVMInternalLinkage);
  4001. }
  4002. lbValue global_val = {global, alloc_type_pointer(e->type)};
  4003. lb_add_entity(p->module, e, global_val);
  4004. lb_add_member(p->module, mangled_name, global_val);
  4005. }
  4006. return;
  4007. }
  4008. if (vd->values.count == 0) { // declared and zero-initialized
  4009. for_array(i, vd->names) {
  4010. Ast *name = vd->names[i];
  4011. if (!is_blank_ident(name)) {
  4012. Entity *e = entity_of_node(name);
  4013. lb_add_local(p, e->type, e, true);
  4014. }
  4015. }
  4016. } else { // Tuple(s)
  4017. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  4018. auto inits = array_make<lbValue>(permanent_allocator(), 0, vd->names.count);
  4019. for_array(i, vd->names) {
  4020. Ast *name = vd->names[i];
  4021. lbAddr lval = {};
  4022. if (!is_blank_ident(name)) {
  4023. Entity *e = entity_of_node(name);
  4024. lval = lb_add_local(p, e->type, e, false);
  4025. }
  4026. array_add(&lvals, lval);
  4027. }
  4028. for_array(i, vd->values) {
  4029. lbValue init = lb_build_expr(p, vd->values[i]);
  4030. Type *t = init.type;
  4031. if (t->kind == Type_Tuple) {
  4032. for_array(i, t->Tuple.variables) {
  4033. Entity *e = t->Tuple.variables[i];
  4034. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4035. array_add(&inits, v);
  4036. }
  4037. } else {
  4038. array_add(&inits, init);
  4039. }
  4040. }
  4041. for_array(i, inits) {
  4042. lbAddr lval = lvals[i];
  4043. lbValue init = inits[i];
  4044. lb_addr_store(p, lval, init);
  4045. }
  4046. }
  4047. case_end;
  4048. case_ast_node(as, AssignStmt, node);
  4049. if (as->op.kind == Token_Eq) {
  4050. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  4051. for_array(i, as->lhs) {
  4052. Ast *lhs = as->lhs[i];
  4053. lbAddr lval = {};
  4054. if (!is_blank_ident(lhs)) {
  4055. lval = lb_build_addr(p, lhs);
  4056. }
  4057. array_add(&lvals, lval);
  4058. }
  4059. if (as->lhs.count == as->rhs.count) {
  4060. if (as->lhs.count == 1) {
  4061. lbAddr lval = lvals[0];
  4062. Ast *rhs = as->rhs[0];
  4063. lbValue init = lb_build_expr(p, rhs);
  4064. lb_addr_store(p, lvals[0], init);
  4065. } else {
  4066. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4067. for_array(i, as->rhs) {
  4068. lbValue init = lb_build_expr(p, as->rhs[i]);
  4069. array_add(&inits, init);
  4070. }
  4071. for_array(i, inits) {
  4072. lbAddr lval = lvals[i];
  4073. lbValue init = inits[i];
  4074. lb_addr_store(p, lval, init);
  4075. }
  4076. }
  4077. } else {
  4078. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4079. for_array(i, as->rhs) {
  4080. lbValue init = lb_build_expr(p, as->rhs[i]);
  4081. Type *t = init.type;
  4082. // TODO(bill): refactor for code reuse as this is repeated a bit
  4083. if (t->kind == Type_Tuple) {
  4084. for_array(i, t->Tuple.variables) {
  4085. Entity *e = t->Tuple.variables[i];
  4086. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4087. array_add(&inits, v);
  4088. }
  4089. } else {
  4090. array_add(&inits, init);
  4091. }
  4092. }
  4093. for_array(i, inits) {
  4094. lbAddr lval = lvals[i];
  4095. lbValue init = inits[i];
  4096. lb_addr_store(p, lval, init);
  4097. }
  4098. }
  4099. } else {
  4100. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  4101. // +=, -=, etc
  4102. i32 op = cast(i32)as->op.kind;
  4103. op += Token_Add - Token_AddEq; // Convert += to +
  4104. if (op == Token_CmpAnd || op == Token_CmpOr) {
  4105. Type *type = as->lhs[0]->tav.type;
  4106. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  4107. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4108. lb_addr_store(p, lhs, new_value);
  4109. } else {
  4110. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4111. lbValue value = lb_build_expr(p, as->rhs[0]);
  4112. lbValue old_value = lb_addr_load(p, lhs);
  4113. Type *type = old_value.type;
  4114. lbValue change = lb_emit_conv(p, value, type);
  4115. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  4116. lb_addr_store(p, lhs, new_value);
  4117. }
  4118. return;
  4119. }
  4120. case_end;
  4121. case_ast_node(es, ExprStmt, node);
  4122. lb_build_expr(p, es->expr);
  4123. case_end;
  4124. case_ast_node(ds, DeferStmt, node);
  4125. isize scope_index = p->scope_index;
  4126. lb_add_defer_node(p, scope_index, ds->stmt);
  4127. case_end;
  4128. case_ast_node(rs, ReturnStmt, node);
  4129. lbValue res = {};
  4130. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  4131. isize return_count = p->type->Proc.result_count;
  4132. isize res_count = rs->results.count;
  4133. if (return_count == 0) {
  4134. // No return values
  4135. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4136. LLVMBuildRetVoid(p->builder);
  4137. return;
  4138. } else if (return_count == 1) {
  4139. Entity *e = tuple->variables[0];
  4140. if (res_count == 0) {
  4141. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4142. GB_ASSERT(found);
  4143. res = lb_emit_load(p, *found);
  4144. } else {
  4145. res = lb_build_expr(p, rs->results[0]);
  4146. res = lb_emit_conv(p, res, e->type);
  4147. }
  4148. if (p->type->Proc.has_named_results) {
  4149. // NOTE(bill): store the named values before returning
  4150. if (e->token.string != "") {
  4151. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4152. GB_ASSERT(found != nullptr);
  4153. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  4154. }
  4155. }
  4156. } else {
  4157. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  4158. if (res_count != 0) {
  4159. for (isize res_index = 0; res_index < res_count; res_index++) {
  4160. lbValue res = lb_build_expr(p, rs->results[res_index]);
  4161. Type *t = res.type;
  4162. if (t->kind == Type_Tuple) {
  4163. for_array(i, t->Tuple.variables) {
  4164. Entity *e = t->Tuple.variables[i];
  4165. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  4166. array_add(&results, v);
  4167. }
  4168. } else {
  4169. array_add(&results, res);
  4170. }
  4171. }
  4172. } else {
  4173. for (isize res_index = 0; res_index < return_count; res_index++) {
  4174. Entity *e = tuple->variables[res_index];
  4175. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4176. GB_ASSERT(found);
  4177. lbValue res = lb_emit_load(p, *found);
  4178. array_add(&results, res);
  4179. }
  4180. }
  4181. GB_ASSERT(results.count == return_count);
  4182. if (p->type->Proc.has_named_results) {
  4183. // NOTE(bill): store the named values before returning
  4184. for_array(i, p->type->Proc.results->Tuple.variables) {
  4185. Entity *e = p->type->Proc.results->Tuple.variables[i];
  4186. if (e->kind != Entity_Variable) {
  4187. continue;
  4188. }
  4189. if (e->token.string == "") {
  4190. continue;
  4191. }
  4192. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4193. GB_ASSERT(found != nullptr);
  4194. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  4195. }
  4196. }
  4197. Type *ret_type = p->type->Proc.results;
  4198. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4199. res = lb_add_local_generated(p, ret_type, false).addr;
  4200. for_array(i, results) {
  4201. Entity *e = tuple->variables[i];
  4202. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  4203. lbValue val = lb_emit_conv(p, results[i], e->type);
  4204. lb_emit_store(p, field, val);
  4205. }
  4206. res = lb_emit_load(p, res);
  4207. }
  4208. lb_ensure_abi_function_type(p->module, p);
  4209. if (p->abi_function_type->ret.kind == lbArg_Indirect) {
  4210. if (res.value != nullptr) {
  4211. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  4212. } else {
  4213. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  4214. }
  4215. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4216. LLVMBuildRetVoid(p->builder);
  4217. } else {
  4218. LLVMValueRef ret_val = res.value;
  4219. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  4220. if (p->abi_function_type->ret.cast_type != nullptr) {
  4221. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  4222. }
  4223. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4224. LLVMBuildRet(p->builder, ret_val);
  4225. }
  4226. case_end;
  4227. case_ast_node(is, IfStmt, node);
  4228. lb_open_scope(p, node->scope); // Scope #1
  4229. if (is->init != nullptr) {
  4230. // TODO(bill): Should this have a separate block to begin with?
  4231. #if 1
  4232. lbBlock *init = lb_create_block(p, "if.init");
  4233. lb_emit_jump(p, init);
  4234. lb_start_block(p, init);
  4235. #endif
  4236. lb_build_stmt(p, is->init);
  4237. }
  4238. lbBlock *then = lb_create_block(p, "if.then");
  4239. lbBlock *done = lb_create_block(p, "if.done");
  4240. lbBlock *else_ = done;
  4241. if (is->else_stmt != nullptr) {
  4242. else_ = lb_create_block(p, "if.else");
  4243. }
  4244. lb_build_cond(p, is->cond, then, else_);
  4245. lb_start_block(p, then);
  4246. if (is->label != nullptr) {
  4247. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  4248. tl->is_block = true;
  4249. }
  4250. lb_build_stmt(p, is->body);
  4251. lb_emit_jump(p, done);
  4252. if (is->else_stmt != nullptr) {
  4253. lb_start_block(p, else_);
  4254. lb_open_scope(p, is->else_stmt->scope);
  4255. lb_build_stmt(p, is->else_stmt);
  4256. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4257. lb_emit_jump(p, done);
  4258. }
  4259. lb_start_block(p, done);
  4260. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4261. case_end;
  4262. case_ast_node(fs, ForStmt, node);
  4263. lb_open_scope(p, node->scope); // Open Scope here
  4264. if (fs->init != nullptr) {
  4265. #if 1
  4266. lbBlock *init = lb_create_block(p, "for.init");
  4267. lb_emit_jump(p, init);
  4268. lb_start_block(p, init);
  4269. #endif
  4270. lb_build_stmt(p, fs->init);
  4271. }
  4272. lbBlock *body = lb_create_block(p, "for.body");
  4273. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  4274. lbBlock *loop = body;
  4275. if (fs->cond != nullptr) {
  4276. loop = lb_create_block(p, "for.loop");
  4277. }
  4278. lbBlock *post = loop;
  4279. if (fs->post != nullptr) {
  4280. post = lb_create_block(p, "for.post");
  4281. }
  4282. lb_emit_jump(p, loop);
  4283. lb_start_block(p, loop);
  4284. if (loop != body) {
  4285. lb_build_cond(p, fs->cond, body, done);
  4286. lb_start_block(p, body);
  4287. }
  4288. lb_push_target_list(p, fs->label, done, post, nullptr);
  4289. lb_build_stmt(p, fs->body);
  4290. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4291. lb_pop_target_list(p);
  4292. lb_emit_jump(p, post);
  4293. if (fs->post != nullptr) {
  4294. lb_start_block(p, post);
  4295. lb_build_stmt(p, fs->post);
  4296. lb_emit_jump(p, loop);
  4297. }
  4298. lb_start_block(p, done);
  4299. case_end;
  4300. case_ast_node(rs, RangeStmt, node);
  4301. lb_build_range_stmt(p, rs, node->scope);
  4302. case_end;
  4303. case_ast_node(rs, InlineRangeStmt, node);
  4304. lb_build_inline_range_stmt(p, rs, node->scope);
  4305. case_end;
  4306. case_ast_node(ss, SwitchStmt, node);
  4307. lb_build_switch_stmt(p, ss, node->scope);
  4308. case_end;
  4309. case_ast_node(ss, TypeSwitchStmt, node);
  4310. lb_build_type_switch_stmt(p, ss);
  4311. case_end;
  4312. case_ast_node(bs, BranchStmt, node);
  4313. lbBlock *block = nullptr;
  4314. if (bs->label != nullptr) {
  4315. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  4316. switch (bs->token.kind) {
  4317. case Token_break: block = bb.break_; break;
  4318. case Token_continue: block = bb.continue_; break;
  4319. case Token_fallthrough:
  4320. GB_PANIC("fallthrough cannot have a label");
  4321. break;
  4322. }
  4323. } else {
  4324. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  4325. if (t->is_block) {
  4326. continue;
  4327. }
  4328. switch (bs->token.kind) {
  4329. case Token_break: block = t->break_; break;
  4330. case Token_continue: block = t->continue_; break;
  4331. case Token_fallthrough: block = t->fallthrough_; break;
  4332. }
  4333. }
  4334. }
  4335. if (block != nullptr) {
  4336. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  4337. }
  4338. lb_emit_jump(p, block);
  4339. case_end;
  4340. }
  4341. }
  4342. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  4343. cond = lb_emit_conv(p, cond, t_llvm_bool);
  4344. lbValue res = {};
  4345. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  4346. res.type = x.type;
  4347. return res;
  4348. }
  4349. lbValue lb_const_nil(lbModule *m, Type *type) {
  4350. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  4351. return lbValue{v, type};
  4352. }
  4353. lbValue lb_const_undef(lbModule *m, Type *type) {
  4354. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  4355. return lbValue{v, type};
  4356. }
  4357. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  4358. lbValue res = {};
  4359. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  4360. res.type = type;
  4361. return res;
  4362. }
  4363. lbValue lb_const_string(lbModule *m, String const &value) {
  4364. return lb_const_value(m, t_string, exact_value_string(value));
  4365. }
  4366. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  4367. lbValue res = {};
  4368. res.value = LLVMConstInt(lb_type(m, type), value, false);
  4369. res.type = type;
  4370. return res;
  4371. }
  4372. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  4373. GB_ASSERT(type_size_of(type) == 4);
  4374. u32 u = bit_cast<u32>(f);
  4375. if (is_type_different_to_arch_endianness(type)) {
  4376. u = gb_endian_swap32(u);
  4377. }
  4378. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  4379. return LLVMConstBitCast(i, lb_type(m, type));
  4380. }
  4381. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4382. x = lb_emit_conv(p, x, t);
  4383. y = lb_emit_conv(p, y, t);
  4384. if (is_type_float(t)) {
  4385. i64 sz = 8*type_size_of(t);
  4386. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4387. args[0] = x;
  4388. args[1] = y;
  4389. switch (sz) {
  4390. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  4391. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  4392. }
  4393. GB_PANIC("Unknown float type");
  4394. }
  4395. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  4396. }
  4397. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4398. x = lb_emit_conv(p, x, t);
  4399. y = lb_emit_conv(p, y, t);
  4400. if (is_type_float(t)) {
  4401. i64 sz = 8*type_size_of(t);
  4402. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4403. args[0] = x;
  4404. args[1] = y;
  4405. switch (sz) {
  4406. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  4407. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  4408. }
  4409. GB_PANIC("Unknown float type");
  4410. }
  4411. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  4412. }
  4413. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  4414. lbValue z = {};
  4415. z = lb_emit_max(p, t, x, min);
  4416. z = lb_emit_min(p, t, z, max);
  4417. return z;
  4418. }
  4419. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  4420. StringHashKey key = string_hash_string(str);
  4421. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  4422. if (found != nullptr) {
  4423. return *found;
  4424. } else {
  4425. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4426. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4427. cast(char const *)str.text,
  4428. cast(unsigned)str.len,
  4429. false);
  4430. isize max_len = 7+8+1;
  4431. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  4432. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4433. len -= 1;
  4434. m->global_array_index++;
  4435. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4436. LLVMSetInitializer(global_data, data);
  4437. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4438. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4439. string_map_set(&m->const_strings, key, ptr);
  4440. return ptr;
  4441. }
  4442. }
  4443. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  4444. LLVMValueRef ptr = nullptr;
  4445. if (str.len != 0) {
  4446. ptr = lb_find_or_add_entity_string_ptr(m, str);
  4447. } else {
  4448. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4449. }
  4450. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4451. LLVMValueRef values[2] = {ptr, str_len};
  4452. lbValue res = {};
  4453. res.value = llvm_const_named_struct(lb_type(m, t_string), values, 2);
  4454. res.type = t_string;
  4455. return res;
  4456. }
  4457. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  4458. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4459. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4460. cast(char const *)str.text,
  4461. cast(unsigned)str.len,
  4462. false);
  4463. char *name = nullptr;
  4464. {
  4465. isize max_len = 7+8+1;
  4466. name = gb_alloc_array(permanent_allocator(), char, max_len);
  4467. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4468. len -= 1;
  4469. m->global_array_index++;
  4470. }
  4471. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4472. LLVMSetInitializer(global_data, data);
  4473. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4474. LLVMValueRef ptr = nullptr;
  4475. if (str.len != 0) {
  4476. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4477. } else {
  4478. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4479. }
  4480. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4481. LLVMValueRef values[2] = {ptr, len};
  4482. lbValue res = {};
  4483. res.value = llvm_const_named_struct(lb_type(m, t_u8_slice), values, 2);
  4484. res.type = t_u8_slice;
  4485. return res;
  4486. }
  4487. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4488. isize index = type_info_index(info, type, false);
  4489. if (index >= 0) {
  4490. auto *set = &info->minimum_dependency_type_info_set;
  4491. for_array(i, set->entries) {
  4492. if (set->entries[i].ptr == index) {
  4493. return i+1;
  4494. }
  4495. }
  4496. }
  4497. if (err_on_not_found) {
  4498. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  4499. }
  4500. return -1;
  4501. }
  4502. lbValue lb_typeid(lbModule *m, Type *type) {
  4503. type = default_type(type);
  4504. u64 id = cast(u64)lb_type_info_index(m->info, type);
  4505. GB_ASSERT(id >= 0);
  4506. u64 kind = Typeid_Invalid;
  4507. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4508. u64 special = 0;
  4509. u64 reserved = 0;
  4510. Type *bt = base_type(type);
  4511. TypeKind tk = bt->kind;
  4512. switch (tk) {
  4513. case Type_Basic: {
  4514. u32 flags = bt->Basic.flags;
  4515. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4516. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4517. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4518. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4519. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4520. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4521. if (flags & BasicFlag_String) kind = Typeid_String;
  4522. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4523. } break;
  4524. case Type_Pointer: kind = Typeid_Pointer; break;
  4525. case Type_Array: kind = Typeid_Array; break;
  4526. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  4527. case Type_Slice: kind = Typeid_Slice; break;
  4528. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4529. case Type_Map: kind = Typeid_Map; break;
  4530. case Type_Struct: kind = Typeid_Struct; break;
  4531. case Type_Enum: kind = Typeid_Enum; break;
  4532. case Type_Union: kind = Typeid_Union; break;
  4533. case Type_Tuple: kind = Typeid_Tuple; break;
  4534. case Type_Proc: kind = Typeid_Procedure; break;
  4535. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4536. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  4537. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  4538. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  4539. }
  4540. if (is_type_cstring(type)) {
  4541. special = 1;
  4542. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4543. special = 1;
  4544. }
  4545. u64 data = 0;
  4546. if (build_context.word_size == 4) {
  4547. GB_ASSERT(id <= (1u<<24u));
  4548. data |= (id &~ (1u<<24)) << 0u; // index
  4549. data |= (kind &~ (1u<<5)) << 24u; // kind
  4550. data |= (named &~ (1u<<1)) << 29u; // kind
  4551. data |= (special &~ (1u<<1)) << 30u; // kind
  4552. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4553. } else {
  4554. GB_ASSERT(build_context.word_size == 8);
  4555. GB_ASSERT(id <= (1ull<<56u));
  4556. data |= (id &~ (1ull<<56)) << 0ul; // index
  4557. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4558. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4559. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4560. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4561. }
  4562. lbValue res = {};
  4563. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  4564. res.type = t_typeid;
  4565. return res;
  4566. }
  4567. lbValue lb_type_info(lbModule *m, Type *type) {
  4568. type = default_type(type);
  4569. isize index = lb_type_info_index(m->info, type);
  4570. GB_ASSERT(index >= 0);
  4571. LLVMTypeRef it = lb_type(m, t_int);
  4572. LLVMValueRef indices[2] = {
  4573. LLVMConstInt(it, 0, false),
  4574. LLVMConstInt(it, index, true),
  4575. };
  4576. lbValue value = {};
  4577. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  4578. value.type = t_type_info_ptr;
  4579. return value;
  4580. }
  4581. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  4582. bool is_local = allow_local && m->curr_procedure != nullptr;
  4583. bool is_const = true;
  4584. if (is_local) {
  4585. for (isize i = 0; i < count; i++) {
  4586. GB_ASSERT(values[i] != nullptr);
  4587. if (!LLVMIsConstant(values[i])) {
  4588. is_const = false;
  4589. break;
  4590. }
  4591. }
  4592. }
  4593. if (!is_const) {
  4594. lbProcedure *p = m->curr_procedure;
  4595. GB_ASSERT(p != nullptr);
  4596. lbAddr v = lb_add_local_generated(p, type, false);
  4597. lbValue ptr = lb_addr_get_ptr(p, v);
  4598. for (isize i = 0; i < count; i++) {
  4599. lbValue elem = lb_emit_array_epi(p, ptr, i);
  4600. LLVMBuildStore(p->builder, values[i], elem.value);
  4601. }
  4602. return lb_addr_load(p, v).value;
  4603. }
  4604. return llvm_const_array(lb_type(m, elem_type), values, cast(unsigned int)count);
  4605. }
  4606. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  4607. LLVMContextRef ctx = m->ctx;
  4608. type = default_type(type);
  4609. Type *original_type = type;
  4610. lbValue res = {};
  4611. res.type = original_type;
  4612. type = core_type(type);
  4613. value = convert_exact_value_for_type(value, type);
  4614. if (value.kind == ExactValue_Typeid) {
  4615. return lb_typeid(m, value.value_typeid);
  4616. }
  4617. if (value.kind == ExactValue_Invalid) {
  4618. return lb_const_nil(m, type);
  4619. }
  4620. if (value.kind == ExactValue_Procedure) {
  4621. Ast *expr = unparen_expr(value.value_procedure);
  4622. if (expr->kind == Ast_ProcLit) {
  4623. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4624. }
  4625. Entity *e = entity_from_expr(expr);
  4626. e = strip_entity_wrapping(e);
  4627. GB_ASSERT(e != nullptr);
  4628. auto *found = map_get(&m->values, hash_entity(e));
  4629. if (found) {
  4630. return *found;
  4631. }
  4632. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  4633. }
  4634. bool is_local = allow_local && m->curr_procedure != nullptr;
  4635. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  4636. if (is_type_slice(type)) {
  4637. if (value.kind == ExactValue_String) {
  4638. GB_ASSERT(is_type_u8_slice(type));
  4639. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  4640. return res;
  4641. } else {
  4642. ast_node(cl, CompoundLit, value.value_compound);
  4643. isize count = cl->elems.count;
  4644. if (count == 0) {
  4645. return lb_const_nil(m, type);
  4646. }
  4647. count = gb_max(cl->max_count, count);
  4648. Type *elem = base_type(type)->Slice.elem;
  4649. Type *t = alloc_type_array(elem, count);
  4650. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4651. LLVMValueRef array_data = nullptr;
  4652. if (is_local) {
  4653. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4654. // its backing data on the stack
  4655. lbProcedure *p = m->curr_procedure;
  4656. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4657. LLVMTypeRef llvm_type = lb_type(m, t);
  4658. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4659. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4660. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4661. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4662. {
  4663. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4664. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4665. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4666. lbAddr slice = lb_add_local_generated(p, type, false);
  4667. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4668. return lb_addr_load(p, slice);
  4669. }
  4670. } else {
  4671. isize max_len = 7+8+1;
  4672. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  4673. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4674. m->global_array_index++;
  4675. String name = make_string(cast(u8 *)str, len-1);
  4676. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4677. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4678. LLVMSetInitializer(array_data, backing_array.value);
  4679. lbValue g = {};
  4680. g.value = array_data;
  4681. g.type = t;
  4682. lb_add_entity(m, e, g);
  4683. lb_add_member(m, name, g);
  4684. {
  4685. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4686. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4687. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4688. LLVMValueRef values[2] = {ptr, len};
  4689. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4690. return res;
  4691. }
  4692. }
  4693. }
  4694. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4695. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  4696. i64 count = type->Array.count;
  4697. Type *elem = type->Array.elem;
  4698. LLVMTypeRef et = lb_type(m, elem);
  4699. Rune rune;
  4700. isize offset = 0;
  4701. isize width = 1;
  4702. String s = value.value_string;
  4703. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4704. for (i64 i = 0; i < count && offset < s.len; i++) {
  4705. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  4706. offset += width;
  4707. elems[i] = LLVMConstInt(et, rune, true);
  4708. }
  4709. GB_ASSERT(offset == s.len);
  4710. res.value = llvm_const_array(et, elems, cast(unsigned)count);
  4711. return res;
  4712. }
  4713. GB_PANIC("HERE!\n");
  4714. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4715. cast(char const *)value.value_string.text,
  4716. cast(unsigned)value.value_string.len,
  4717. false /*DontNullTerminate*/);
  4718. res.value = data;
  4719. return res;
  4720. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  4721. GB_ASSERT(type->Array.count == value.value_string.len);
  4722. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4723. cast(char const *)value.value_string.text,
  4724. cast(unsigned)value.value_string.len,
  4725. true /*DontNullTerminate*/);
  4726. res.value = data;
  4727. return res;
  4728. } else if (is_type_array(type) &&
  4729. value.kind != ExactValue_Invalid &&
  4730. value.kind != ExactValue_String &&
  4731. value.kind != ExactValue_Compound) {
  4732. i64 count = type->Array.count;
  4733. Type *elem = type->Array.elem;
  4734. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4735. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4736. for (i64 i = 0; i < count; i++) {
  4737. elems[i] = single_elem.value;
  4738. }
  4739. res.value = llvm_const_array(lb_type(m, elem), elems, cast(unsigned)count);
  4740. return res;
  4741. }
  4742. switch (value.kind) {
  4743. case ExactValue_Invalid:
  4744. res.value = LLVMConstNull(lb_type(m, original_type));
  4745. return res;
  4746. case ExactValue_Bool:
  4747. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4748. return res;
  4749. case ExactValue_String:
  4750. {
  4751. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4752. lbValue res = {};
  4753. res.type = default_type(original_type);
  4754. if (is_type_cstring(res.type)) {
  4755. res.value = ptr;
  4756. } else {
  4757. if (value.value_string.len == 0) {
  4758. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4759. }
  4760. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4761. LLVMValueRef values[2] = {ptr, str_len};
  4762. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4763. }
  4764. return res;
  4765. }
  4766. case ExactValue_Integer:
  4767. if (is_type_pointer(type)) {
  4768. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  4769. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  4770. } else {
  4771. unsigned len = cast(unsigned)value.value_integer.len;
  4772. if (len == 0) {
  4773. u64 word = 0;
  4774. res.value = LLVMConstNull(lb_type(m, original_type));
  4775. } else {
  4776. u64 *words = big_int_ptr(&value.value_integer);
  4777. if (is_type_different_to_arch_endianness(type)) {
  4778. // NOTE(bill): Swap byte order for different endianness
  4779. i64 sz = type_size_of(type);
  4780. isize byte_len = gb_size_of(u64)*len;
  4781. u8 *old_bytes = cast(u8 *)words;
  4782. // TODO(bill): Use a different allocator here for a temporary allocation
  4783. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  4784. for (i64 i = 0; i < sz; i++) {
  4785. new_bytes[i] = old_bytes[sz-1-i];
  4786. }
  4787. words = cast(u64 *)new_bytes;
  4788. }
  4789. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4790. if (value.value_integer.neg) {
  4791. res.value = LLVMConstNeg(res.value);
  4792. }
  4793. }
  4794. }
  4795. return res;
  4796. case ExactValue_Float:
  4797. if (type_size_of(type) == 4) {
  4798. f32 f = cast(f32)value.value_float;
  4799. res.value = lb_const_f32(m, f, type);
  4800. return res;
  4801. }
  4802. if (is_type_different_to_arch_endianness(type)) {
  4803. u64 u = bit_cast<u64>(value.value_float);
  4804. u = gb_endian_swap64(u);
  4805. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4806. } else {
  4807. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4808. }
  4809. return res;
  4810. case ExactValue_Complex:
  4811. {
  4812. LLVMValueRef values[2] = {};
  4813. switch (8*type_size_of(type)) {
  4814. case 64:
  4815. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  4816. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  4817. break;
  4818. case 128:
  4819. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  4820. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  4821. break;
  4822. }
  4823. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4824. return res;
  4825. }
  4826. break;
  4827. case ExactValue_Quaternion:
  4828. {
  4829. LLVMValueRef values[4] = {};
  4830. switch (8*type_size_of(type)) {
  4831. case 128:
  4832. // @QuaternionLayout
  4833. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  4834. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  4835. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  4836. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  4837. break;
  4838. case 256:
  4839. // @QuaternionLayout
  4840. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  4841. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  4842. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  4843. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  4844. break;
  4845. }
  4846. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 4);
  4847. return res;
  4848. }
  4849. break;
  4850. case ExactValue_Pointer:
  4851. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4852. return res;
  4853. case ExactValue_Compound:
  4854. if (is_type_slice(type)) {
  4855. return lb_const_value(m, type, value, allow_local);
  4856. } else if (is_type_array(type)) {
  4857. ast_node(cl, CompoundLit, value.value_compound);
  4858. Type *elem_type = type->Array.elem;
  4859. isize elem_count = cl->elems.count;
  4860. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4861. return lb_const_nil(m, original_type);
  4862. }
  4863. if (cl->elems[0]->kind == Ast_FieldValue) {
  4864. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4865. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4866. isize value_index = 0;
  4867. for (i64 i = 0; i < type->Array.count; i++) {
  4868. bool found = false;
  4869. for (isize j = 0; j < elem_count; j++) {
  4870. Ast *elem = cl->elems[j];
  4871. ast_node(fv, FieldValue, elem);
  4872. if (is_ast_range(fv->field)) {
  4873. ast_node(ie, BinaryExpr, fv->field);
  4874. TypeAndValue lo_tav = ie->left->tav;
  4875. TypeAndValue hi_tav = ie->right->tav;
  4876. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4877. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4878. TokenKind op = ie->op.kind;
  4879. i64 lo = exact_value_to_i64(lo_tav.value);
  4880. i64 hi = exact_value_to_i64(hi_tav.value);
  4881. if (op == Token_Ellipsis) {
  4882. hi += 1;
  4883. }
  4884. if (lo == i) {
  4885. TypeAndValue tav = fv->value->tav;
  4886. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4887. for (i64 k = lo; k < hi; k++) {
  4888. values[value_index++] = val;
  4889. }
  4890. found = true;
  4891. i += (hi-lo-1);
  4892. break;
  4893. }
  4894. } else {
  4895. TypeAndValue index_tav = fv->field->tav;
  4896. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4897. i64 index = exact_value_to_i64(index_tav.value);
  4898. if (index == i) {
  4899. TypeAndValue tav = fv->value->tav;
  4900. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4901. values[value_index++] = val;
  4902. found = true;
  4903. break;
  4904. }
  4905. }
  4906. }
  4907. if (!found) {
  4908. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4909. }
  4910. }
  4911. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4912. return res;
  4913. } else {
  4914. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  4915. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4916. for (isize i = 0; i < elem_count; i++) {
  4917. TypeAndValue tav = cl->elems[i]->tav;
  4918. GB_ASSERT(tav.mode != Addressing_Invalid);
  4919. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4920. }
  4921. for (isize i = elem_count; i < type->Array.count; i++) {
  4922. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4923. }
  4924. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4925. return res;
  4926. }
  4927. } else if (is_type_enumerated_array(type)) {
  4928. ast_node(cl, CompoundLit, value.value_compound);
  4929. Type *elem_type = type->EnumeratedArray.elem;
  4930. isize elem_count = cl->elems.count;
  4931. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4932. return lb_const_nil(m, original_type);
  4933. }
  4934. if (cl->elems[0]->kind == Ast_FieldValue) {
  4935. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4936. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4937. isize value_index = 0;
  4938. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  4939. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  4940. for (i64 i = total_lo; i <= total_hi; i++) {
  4941. bool found = false;
  4942. for (isize j = 0; j < elem_count; j++) {
  4943. Ast *elem = cl->elems[j];
  4944. ast_node(fv, FieldValue, elem);
  4945. if (is_ast_range(fv->field)) {
  4946. ast_node(ie, BinaryExpr, fv->field);
  4947. TypeAndValue lo_tav = ie->left->tav;
  4948. TypeAndValue hi_tav = ie->right->tav;
  4949. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4950. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4951. TokenKind op = ie->op.kind;
  4952. i64 lo = exact_value_to_i64(lo_tav.value);
  4953. i64 hi = exact_value_to_i64(hi_tav.value);
  4954. if (op == Token_Ellipsis) {
  4955. hi += 1;
  4956. }
  4957. if (lo == i) {
  4958. TypeAndValue tav = fv->value->tav;
  4959. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4960. for (i64 k = lo; k < hi; k++) {
  4961. values[value_index++] = val;
  4962. }
  4963. found = true;
  4964. i += (hi-lo-1);
  4965. break;
  4966. }
  4967. } else {
  4968. TypeAndValue index_tav = fv->field->tav;
  4969. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4970. i64 index = exact_value_to_i64(index_tav.value);
  4971. if (index == i) {
  4972. TypeAndValue tav = fv->value->tav;
  4973. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4974. values[value_index++] = val;
  4975. found = true;
  4976. break;
  4977. }
  4978. }
  4979. }
  4980. if (!found) {
  4981. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4982. }
  4983. }
  4984. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  4985. return res;
  4986. } else {
  4987. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  4988. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4989. for (isize i = 0; i < elem_count; i++) {
  4990. TypeAndValue tav = cl->elems[i]->tav;
  4991. GB_ASSERT(tav.mode != Addressing_Invalid);
  4992. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4993. }
  4994. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  4995. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4996. }
  4997. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  4998. return res;
  4999. }
  5000. } else if (is_type_simd_vector(type)) {
  5001. ast_node(cl, CompoundLit, value.value_compound);
  5002. Type *elem_type = type->SimdVector.elem;
  5003. isize elem_count = cl->elems.count;
  5004. if (elem_count == 0) {
  5005. return lb_const_nil(m, original_type);
  5006. }
  5007. GB_ASSERT(elem_type_can_be_constant(elem_type));
  5008. isize total_elem_count = type->SimdVector.count;
  5009. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  5010. for (isize i = 0; i < elem_count; i++) {
  5011. TypeAndValue tav = cl->elems[i]->tav;
  5012. GB_ASSERT(tav.mode != Addressing_Invalid);
  5013. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5014. }
  5015. LLVMTypeRef et = lb_type(m, elem_type);
  5016. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  5017. values[i] = LLVMConstNull(et);
  5018. }
  5019. for (isize i = 0; i< total_elem_count; i++) {
  5020. values[i] = llvm_const_cast(values[i], et);
  5021. }
  5022. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  5023. return res;
  5024. } else if (is_type_struct(type)) {
  5025. ast_node(cl, CompoundLit, value.value_compound);
  5026. if (cl->elems.count == 0) {
  5027. return lb_const_nil(m, original_type);
  5028. }
  5029. isize offset = 0;
  5030. if (type->Struct.custom_align > 0) {
  5031. offset = 1;
  5032. }
  5033. isize value_count = type->Struct.fields.count + offset;
  5034. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5035. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  5036. if (cl->elems.count > 0) {
  5037. if (cl->elems[0]->kind == Ast_FieldValue) {
  5038. isize elem_count = cl->elems.count;
  5039. for (isize i = 0; i < elem_count; i++) {
  5040. ast_node(fv, FieldValue, cl->elems[i]);
  5041. String name = fv->field->Ident.token.string;
  5042. TypeAndValue tav = fv->value->tav;
  5043. GB_ASSERT(tav.mode != Addressing_Invalid);
  5044. Selection sel = lookup_field(type, name, false);
  5045. Entity *f = type->Struct.fields[sel.index[0]];
  5046. if (elem_type_can_be_constant(f->type)) {
  5047. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  5048. visited[offset+f->Variable.field_index] = true;
  5049. }
  5050. }
  5051. } else {
  5052. for_array(i, cl->elems) {
  5053. Entity *f = type->Struct.fields[i];
  5054. TypeAndValue tav = cl->elems[i]->tav;
  5055. ExactValue val = {};
  5056. if (tav.mode != Addressing_Invalid) {
  5057. val = tav.value;
  5058. }
  5059. if (elem_type_can_be_constant(f->type)) {
  5060. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  5061. visited[offset+f->Variable.field_index] = true;
  5062. }
  5063. }
  5064. }
  5065. }
  5066. for (isize i = 0; i < type->Struct.fields.count; i++) {
  5067. if (!visited[offset+i]) {
  5068. GB_ASSERT(values[offset+i] == nullptr);
  5069. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  5070. }
  5071. }
  5072. if (type->Struct.custom_align > 0) {
  5073. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  5074. }
  5075. bool is_constant = true;
  5076. for (isize i = 0; i < value_count; i++) {
  5077. LLVMValueRef val = values[i];
  5078. if (!LLVMIsConstant(val)) {
  5079. GB_ASSERT(is_local);
  5080. GB_ASSERT(LLVMGetInstructionOpcode(val) == LLVMLoad);
  5081. is_constant = false;
  5082. }
  5083. }
  5084. if (is_constant) {
  5085. res.value = llvm_const_named_struct(lb_type(m, original_type), values, cast(unsigned)value_count);
  5086. return res;
  5087. } else {
  5088. // TODO(bill): THIS IS HACK BUT IT WORKS FOR WHAT I NEED
  5089. LLVMValueRef *old_values = values;
  5090. LLVMValueRef *new_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5091. for (isize i = 0; i < value_count; i++) {
  5092. LLVMValueRef old_value = old_values[i];
  5093. if (LLVMIsConstant(old_value)) {
  5094. new_values[i] = old_value;
  5095. } else {
  5096. new_values[i] = LLVMConstNull(LLVMTypeOf(old_value));
  5097. }
  5098. }
  5099. LLVMValueRef constant_value = llvm_const_named_struct(lb_type(m, original_type), new_values, cast(unsigned)value_count);
  5100. GB_ASSERT(is_local);
  5101. lbProcedure *p = m->curr_procedure;
  5102. lbAddr v = lb_add_local_generated(p, res.type, true);
  5103. LLVMBuildStore(p->builder, constant_value, v.addr.value);
  5104. for (isize i = 0; i < value_count; i++) {
  5105. LLVMValueRef val = old_values[i];
  5106. if (!LLVMIsConstant(val)) {
  5107. LLVMValueRef dst = LLVMBuildStructGEP(p->builder, v.addr.value, cast(unsigned)i, "");
  5108. LLVMBuildStore(p->builder, val, dst);
  5109. }
  5110. }
  5111. return lb_addr_load(p, v);
  5112. }
  5113. } else if (is_type_bit_set(type)) {
  5114. ast_node(cl, CompoundLit, value.value_compound);
  5115. if (cl->elems.count == 0) {
  5116. return lb_const_nil(m, original_type);
  5117. }
  5118. i64 sz = type_size_of(type);
  5119. if (sz == 0) {
  5120. return lb_const_nil(m, original_type);
  5121. }
  5122. u64 bits = 0;
  5123. for_array(i, cl->elems) {
  5124. Ast *e = cl->elems[i];
  5125. GB_ASSERT(e->kind != Ast_FieldValue);
  5126. TypeAndValue tav = e->tav;
  5127. if (tav.mode != Addressing_Constant) {
  5128. continue;
  5129. }
  5130. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  5131. i64 v = big_int_to_i64(&tav.value.value_integer);
  5132. i64 lower = type->BitSet.lower;
  5133. bits |= 1ull<<cast(u64)(v-lower);
  5134. }
  5135. if (is_type_different_to_arch_endianness(type)) {
  5136. i64 size = type_size_of(type);
  5137. switch (size) {
  5138. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  5139. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  5140. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  5141. }
  5142. }
  5143. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  5144. return res;
  5145. } else {
  5146. return lb_const_nil(m, original_type);
  5147. }
  5148. break;
  5149. case ExactValue_Procedure:
  5150. {
  5151. Ast *expr = value.value_procedure;
  5152. GB_ASSERT(expr != nullptr);
  5153. if (expr->kind == Ast_ProcLit) {
  5154. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5155. }
  5156. }
  5157. break;
  5158. case ExactValue_Typeid:
  5159. return lb_typeid(m, value.value_typeid);
  5160. }
  5161. return lb_const_nil(m, original_type);
  5162. }
  5163. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  5164. lbModule *m = p->module;
  5165. LLVMValueRef fields[4] = {};
  5166. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)).value;
  5167. fields[1]/*line*/ = lb_const_int(m, t_i32, pos.line).value;
  5168. fields[2]/*column*/ = lb_const_int(m, t_i32, pos.column).value;
  5169. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  5170. lbValue res = {};
  5171. res.value = llvm_const_named_struct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  5172. res.type = t_source_code_location;
  5173. return res;
  5174. }
  5175. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  5176. String proc_name = {};
  5177. if (p->entity) {
  5178. proc_name = p->entity->token.string;
  5179. }
  5180. TokenPos pos = {};
  5181. if (node) {
  5182. pos = ast_token(node).pos;
  5183. }
  5184. return lb_emit_source_code_location(p, proc_name, pos);
  5185. }
  5186. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  5187. switch (op) {
  5188. case Token_Add:
  5189. return x;
  5190. case Token_Not: // Boolean not
  5191. case Token_Xor: // Bitwise not
  5192. case Token_Sub: // Number negation
  5193. break;
  5194. case Token_Pointer:
  5195. GB_PANIC("This should be handled elsewhere");
  5196. break;
  5197. }
  5198. if (is_type_array(x.type)) {
  5199. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  5200. Type *tl = base_type(x.type);
  5201. lbValue val = lb_address_from_load_or_generate_local(p, x);
  5202. GB_ASSERT(is_type_array(type));
  5203. Type *elem_type = base_array_type(type);
  5204. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5205. lbAddr res_addr = lb_add_local_generated(p, type, false);
  5206. lbValue res = lb_addr_get_ptr(p, res_addr);
  5207. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5208. i32 count = cast(i32)tl->Array.count;
  5209. if (inline_array_arith) {
  5210. // inline
  5211. for (i32 i = 0; i < count; i++) {
  5212. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  5213. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5214. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  5215. }
  5216. } else {
  5217. auto loop_data = lb_loop_start(p, count, t_i32);
  5218. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  5219. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5220. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  5221. lb_loop_end(p, loop_data);
  5222. }
  5223. return lb_emit_load(p, res);
  5224. }
  5225. if (op == Token_Xor) {
  5226. lbValue cmp = {};
  5227. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  5228. cmp.type = x.type;
  5229. return lb_emit_conv(p, cmp, type);
  5230. }
  5231. if (op == Token_Not) {
  5232. lbValue cmp = {};
  5233. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  5234. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  5235. cmp.type = t_llvm_bool;
  5236. return lb_emit_conv(p, cmp, type);
  5237. }
  5238. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5239. Type *platform_type = integer_endian_type_to_platform_type(type);
  5240. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5241. lbValue res = {};
  5242. res.value = LLVMBuildNeg(p->builder, v.value, "");
  5243. res.type = platform_type;
  5244. return lb_emit_byte_swap(p, res, type);
  5245. }
  5246. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5247. Type *platform_type = integer_endian_type_to_platform_type(type);
  5248. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5249. lbValue res = {};
  5250. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  5251. res.type = platform_type;
  5252. return lb_emit_byte_swap(p, res, type);
  5253. }
  5254. lbValue res = {};
  5255. switch (op) {
  5256. case Token_Not: // Boolean not
  5257. case Token_Xor: // Bitwise not
  5258. res.value = LLVMBuildNot(p->builder, x.value, "");
  5259. res.type = x.type;
  5260. return res;
  5261. case Token_Sub: // Number negation
  5262. if (is_type_integer(x.type)) {
  5263. res.value = LLVMBuildNeg(p->builder, x.value, "");
  5264. } else if (is_type_float(x.type)) {
  5265. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  5266. } else if (is_type_complex(x.type)) {
  5267. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5268. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5269. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5270. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5271. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5272. return lb_addr_load(p, addr);
  5273. } else if (is_type_quaternion(x.type)) {
  5274. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5275. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5276. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  5277. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  5278. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5279. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5280. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5281. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  5282. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  5283. return lb_addr_load(p, addr);
  5284. } else {
  5285. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  5286. }
  5287. res.type = x.type;
  5288. return res;
  5289. }
  5290. return res;
  5291. }
  5292. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  5293. lbModule *m = p->module;
  5294. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  5295. lhs = lb_emit_conv(p, lhs, type);
  5296. rhs = lb_emit_conv(p, rhs, type);
  5297. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  5298. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  5299. GB_ASSERT(is_type_array(type));
  5300. Type *elem_type = base_array_type(type);
  5301. lbAddr res = lb_add_local_generated(p, type, false);
  5302. i64 count = base_type(type)->Array.count;
  5303. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5304. if (inline_array_arith) {
  5305. for (i64 i = 0; i < count; i++) {
  5306. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  5307. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  5308. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  5309. lbValue a = lb_emit_load(p, a_ptr);
  5310. lbValue b = lb_emit_load(p, b_ptr);
  5311. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5312. lb_emit_store(p, dst_ptr, c);
  5313. }
  5314. } else {
  5315. auto loop_data = lb_loop_start(p, count, t_i32);
  5316. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  5317. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  5318. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  5319. lbValue a = lb_emit_load(p, a_ptr);
  5320. lbValue b = lb_emit_load(p, b_ptr);
  5321. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5322. lb_emit_store(p, dst_ptr, c);
  5323. lb_loop_end(p, loop_data);
  5324. }
  5325. return lb_addr_load(p, res);
  5326. } else if (is_type_complex(type)) {
  5327. lhs = lb_emit_conv(p, lhs, type);
  5328. rhs = lb_emit_conv(p, rhs, type);
  5329. Type *ft = base_complex_elem_type(type);
  5330. if (op == Token_Quo) {
  5331. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5332. args[0] = lhs;
  5333. args[1] = rhs;
  5334. switch (type_size_of(ft)) {
  5335. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  5336. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  5337. default: GB_PANIC("Unknown float type"); break;
  5338. }
  5339. }
  5340. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5341. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  5342. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  5343. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  5344. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  5345. lbValue real = {};
  5346. lbValue imag = {};
  5347. switch (op) {
  5348. case Token_Add:
  5349. real = lb_emit_arith(p, Token_Add, a, c, ft);
  5350. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  5351. break;
  5352. case Token_Sub:
  5353. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  5354. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  5355. break;
  5356. case Token_Mul: {
  5357. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  5358. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  5359. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  5360. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  5361. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  5362. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  5363. break;
  5364. }
  5365. }
  5366. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  5367. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  5368. return lb_addr_load(p, res);
  5369. } else if (is_type_quaternion(type)) {
  5370. lhs = lb_emit_conv(p, lhs, type);
  5371. rhs = lb_emit_conv(p, rhs, type);
  5372. Type *ft = base_complex_elem_type(type);
  5373. if (op == Token_Add || op == Token_Sub) {
  5374. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5375. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  5376. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  5377. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  5378. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  5379. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  5380. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  5381. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  5382. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  5383. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  5384. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  5385. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  5386. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  5387. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  5388. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  5389. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  5390. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  5391. return lb_addr_load(p, res);
  5392. } else if (op == Token_Mul) {
  5393. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5394. args[0] = lhs;
  5395. args[1] = rhs;
  5396. switch (8*type_size_of(ft)) {
  5397. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  5398. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  5399. default: GB_PANIC("Unknown float type"); break;
  5400. }
  5401. } else if (op == Token_Quo) {
  5402. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5403. args[0] = lhs;
  5404. args[1] = rhs;
  5405. switch (8*type_size_of(ft)) {
  5406. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  5407. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  5408. default: GB_PANIC("Unknown float type"); break;
  5409. }
  5410. }
  5411. }
  5412. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5413. switch (op) {
  5414. case Token_AndNot:
  5415. case Token_And:
  5416. case Token_Or:
  5417. case Token_Xor:
  5418. goto handle_op;
  5419. }
  5420. Type *platform_type = integer_endian_type_to_platform_type(type);
  5421. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5422. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5423. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5424. return lb_emit_byte_swap(p, res, type);
  5425. }
  5426. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5427. Type *platform_type = integer_endian_type_to_platform_type(type);
  5428. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5429. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5430. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5431. return lb_emit_byte_swap(p, res, type);
  5432. }
  5433. handle_op:
  5434. lhs = lb_emit_conv(p, lhs, type);
  5435. rhs = lb_emit_conv(p, rhs, type);
  5436. lbValue res = {};
  5437. res.type = type;
  5438. // NOTE(bill): Bit Set Aliases for + and -
  5439. if (is_type_bit_set(type)) {
  5440. switch (op) {
  5441. case Token_Add: op = Token_Or; break;
  5442. case Token_Sub: op = Token_AndNot; break;
  5443. }
  5444. }
  5445. switch (op) {
  5446. case Token_Add:
  5447. if (is_type_float(type)) {
  5448. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  5449. return res;
  5450. }
  5451. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  5452. return res;
  5453. case Token_Sub:
  5454. if (is_type_float(type)) {
  5455. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  5456. return res;
  5457. }
  5458. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  5459. return res;
  5460. case Token_Mul:
  5461. if (is_type_float(type)) {
  5462. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  5463. return res;
  5464. }
  5465. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  5466. return res;
  5467. case Token_Quo:
  5468. if (is_type_float(type)) {
  5469. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  5470. return res;
  5471. } else if (is_type_unsigned(type)) {
  5472. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  5473. return res;
  5474. }
  5475. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  5476. return res;
  5477. case Token_Mod:
  5478. if (is_type_float(type)) {
  5479. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  5480. return res;
  5481. } else if (is_type_unsigned(type)) {
  5482. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5483. return res;
  5484. }
  5485. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5486. return res;
  5487. case Token_ModMod:
  5488. if (is_type_unsigned(type)) {
  5489. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5490. return res;
  5491. } else {
  5492. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5493. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  5494. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  5495. res.value = c;
  5496. return res;
  5497. }
  5498. case Token_And:
  5499. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  5500. return res;
  5501. case Token_Or:
  5502. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  5503. return res;
  5504. case Token_Xor:
  5505. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  5506. return res;
  5507. case Token_Shl:
  5508. {
  5509. rhs = lb_emit_conv(p, rhs, lhs.type);
  5510. LLVMValueRef lhsval = lhs.value;
  5511. LLVMValueRef bits = rhs.value;
  5512. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5513. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULT, bits, max, "");
  5514. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  5515. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5516. res.value = LLVMBuildSelect(p->builder, less_equal_width, res.value, zero, "");
  5517. return res;
  5518. }
  5519. case Token_Shr:
  5520. {
  5521. rhs = lb_emit_conv(p, rhs, lhs.type);
  5522. LLVMValueRef lhsval = lhs.value;
  5523. LLVMValueRef bits = rhs.value;
  5524. bool is_unsigned = is_type_unsigned(type);
  5525. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5526. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULT, bits, max, "");
  5527. bits = LLVMBuildSelect(p->builder, less_equal_width, bits, max, "");
  5528. if (is_unsigned) {
  5529. res.value = LLVMBuildLShr(p->builder, lhs.value, bits, "");
  5530. } else {
  5531. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  5532. }
  5533. return res;
  5534. }
  5535. case Token_AndNot:
  5536. {
  5537. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  5538. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  5539. return res;
  5540. }
  5541. break;
  5542. }
  5543. GB_PANIC("unhandled operator of lb_emit_arith");
  5544. return {};
  5545. }
  5546. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  5547. ast_node(be, BinaryExpr, expr);
  5548. TypeAndValue tv = type_and_value_of_expr(expr);
  5549. switch (be->op.kind) {
  5550. case Token_Add:
  5551. case Token_Sub:
  5552. case Token_Mul:
  5553. case Token_Quo:
  5554. case Token_Mod:
  5555. case Token_ModMod:
  5556. case Token_And:
  5557. case Token_Or:
  5558. case Token_Xor:
  5559. case Token_AndNot:
  5560. case Token_Shl:
  5561. case Token_Shr: {
  5562. Type *type = default_type(tv.type);
  5563. lbValue left = lb_build_expr(p, be->left);
  5564. lbValue right = lb_build_expr(p, be->right);
  5565. return lb_emit_arith(p, be->op.kind, left, right, type);
  5566. }
  5567. case Token_CmpEq:
  5568. case Token_NotEq:
  5569. case Token_Lt:
  5570. case Token_LtEq:
  5571. case Token_Gt:
  5572. case Token_GtEq:
  5573. {
  5574. lbValue left = {};
  5575. lbValue right = {};
  5576. if (be->left->tav.mode == Addressing_Type) {
  5577. left = lb_typeid(p->module, be->left->tav.type);
  5578. }
  5579. if (be->right->tav.mode == Addressing_Type) {
  5580. right = lb_typeid(p->module, be->right->tav.type);
  5581. }
  5582. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  5583. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  5584. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  5585. Type *type = default_type(tv.type);
  5586. return lb_emit_conv(p, cmp, type);
  5587. }
  5588. case Token_CmpAnd:
  5589. case Token_CmpOr:
  5590. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  5591. case Token_in:
  5592. case Token_not_in:
  5593. {
  5594. lbValue left = lb_build_expr(p, be->left);
  5595. Type *type = default_type(tv.type);
  5596. lbValue right = lb_build_expr(p, be->right);
  5597. Type *rt = base_type(right.type);
  5598. switch (rt->kind) {
  5599. case Type_Map:
  5600. {
  5601. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  5602. lbValue h = lb_gen_map_header(p, addr, rt);
  5603. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  5604. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5605. args[0] = h;
  5606. args[1] = key;
  5607. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  5608. if (be->op.kind == Token_in) {
  5609. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  5610. } else {
  5611. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  5612. }
  5613. }
  5614. break;
  5615. case Type_BitSet:
  5616. {
  5617. Type *key_type = rt->BitSet.elem;
  5618. GB_ASSERT(are_types_identical(left.type, key_type));
  5619. Type *it = bit_set_to_int(rt);
  5620. left = lb_emit_conv(p, left, it);
  5621. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  5622. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  5623. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  5624. bit = lb_emit_conv(p, bit, it);
  5625. lbValue old_value = lb_emit_transmute(p, right, it);
  5626. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  5627. if (be->op.kind == Token_in) {
  5628. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5629. } else {
  5630. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5631. }
  5632. }
  5633. break;
  5634. default:
  5635. GB_PANIC("Invalid 'in' type");
  5636. }
  5637. break;
  5638. }
  5639. break;
  5640. default:
  5641. GB_PANIC("Invalid binary expression");
  5642. break;
  5643. }
  5644. return {};
  5645. }
  5646. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  5647. Type *prev_src = src;
  5648. // Type *prev_dst = dst;
  5649. src = base_type(type_deref(src));
  5650. // dst = base_type(type_deref(dst));
  5651. bool src_is_ptr = src != prev_src;
  5652. // bool dst_is_ptr = dst != prev_dst;
  5653. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  5654. for_array(i, src->Struct.fields) {
  5655. Entity *f = src->Struct.fields[i];
  5656. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  5657. if (are_types_identical(dst, f->type)) {
  5658. return f->token.string;
  5659. }
  5660. if (src_is_ptr && is_type_pointer(dst)) {
  5661. if (are_types_identical(type_deref(dst), f->type)) {
  5662. return f->token.string;
  5663. }
  5664. }
  5665. if (is_type_struct(f->type)) {
  5666. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  5667. if (name.len > 0) {
  5668. return name;
  5669. }
  5670. }
  5671. }
  5672. }
  5673. return str_lit("");
  5674. }
  5675. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  5676. GB_ASSERT(is_type_pointer(value.type));
  5677. GB_ASSERT(is_type_pointer(t));
  5678. GB_ASSERT(lb_is_const(value));
  5679. lbValue res = {};
  5680. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  5681. res.type = t;
  5682. return res;
  5683. }
  5684. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  5685. lbModule *m = p->module;
  5686. t = reduce_tuple_to_single_type(t);
  5687. Type *src_type = value.type;
  5688. if (are_types_identical(t, src_type)) {
  5689. return value;
  5690. }
  5691. Type *src = core_type(src_type);
  5692. Type *dst = core_type(t);
  5693. GB_ASSERT(src != nullptr);
  5694. GB_ASSERT(dst != nullptr);
  5695. if (is_type_untyped_nil(src)) {
  5696. return lb_const_nil(m, t);
  5697. }
  5698. if (is_type_untyped_undef(src)) {
  5699. return lb_const_undef(m, t);
  5700. }
  5701. if (LLVMIsConstant(value.value)) {
  5702. if (is_type_any(dst)) {
  5703. Type *st = default_type(src_type);
  5704. lbAddr default_value = lb_add_local_generated(p, st, false);
  5705. lb_addr_store(p, default_value, value);
  5706. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  5707. lbValue id = lb_typeid(m, st);
  5708. lbAddr res = lb_add_local_generated(p, t, false);
  5709. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  5710. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  5711. lb_emit_store(p, a0, data);
  5712. lb_emit_store(p, a1, id);
  5713. return lb_addr_load(p, res);
  5714. } else if (dst->kind == Type_Basic) {
  5715. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5716. String str = lb_get_const_string(m, value);
  5717. lbValue res = {};
  5718. res.type = t;
  5719. res.value = llvm_cstring(m, str);
  5720. return res;
  5721. }
  5722. // if (is_type_float(dst)) {
  5723. // return value;
  5724. // } else if (is_type_integer(dst)) {
  5725. // return value;
  5726. // }
  5727. // ExactValue ev = value->Constant.value;
  5728. // if (is_type_float(dst)) {
  5729. // ev = exact_value_to_float(ev);
  5730. // } else if (is_type_complex(dst)) {
  5731. // ev = exact_value_to_complex(ev);
  5732. // } else if (is_type_quaternion(dst)) {
  5733. // ev = exact_value_to_quaternion(ev);
  5734. // } else if (is_type_string(dst)) {
  5735. // // Handled elsewhere
  5736. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5737. // } else if (is_type_integer(dst)) {
  5738. // ev = exact_value_to_integer(ev);
  5739. // } else if (is_type_pointer(dst)) {
  5740. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5741. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5742. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5743. // }
  5744. // return lb_const_value(p->module, t, ev);
  5745. }
  5746. }
  5747. if (are_types_identical(src, dst)) {
  5748. if (!are_types_identical(src_type, t)) {
  5749. return lb_emit_transmute(p, value, t);
  5750. }
  5751. return value;
  5752. }
  5753. // bool <-> llvm bool
  5754. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5755. lbValue res = {};
  5756. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5757. res.type = dst;
  5758. return res;
  5759. }
  5760. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5761. lbValue res = {};
  5762. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5763. res.type = dst;
  5764. return res;
  5765. }
  5766. // integer -> integer
  5767. if (is_type_integer(src) && is_type_integer(dst)) {
  5768. GB_ASSERT(src->kind == Type_Basic &&
  5769. dst->kind == Type_Basic);
  5770. i64 sz = type_size_of(default_type(src));
  5771. i64 dz = type_size_of(default_type(dst));
  5772. if (sz == dz) {
  5773. if (dz > 1 && !types_have_same_internal_endian(src, dst)) {
  5774. return lb_emit_byte_swap(p, value, t);
  5775. }
  5776. lbValue res = {};
  5777. res.value = value.value;
  5778. res.type = t;
  5779. return res;
  5780. }
  5781. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5782. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5783. value = lb_emit_byte_swap(p, value, platform_src_type);
  5784. }
  5785. LLVMOpcode op = LLVMTrunc;
  5786. if (dz < sz) {
  5787. op = LLVMTrunc;
  5788. } else if (dz == sz) {
  5789. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5790. // NOTE(bill): Copy the value just for type correctness
  5791. op = LLVMBitCast;
  5792. } else if (dz > sz) {
  5793. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5794. }
  5795. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5796. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5797. lbValue res = {};
  5798. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5799. res.type = t;
  5800. return lb_emit_byte_swap(p, res, t);
  5801. } else {
  5802. lbValue res = {};
  5803. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5804. res.type = t;
  5805. return res;
  5806. }
  5807. }
  5808. // boolean -> boolean/integer
  5809. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5810. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5811. lbValue res = {};
  5812. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5813. res.type = t;
  5814. return res;
  5815. }
  5816. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5817. return lb_emit_transmute(p, value, dst);
  5818. }
  5819. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5820. return lb_emit_transmute(p, value, dst);
  5821. }
  5822. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5823. return lb_emit_transmute(p, value, dst);
  5824. }
  5825. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5826. return lb_emit_transmute(p, value, dst);
  5827. }
  5828. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5829. lbValue c = lb_emit_conv(p, value, t_cstring);
  5830. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5831. args[0] = c;
  5832. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5833. return lb_emit_conv(p, s, dst);
  5834. }
  5835. // integer -> boolean
  5836. if (is_type_integer(src) && is_type_boolean(dst)) {
  5837. lbValue res = {};
  5838. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5839. res.type = t_llvm_bool;
  5840. return lb_emit_conv(p, res, t);
  5841. }
  5842. // float -> float
  5843. if (is_type_float(src) && is_type_float(dst)) {
  5844. i64 sz = type_size_of(src);
  5845. i64 dz = type_size_of(dst);
  5846. if (dz == sz) {
  5847. if (types_have_same_internal_endian(src, dst)) {
  5848. lbValue res = {};
  5849. res.type = t;
  5850. res.value = value.value;
  5851. return res;
  5852. } else {
  5853. return lb_emit_byte_swap(p, value, t);
  5854. }
  5855. }
  5856. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5857. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5858. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5859. lbValue res = {};
  5860. res = lb_emit_conv(p, value, platform_src_type);
  5861. res = lb_emit_conv(p, res, platform_dst_type);
  5862. if (is_type_different_to_arch_endianness(dst)) {
  5863. res = lb_emit_byte_swap(p, res, t);
  5864. }
  5865. return lb_emit_conv(p, res, t);
  5866. }
  5867. lbValue res = {};
  5868. res.type = t;
  5869. if (dz >= sz) {
  5870. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  5871. } else {
  5872. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  5873. }
  5874. return res;
  5875. }
  5876. if (is_type_complex(src) && is_type_complex(dst)) {
  5877. Type *ft = base_complex_elem_type(dst);
  5878. lbAddr gen = lb_add_local_generated(p, dst, false);
  5879. lbValue gp = lb_addr_get_ptr(p, gen);
  5880. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5881. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5882. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5883. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  5884. return lb_addr_load(p, gen);
  5885. }
  5886. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5887. // @QuaternionLayout
  5888. Type *ft = base_complex_elem_type(dst);
  5889. lbAddr gen = lb_add_local_generated(p, dst, false);
  5890. lbValue gp = lb_addr_get_ptr(p, gen);
  5891. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5892. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5893. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  5894. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  5895. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  5896. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  5897. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  5898. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  5899. return lb_addr_load(p, gen);
  5900. }
  5901. if (is_type_float(src) && is_type_complex(dst)) {
  5902. Type *ft = base_complex_elem_type(dst);
  5903. lbAddr gen = lb_add_local_generated(p, dst, true);
  5904. lbValue gp = lb_addr_get_ptr(p, gen);
  5905. lbValue real = lb_emit_conv(p, value, ft);
  5906. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5907. return lb_addr_load(p, gen);
  5908. }
  5909. if (is_type_float(src) && is_type_quaternion(dst)) {
  5910. Type *ft = base_complex_elem_type(dst);
  5911. lbAddr gen = lb_add_local_generated(p, dst, true);
  5912. lbValue gp = lb_addr_get_ptr(p, gen);
  5913. lbValue real = lb_emit_conv(p, value, ft);
  5914. // @QuaternionLayout
  5915. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5916. return lb_addr_load(p, gen);
  5917. }
  5918. if (is_type_complex(src) && is_type_quaternion(dst)) {
  5919. Type *ft = base_complex_elem_type(dst);
  5920. lbAddr gen = lb_add_local_generated(p, dst, true);
  5921. lbValue gp = lb_addr_get_ptr(p, gen);
  5922. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5923. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5924. // @QuaternionLayout
  5925. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5926. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  5927. return lb_addr_load(p, gen);
  5928. }
  5929. // float <-> integer
  5930. if (is_type_float(src) && is_type_integer(dst)) {
  5931. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5932. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5933. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5934. lbValue res = {};
  5935. res = lb_emit_conv(p, value, platform_src_type);
  5936. res = lb_emit_conv(p, res, platform_dst_type);
  5937. if (is_type_different_to_arch_endianness(dst)) {
  5938. res = lb_emit_byte_swap(p, res, t);
  5939. }
  5940. return lb_emit_conv(p, res, t);
  5941. }
  5942. lbValue res = {};
  5943. res.type = t;
  5944. if (is_type_unsigned(dst)) {
  5945. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  5946. } else {
  5947. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  5948. }
  5949. return res;
  5950. }
  5951. if (is_type_integer(src) && is_type_float(dst)) {
  5952. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5953. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5954. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5955. lbValue res = {};
  5956. res = lb_emit_conv(p, value, platform_src_type);
  5957. res = lb_emit_conv(p, res, platform_dst_type);
  5958. if (is_type_different_to_arch_endianness(dst)) {
  5959. res = lb_emit_byte_swap(p, res, t);
  5960. }
  5961. return lb_emit_conv(p, res, t);
  5962. }
  5963. lbValue res = {};
  5964. res.type = t;
  5965. if (is_type_unsigned(src)) {
  5966. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  5967. } else {
  5968. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  5969. }
  5970. return res;
  5971. }
  5972. // Pointer <-> uintptr
  5973. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5974. lbValue res = {};
  5975. res.type = t;
  5976. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5977. return res;
  5978. }
  5979. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5980. lbValue res = {};
  5981. res.type = t;
  5982. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5983. return res;
  5984. }
  5985. #if 1
  5986. if (is_type_union(dst)) {
  5987. for_array(i, dst->Union.variants) {
  5988. Type *vt = dst->Union.variants[i];
  5989. if (are_types_identical(vt, src_type)) {
  5990. lbAddr parent = lb_add_local_generated(p, t, true);
  5991. lb_emit_store_union_variant(p, parent.addr, value, vt);
  5992. return lb_addr_load(p, parent);
  5993. }
  5994. }
  5995. }
  5996. #endif
  5997. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  5998. // subtype polymorphism casting
  5999. if (check_is_assignable_to_using_subtype(src_type, t)) {
  6000. Type *st = type_deref(src_type);
  6001. Type *pst = st;
  6002. st = type_deref(st);
  6003. bool st_is_ptr = is_type_pointer(src_type);
  6004. st = base_type(st);
  6005. Type *dt = t;
  6006. bool dt_is_ptr = type_deref(dt) != dt;
  6007. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  6008. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  6009. if (field_name.len > 0) {
  6010. // NOTE(bill): It can be casted
  6011. Selection sel = lookup_field(st, field_name, false, true);
  6012. if (sel.entity != nullptr) {
  6013. if (st_is_ptr) {
  6014. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  6015. Type *rt = res.type;
  6016. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6017. res = lb_emit_load(p, res);
  6018. }
  6019. return res;
  6020. } else {
  6021. if (is_type_pointer(value.type)) {
  6022. Type *rt = value.type;
  6023. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6024. value = lb_emit_load(p, value);
  6025. } else {
  6026. value = lb_emit_deep_field_gep(p, value, sel);
  6027. return lb_emit_load(p, value);
  6028. }
  6029. }
  6030. return lb_emit_deep_field_ev(p, value, sel);
  6031. }
  6032. } else {
  6033. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  6034. }
  6035. }
  6036. }
  6037. // Pointer <-> Pointer
  6038. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6039. lbValue res = {};
  6040. res.type = t;
  6041. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6042. return res;
  6043. }
  6044. // proc <-> proc
  6045. if (is_type_proc(src) && is_type_proc(dst)) {
  6046. lbValue res = {};
  6047. res.type = t;
  6048. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6049. return res;
  6050. }
  6051. // pointer -> proc
  6052. if (is_type_pointer(src) && is_type_proc(dst)) {
  6053. lbValue res = {};
  6054. res.type = t;
  6055. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6056. return res;
  6057. }
  6058. // proc -> pointer
  6059. if (is_type_proc(src) && is_type_pointer(dst)) {
  6060. lbValue res = {};
  6061. res.type = t;
  6062. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6063. return res;
  6064. }
  6065. // []byte/[]u8 <-> string
  6066. if (is_type_u8_slice(src) && is_type_string(dst)) {
  6067. return lb_emit_transmute(p, value, t);
  6068. }
  6069. if (is_type_string(src) && is_type_u8_slice(dst)) {
  6070. return lb_emit_transmute(p, value, t);
  6071. }
  6072. if (is_type_array(dst)) {
  6073. Type *elem = dst->Array.elem;
  6074. lbValue e = lb_emit_conv(p, value, elem);
  6075. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6076. lbAddr v = lb_add_local_generated(p, t, false);
  6077. isize index_count = cast(isize)dst->Array.count;
  6078. for (isize i = 0; i < index_count; i++) {
  6079. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  6080. lb_emit_store(p, elem, e);
  6081. }
  6082. return lb_addr_load(p, v);
  6083. }
  6084. if (is_type_any(dst)) {
  6085. if (is_type_untyped_nil(src)) {
  6086. return lb_const_nil(p->module, t);
  6087. }
  6088. if (is_type_untyped_undef(src)) {
  6089. return lb_const_undef(p->module, t);
  6090. }
  6091. lbAddr result = lb_add_local_generated(p, t, true);
  6092. Type *st = default_type(src_type);
  6093. lbValue data = lb_address_from_load_or_generate_local(p, value);
  6094. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  6095. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  6096. data = lb_emit_conv(p, data, t_rawptr);
  6097. lbValue id = lb_typeid(p->module, st);
  6098. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  6099. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  6100. lb_emit_store(p, any_data, data);
  6101. lb_emit_store(p, any_id, id);
  6102. return lb_addr_load(p, result);
  6103. }
  6104. i64 src_sz = type_size_of(src);
  6105. i64 dst_sz = type_size_of(dst);
  6106. if (src_sz == dst_sz) {
  6107. // bit_set <-> integer
  6108. if (is_type_integer(src) && is_type_bit_set(dst)) {
  6109. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  6110. res.type = dst;
  6111. return res;
  6112. }
  6113. if (is_type_bit_set(src) && is_type_integer(dst)) {
  6114. lbValue bs = value;
  6115. bs.type = bit_set_to_int(src);
  6116. return lb_emit_conv(p, bs, dst);
  6117. }
  6118. // typeid <-> integer
  6119. if (is_type_integer(src) && is_type_typeid(dst)) {
  6120. return lb_emit_transmute(p, value, dst);
  6121. }
  6122. if (is_type_typeid(src) && is_type_integer(dst)) {
  6123. return lb_emit_transmute(p, value, dst);
  6124. }
  6125. }
  6126. if (is_type_untyped(src)) {
  6127. if (is_type_string(src) && is_type_string(dst)) {
  6128. lbAddr result = lb_add_local_generated(p, t, false);
  6129. lb_addr_store(p, result, value);
  6130. return lb_addr_load(p, result);
  6131. }
  6132. }
  6133. gb_printf_err("%.*s\n", LIT(p->name));
  6134. gb_printf_err("lb_emit_conv: src -> dst\n");
  6135. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  6136. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  6137. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  6138. gb_printf_err("Not Identical %p != %p\n", src, dst);
  6139. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  6140. type_to_string(src_type), type_to_string(t),
  6141. LIT(p->name));
  6142. return {};
  6143. }
  6144. bool lb_is_type_aggregate(Type *t) {
  6145. t = base_type(t);
  6146. switch (t->kind) {
  6147. case Type_Basic:
  6148. switch (t->Basic.kind) {
  6149. case Basic_string:
  6150. case Basic_any:
  6151. return true;
  6152. // case Basic_complex32:
  6153. case Basic_complex64:
  6154. case Basic_complex128:
  6155. case Basic_quaternion128:
  6156. case Basic_quaternion256:
  6157. return true;
  6158. }
  6159. break;
  6160. case Type_Pointer:
  6161. return false;
  6162. case Type_Array:
  6163. case Type_Slice:
  6164. case Type_Struct:
  6165. case Type_Union:
  6166. case Type_Tuple:
  6167. case Type_DynamicArray:
  6168. case Type_Map:
  6169. case Type_SimdVector:
  6170. return true;
  6171. case Type_Named:
  6172. return lb_is_type_aggregate(t->Named.base);
  6173. }
  6174. return false;
  6175. }
  6176. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  6177. Type *src_type = value.type;
  6178. if (are_types_identical(t, src_type)) {
  6179. return value;
  6180. }
  6181. lbValue res = {};
  6182. res.type = t;
  6183. Type *src = base_type(src_type);
  6184. Type *dst = base_type(t);
  6185. lbModule *m = p->module;
  6186. i64 sz = type_size_of(src);
  6187. i64 dz = type_size_of(dst);
  6188. if (sz != dz) {
  6189. LLVMTypeRef s = lb_type(m, src);
  6190. LLVMTypeRef d = lb_type(m, dst);
  6191. i64 llvm_sz = lb_sizeof(s);
  6192. i64 llvm_dz = lb_sizeof(d);
  6193. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  6194. }
  6195. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  6196. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  6197. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6198. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6199. return res;
  6200. }
  6201. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6202. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6203. return res;
  6204. }
  6205. if (is_type_uintptr(src) && is_type_proc(dst)) {
  6206. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6207. return res;
  6208. }
  6209. if (is_type_proc(src) && is_type_uintptr(dst)) {
  6210. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6211. return res;
  6212. }
  6213. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  6214. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6215. return res;
  6216. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  6217. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6218. return res;
  6219. }
  6220. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6221. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  6222. return res;
  6223. }
  6224. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  6225. lbValue s = lb_address_from_load_or_generate_local(p, value);
  6226. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  6227. return lb_emit_load(p, d);
  6228. }
  6229. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  6230. // GB_PANIC("lb_emit_transmute");
  6231. return res;
  6232. }
  6233. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  6234. GB_ASSERT(addr.kind == lbAddr_Context);
  6235. GB_ASSERT(addr.ctx.sel.index.count == 0);
  6236. lbModule *m = p->module;
  6237. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6238. args[0] = addr.addr;
  6239. lb_emit_runtime_call(p, "__init_context", args);
  6240. }
  6241. lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  6242. Type *pt = base_type(p->type);
  6243. GB_ASSERT(pt->kind == Type_Proc);
  6244. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  6245. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  6246. e->flags |= EntityFlag_NoAlias;
  6247. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  6248. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  6249. lbValue param = {context_ptr, e->type};
  6250. lb_add_entity(p->module, e, param);
  6251. lbAddr ctx_addr = {};
  6252. ctx_addr.kind = lbAddr_Context;
  6253. ctx_addr.addr = param;
  6254. lbContextData *cd = array_add_and_get(&p->context_stack);
  6255. cd->ctx = ctx_addr;
  6256. cd->scope_index = -1;
  6257. return cd;
  6258. }
  6259. lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  6260. ctx.kind = lbAddr_Context;
  6261. lbContextData *cd = array_add_and_get(&p->context_stack);
  6262. cd->ctx = ctx;
  6263. cd->scope_index = p->scope_index;
  6264. return cd;
  6265. }
  6266. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  6267. if (p->context_stack.count > 0) {
  6268. return p->context_stack[p->context_stack.count-1].ctx;
  6269. }
  6270. Type *pt = base_type(p->type);
  6271. GB_ASSERT(pt->kind == Type_Proc);
  6272. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  6273. lbAddr c = lb_add_local_generated(p, t_context, true);
  6274. c.kind = lbAddr_Context;
  6275. lb_emit_init_context(p, c);
  6276. lb_push_context_onto_stack(p, c);
  6277. lb_add_debug_context_variable(p, c);
  6278. return c;
  6279. }
  6280. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  6281. if (LLVMIsALoadInst(value.value)) {
  6282. lbValue res = {};
  6283. res.value = LLVMGetOperand(value.value, 0);
  6284. res.type = alloc_type_pointer(value.type);
  6285. return res;
  6286. }
  6287. GB_ASSERT(is_type_typed(value.type));
  6288. lbAddr res = lb_add_local_generated(p, value.type, false);
  6289. lb_addr_store(p, res, value);
  6290. return res.addr;
  6291. }
  6292. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  6293. if (LLVMIsALoadInst(value.value)) {
  6294. lbValue res = {};
  6295. res.value = LLVMGetOperand(value.value, 0);
  6296. res.type = alloc_type_pointer(value.type);
  6297. return res;
  6298. }
  6299. GB_PANIC("lb_address_from_load");
  6300. return {};
  6301. }
  6302. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  6303. i64 type_alignment = type_align_of(new_type);
  6304. if (alignment < type_alignment) {
  6305. alignment = type_alignment;
  6306. }
  6307. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  6308. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  6309. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  6310. lb_addr_store(p, ptr, val);
  6311. // ptr.kind = lbAddr_Context;
  6312. return ptr.addr;
  6313. }
  6314. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  6315. GB_ASSERT(is_type_pointer(s.type));
  6316. Type *t = base_type(type_deref(s.type));
  6317. Type *result_type = nullptr;
  6318. if (is_type_relative_pointer(t)) {
  6319. s = lb_addr_get_ptr(p, lb_addr(s));
  6320. }
  6321. if (is_type_struct(t)) {
  6322. result_type = get_struct_field_type(t, index);
  6323. } else if (is_type_union(t)) {
  6324. GB_ASSERT(index == -1);
  6325. return lb_emit_union_tag_ptr(p, s);
  6326. } else if (is_type_tuple(t)) {
  6327. GB_ASSERT(t->Tuple.variables.count > 0);
  6328. result_type = t->Tuple.variables[index]->type;
  6329. } else if (is_type_complex(t)) {
  6330. Type *ft = base_complex_elem_type(t);
  6331. switch (index) {
  6332. case 0: result_type = ft; break;
  6333. case 1: result_type = ft; break;
  6334. }
  6335. } else if (is_type_quaternion(t)) {
  6336. Type *ft = base_complex_elem_type(t);
  6337. switch (index) {
  6338. case 0: result_type = ft; break;
  6339. case 1: result_type = ft; break;
  6340. case 2: result_type = ft; break;
  6341. case 3: result_type = ft; break;
  6342. }
  6343. } else if (is_type_slice(t)) {
  6344. switch (index) {
  6345. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6346. case 1: result_type = t_int; break;
  6347. }
  6348. } else if (is_type_string(t)) {
  6349. switch (index) {
  6350. case 0: result_type = t_u8_ptr; break;
  6351. case 1: result_type = t_int; break;
  6352. }
  6353. } else if (is_type_any(t)) {
  6354. switch (index) {
  6355. case 0: result_type = t_rawptr; break;
  6356. case 1: result_type = t_typeid; break;
  6357. }
  6358. } else if (is_type_dynamic_array(t)) {
  6359. switch (index) {
  6360. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6361. case 1: result_type = t_int; break;
  6362. case 2: result_type = t_int; break;
  6363. case 3: result_type = t_allocator; break;
  6364. }
  6365. } else if (is_type_map(t)) {
  6366. init_map_internal_types(t);
  6367. Type *itp = alloc_type_pointer(t->Map.internal_type);
  6368. s = lb_emit_transmute(p, s, itp);
  6369. Type *gst = t->Map.internal_type;
  6370. GB_ASSERT(gst->kind == Type_Struct);
  6371. switch (index) {
  6372. case 0: result_type = get_struct_field_type(gst, 0); break;
  6373. case 1: result_type = get_struct_field_type(gst, 1); break;
  6374. }
  6375. } else if (is_type_array(t)) {
  6376. return lb_emit_array_epi(p, s, index);
  6377. } else if (is_type_relative_slice(t)) {
  6378. switch (index) {
  6379. case 0: result_type = t->RelativeSlice.base_integer; break;
  6380. case 1: result_type = t->RelativeSlice.base_integer; break;
  6381. }
  6382. } else {
  6383. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  6384. }
  6385. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  6386. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6387. index += 1;
  6388. }
  6389. if (lb_is_const(s)) {
  6390. lbModule *m = p->module;
  6391. lbValue res = {};
  6392. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  6393. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6394. res.type = alloc_type_pointer(result_type);
  6395. return res;
  6396. } else {
  6397. lbValue res = {};
  6398. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  6399. res.type = alloc_type_pointer(result_type);
  6400. return res;
  6401. }
  6402. }
  6403. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  6404. if (LLVMIsALoadInst(s.value)) {
  6405. lbValue res = {};
  6406. res.value = LLVMGetOperand(s.value, 0);
  6407. res.type = alloc_type_pointer(s.type);
  6408. lbValue ptr = lb_emit_struct_ep(p, res, index);
  6409. return lb_emit_load(p, ptr);
  6410. }
  6411. Type *t = base_type(s.type);
  6412. Type *result_type = nullptr;
  6413. switch (t->kind) {
  6414. case Type_Basic:
  6415. switch (t->Basic.kind) {
  6416. case Basic_string:
  6417. switch (index) {
  6418. case 0: result_type = t_u8_ptr; break;
  6419. case 1: result_type = t_int; break;
  6420. }
  6421. break;
  6422. case Basic_any:
  6423. switch (index) {
  6424. case 0: result_type = t_rawptr; break;
  6425. case 1: result_type = t_typeid; break;
  6426. }
  6427. break;
  6428. case Basic_complex64: case Basic_complex128:
  6429. {
  6430. Type *ft = base_complex_elem_type(t);
  6431. switch (index) {
  6432. case 0: result_type = ft; break;
  6433. case 1: result_type = ft; break;
  6434. }
  6435. break;
  6436. }
  6437. case Basic_quaternion128: case Basic_quaternion256:
  6438. {
  6439. Type *ft = base_complex_elem_type(t);
  6440. switch (index) {
  6441. case 0: result_type = ft; break;
  6442. case 1: result_type = ft; break;
  6443. case 2: result_type = ft; break;
  6444. case 3: result_type = ft; break;
  6445. }
  6446. break;
  6447. }
  6448. }
  6449. break;
  6450. case Type_Struct:
  6451. result_type = get_struct_field_type(t, index);
  6452. break;
  6453. case Type_Union:
  6454. GB_ASSERT(index == -1);
  6455. // return lb_emit_union_tag_value(p, s);
  6456. GB_PANIC("lb_emit_union_tag_value");
  6457. case Type_Tuple:
  6458. GB_ASSERT(t->Tuple.variables.count > 0);
  6459. result_type = t->Tuple.variables[index]->type;
  6460. if (t->Tuple.variables.count == 1) {
  6461. return s;
  6462. }
  6463. break;
  6464. case Type_Slice:
  6465. switch (index) {
  6466. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6467. case 1: result_type = t_int; break;
  6468. }
  6469. break;
  6470. case Type_DynamicArray:
  6471. switch (index) {
  6472. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6473. case 1: result_type = t_int; break;
  6474. case 2: result_type = t_int; break;
  6475. case 3: result_type = t_allocator; break;
  6476. }
  6477. break;
  6478. case Type_Map:
  6479. {
  6480. init_map_internal_types(t);
  6481. Type *gst = t->Map.generated_struct_type;
  6482. switch (index) {
  6483. case 0: result_type = get_struct_field_type(gst, 0); break;
  6484. case 1: result_type = get_struct_field_type(gst, 1); break;
  6485. }
  6486. }
  6487. break;
  6488. case Type_Array:
  6489. result_type = t->Array.elem;
  6490. break;
  6491. default:
  6492. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  6493. break;
  6494. }
  6495. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  6496. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6497. index += 1;
  6498. }
  6499. lbValue res = {};
  6500. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  6501. res.type = result_type;
  6502. return res;
  6503. }
  6504. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  6505. GB_ASSERT(sel.index.count > 0);
  6506. Type *type = type_deref(e.type);
  6507. for_array(i, sel.index) {
  6508. i32 index = cast(i32)sel.index[i];
  6509. if (is_type_pointer(type)) {
  6510. type = type_deref(type);
  6511. e = lb_emit_load(p, e);
  6512. }
  6513. type = core_type(type);
  6514. if (is_type_quaternion(type)) {
  6515. e = lb_emit_struct_ep(p, e, index);
  6516. } else if (is_type_raw_union(type)) {
  6517. type = get_struct_field_type(type, index);
  6518. GB_ASSERT(is_type_pointer(e.type));
  6519. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  6520. } else if (is_type_struct(type)) {
  6521. type = get_struct_field_type(type, index);
  6522. e = lb_emit_struct_ep(p, e, index);
  6523. } else if (type->kind == Type_Union) {
  6524. GB_ASSERT(index == -1);
  6525. type = t_type_info_ptr;
  6526. e = lb_emit_struct_ep(p, e, index);
  6527. } else if (type->kind == Type_Tuple) {
  6528. type = type->Tuple.variables[index]->type;
  6529. e = lb_emit_struct_ep(p, e, index);
  6530. } else if (type->kind == Type_Basic) {
  6531. switch (type->Basic.kind) {
  6532. case Basic_any: {
  6533. if (index == 0) {
  6534. type = t_rawptr;
  6535. } else if (index == 1) {
  6536. type = t_type_info_ptr;
  6537. }
  6538. e = lb_emit_struct_ep(p, e, index);
  6539. break;
  6540. }
  6541. case Basic_string:
  6542. e = lb_emit_struct_ep(p, e, index);
  6543. break;
  6544. default:
  6545. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6546. break;
  6547. }
  6548. } else if (type->kind == Type_Slice) {
  6549. e = lb_emit_struct_ep(p, e, index);
  6550. } else if (type->kind == Type_DynamicArray) {
  6551. e = lb_emit_struct_ep(p, e, index);
  6552. } else if (type->kind == Type_Array) {
  6553. e = lb_emit_array_epi(p, e, index);
  6554. } else if (type->kind == Type_Map) {
  6555. e = lb_emit_struct_ep(p, e, index);
  6556. } else if (type->kind == Type_RelativePointer) {
  6557. e = lb_emit_struct_ep(p, e, index);
  6558. } else {
  6559. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6560. }
  6561. }
  6562. return e;
  6563. }
  6564. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  6565. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  6566. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  6567. return lb_emit_load(p, res);
  6568. }
  6569. void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  6570. // NOTE(bill): The prev block may defer injection before it's terminator
  6571. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  6572. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  6573. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  6574. return;
  6575. }
  6576. isize prev_context_stack_count = p->context_stack.count;
  6577. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  6578. defer (p->context_stack.count = prev_context_stack_count);
  6579. p->context_stack.count = d.context_stack_count;
  6580. lbBlock *b = lb_create_block(p, "defer");
  6581. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6582. lb_emit_jump(p, b);
  6583. }
  6584. lb_start_block(p, b);
  6585. if (d.kind == lbDefer_Node) {
  6586. lb_build_stmt(p, d.stmt);
  6587. } else if (d.kind == lbDefer_Instr) {
  6588. // NOTE(bill): Need to make a new copy
  6589. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  6590. LLVMInsertIntoBuilder(p->builder, instr);
  6591. } else if (d.kind == lbDefer_Proc) {
  6592. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  6593. }
  6594. }
  6595. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  6596. isize count = p->defer_stmts.count;
  6597. isize i = count;
  6598. while (i --> 0) {
  6599. lbDefer const &d = p->defer_stmts[i];
  6600. if (kind == lbDeferExit_Default) {
  6601. if (p->scope_index == d.scope_index &&
  6602. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  6603. lb_build_defer_stmt(p, d);
  6604. array_pop(&p->defer_stmts);
  6605. continue;
  6606. } else {
  6607. break;
  6608. }
  6609. } else if (kind == lbDeferExit_Return) {
  6610. lb_build_defer_stmt(p, d);
  6611. } else if (kind == lbDeferExit_Branch) {
  6612. GB_ASSERT(block != nullptr);
  6613. isize lower_limit = block->scope_index;
  6614. if (lower_limit < d.scope_index) {
  6615. lb_build_defer_stmt(p, d);
  6616. }
  6617. }
  6618. }
  6619. }
  6620. void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  6621. Type *pt = base_type(p->type);
  6622. GB_ASSERT(pt->kind == Type_Proc);
  6623. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6624. GB_ASSERT(p->context_stack.count != 0);
  6625. }
  6626. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6627. d->kind = lbDefer_Node;
  6628. d->scope_index = scope_index;
  6629. d->context_stack_count = p->context_stack.count;
  6630. d->block = p->curr_block;
  6631. d->stmt = stmt;
  6632. }
  6633. void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  6634. Type *pt = base_type(p->type);
  6635. GB_ASSERT(pt->kind == Type_Proc);
  6636. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6637. GB_ASSERT(p->context_stack.count != 0);
  6638. }
  6639. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6640. d->kind = lbDefer_Proc;
  6641. d->scope_index = p->scope_index;
  6642. d->block = p->curr_block;
  6643. d->context_stack_count = p->context_stack.count;
  6644. d->proc.deferred = deferred;
  6645. d->proc.result_as_args = result_as_args;
  6646. }
  6647. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  6648. Array<lbValue> array = {};
  6649. Type *t = base_type(value.type);
  6650. if (t == nullptr) {
  6651. // Do nothing
  6652. } else if (is_type_tuple(t)) {
  6653. GB_ASSERT(t->kind == Type_Tuple);
  6654. auto *rt = &t->Tuple;
  6655. if (rt->variables.count > 0) {
  6656. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  6657. for_array(i, rt->variables) {
  6658. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  6659. array[i] = elem;
  6660. }
  6661. }
  6662. } else {
  6663. array = array_make<lbValue>(permanent_allocator(), 1);
  6664. array[0] = value;
  6665. }
  6666. return array;
  6667. }
  6668. 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) {
  6669. unsigned arg_count = cast(unsigned)processed_args.count;
  6670. if (return_ptr.value != nullptr) {
  6671. arg_count += 1;
  6672. }
  6673. if (context_ptr.addr.value != nullptr) {
  6674. arg_count += 1;
  6675. }
  6676. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  6677. isize arg_index = 0;
  6678. if (return_ptr.value != nullptr) {
  6679. args[arg_index++] = return_ptr.value;
  6680. }
  6681. for_array(i, processed_args) {
  6682. lbValue arg = processed_args[i];
  6683. args[arg_index++] = arg.value;
  6684. }
  6685. if (context_ptr.addr.value != nullptr) {
  6686. LLVMValueRef cp = context_ptr.addr.value;
  6687. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  6688. args[arg_index++] = cp;
  6689. }
  6690. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  6691. GB_ASSERT(curr_block != p->decl_block->block);
  6692. {
  6693. LLVMTypeRef ftp = lb_type(p->module, value.type);
  6694. LLVMTypeRef ft = LLVMGetElementType(ftp);
  6695. LLVMValueRef fn = value.value;
  6696. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  6697. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  6698. }
  6699. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  6700. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  6701. LLVMValueRef ret = LLVMBuildCall2(p->builder, ft, fn, args, arg_count, "");;
  6702. lbValue res = {};
  6703. res.value = ret;
  6704. res.type = abi_rt;
  6705. return res;
  6706. }
  6707. }
  6708. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  6709. // LLVMMetadataRef curr_loc = LLVMGetCurrentDebugLocation2(p->builder);
  6710. // LLVMSetCurrentDebugLocation2(p->builder, nullptr);
  6711. // defer (if (curr_loc) {
  6712. // LLVMSetCurrentDebugLocation2(p->builder, curr_loc);
  6713. // });
  6714. String name = make_string_c(c_name);
  6715. AstPackage *pkg = p->module->info->runtime_package;
  6716. Entity *e = scope_lookup_current(pkg->scope, name);
  6717. lbValue *found = nullptr;
  6718. if (p->module != e->code_gen_module) {
  6719. gb_mutex_lock(&p->module->mutex);
  6720. }
  6721. GB_ASSERT(e->code_gen_module != nullptr);
  6722. found = map_get(&e->code_gen_module->values, hash_entity(e));
  6723. if (p->module != e->code_gen_module) {
  6724. gb_mutex_unlock(&p->module->mutex);
  6725. }
  6726. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  6727. return lb_emit_call(p, *found, args);
  6728. }
  6729. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  6730. lbModule *m = p->module;
  6731. Type *pt = base_type(value.type);
  6732. GB_ASSERT(pt->kind == Type_Proc);
  6733. Type *results = pt->Proc.results;
  6734. if (p->entity != nullptr) {
  6735. if (p->entity->flags & EntityFlag_Disabled) {
  6736. return {};
  6737. }
  6738. }
  6739. lbAddr context_ptr = {};
  6740. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6741. context_ptr = lb_find_or_generate_context_ptr(p);
  6742. }
  6743. defer (if (pt->Proc.diverging) {
  6744. LLVMBuildUnreachable(p->builder);
  6745. });
  6746. set_procedure_abi_types(pt);
  6747. bool is_c_vararg = pt->Proc.c_vararg;
  6748. isize param_count = pt->Proc.param_count;
  6749. if (is_c_vararg) {
  6750. GB_ASSERT(param_count-1 <= args.count);
  6751. param_count -= 1;
  6752. } else {
  6753. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  6754. }
  6755. lbValue result = {};
  6756. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  6757. {
  6758. lbFunctionType **ft_found = nullptr;
  6759. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6760. if (!ft_found) {
  6761. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  6762. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6763. }
  6764. GB_ASSERT(ft_found != nullptr);
  6765. lbFunctionType *ft = *ft_found;
  6766. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  6767. unsigned param_index = 0;
  6768. for (isize i = 0; i < param_count; i++) {
  6769. Entity *e = pt->Proc.params->Tuple.variables[i];
  6770. if (e->kind != Entity_Variable) {
  6771. continue;
  6772. }
  6773. GB_ASSERT(e->flags & EntityFlag_Param);
  6774. Type *original_type = e->type;
  6775. lbArgType *arg = &ft->args[param_index];
  6776. if (arg->kind == lbArg_Ignore) {
  6777. continue;
  6778. }
  6779. lbValue x = lb_emit_conv(p, args[i], original_type);
  6780. LLVMTypeRef xt = lb_type(p->module, x.type);
  6781. if (arg->kind == lbArg_Direct) {
  6782. LLVMTypeRef abi_type = arg->cast_type;
  6783. if (!abi_type) {
  6784. abi_type = arg->type;
  6785. }
  6786. if (xt == abi_type) {
  6787. array_add(&processed_args, x);
  6788. } else {
  6789. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  6790. array_add(&processed_args, x);
  6791. }
  6792. } else if (arg->kind == lbArg_Indirect) {
  6793. lbValue ptr = {};
  6794. if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  6795. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  6796. // i.e. `T const &` in C++
  6797. ptr = lb_address_from_load_or_generate_local(p, x);
  6798. } else {
  6799. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  6800. }
  6801. array_add(&processed_args, ptr);
  6802. }
  6803. param_index += 1;
  6804. }
  6805. if (inlining == ProcInlining_none) {
  6806. inlining = p->inlining;
  6807. }
  6808. Type *rt = reduce_tuple_to_single_type(results);
  6809. if (return_by_pointer) {
  6810. lbValue return_ptr = {};
  6811. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6812. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6813. return_ptr = p->return_ptr_hint_value;
  6814. p->return_ptr_hint_used = true;
  6815. }
  6816. }
  6817. if (return_ptr.value == nullptr) {
  6818. lbAddr r = lb_add_local_generated(p, rt, true);
  6819. return_ptr = r.addr;
  6820. }
  6821. GB_ASSERT(is_type_pointer(return_ptr.type));
  6822. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6823. result = lb_emit_load(p, return_ptr);
  6824. } else if (rt != nullptr) {
  6825. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  6826. if (ft->ret.cast_type) {
  6827. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  6828. }
  6829. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  6830. result.type = rt;
  6831. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  6832. result.type = t_llvm_bool;
  6833. }
  6834. if (!is_type_tuple(rt)) {
  6835. result = lb_emit_conv(p, result, rt);
  6836. }
  6837. } else {
  6838. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  6839. }
  6840. }
  6841. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  6842. if (found != nullptr) {
  6843. Entity *e = *found;
  6844. if (e != nullptr && entity_has_deferred_procedure(e)) {
  6845. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  6846. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  6847. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  6848. GB_ASSERT(deferred_found != nullptr);
  6849. lbValue deferred = *deferred_found;
  6850. auto in_args = args;
  6851. Array<lbValue> result_as_args = {};
  6852. switch (kind) {
  6853. case DeferredProcedure_none:
  6854. break;
  6855. case DeferredProcedure_in:
  6856. result_as_args = in_args;
  6857. break;
  6858. case DeferredProcedure_out:
  6859. result_as_args = lb_value_to_array(p, result);
  6860. break;
  6861. case DeferredProcedure_in_out:
  6862. {
  6863. auto out_args = lb_value_to_array(p, result);
  6864. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  6865. array_copy(&result_as_args, in_args, 0);
  6866. array_copy(&result_as_args, out_args, in_args.count);
  6867. }
  6868. break;
  6869. }
  6870. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  6871. }
  6872. }
  6873. return result;
  6874. }
  6875. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  6876. Type *t = s.type;
  6877. GB_ASSERT(is_type_pointer(t));
  6878. Type *st = base_type(type_deref(t));
  6879. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6880. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  6881. LLVMValueRef indices[2] = {};
  6882. indices[0] = llvm_zero(p->module);
  6883. indices[1] = lb_emit_conv(p, index, t_int).value;
  6884. Type *ptr = base_array_type(st);
  6885. lbValue res = {};
  6886. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  6887. res.type = alloc_type_pointer(ptr);
  6888. return res;
  6889. }
  6890. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  6891. Type *t = s.type;
  6892. GB_ASSERT(is_type_pointer(t));
  6893. Type *st = base_type(type_deref(t));
  6894. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6895. GB_ASSERT(0 <= index);
  6896. Type *ptr = base_array_type(st);
  6897. LLVMValueRef indices[2] = {
  6898. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  6899. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  6900. };
  6901. lbValue res = {};
  6902. if (lb_is_const(s)) {
  6903. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6904. } else {
  6905. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  6906. }
  6907. res.type = alloc_type_pointer(ptr);
  6908. return res;
  6909. }
  6910. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  6911. LLVMValueRef indices[1] = {index.value};
  6912. lbValue res = {};
  6913. res.type = ptr.type;
  6914. if (lb_is_const(ptr) && lb_is_const(index)) {
  6915. res.value = LLVMConstGEP(ptr.value, indices, 1);
  6916. } else {
  6917. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  6918. }
  6919. return res;
  6920. }
  6921. LLVMValueRef llvm_const_slice(lbModule *m, lbValue data, lbValue len) {
  6922. GB_ASSERT(is_type_pointer(data.type));
  6923. GB_ASSERT(are_types_identical(len.type, t_int));
  6924. LLVMValueRef vals[2] = {
  6925. data.value,
  6926. len.value,
  6927. };
  6928. return LLVMConstStructInContext(m->ctx, vals, gb_count_of(vals), false);
  6929. }
  6930. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  6931. Type *t = lb_addr_type(slice);
  6932. GB_ASSERT(is_type_slice(t));
  6933. lbValue ptr = lb_addr_get_ptr(p, slice);
  6934. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6935. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6936. }
  6937. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  6938. Type *t = lb_addr_type(string);
  6939. GB_ASSERT(is_type_string(t));
  6940. lbValue ptr = lb_addr_get_ptr(p, string);
  6941. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6942. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6943. }
  6944. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  6945. Type *t = base_type(string.type);
  6946. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  6947. return lb_emit_struct_ev(p, string, 0);
  6948. }
  6949. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  6950. Type *t = base_type(string.type);
  6951. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  6952. return lb_emit_struct_ev(p, string, 1);
  6953. }
  6954. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  6955. GB_ASSERT(is_type_cstring(value.type));
  6956. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6957. args[0] = lb_emit_conv(p, value, t_cstring);
  6958. return lb_emit_runtime_call(p, "cstring_len", args);
  6959. }
  6960. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  6961. Type *t = type_deref(array_ptr.type);
  6962. GB_ASSERT(is_type_array(t));
  6963. return lb_emit_struct_ep(p, array_ptr, 0);
  6964. }
  6965. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  6966. GB_ASSERT(is_type_slice(slice.type));
  6967. return lb_emit_struct_ev(p, slice, 0);
  6968. }
  6969. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  6970. GB_ASSERT(is_type_slice(slice.type));
  6971. return lb_emit_struct_ev(p, slice, 1);
  6972. }
  6973. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  6974. GB_ASSERT(is_type_dynamic_array(da.type));
  6975. return lb_emit_struct_ev(p, da, 0);
  6976. }
  6977. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  6978. GB_ASSERT(is_type_dynamic_array(da.type));
  6979. return lb_emit_struct_ev(p, da, 1);
  6980. }
  6981. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  6982. GB_ASSERT(is_type_dynamic_array(da.type));
  6983. return lb_emit_struct_ev(p, da, 2);
  6984. }
  6985. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  6986. GB_ASSERT(is_type_dynamic_array(da.type));
  6987. return lb_emit_struct_ev(p, da, 3);
  6988. }
  6989. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  6990. Type *t = base_type(value.type);
  6991. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6992. init_map_internal_types(t);
  6993. Type *gst = t->Map.generated_struct_type;
  6994. i32 index = 1;
  6995. lbValue entries = lb_emit_struct_ev(p, value, index);
  6996. return entries;
  6997. }
  6998. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  6999. Type *t = base_type(type_deref(value.type));
  7000. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7001. init_map_internal_types(t);
  7002. Type *gst = t->Map.generated_struct_type;
  7003. i32 index = 1;
  7004. lbValue entries = lb_emit_struct_ep(p, value, index);
  7005. return entries;
  7006. }
  7007. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  7008. lbValue entries = lb_map_entries(p, value);
  7009. return lb_dynamic_array_len(p, entries);
  7010. }
  7011. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  7012. lbValue entries = lb_map_entries(p, value);
  7013. return lb_dynamic_array_cap(p, entries);
  7014. }
  7015. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  7016. Type *t = base_type(value.type);
  7017. bool is_ptr = false;
  7018. if (is_type_pointer(t)) {
  7019. is_ptr = true;
  7020. t = base_type(type_deref(t));
  7021. }
  7022. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7023. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7024. }
  7025. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  7026. t->Struct.soa_kind == StructSoa_Dynamic);
  7027. isize n = 0;
  7028. Type *elem = base_type(t->Struct.soa_elem);
  7029. if (elem->kind == Type_Struct) {
  7030. n = elem->Struct.fields.count;
  7031. } else if (elem->kind == Type_Array) {
  7032. n = elem->Array.count;
  7033. } else {
  7034. GB_PANIC("Unreachable");
  7035. }
  7036. if (is_ptr) {
  7037. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7038. return lb_emit_load(p, v);
  7039. }
  7040. return lb_emit_struct_ev(p, value, cast(i32)n);
  7041. }
  7042. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  7043. Type *t = base_type(value.type);
  7044. bool is_ptr = false;
  7045. if (is_type_pointer(t)) {
  7046. is_ptr = true;
  7047. t = base_type(type_deref(t));
  7048. }
  7049. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7050. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7051. }
  7052. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  7053. isize n = 0;
  7054. Type *elem = base_type(t->Struct.soa_elem);
  7055. if (elem->kind == Type_Struct) {
  7056. n = elem->Struct.fields.count+1;
  7057. } else if (elem->kind == Type_Array) {
  7058. n = elem->Array.count+1;
  7059. } else {
  7060. GB_PANIC("Unreachable");
  7061. }
  7062. if (is_ptr) {
  7063. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7064. return lb_emit_load(p, v);
  7065. }
  7066. return lb_emit_struct_ev(p, value, cast(i32)n);
  7067. }
  7068. lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7069. GB_ASSERT(ce->args.count > 0);
  7070. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  7071. for_array(i, slices) {
  7072. Ast *arg = ce->args[i];
  7073. if (arg->kind == Ast_FieldValue) {
  7074. arg = arg->FieldValue.value;
  7075. }
  7076. slices[i] = lb_build_expr(p, arg);
  7077. }
  7078. lbValue len = lb_slice_len(p, slices[0]);
  7079. for (isize i = 1; i < slices.count; i++) {
  7080. lbValue other_len = lb_slice_len(p, slices[i]);
  7081. len = lb_emit_min(p, t_int, len, other_len);
  7082. }
  7083. GB_ASSERT(is_type_soa_struct(tv.type));
  7084. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7085. for_array(i, slices) {
  7086. lbValue src = lb_slice_elem(p, slices[i]);
  7087. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  7088. lb_emit_store(p, dst, src);
  7089. }
  7090. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  7091. lb_emit_store(p, len_dst, len);
  7092. return lb_addr_load(p, res);
  7093. }
  7094. lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7095. GB_ASSERT(ce->args.count == 1);
  7096. lbValue arg = lb_build_expr(p, ce->args[0]);
  7097. Type *t = base_type(arg.type);
  7098. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  7099. lbValue len = lb_soa_struct_len(p, arg);
  7100. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7101. if (is_type_tuple(tv.type)) {
  7102. lbValue rp = lb_addr_get_ptr(p, res);
  7103. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  7104. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  7105. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  7106. lb_fill_slice(p, dst, ptr, len);
  7107. }
  7108. } else {
  7109. GB_ASSERT(is_type_slice(tv.type));
  7110. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  7111. lb_fill_slice(p, res, ptr, len);
  7112. }
  7113. return lb_addr_load(p, res);
  7114. }
  7115. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  7116. ast_node(ce, CallExpr, expr);
  7117. switch (id) {
  7118. case BuiltinProc_DIRECTIVE: {
  7119. ast_node(bd, BasicDirective, ce->proc);
  7120. String name = bd->name;
  7121. GB_ASSERT(name == "location");
  7122. String procedure = p->entity->token.string;
  7123. TokenPos pos = ast_token(ce->proc).pos;
  7124. if (ce->args.count > 0) {
  7125. Ast *ident = unselector_expr(ce->args[0]);
  7126. GB_ASSERT(ident->kind == Ast_Ident);
  7127. Entity *e = entity_of_node(ident);
  7128. GB_ASSERT(e != nullptr);
  7129. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  7130. procedure = e->parent_proc_decl->entity->token.string;
  7131. } else {
  7132. procedure = str_lit("");
  7133. }
  7134. pos = e->token.pos;
  7135. }
  7136. return lb_emit_source_code_location(p, procedure, pos);
  7137. }
  7138. case BuiltinProc_type_info_of: {
  7139. Ast *arg = ce->args[0];
  7140. TypeAndValue tav = type_and_value_of_expr(arg);
  7141. if (tav.mode == Addressing_Type) {
  7142. Type *t = default_type(type_of_expr(arg));
  7143. return lb_type_info(p->module, t);
  7144. }
  7145. GB_ASSERT(is_type_typeid(tav.type));
  7146. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7147. args[0] = lb_build_expr(p, arg);
  7148. return lb_emit_runtime_call(p, "__type_info_of", args);
  7149. }
  7150. case BuiltinProc_typeid_of: {
  7151. Ast *arg = ce->args[0];
  7152. TypeAndValue tav = type_and_value_of_expr(arg);
  7153. GB_ASSERT(tav.mode == Addressing_Type);
  7154. Type *t = default_type(type_of_expr(arg));
  7155. return lb_typeid(p->module, t);
  7156. }
  7157. case BuiltinProc_len: {
  7158. lbValue v = lb_build_expr(p, ce->args[0]);
  7159. Type *t = base_type(v.type);
  7160. if (is_type_pointer(t)) {
  7161. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7162. v = lb_emit_load(p, v);
  7163. t = type_deref(t);
  7164. }
  7165. if (is_type_cstring(t)) {
  7166. return lb_cstring_len(p, v);
  7167. } else if (is_type_string(t)) {
  7168. return lb_string_len(p, v);
  7169. } else if (is_type_array(t)) {
  7170. GB_PANIC("Array lengths are constant");
  7171. } else if (is_type_slice(t)) {
  7172. return lb_slice_len(p, v);
  7173. } else if (is_type_dynamic_array(t)) {
  7174. return lb_dynamic_array_len(p, v);
  7175. } else if (is_type_map(t)) {
  7176. return lb_map_len(p, v);
  7177. } else if (is_type_soa_struct(t)) {
  7178. return lb_soa_struct_len(p, v);
  7179. }
  7180. GB_PANIC("Unreachable");
  7181. break;
  7182. }
  7183. case BuiltinProc_cap: {
  7184. lbValue v = lb_build_expr(p, ce->args[0]);
  7185. Type *t = base_type(v.type);
  7186. if (is_type_pointer(t)) {
  7187. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7188. v = lb_emit_load(p, v);
  7189. t = type_deref(t);
  7190. }
  7191. if (is_type_string(t)) {
  7192. GB_PANIC("Unreachable");
  7193. } else if (is_type_array(t)) {
  7194. GB_PANIC("Array lengths are constant");
  7195. } else if (is_type_slice(t)) {
  7196. return lb_slice_len(p, v);
  7197. } else if (is_type_dynamic_array(t)) {
  7198. return lb_dynamic_array_cap(p, v);
  7199. } else if (is_type_map(t)) {
  7200. return lb_map_cap(p, v);
  7201. } else if (is_type_soa_struct(t)) {
  7202. return lb_soa_struct_cap(p, v);
  7203. }
  7204. GB_PANIC("Unreachable");
  7205. break;
  7206. }
  7207. case BuiltinProc_swizzle: {
  7208. isize index_count = ce->args.count-1;
  7209. if (is_type_simd_vector(tv.type)) {
  7210. lbValue vec = lb_build_expr(p, ce->args[0]);
  7211. if (index_count == 0) {
  7212. return vec;
  7213. }
  7214. unsigned mask_len = cast(unsigned)index_count;
  7215. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  7216. for (isize i = 1; i < ce->args.count; i++) {
  7217. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7218. GB_ASSERT(is_type_integer(tv.type));
  7219. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7220. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  7221. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  7222. }
  7223. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  7224. LLVMValueRef v1 = vec.value;
  7225. LLVMValueRef v2 = vec.value;
  7226. lbValue res = {};
  7227. res.type = tv.type;
  7228. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  7229. return res;
  7230. }
  7231. lbAddr addr = lb_build_addr(p, ce->args[0]);
  7232. if (index_count == 0) {
  7233. return lb_addr_load(p, addr);
  7234. }
  7235. lbValue src = lb_addr_get_ptr(p, addr);
  7236. // TODO(bill): Should this be zeroed or not?
  7237. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  7238. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  7239. for (i32 i = 1; i < ce->args.count; i++) {
  7240. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7241. GB_ASSERT(is_type_integer(tv.type));
  7242. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7243. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  7244. i32 dst_index = i-1;
  7245. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  7246. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  7247. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  7248. }
  7249. return lb_addr_load(p, dst);
  7250. }
  7251. case BuiltinProc_complex: {
  7252. lbValue real = lb_build_expr(p, ce->args[0]);
  7253. lbValue imag = lb_build_expr(p, ce->args[1]);
  7254. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7255. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7256. Type *ft = base_complex_elem_type(tv.type);
  7257. real = lb_emit_conv(p, real, ft);
  7258. imag = lb_emit_conv(p, imag, ft);
  7259. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  7260. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  7261. return lb_emit_load(p, dst);
  7262. }
  7263. case BuiltinProc_quaternion: {
  7264. lbValue real = lb_build_expr(p, ce->args[0]);
  7265. lbValue imag = lb_build_expr(p, ce->args[1]);
  7266. lbValue jmag = lb_build_expr(p, ce->args[2]);
  7267. lbValue kmag = lb_build_expr(p, ce->args[3]);
  7268. // @QuaternionLayout
  7269. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7270. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7271. Type *ft = base_complex_elem_type(tv.type);
  7272. real = lb_emit_conv(p, real, ft);
  7273. imag = lb_emit_conv(p, imag, ft);
  7274. jmag = lb_emit_conv(p, jmag, ft);
  7275. kmag = lb_emit_conv(p, kmag, ft);
  7276. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  7277. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  7278. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  7279. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  7280. return lb_emit_load(p, dst);
  7281. }
  7282. case BuiltinProc_real: {
  7283. lbValue val = lb_build_expr(p, ce->args[0]);
  7284. if (is_type_complex(val.type)) {
  7285. lbValue real = lb_emit_struct_ev(p, val, 0);
  7286. return lb_emit_conv(p, real, tv.type);
  7287. } else if (is_type_quaternion(val.type)) {
  7288. // @QuaternionLayout
  7289. lbValue real = lb_emit_struct_ev(p, val, 3);
  7290. return lb_emit_conv(p, real, tv.type);
  7291. }
  7292. GB_PANIC("invalid type for real");
  7293. return {};
  7294. }
  7295. case BuiltinProc_imag: {
  7296. lbValue val = lb_build_expr(p, ce->args[0]);
  7297. if (is_type_complex(val.type)) {
  7298. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7299. return lb_emit_conv(p, imag, tv.type);
  7300. } else if (is_type_quaternion(val.type)) {
  7301. // @QuaternionLayout
  7302. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7303. return lb_emit_conv(p, imag, tv.type);
  7304. }
  7305. GB_PANIC("invalid type for imag");
  7306. return {};
  7307. }
  7308. case BuiltinProc_jmag: {
  7309. lbValue val = lb_build_expr(p, ce->args[0]);
  7310. if (is_type_quaternion(val.type)) {
  7311. // @QuaternionLayout
  7312. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7313. return lb_emit_conv(p, imag, tv.type);
  7314. }
  7315. GB_PANIC("invalid type for jmag");
  7316. return {};
  7317. }
  7318. case BuiltinProc_kmag: {
  7319. lbValue val = lb_build_expr(p, ce->args[0]);
  7320. if (is_type_quaternion(val.type)) {
  7321. // @QuaternionLayout
  7322. lbValue imag = lb_emit_struct_ev(p, val, 2);
  7323. return lb_emit_conv(p, imag, tv.type);
  7324. }
  7325. GB_PANIC("invalid type for kmag");
  7326. return {};
  7327. }
  7328. case BuiltinProc_conj: {
  7329. lbValue val = lb_build_expr(p, ce->args[0]);
  7330. lbValue res = {};
  7331. Type *t = val.type;
  7332. if (is_type_complex(t)) {
  7333. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7334. lbValue real = lb_emit_struct_ev(p, val, 0);
  7335. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7336. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7337. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  7338. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  7339. } else if (is_type_quaternion(t)) {
  7340. // @QuaternionLayout
  7341. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7342. lbValue real = lb_emit_struct_ev(p, val, 3);
  7343. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7344. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  7345. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  7346. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7347. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  7348. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  7349. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  7350. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  7351. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  7352. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  7353. }
  7354. return lb_emit_load(p, res);
  7355. }
  7356. case BuiltinProc_expand_to_tuple: {
  7357. lbValue val = lb_build_expr(p, ce->args[0]);
  7358. Type *t = base_type(val.type);
  7359. if (!is_type_tuple(tv.type)) {
  7360. if (t->kind == Type_Struct) {
  7361. GB_ASSERT(t->Struct.fields.count == 1);
  7362. return lb_emit_struct_ev(p, val, 0);
  7363. } else if (t->kind == Type_Array) {
  7364. GB_ASSERT(t->Array.count == 1);
  7365. return lb_emit_array_epi(p, val, 0);
  7366. } else {
  7367. GB_PANIC("Unknown type of expand_to_tuple");
  7368. }
  7369. }
  7370. GB_ASSERT(is_type_tuple(tv.type));
  7371. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  7372. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7373. if (t->kind == Type_Struct) {
  7374. for_array(src_index, t->Struct.fields) {
  7375. Entity *field = t->Struct.fields[src_index];
  7376. i32 field_index = field->Variable.field_index;
  7377. lbValue f = lb_emit_struct_ev(p, val, field_index);
  7378. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  7379. lb_emit_store(p, ep, f);
  7380. }
  7381. } else if (t->kind == Type_Array) {
  7382. // TODO(bill): Clean-up this code
  7383. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  7384. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  7385. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  7386. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  7387. lb_emit_store(p, ep, f);
  7388. }
  7389. } else {
  7390. GB_PANIC("Unknown type of expand_to_tuple");
  7391. }
  7392. return lb_emit_load(p, tuple);
  7393. }
  7394. case BuiltinProc_min: {
  7395. Type *t = type_of_expr(expr);
  7396. if (ce->args.count == 2) {
  7397. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7398. } else {
  7399. lbValue x = lb_build_expr(p, ce->args[0]);
  7400. for (isize i = 1; i < ce->args.count; i++) {
  7401. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  7402. }
  7403. return x;
  7404. }
  7405. }
  7406. case BuiltinProc_max: {
  7407. Type *t = type_of_expr(expr);
  7408. if (ce->args.count == 2) {
  7409. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7410. } else {
  7411. lbValue x = lb_build_expr(p, ce->args[0]);
  7412. for (isize i = 1; i < ce->args.count; i++) {
  7413. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  7414. }
  7415. return x;
  7416. }
  7417. }
  7418. case BuiltinProc_abs: {
  7419. lbValue x = lb_build_expr(p, ce->args[0]);
  7420. Type *t = x.type;
  7421. if (is_type_unsigned(t)) {
  7422. return x;
  7423. }
  7424. if (is_type_quaternion(t)) {
  7425. i64 sz = 8*type_size_of(t);
  7426. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7427. args[0] = x;
  7428. switch (sz) {
  7429. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  7430. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  7431. }
  7432. GB_PANIC("Unknown complex type");
  7433. } else if (is_type_complex(t)) {
  7434. i64 sz = 8*type_size_of(t);
  7435. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7436. args[0] = x;
  7437. switch (sz) {
  7438. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  7439. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  7440. }
  7441. GB_PANIC("Unknown complex type");
  7442. } else if (is_type_float(t)) {
  7443. i64 sz = 8*type_size_of(t);
  7444. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7445. args[0] = x;
  7446. switch (sz) {
  7447. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  7448. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  7449. }
  7450. GB_PANIC("Unknown float type");
  7451. }
  7452. lbValue zero = lb_const_nil(p->module, t);
  7453. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  7454. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  7455. return lb_emit_select(p, cond, neg, x);
  7456. }
  7457. case BuiltinProc_clamp:
  7458. return lb_emit_clamp(p, type_of_expr(expr),
  7459. lb_build_expr(p, ce->args[0]),
  7460. lb_build_expr(p, ce->args[1]),
  7461. lb_build_expr(p, ce->args[2]));
  7462. case BuiltinProc_soa_zip:
  7463. return lb_soa_zip(p, ce, tv);
  7464. case BuiltinProc_soa_unzip:
  7465. return lb_soa_unzip(p, ce, tv);
  7466. // "Intrinsics"
  7467. case BuiltinProc_alloca:
  7468. {
  7469. lbValue sz = lb_build_expr(p, ce->args[0]);
  7470. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  7471. lbValue res = {};
  7472. res.type = t_u8_ptr;
  7473. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  7474. LLVMSetAlignment(res.value, cast(unsigned)al);
  7475. return res;
  7476. }
  7477. case BuiltinProc_cpu_relax:
  7478. if (build_context.metrics.arch == TargetArch_386 ||
  7479. build_context.metrics.arch == TargetArch_amd64) {
  7480. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7481. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7482. cast(char *)"pause", 5,
  7483. cast(char *)"", 0,
  7484. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7485. LLVMInlineAsmDialectATT
  7486. );
  7487. GB_ASSERT(the_asm != nullptr);
  7488. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7489. }
  7490. return {};
  7491. case BuiltinProc_atomic_fence:
  7492. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  7493. return {};
  7494. case BuiltinProc_atomic_fence_acq:
  7495. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  7496. return {};
  7497. case BuiltinProc_atomic_fence_rel:
  7498. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  7499. return {};
  7500. case BuiltinProc_atomic_fence_acqrel:
  7501. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  7502. return {};
  7503. case BuiltinProc_volatile_store:
  7504. case BuiltinProc_atomic_store:
  7505. case BuiltinProc_atomic_store_rel:
  7506. case BuiltinProc_atomic_store_relaxed:
  7507. case BuiltinProc_atomic_store_unordered: {
  7508. lbValue dst = lb_build_expr(p, ce->args[0]);
  7509. lbValue val = lb_build_expr(p, ce->args[1]);
  7510. val = lb_emit_conv(p, val, type_deref(dst.type));
  7511. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  7512. switch (id) {
  7513. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  7514. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7515. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  7516. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7517. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7518. }
  7519. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7520. return {};
  7521. }
  7522. case BuiltinProc_volatile_load:
  7523. case BuiltinProc_atomic_load:
  7524. case BuiltinProc_atomic_load_acq:
  7525. case BuiltinProc_atomic_load_relaxed:
  7526. case BuiltinProc_atomic_load_unordered: {
  7527. lbValue dst = lb_build_expr(p, ce->args[0]);
  7528. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  7529. switch (id) {
  7530. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  7531. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7532. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  7533. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7534. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7535. }
  7536. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7537. lbValue res = {};
  7538. res.value = instr;
  7539. res.type = type_deref(dst.type);
  7540. return res;
  7541. }
  7542. case BuiltinProc_atomic_add:
  7543. case BuiltinProc_atomic_add_acq:
  7544. case BuiltinProc_atomic_add_rel:
  7545. case BuiltinProc_atomic_add_acqrel:
  7546. case BuiltinProc_atomic_add_relaxed:
  7547. case BuiltinProc_atomic_sub:
  7548. case BuiltinProc_atomic_sub_acq:
  7549. case BuiltinProc_atomic_sub_rel:
  7550. case BuiltinProc_atomic_sub_acqrel:
  7551. case BuiltinProc_atomic_sub_relaxed:
  7552. case BuiltinProc_atomic_and:
  7553. case BuiltinProc_atomic_and_acq:
  7554. case BuiltinProc_atomic_and_rel:
  7555. case BuiltinProc_atomic_and_acqrel:
  7556. case BuiltinProc_atomic_and_relaxed:
  7557. case BuiltinProc_atomic_nand:
  7558. case BuiltinProc_atomic_nand_acq:
  7559. case BuiltinProc_atomic_nand_rel:
  7560. case BuiltinProc_atomic_nand_acqrel:
  7561. case BuiltinProc_atomic_nand_relaxed:
  7562. case BuiltinProc_atomic_or:
  7563. case BuiltinProc_atomic_or_acq:
  7564. case BuiltinProc_atomic_or_rel:
  7565. case BuiltinProc_atomic_or_acqrel:
  7566. case BuiltinProc_atomic_or_relaxed:
  7567. case BuiltinProc_atomic_xor:
  7568. case BuiltinProc_atomic_xor_acq:
  7569. case BuiltinProc_atomic_xor_rel:
  7570. case BuiltinProc_atomic_xor_acqrel:
  7571. case BuiltinProc_atomic_xor_relaxed:
  7572. case BuiltinProc_atomic_xchg:
  7573. case BuiltinProc_atomic_xchg_acq:
  7574. case BuiltinProc_atomic_xchg_rel:
  7575. case BuiltinProc_atomic_xchg_acqrel:
  7576. case BuiltinProc_atomic_xchg_relaxed: {
  7577. lbValue dst = lb_build_expr(p, ce->args[0]);
  7578. lbValue val = lb_build_expr(p, ce->args[1]);
  7579. val = lb_emit_conv(p, val, type_deref(dst.type));
  7580. LLVMAtomicRMWBinOp op = {};
  7581. LLVMAtomicOrdering ordering = {};
  7582. switch (id) {
  7583. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7584. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  7585. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  7586. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7587. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  7588. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7589. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  7590. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  7591. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7592. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  7593. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7594. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  7595. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  7596. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7597. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  7598. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7599. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  7600. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  7601. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7602. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  7603. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7604. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  7605. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  7606. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7607. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  7608. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7609. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  7610. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  7611. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7612. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  7613. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7614. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  7615. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  7616. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7617. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  7618. }
  7619. lbValue res = {};
  7620. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  7621. res.type = tv.type;
  7622. return res;
  7623. }
  7624. case BuiltinProc_atomic_cxchg:
  7625. case BuiltinProc_atomic_cxchg_acq:
  7626. case BuiltinProc_atomic_cxchg_rel:
  7627. case BuiltinProc_atomic_cxchg_acqrel:
  7628. case BuiltinProc_atomic_cxchg_relaxed:
  7629. case BuiltinProc_atomic_cxchg_failrelaxed:
  7630. case BuiltinProc_atomic_cxchg_failacq:
  7631. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  7632. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  7633. case BuiltinProc_atomic_cxchgweak:
  7634. case BuiltinProc_atomic_cxchgweak_acq:
  7635. case BuiltinProc_atomic_cxchgweak_rel:
  7636. case BuiltinProc_atomic_cxchgweak_acqrel:
  7637. case BuiltinProc_atomic_cxchgweak_relaxed:
  7638. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  7639. case BuiltinProc_atomic_cxchgweak_failacq:
  7640. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  7641. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  7642. Type *type = expr->tav.type;
  7643. lbValue address = lb_build_expr(p, ce->args[0]);
  7644. Type *elem = type_deref(address.type);
  7645. lbValue old_value = lb_build_expr(p, ce->args[1]);
  7646. lbValue new_value = lb_build_expr(p, ce->args[2]);
  7647. old_value = lb_emit_conv(p, old_value, elem);
  7648. new_value = lb_emit_conv(p, new_value, elem);
  7649. LLVMAtomicOrdering success_ordering = {};
  7650. LLVMAtomicOrdering failure_ordering = {};
  7651. LLVMBool weak = false;
  7652. switch (id) {
  7653. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7654. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7655. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7656. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7657. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7658. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7659. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  7660. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7661. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7662. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7663. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7664. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7665. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7666. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7667. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7668. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  7669. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7670. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7671. }
  7672. // TODO(bill): Figure out how to make it weak
  7673. LLVMBool single_threaded = weak;
  7674. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  7675. p->builder, address.value,
  7676. old_value.value, new_value.value,
  7677. success_ordering,
  7678. failure_ordering,
  7679. single_threaded
  7680. );
  7681. GB_ASSERT(tv.type->kind == Type_Tuple);
  7682. Type *fix_typed = alloc_type_tuple();
  7683. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  7684. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  7685. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  7686. lbValue res = {};
  7687. res.value = value;
  7688. res.type = fix_typed;
  7689. return res;
  7690. }
  7691. case BuiltinProc_type_equal_proc:
  7692. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  7693. case BuiltinProc_type_hasher_proc:
  7694. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  7695. }
  7696. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  7697. return {};
  7698. }
  7699. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  7700. switch (param_value.kind) {
  7701. case ParameterValue_Constant:
  7702. if (is_type_constant_type(parameter_type)) {
  7703. return lb_const_value(p->module, parameter_type, param_value.value);
  7704. } else {
  7705. ExactValue ev = param_value.value;
  7706. lbValue arg = {};
  7707. Type *type = type_of_expr(param_value.original_ast_expr);
  7708. if (type != nullptr) {
  7709. arg = lb_const_value(p->module, type, ev);
  7710. } else {
  7711. arg = lb_const_value(p->module, parameter_type, param_value.value);
  7712. }
  7713. return lb_emit_conv(p, arg, parameter_type);
  7714. }
  7715. case ParameterValue_Nil:
  7716. return lb_const_nil(p->module, parameter_type);
  7717. case ParameterValue_Location:
  7718. {
  7719. String proc_name = {};
  7720. if (p->entity != nullptr) {
  7721. proc_name = p->entity->token.string;
  7722. }
  7723. return lb_emit_source_code_location(p, proc_name, pos);
  7724. }
  7725. case ParameterValue_Value:
  7726. return lb_build_expr(p, param_value.ast_value);
  7727. }
  7728. return lb_const_nil(p->module, parameter_type);
  7729. }
  7730. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  7731. lbModule *m = p->module;
  7732. TypeAndValue tv = type_and_value_of_expr(expr);
  7733. ast_node(ce, CallExpr, expr);
  7734. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  7735. AddressingMode proc_mode = proc_tv.mode;
  7736. if (proc_mode == Addressing_Type) {
  7737. GB_ASSERT(ce->args.count == 1);
  7738. lbValue x = lb_build_expr(p, ce->args[0]);
  7739. lbValue y = lb_emit_conv(p, x, tv.type);
  7740. return y;
  7741. }
  7742. Ast *pexpr = unparen_expr(ce->proc);
  7743. if (proc_mode == Addressing_Builtin) {
  7744. Entity *e = entity_of_node(pexpr);
  7745. BuiltinProcId id = BuiltinProc_Invalid;
  7746. if (e != nullptr) {
  7747. id = cast(BuiltinProcId)e->Builtin.id;
  7748. } else {
  7749. id = BuiltinProc_DIRECTIVE;
  7750. }
  7751. return lb_build_builtin_proc(p, expr, tv, id);
  7752. }
  7753. // NOTE(bill): Regular call
  7754. lbValue value = {};
  7755. Ast *proc_expr = unparen_expr(ce->proc);
  7756. if (proc_expr->tav.mode == Addressing_Constant) {
  7757. ExactValue v = proc_expr->tav.value;
  7758. switch (v.kind) {
  7759. case ExactValue_Integer:
  7760. {
  7761. u64 u = big_int_to_u64(&v.value_integer);
  7762. lbValue x = {};
  7763. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7764. x.type = t_uintptr;
  7765. x = lb_emit_conv(p, x, t_rawptr);
  7766. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7767. break;
  7768. }
  7769. case ExactValue_Pointer:
  7770. {
  7771. u64 u = cast(u64)v.value_pointer;
  7772. lbValue x = {};
  7773. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7774. x.type = t_uintptr;
  7775. x = lb_emit_conv(p, x, t_rawptr);
  7776. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7777. break;
  7778. }
  7779. }
  7780. }
  7781. Entity *proc_entity = entity_of_node(proc_expr);
  7782. if (proc_entity != nullptr) {
  7783. if (proc_entity->flags & EntityFlag_Disabled) {
  7784. return {};
  7785. }
  7786. }
  7787. if (value.value == nullptr) {
  7788. value = lb_build_expr(p, proc_expr);
  7789. }
  7790. GB_ASSERT(value.value != nullptr);
  7791. Type *proc_type_ = base_type(value.type);
  7792. GB_ASSERT(proc_type_->kind == Type_Proc);
  7793. TypeProc *pt = &proc_type_->Proc;
  7794. set_procedure_abi_types(proc_type_);
  7795. if (is_call_expr_field_value(ce)) {
  7796. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  7797. for_array(arg_index, ce->args) {
  7798. Ast *arg = ce->args[arg_index];
  7799. ast_node(fv, FieldValue, arg);
  7800. GB_ASSERT(fv->field->kind == Ast_Ident);
  7801. String name = fv->field->Ident.token.string;
  7802. isize index = lookup_procedure_parameter(pt, name);
  7803. GB_ASSERT(index >= 0);
  7804. TypeAndValue tav = type_and_value_of_expr(fv->value);
  7805. if (tav.mode == Addressing_Type) {
  7806. args[index] = lb_const_nil(m, tav.type);
  7807. } else {
  7808. args[index] = lb_build_expr(p, fv->value);
  7809. }
  7810. }
  7811. TypeTuple *params = &pt->params->Tuple;
  7812. for (isize i = 0; i < args.count; i++) {
  7813. Entity *e = params->variables[i];
  7814. if (e->kind == Entity_TypeName) {
  7815. args[i] = lb_const_nil(m, e->type);
  7816. } else if (e->kind == Entity_Constant) {
  7817. continue;
  7818. } else {
  7819. GB_ASSERT(e->kind == Entity_Variable);
  7820. if (args[i].value == nullptr) {
  7821. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7822. } else {
  7823. args[i] = lb_emit_conv(p, args[i], e->type);
  7824. }
  7825. }
  7826. }
  7827. for (isize i = 0; i < args.count; i++) {
  7828. Entity *e = params->variables[i];
  7829. if (args[i].type == nullptr) {
  7830. continue;
  7831. } else if (is_type_untyped_nil(args[i].type)) {
  7832. args[i] = lb_const_nil(m, e->type);
  7833. } else if (is_type_untyped_undef(args[i].type)) {
  7834. args[i] = lb_const_undef(m, e->type);
  7835. }
  7836. }
  7837. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  7838. }
  7839. isize arg_index = 0;
  7840. isize arg_count = 0;
  7841. for_array(i, ce->args) {
  7842. Ast *arg = ce->args[i];
  7843. TypeAndValue tav = type_and_value_of_expr(arg);
  7844. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  7845. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  7846. Type *at = tav.type;
  7847. if (at->kind == Type_Tuple) {
  7848. arg_count += at->Tuple.variables.count;
  7849. } else {
  7850. arg_count++;
  7851. }
  7852. }
  7853. isize param_count = 0;
  7854. if (pt->params) {
  7855. GB_ASSERT(pt->params->kind == Type_Tuple);
  7856. param_count = pt->params->Tuple.variables.count;
  7857. }
  7858. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  7859. isize variadic_index = pt->variadic_index;
  7860. bool variadic = pt->variadic && variadic_index >= 0;
  7861. bool vari_expand = ce->ellipsis.pos.line != 0;
  7862. bool is_c_vararg = pt->c_vararg;
  7863. String proc_name = {};
  7864. if (p->entity != nullptr) {
  7865. proc_name = p->entity->token.string;
  7866. }
  7867. TokenPos pos = ast_token(ce->proc).pos;
  7868. TypeTuple *param_tuple = nullptr;
  7869. if (pt->params) {
  7870. GB_ASSERT(pt->params->kind == Type_Tuple);
  7871. param_tuple = &pt->params->Tuple;
  7872. }
  7873. for_array(i, ce->args) {
  7874. Ast *arg = ce->args[i];
  7875. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  7876. if (arg_tv.mode == Addressing_Type) {
  7877. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  7878. } else {
  7879. lbValue a = lb_build_expr(p, arg);
  7880. Type *at = a.type;
  7881. if (at->kind == Type_Tuple) {
  7882. for_array(i, at->Tuple.variables) {
  7883. Entity *e = at->Tuple.variables[i];
  7884. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  7885. args[arg_index++] = v;
  7886. }
  7887. } else {
  7888. args[arg_index++] = a;
  7889. }
  7890. }
  7891. }
  7892. if (param_count > 0) {
  7893. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  7894. GB_ASSERT(param_count < 1000000);
  7895. if (arg_count < param_count) {
  7896. isize end = cast(isize)param_count;
  7897. if (variadic) {
  7898. end = variadic_index;
  7899. }
  7900. while (arg_index < end) {
  7901. Entity *e = param_tuple->variables[arg_index];
  7902. GB_ASSERT(e->kind == Entity_Variable);
  7903. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7904. }
  7905. }
  7906. if (is_c_vararg) {
  7907. GB_ASSERT(variadic);
  7908. GB_ASSERT(!vari_expand);
  7909. isize i = 0;
  7910. for (; i < variadic_index; i++) {
  7911. Entity *e = param_tuple->variables[i];
  7912. if (e->kind == Entity_Variable) {
  7913. args[i] = lb_emit_conv(p, args[i], e->type);
  7914. }
  7915. }
  7916. Type *variadic_type = param_tuple->variables[i]->type;
  7917. GB_ASSERT(is_type_slice(variadic_type));
  7918. variadic_type = base_type(variadic_type)->Slice.elem;
  7919. if (!is_type_any(variadic_type)) {
  7920. for (; i < arg_count; i++) {
  7921. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7922. }
  7923. } else {
  7924. for (; i < arg_count; i++) {
  7925. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  7926. }
  7927. }
  7928. } else if (variadic) {
  7929. isize i = 0;
  7930. for (; i < variadic_index; i++) {
  7931. Entity *e = param_tuple->variables[i];
  7932. if (e->kind == Entity_Variable) {
  7933. args[i] = lb_emit_conv(p, args[i], e->type);
  7934. }
  7935. }
  7936. if (!vari_expand) {
  7937. Type *variadic_type = param_tuple->variables[i]->type;
  7938. GB_ASSERT(is_type_slice(variadic_type));
  7939. variadic_type = base_type(variadic_type)->Slice.elem;
  7940. for (; i < arg_count; i++) {
  7941. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7942. }
  7943. }
  7944. } else {
  7945. for (isize i = 0; i < param_count; i++) {
  7946. Entity *e = param_tuple->variables[i];
  7947. if (e->kind == Entity_Variable) {
  7948. if (args[i].value == nullptr) {
  7949. continue;
  7950. }
  7951. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  7952. args[i] = lb_emit_conv(p, args[i], e->type);
  7953. }
  7954. }
  7955. }
  7956. if (variadic && !vari_expand && !is_c_vararg) {
  7957. // variadic call argument generation
  7958. Type *slice_type = param_tuple->variables[variadic_index]->type;
  7959. Type *elem_type = base_type(slice_type)->Slice.elem;
  7960. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  7961. isize slice_len = arg_count+1 - (variadic_index+1);
  7962. if (slice_len > 0) {
  7963. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  7964. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  7965. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  7966. lb_emit_store(p, addr, args[i]);
  7967. }
  7968. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  7969. lbValue len = lb_const_int(m, t_int, slice_len);
  7970. lb_fill_slice(p, slice, base_elem, len);
  7971. }
  7972. arg_count = param_count;
  7973. args[variadic_index] = lb_addr_load(p, slice);
  7974. }
  7975. }
  7976. if (variadic && variadic_index+1 < param_count) {
  7977. for (isize i = variadic_index+1; i < param_count; i++) {
  7978. Entity *e = param_tuple->variables[i];
  7979. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7980. }
  7981. }
  7982. isize final_count = param_count;
  7983. if (is_c_vararg) {
  7984. final_count = arg_count;
  7985. }
  7986. if (param_tuple != nullptr) {
  7987. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  7988. Entity *e = param_tuple->variables[i];
  7989. if (args[i].type == nullptr) {
  7990. continue;
  7991. } else if (is_type_untyped_nil(args[i].type)) {
  7992. args[i] = lb_const_nil(m, e->type);
  7993. } else if (is_type_untyped_undef(args[i].type)) {
  7994. args[i] = lb_const_undef(m, e->type);
  7995. }
  7996. }
  7997. }
  7998. auto call_args = array_slice(args, 0, final_count);
  7999. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  8000. }
  8001. bool lb_is_const(lbValue value) {
  8002. LLVMValueRef v = value.value;
  8003. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  8004. // TODO(bill): Is this correct behaviour?
  8005. return true;
  8006. }
  8007. if (LLVMIsConstant(v)) {
  8008. return true;
  8009. }
  8010. return false;
  8011. }
  8012. bool lb_is_const_or_global(lbValue value) {
  8013. if (lb_is_const(value)) {
  8014. return true;
  8015. }
  8016. if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
  8017. LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
  8018. if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
  8019. return false;
  8020. }
  8021. LLVMTypeRef elem = LLVMGetElementType(t);
  8022. return lb_is_type_kind(elem, LLVMFunctionTypeKind);
  8023. }
  8024. return false;
  8025. }
  8026. bool lb_is_const_nil(lbValue value) {
  8027. LLVMValueRef v = value.value;
  8028. if (LLVMIsConstant(v)) {
  8029. if (LLVMIsAConstantAggregateZero(v)) {
  8030. return true;
  8031. } else if (LLVMIsAConstantPointerNull(v)) {
  8032. return true;
  8033. }
  8034. }
  8035. return false;
  8036. }
  8037. String lb_get_const_string(lbModule *m, lbValue value) {
  8038. GB_ASSERT(lb_is_const(value));
  8039. Type *t = base_type(value.type);
  8040. GB_ASSERT(are_types_identical(t, t_string));
  8041. unsigned ptr_indices[1] = {0};
  8042. unsigned len_indices[1] = {1};
  8043. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  8044. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  8045. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  8046. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  8047. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  8048. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  8049. size_t length = 0;
  8050. char const *text = LLVMGetAsString(underlying_ptr, &length);
  8051. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  8052. return make_string(cast(u8 const *)text, real_length);
  8053. }
  8054. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  8055. GB_ASSERT(is_type_pointer(addr.type));
  8056. Type *type = type_deref(addr.type);
  8057. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  8058. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  8059. }
  8060. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  8061. AstPackage *pkg = m->info->runtime_package;
  8062. Entity *e = scope_lookup_current(pkg->scope, name);
  8063. lbValue *found = nullptr;
  8064. if (m != e->code_gen_module) {
  8065. gb_mutex_lock(&m->mutex);
  8066. }
  8067. GB_ASSERT(e->code_gen_module != nullptr);
  8068. found = map_get(&e->code_gen_module->values, hash_entity(e));
  8069. if (m != e->code_gen_module) {
  8070. gb_mutex_unlock(&m->mutex);
  8071. }
  8072. GB_ASSERT(found != nullptr);
  8073. return found->value;
  8074. }
  8075. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  8076. Type *vt = core_type(value.type);
  8077. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  8078. // TODO(bill): lb_emit_byte_swap
  8079. lbValue res = {};
  8080. res.type = platform_type;
  8081. res.value = value.value;
  8082. int sz = cast(int)type_size_of(vt);
  8083. if (sz > 1) {
  8084. if (is_type_float(platform_type)) {
  8085. String name = {};
  8086. switch (sz) {
  8087. case 4: name = str_lit("bswap_f32"); break;
  8088. case 8: name = str_lit("bswap_f64"); break;
  8089. default: GB_PANIC("unhandled byteswap size"); break;
  8090. }
  8091. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  8092. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  8093. } else {
  8094. GB_ASSERT(is_type_integer(platform_type));
  8095. String name = {};
  8096. switch (sz) {
  8097. case 2: name = str_lit("bswap_16"); break;
  8098. case 4: name = str_lit("bswap_32"); break;
  8099. case 8: name = str_lit("bswap_64"); break;
  8100. case 16: name = str_lit("bswap_128"); break;
  8101. default: GB_PANIC("unhandled byteswap size"); break;
  8102. }
  8103. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  8104. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  8105. }
  8106. }
  8107. return res;
  8108. }
  8109. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  8110. lbLoopData data = {};
  8111. lbValue max = lb_const_int(p->module, t_int, count);
  8112. data.idx_addr = lb_add_local_generated(p, index_type, true);
  8113. data.body = lb_create_block(p, "loop.body");
  8114. data.done = lb_create_block(p, "loop.done");
  8115. data.loop = lb_create_block(p, "loop.loop");
  8116. lb_emit_jump(p, data.loop);
  8117. lb_start_block(p, data.loop);
  8118. data.idx = lb_addr_load(p, data.idx_addr);
  8119. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  8120. lb_emit_if(p, cond, data.body, data.done);
  8121. lb_start_block(p, data.body);
  8122. return data;
  8123. }
  8124. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  8125. if (data.idx_addr.addr.value != nullptr) {
  8126. lb_emit_increment(p, data.idx_addr.addr);
  8127. lb_emit_jump(p, data.loop);
  8128. lb_start_block(p, data.done);
  8129. }
  8130. }
  8131. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  8132. lbValue res = {};
  8133. res.type = t_llvm_bool;
  8134. Type *t = x.type;
  8135. if (is_type_pointer(t)) {
  8136. if (op_kind == Token_CmpEq) {
  8137. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8138. } else if (op_kind == Token_NotEq) {
  8139. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8140. }
  8141. return res;
  8142. } else if (is_type_cstring(t)) {
  8143. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  8144. if (op_kind == Token_CmpEq) {
  8145. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  8146. } else if (op_kind == Token_NotEq) {
  8147. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  8148. }
  8149. return res;
  8150. } else if (is_type_proc(t)) {
  8151. if (op_kind == Token_CmpEq) {
  8152. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8153. } else if (op_kind == Token_NotEq) {
  8154. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8155. }
  8156. return res;
  8157. } else if (is_type_any(t)) {
  8158. // TODO(bill): is this correct behaviour for nil comparison for any?
  8159. lbValue data = lb_emit_struct_ev(p, x, 0);
  8160. lbValue ti = lb_emit_struct_ev(p, x, 1);
  8161. if (op_kind == Token_CmpEq) {
  8162. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  8163. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  8164. res.value = LLVMBuildOr(p->builder, a, b, "");
  8165. return res;
  8166. } else if (op_kind == Token_NotEq) {
  8167. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  8168. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  8169. res.value = LLVMBuildAnd(p->builder, a, b, "");
  8170. return res;
  8171. }
  8172. } else if (is_type_slice(t)) {
  8173. lbValue len = lb_emit_struct_ev(p, x, 1);
  8174. if (op_kind == Token_CmpEq) {
  8175. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8176. return res;
  8177. } else if (op_kind == Token_NotEq) {
  8178. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8179. return res;
  8180. }
  8181. } else if (is_type_dynamic_array(t)) {
  8182. lbValue cap = lb_emit_struct_ev(p, x, 2);
  8183. if (op_kind == Token_CmpEq) {
  8184. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8185. return res;
  8186. } else if (op_kind == Token_NotEq) {
  8187. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8188. return res;
  8189. }
  8190. } else if (is_type_map(t)) {
  8191. lbValue cap = lb_map_cap(p, x);
  8192. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  8193. } else if (is_type_union(t)) {
  8194. if (type_size_of(t) == 0) {
  8195. if (op_kind == Token_CmpEq) {
  8196. return lb_const_bool(p->module, t_llvm_bool, true);
  8197. } else if (op_kind == Token_NotEq) {
  8198. return lb_const_bool(p->module, t_llvm_bool, false);
  8199. }
  8200. } else {
  8201. lbValue tag = lb_emit_union_tag_value(p, x);
  8202. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  8203. }
  8204. } else if (is_type_typeid(t)) {
  8205. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  8206. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  8207. } else if (is_type_soa_struct(t)) {
  8208. Type *bt = base_type(t);
  8209. if (bt->Struct.soa_kind == StructSoa_Slice) {
  8210. lbValue len = lb_soa_struct_len(p, x);
  8211. if (op_kind == Token_CmpEq) {
  8212. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8213. return res;
  8214. } else if (op_kind == Token_NotEq) {
  8215. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8216. return res;
  8217. }
  8218. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  8219. lbValue cap = lb_soa_struct_cap(p, x);
  8220. if (op_kind == Token_CmpEq) {
  8221. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8222. return res;
  8223. } else if (op_kind == Token_NotEq) {
  8224. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8225. return res;
  8226. }
  8227. }
  8228. } else if (is_type_struct(t) && type_has_nil(t)) {
  8229. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8230. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  8231. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8232. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  8233. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  8234. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  8235. return res;
  8236. }
  8237. return {};
  8238. }
  8239. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  8240. Type *original_type = type;
  8241. type = base_type(type);
  8242. GB_ASSERT(is_type_comparable(type));
  8243. Type *pt = alloc_type_pointer(type);
  8244. LLVMTypeRef ptr_type = lb_type(m, pt);
  8245. auto key = hash_type(type);
  8246. lbProcedure **found = map_get(&m->equal_procs, key);
  8247. lbProcedure *compare_proc = nullptr;
  8248. if (found) {
  8249. compare_proc = *found;
  8250. GB_ASSERT(compare_proc != nullptr);
  8251. return {compare_proc->value, compare_proc->type};
  8252. }
  8253. static u32 proc_index = 0;
  8254. char buf[16] = {};
  8255. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  8256. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8257. String proc_name = make_string_c(str);
  8258. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  8259. map_set(&m->equal_procs, key, p);
  8260. lb_begin_procedure_body(p);
  8261. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8262. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8263. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  8264. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  8265. lbValue lhs = {x, pt};
  8266. lbValue rhs = {y, pt};
  8267. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  8268. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  8269. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  8270. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  8271. lb_start_block(p, block_same_ptr);
  8272. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8273. lb_start_block(p, block_diff_ptr);
  8274. if (type->kind == Type_Struct) {
  8275. type_set_offsets(type);
  8276. lbBlock *block_false = lb_create_block(p, "bfalse");
  8277. lbValue res = lb_const_bool(m, t_bool, true);
  8278. for_array(i, type->Struct.fields) {
  8279. lbBlock *next_block = lb_create_block(p, "btrue");
  8280. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  8281. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  8282. lbValue left = lb_emit_load(p, pleft);
  8283. lbValue right = lb_emit_load(p, pright);
  8284. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8285. lb_emit_if(p, ok, next_block, block_false);
  8286. lb_emit_jump(p, next_block);
  8287. lb_start_block(p, next_block);
  8288. }
  8289. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8290. lb_start_block(p, block_false);
  8291. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  8292. } else {
  8293. lbValue left = lb_emit_load(p, lhs);
  8294. lbValue right = lb_emit_load(p, rhs);
  8295. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8296. ok = lb_emit_conv(p, ok, t_bool);
  8297. LLVMBuildRet(p->builder, ok.value);
  8298. }
  8299. lb_end_procedure_body(p);
  8300. compare_proc = p;
  8301. return {compare_proc->value, compare_proc->type};
  8302. }
  8303. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  8304. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  8305. i64 sz = type_size_of(type);
  8306. if (1 <= sz && sz <= 16) {
  8307. char name[20] = {};
  8308. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  8309. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8310. args[0] = data;
  8311. args[1] = seed;
  8312. return lb_emit_runtime_call(p, name, args);
  8313. }
  8314. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8315. args[0] = data;
  8316. args[1] = seed;
  8317. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  8318. return lb_emit_runtime_call(p, "default_hasher_n", args);
  8319. }
  8320. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  8321. Type *original_type = type;
  8322. type = core_type(type);
  8323. GB_ASSERT(is_type_valid_for_keys(type));
  8324. Type *pt = alloc_type_pointer(type);
  8325. LLVMTypeRef ptr_type = lb_type(m, pt);
  8326. auto key = hash_type(type);
  8327. lbProcedure **found = map_get(&m->hasher_procs, key);
  8328. if (found) {
  8329. GB_ASSERT(*found != nullptr);
  8330. return {(*found)->value, (*found)->type};
  8331. }
  8332. static u32 proc_index = 0;
  8333. char buf[16] = {};
  8334. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  8335. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8336. String proc_name = make_string_c(str);
  8337. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  8338. map_set(&m->hasher_procs, key, p);
  8339. lb_begin_procedure_body(p);
  8340. defer (lb_end_procedure_body(p));
  8341. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8342. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8343. lbValue data = {x, t_rawptr};
  8344. lbValue seed = {y, t_uintptr};
  8345. if (is_type_simple_compare(type)) {
  8346. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  8347. LLVMBuildRet(p->builder, res.value);
  8348. return {p->value, p->type};
  8349. }
  8350. if (type->kind == Type_Struct) {
  8351. type_set_offsets(type);
  8352. data = lb_emit_conv(p, data, t_u8_ptr);
  8353. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8354. for_array(i, type->Struct.fields) {
  8355. i64 offset = type->Struct.offsets[i];
  8356. Entity *field = type->Struct.fields[i];
  8357. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  8358. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  8359. args[0] = ptr;
  8360. args[1] = seed;
  8361. seed = lb_emit_call(p, field_hasher, args);
  8362. }
  8363. LLVMBuildRet(p->builder, seed.value);
  8364. } else if (type->kind == Type_Array) {
  8365. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  8366. lb_addr_store(p, pres, seed);
  8367. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8368. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  8369. auto loop_data = lb_loop_start(p, type->Array.count, t_i32);
  8370. data = lb_emit_conv(p, data, pt);
  8371. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8372. args[0] = ptr;
  8373. args[1] = lb_addr_load(p, pres);
  8374. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8375. lb_addr_store(p, pres, new_seed);
  8376. lb_loop_end(p, loop_data);
  8377. lbValue res = lb_addr_load(p, pres);
  8378. LLVMBuildRet(p->builder, res.value);
  8379. } else if (type->kind == Type_EnumeratedArray) {
  8380. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  8381. lb_addr_store(p, res, seed);
  8382. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8383. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  8384. auto loop_data = lb_loop_start(p, type->EnumeratedArray.count, t_i32);
  8385. data = lb_emit_conv(p, data, pt);
  8386. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8387. args[0] = ptr;
  8388. args[1] = lb_addr_load(p, res);
  8389. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8390. lb_addr_store(p, res, new_seed);
  8391. lb_loop_end(p, loop_data);
  8392. lbValue vres = lb_addr_load(p, res);
  8393. LLVMBuildRet(p->builder, vres.value);
  8394. } else if (is_type_cstring(type)) {
  8395. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8396. args[0] = data;
  8397. args[1] = seed;
  8398. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  8399. LLVMBuildRet(p->builder, res.value);
  8400. } else if (is_type_string(type)) {
  8401. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8402. args[0] = data;
  8403. args[1] = seed;
  8404. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  8405. LLVMBuildRet(p->builder, res.value);
  8406. } else {
  8407. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  8408. }
  8409. return {p->value, p->type};
  8410. }
  8411. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  8412. Type *a = core_type(left.type);
  8413. Type *b = core_type(right.type);
  8414. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  8415. lbValue nil_check = {};
  8416. if (is_type_untyped_nil(left.type)) {
  8417. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  8418. } else if (is_type_untyped_nil(right.type)) {
  8419. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  8420. }
  8421. if (nil_check.value != nullptr) {
  8422. return nil_check;
  8423. }
  8424. if (are_types_identical(a, b)) {
  8425. // NOTE(bill): No need for a conversion
  8426. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  8427. left = lb_emit_conv(p, left, right.type);
  8428. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  8429. right = lb_emit_conv(p, right, left.type);
  8430. } else {
  8431. Type *lt = left.type;
  8432. Type *rt = right.type;
  8433. // if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  8434. // Type *blt = base_type(lt);
  8435. // Type *brt = base_type(rt);
  8436. // i64 bits = gb_max(blt->BitSet.bits, brt->BitSet.bits);
  8437. // i64 bytes = bits / 8;
  8438. // switch (bytes) {
  8439. // case 1:
  8440. // left = lb_emit_conv(p, left, t_u8);
  8441. // right = lb_emit_conv(p, right, t_u8);
  8442. // break;
  8443. // case 2:
  8444. // left = lb_emit_conv(p, left, t_u16);
  8445. // right = lb_emit_conv(p, right, t_u16);
  8446. // break;
  8447. // case 4:
  8448. // left = lb_emit_conv(p, left, t_u32);
  8449. // right = lb_emit_conv(p, right, t_u32);
  8450. // break;
  8451. // case 8:
  8452. // left = lb_emit_conv(p, left, t_u64);
  8453. // right = lb_emit_conv(p, right, t_u64);
  8454. // break;
  8455. // default: GB_PANIC("Unknown integer size"); break;
  8456. // }
  8457. // }
  8458. lt = left.type;
  8459. rt = right.type;
  8460. i64 ls = type_size_of(lt);
  8461. i64 rs = type_size_of(rt);
  8462. if (ls < rs) {
  8463. left = lb_emit_conv(p, left, rt);
  8464. } else if (ls > rs) {
  8465. right = lb_emit_conv(p, right, lt);
  8466. } else {
  8467. right = lb_emit_conv(p, right, lt);
  8468. }
  8469. }
  8470. if (is_type_array(a)) {
  8471. Type *tl = base_type(a);
  8472. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  8473. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  8474. TokenKind cmp_op = Token_And;
  8475. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  8476. if (op_kind == Token_NotEq) {
  8477. res = lb_const_bool(p->module, t_llvm_bool, false);
  8478. cmp_op = Token_Or;
  8479. } else if (op_kind == Token_CmpEq) {
  8480. res = lb_const_bool(p->module, t_llvm_bool, true);
  8481. cmp_op = Token_And;
  8482. }
  8483. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  8484. i32 count = cast(i32)tl->Array.count;
  8485. if (inline_array_arith) {
  8486. // inline
  8487. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8488. lb_addr_store(p, val, res);
  8489. for (i32 i = 0; i < count; i++) {
  8490. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  8491. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  8492. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8493. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8494. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8495. }
  8496. return lb_addr_load(p, val);
  8497. } else {
  8498. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  8499. // TODO(bill): Test to see if this is actually faster!!!!
  8500. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8501. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8502. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  8503. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  8504. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  8505. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  8506. return lb_emit_conv(p, res, t_bool);
  8507. } else {
  8508. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8509. lb_addr_store(p, val, res);
  8510. auto loop_data = lb_loop_start(p, count, t_i32);
  8511. {
  8512. lbValue i = loop_data.idx;
  8513. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  8514. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  8515. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8516. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8517. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8518. }
  8519. lb_loop_end(p, loop_data);
  8520. return lb_addr_load(p, val);
  8521. }
  8522. }
  8523. }
  8524. if (is_type_struct(a) && is_type_comparable(a)) {
  8525. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  8526. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  8527. lbValue res = {};
  8528. if (is_type_simple_compare(a)) {
  8529. // TODO(bill): Test to see if this is actually faster!!!!
  8530. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8531. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8532. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8533. args[2] = lb_const_int(p->module, t_int, type_size_of(a));
  8534. res = lb_emit_runtime_call(p, "memory_equal", args);
  8535. } else {
  8536. lbValue value = lb_get_equal_proc_for_type(p->module, a);
  8537. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8538. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8539. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8540. res = lb_emit_call(p, value, args);
  8541. }
  8542. if (op_kind == Token_NotEq) {
  8543. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  8544. }
  8545. return res;
  8546. }
  8547. if (is_type_string(a)) {
  8548. if (is_type_cstring(a)) {
  8549. left = lb_emit_conv(p, left, t_string);
  8550. right = lb_emit_conv(p, right, t_string);
  8551. }
  8552. char const *runtime_procedure = nullptr;
  8553. switch (op_kind) {
  8554. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  8555. case Token_NotEq: runtime_procedure = "string_ne"; break;
  8556. case Token_Lt: runtime_procedure = "string_lt"; break;
  8557. case Token_Gt: runtime_procedure = "string_gt"; break;
  8558. case Token_LtEq: runtime_procedure = "string_le"; break;
  8559. case Token_GtEq: runtime_procedure = "string_gt"; break;
  8560. }
  8561. GB_ASSERT(runtime_procedure != nullptr);
  8562. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8563. args[0] = left;
  8564. args[1] = right;
  8565. return lb_emit_runtime_call(p, runtime_procedure, args);
  8566. }
  8567. if (is_type_complex(a)) {
  8568. char const *runtime_procedure = "";
  8569. i64 sz = 8*type_size_of(a);
  8570. switch (sz) {
  8571. case 64:
  8572. switch (op_kind) {
  8573. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  8574. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  8575. }
  8576. break;
  8577. case 128:
  8578. switch (op_kind) {
  8579. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  8580. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  8581. }
  8582. break;
  8583. }
  8584. GB_ASSERT(runtime_procedure != nullptr);
  8585. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8586. args[0] = left;
  8587. args[1] = right;
  8588. return lb_emit_runtime_call(p, runtime_procedure, args);
  8589. }
  8590. if (is_type_quaternion(a)) {
  8591. char const *runtime_procedure = "";
  8592. i64 sz = 8*type_size_of(a);
  8593. switch (sz) {
  8594. case 128:
  8595. switch (op_kind) {
  8596. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  8597. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  8598. }
  8599. break;
  8600. case 256:
  8601. switch (op_kind) {
  8602. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  8603. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  8604. }
  8605. break;
  8606. }
  8607. GB_ASSERT(runtime_procedure != nullptr);
  8608. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8609. args[0] = left;
  8610. args[1] = right;
  8611. return lb_emit_runtime_call(p, runtime_procedure, args);
  8612. }
  8613. if (is_type_bit_set(a)) {
  8614. switch (op_kind) {
  8615. case Token_Lt:
  8616. case Token_LtEq:
  8617. case Token_Gt:
  8618. case Token_GtEq:
  8619. {
  8620. Type *it = bit_set_to_int(a);
  8621. lbValue lhs = lb_emit_transmute(p, left, it);
  8622. lbValue rhs = lb_emit_transmute(p, right, it);
  8623. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  8624. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  8625. // (lhs & rhs) == lhs
  8626. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  8627. res.type = t_llvm_bool;
  8628. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  8629. // (lhs & rhs) == rhs
  8630. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  8631. res.type = t_llvm_bool;
  8632. }
  8633. // NOTE(bill): Strict subsets
  8634. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  8635. // res &~ (lhs == rhs)
  8636. lbValue eq = {};
  8637. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  8638. eq.type = t_llvm_bool;
  8639. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  8640. }
  8641. return res;
  8642. }
  8643. case Token_CmpEq:
  8644. case Token_NotEq:
  8645. {
  8646. LLVMIntPredicate pred = {};
  8647. switch (op_kind) {
  8648. case Token_CmpEq: pred = LLVMIntEQ; break;
  8649. case Token_NotEq: pred = LLVMIntNE; break;
  8650. }
  8651. lbValue res = {};
  8652. res.type = t_llvm_bool;
  8653. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8654. return res;
  8655. }
  8656. }
  8657. }
  8658. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  8659. Type *t = left.type;
  8660. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  8661. Type *platform_type = integer_endian_type_to_platform_type(t);
  8662. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  8663. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  8664. left = x;
  8665. right = y;
  8666. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  8667. Type *platform_type = integer_endian_type_to_platform_type(t);
  8668. lbValue x = lb_emit_conv(p, left, platform_type);
  8669. lbValue y = lb_emit_conv(p, right, platform_type);
  8670. left = x;
  8671. right = y;
  8672. }
  8673. }
  8674. a = core_type(left.type);
  8675. b = core_type(right.type);
  8676. lbValue res = {};
  8677. res.type = t_llvm_bool;
  8678. if (is_type_integer(a) ||
  8679. is_type_boolean(a) ||
  8680. is_type_pointer(a) ||
  8681. is_type_proc(a) ||
  8682. is_type_enum(a)) {
  8683. LLVMIntPredicate pred = {};
  8684. if (is_type_unsigned(left.type)) {
  8685. switch (op_kind) {
  8686. case Token_Gt: pred = LLVMIntUGT; break;
  8687. case Token_GtEq: pred = LLVMIntUGE; break;
  8688. case Token_Lt: pred = LLVMIntULT; break;
  8689. case Token_LtEq: pred = LLVMIntULE; break;
  8690. }
  8691. } else {
  8692. switch (op_kind) {
  8693. case Token_Gt: pred = LLVMIntSGT; break;
  8694. case Token_GtEq: pred = LLVMIntSGE; break;
  8695. case Token_Lt: pred = LLVMIntSLT; break;
  8696. case Token_LtEq: pred = LLVMIntSLE; break;
  8697. }
  8698. }
  8699. switch (op_kind) {
  8700. case Token_CmpEq: pred = LLVMIntEQ; break;
  8701. case Token_NotEq: pred = LLVMIntNE; break;
  8702. }
  8703. LLVMValueRef lhs = left.value;
  8704. LLVMValueRef rhs = right.value;
  8705. if (LLVMTypeOf(lhs) != LLVMTypeOf(rhs)) {
  8706. if (lb_is_type_kind(LLVMTypeOf(lhs), LLVMPointerTypeKind)) {
  8707. rhs = LLVMBuildPointerCast(p->builder, rhs, LLVMTypeOf(lhs), "");
  8708. }
  8709. }
  8710. res.value = LLVMBuildICmp(p->builder, pred, lhs, rhs, "");
  8711. } else if (is_type_float(a)) {
  8712. LLVMRealPredicate pred = {};
  8713. switch (op_kind) {
  8714. case Token_CmpEq: pred = LLVMRealOEQ; break;
  8715. case Token_Gt: pred = LLVMRealOGT; break;
  8716. case Token_GtEq: pred = LLVMRealOGE; break;
  8717. case Token_Lt: pred = LLVMRealOLT; break;
  8718. case Token_LtEq: pred = LLVMRealOLE; break;
  8719. case Token_NotEq: pred = LLVMRealONE; break;
  8720. }
  8721. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  8722. } else if (is_type_typeid(a)) {
  8723. LLVMIntPredicate pred = {};
  8724. switch (op_kind) {
  8725. case Token_Gt: pred = LLVMIntUGT; break;
  8726. case Token_GtEq: pred = LLVMIntUGE; break;
  8727. case Token_Lt: pred = LLVMIntULT; break;
  8728. case Token_LtEq: pred = LLVMIntULE; break;
  8729. case Token_CmpEq: pred = LLVMIntEQ; break;
  8730. case Token_NotEq: pred = LLVMIntNE; break;
  8731. }
  8732. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8733. } else {
  8734. 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)));
  8735. }
  8736. return res;
  8737. }
  8738. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  8739. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  8740. if (found != nullptr) {
  8741. lbValue value = {};
  8742. value.value = (*found)->value;
  8743. value.type = (*found)->type;
  8744. return value;
  8745. }
  8746. ast_node(pl, ProcLit, expr);
  8747. // NOTE(bill): Generate a new name
  8748. // parent$count
  8749. isize name_len = prefix_name.len + 1 + 8 + 1;
  8750. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  8751. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  8752. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  8753. String name = make_string((u8 *)name_text, name_len-1);
  8754. Type *type = type_of_expr(expr);
  8755. set_procedure_abi_types(type);
  8756. Token token = {};
  8757. token.pos = ast_token(expr).pos;
  8758. token.kind = Token_Ident;
  8759. token.string = name;
  8760. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  8761. e->file = expr->file;
  8762. e->decl_info = pl->decl;
  8763. lbProcedure *p = lb_create_procedure(m, e);
  8764. lbValue value = {};
  8765. value.value = p->value;
  8766. value.type = p->type;
  8767. array_add(&m->procedures_to_generate, p);
  8768. if (parent != nullptr) {
  8769. array_add(&parent->children, p);
  8770. } else {
  8771. string_map_set(&m->members, name, value);
  8772. }
  8773. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  8774. return value;
  8775. }
  8776. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  8777. lbModule *m = p->module;
  8778. Type *src_type = value.type;
  8779. bool is_ptr = is_type_pointer(src_type);
  8780. bool is_tuple = true;
  8781. Type *tuple = type;
  8782. if (type->kind != Type_Tuple) {
  8783. is_tuple = false;
  8784. tuple = make_optional_ok_type(type);
  8785. }
  8786. lbAddr v = lb_add_local_generated(p, tuple, true);
  8787. if (is_ptr) {
  8788. value = lb_emit_load(p, value);
  8789. }
  8790. Type *src = base_type(type_deref(src_type));
  8791. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  8792. Type *dst = tuple->Tuple.variables[0]->type;
  8793. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  8794. lbValue tag = {};
  8795. lbValue dst_tag = {};
  8796. lbValue cond = {};
  8797. lbValue data = {};
  8798. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8799. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8800. if (is_type_union_maybe_pointer(src)) {
  8801. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8802. } else {
  8803. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  8804. dst_tag = lb_const_union_tag(m, src, dst);
  8805. }
  8806. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  8807. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  8808. if (data.value != nullptr) {
  8809. GB_ASSERT(is_type_union_maybe_pointer(src));
  8810. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  8811. } else {
  8812. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  8813. }
  8814. lb_emit_if(p, cond, ok_block, end_block);
  8815. lb_start_block(p, ok_block);
  8816. if (data.value == nullptr) {
  8817. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8818. }
  8819. lb_emit_store(p, gep0, data);
  8820. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8821. lb_emit_jump(p, end_block);
  8822. lb_start_block(p, end_block);
  8823. if (!is_tuple) {
  8824. if (do_conversion_check) {
  8825. // NOTE(bill): Panic on invalid conversion
  8826. Type *dst_type = tuple->Tuple.variables[0]->type;
  8827. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8828. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8829. args[0] = ok;
  8830. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  8831. args[2] = lb_const_int(m, t_i32, pos.line);
  8832. args[3] = lb_const_int(m, t_i32, pos.column);
  8833. args[4] = lb_typeid(m, src_type);
  8834. args[5] = lb_typeid(m, dst_type);
  8835. args[6] = lb_emit_conv(p, value_, t_rawptr);
  8836. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8837. }
  8838. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  8839. }
  8840. return lb_addr_load(p, v);
  8841. }
  8842. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8843. lbModule *m = p->module;
  8844. Type *src_type = value.type;
  8845. if (is_type_pointer(src_type)) {
  8846. value = lb_emit_load(p, value);
  8847. }
  8848. bool is_tuple = true;
  8849. Type *tuple = type;
  8850. if (type->kind != Type_Tuple) {
  8851. is_tuple = false;
  8852. tuple = make_optional_ok_type(type);
  8853. }
  8854. Type *dst_type = tuple->Tuple.variables[0]->type;
  8855. lbAddr v = lb_add_local_generated(p, tuple, true);
  8856. lbValue dst_typeid = lb_typeid(m, dst_type);
  8857. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  8858. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  8859. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  8860. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  8861. lb_emit_if(p, cond, ok_block, end_block);
  8862. lb_start_block(p, ok_block);
  8863. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8864. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8865. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  8866. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  8867. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  8868. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8869. lb_emit_jump(p, end_block);
  8870. lb_start_block(p, end_block);
  8871. if (!is_tuple) {
  8872. // NOTE(bill): Panic on invalid conversion
  8873. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8874. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8875. args[0] = ok;
  8876. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  8877. args[2] = lb_const_int(m, t_i32, pos.line);
  8878. args[3] = lb_const_int(m, t_i32, pos.column);
  8879. args[4] = any_typeid;
  8880. args[5] = dst_typeid;
  8881. args[6] = lb_emit_struct_ev(p, value, 0);;
  8882. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8883. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  8884. }
  8885. return v;
  8886. }
  8887. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8888. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  8889. }
  8890. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  8891. lbModule *m = p->module;
  8892. u64 prev_state_flags = p->module->state_flags;
  8893. defer (p->module->state_flags = prev_state_flags);
  8894. if (expr->state_flags != 0) {
  8895. u64 in = expr->state_flags;
  8896. u64 out = p->module->state_flags;
  8897. if (in & StateFlag_bounds_check) {
  8898. out |= StateFlag_bounds_check;
  8899. out &= ~StateFlag_no_bounds_check;
  8900. } else if (in & StateFlag_no_bounds_check) {
  8901. out |= StateFlag_no_bounds_check;
  8902. out &= ~StateFlag_bounds_check;
  8903. }
  8904. p->module->state_flags = out;
  8905. }
  8906. expr = unparen_expr(expr);
  8907. TokenPos expr_pos = ast_token(expr).pos;
  8908. TypeAndValue tv = type_and_value_of_expr(expr);
  8909. 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));
  8910. if (tv.value.kind != ExactValue_Invalid) {
  8911. // NOTE(bill): Short on constant values
  8912. return lb_const_value(p->module, tv.type, tv.value);
  8913. }
  8914. #if 0
  8915. LLVMMetadataRef prev_debug_location = nullptr;
  8916. if (p->debug_info != nullptr) {
  8917. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  8918. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, expr));
  8919. }
  8920. defer (if (prev_debug_location != nullptr) {
  8921. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  8922. });
  8923. #endif
  8924. switch (expr->kind) {
  8925. case_ast_node(bl, BasicLit, expr);
  8926. TokenPos pos = bl->token.pos;
  8927. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  8928. case_end;
  8929. case_ast_node(bd, BasicDirective, expr);
  8930. TokenPos pos = bd->token.pos;
  8931. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name));
  8932. case_end;
  8933. case_ast_node(i, Implicit, expr);
  8934. return lb_addr_load(p, lb_build_addr(p, expr));
  8935. case_end;
  8936. case_ast_node(u, Undef, expr)
  8937. lbValue res = {};
  8938. if (is_type_untyped(tv.type)) {
  8939. res.value = nullptr;
  8940. res.type = t_untyped_undef;
  8941. } else {
  8942. res.value = LLVMGetUndef(lb_type(m, tv.type));
  8943. res.type = tv.type;
  8944. }
  8945. return res;
  8946. case_end;
  8947. case_ast_node(i, Ident, expr);
  8948. Entity *e = entity_from_expr(expr);
  8949. e = strip_entity_wrapping(e);
  8950. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  8951. if (e->kind == Entity_Builtin) {
  8952. Token token = ast_token(expr);
  8953. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  8954. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  8955. token_pos_to_string(token.pos));
  8956. return {};
  8957. } else if (e->kind == Entity_Nil) {
  8958. lbValue res = {};
  8959. res.value = nullptr;
  8960. res.type = e->type;
  8961. return res;
  8962. }
  8963. GB_ASSERT(e->kind != Entity_ProcGroup);
  8964. auto *found = map_get(&p->module->values, hash_entity(e));
  8965. if (found) {
  8966. auto v = *found;
  8967. // NOTE(bill): This is because pointers are already pointers in LLVM
  8968. if (is_type_proc(v.type)) {
  8969. return v;
  8970. }
  8971. return lb_emit_load(p, v);
  8972. } else if (e != nullptr && e->kind == Entity_Variable) {
  8973. return lb_addr_load(p, lb_build_addr(p, expr));
  8974. }
  8975. gb_printf_err("Error in: %s\n", token_pos_to_string(i->token.pos));
  8976. String pkg = {};
  8977. if (e->pkg) {
  8978. pkg = e->pkg->name;
  8979. }
  8980. 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);
  8981. return {};
  8982. case_end;
  8983. case_ast_node(de, DerefExpr, expr);
  8984. return lb_addr_load(p, lb_build_addr(p, expr));
  8985. case_end;
  8986. case_ast_node(se, SelectorExpr, expr);
  8987. TypeAndValue tav = type_and_value_of_expr(expr);
  8988. GB_ASSERT(tav.mode != Addressing_Invalid);
  8989. return lb_addr_load(p, lb_build_addr(p, expr));
  8990. case_end;
  8991. case_ast_node(ise, ImplicitSelectorExpr, expr);
  8992. TypeAndValue tav = type_and_value_of_expr(expr);
  8993. GB_ASSERT(tav.mode == Addressing_Constant);
  8994. return lb_const_value(p->module, tv.type, tv.value);
  8995. case_end;
  8996. case_ast_node(se, SelectorCallExpr, expr);
  8997. GB_ASSERT(se->modified_call);
  8998. TypeAndValue tav = type_and_value_of_expr(expr);
  8999. GB_ASSERT(tav.mode != Addressing_Invalid);
  9000. return lb_build_expr(p, se->call);
  9001. case_end;
  9002. case_ast_node(te, TernaryExpr, expr);
  9003. LLVMValueRef incoming_values[2] = {};
  9004. LLVMBasicBlockRef incoming_blocks[2] = {};
  9005. GB_ASSERT(te->y != nullptr);
  9006. lbBlock *then = lb_create_block(p, "if.then");
  9007. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  9008. lbBlock *else_ = lb_create_block(p, "if.else");
  9009. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  9010. lb_start_block(p, then);
  9011. Type *type = default_type(type_of_expr(expr));
  9012. lb_open_scope(p, nullptr);
  9013. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  9014. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9015. lb_emit_jump(p, done);
  9016. lb_start_block(p, else_);
  9017. lb_open_scope(p, nullptr);
  9018. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  9019. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9020. lb_emit_jump(p, done);
  9021. lb_start_block(p, done);
  9022. lbValue res = {};
  9023. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  9024. res.type = type;
  9025. GB_ASSERT(p->curr_block->preds.count >= 2);
  9026. incoming_blocks[0] = p->curr_block->preds[0]->block;
  9027. incoming_blocks[1] = p->curr_block->preds[1]->block;
  9028. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  9029. return res;
  9030. case_end;
  9031. case_ast_node(te, TernaryIfExpr, expr);
  9032. LLVMValueRef incoming_values[2] = {};
  9033. LLVMBasicBlockRef incoming_blocks[2] = {};
  9034. GB_ASSERT(te->y != nullptr);
  9035. lbBlock *then = lb_create_block(p, "if.then");
  9036. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  9037. lbBlock *else_ = lb_create_block(p, "if.else");
  9038. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  9039. lb_start_block(p, then);
  9040. Type *type = default_type(type_of_expr(expr));
  9041. lb_open_scope(p, nullptr);
  9042. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  9043. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9044. lb_emit_jump(p, done);
  9045. lb_start_block(p, else_);
  9046. lb_open_scope(p, nullptr);
  9047. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  9048. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9049. lb_emit_jump(p, done);
  9050. lb_start_block(p, done);
  9051. lbValue res = {};
  9052. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  9053. res.type = type;
  9054. GB_ASSERT(p->curr_block->preds.count >= 2);
  9055. incoming_blocks[0] = p->curr_block->preds[0]->block;
  9056. incoming_blocks[1] = p->curr_block->preds[1]->block;
  9057. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  9058. return res;
  9059. case_end;
  9060. case_ast_node(te, TernaryWhenExpr, expr);
  9061. TypeAndValue tav = type_and_value_of_expr(te->cond);
  9062. GB_ASSERT(tav.mode == Addressing_Constant);
  9063. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  9064. if (tav.value.value_bool) {
  9065. return lb_build_expr(p, te->x);
  9066. } else {
  9067. return lb_build_expr(p, te->y);
  9068. }
  9069. case_end;
  9070. case_ast_node(ta, TypeAssertion, expr);
  9071. TokenPos pos = ast_token(expr).pos;
  9072. Type *type = tv.type;
  9073. lbValue e = lb_build_expr(p, ta->expr);
  9074. Type *t = type_deref(e.type);
  9075. if (is_type_union(t)) {
  9076. return lb_emit_union_cast(p, e, type, pos);
  9077. } else if (is_type_any(t)) {
  9078. return lb_emit_any_cast(p, e, type, pos);
  9079. } else {
  9080. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  9081. }
  9082. case_end;
  9083. case_ast_node(tc, TypeCast, expr);
  9084. lbValue e = lb_build_expr(p, tc->expr);
  9085. switch (tc->token.kind) {
  9086. case Token_cast:
  9087. return lb_emit_conv(p, e, tv.type);
  9088. case Token_transmute:
  9089. return lb_emit_transmute(p, e, tv.type);
  9090. }
  9091. GB_PANIC("Invalid AST TypeCast");
  9092. case_end;
  9093. case_ast_node(ac, AutoCast, expr);
  9094. return lb_build_expr(p, ac->expr);
  9095. case_end;
  9096. case_ast_node(ue, UnaryExpr, expr);
  9097. switch (ue->op.kind) {
  9098. case Token_And: {
  9099. Ast *ue_expr = unparen_expr(ue->expr);
  9100. if (ue_expr->kind == Ast_CompoundLit) {
  9101. lbValue v = lb_build_expr(p, ue->expr);
  9102. Type *type = v.type;
  9103. lbAddr addr = {};
  9104. if (p->is_startup) {
  9105. addr = lb_add_global_generated(p->module, type, v);
  9106. } else {
  9107. addr = lb_add_local_generated(p, type, false);
  9108. }
  9109. lb_addr_store(p, addr, v);
  9110. return addr.addr;
  9111. } else if (ue_expr->kind == Ast_TypeAssertion) {
  9112. GB_ASSERT(is_type_pointer(tv.type));
  9113. ast_node(ta, TypeAssertion, ue_expr);
  9114. TokenPos pos = ast_token(expr).pos;
  9115. Type *type = type_of_expr(ue_expr);
  9116. GB_ASSERT(!is_type_tuple(type));
  9117. lbValue e = lb_build_expr(p, ta->expr);
  9118. Type *t = type_deref(e.type);
  9119. if (is_type_union(t)) {
  9120. lbValue v = e;
  9121. if (!is_type_pointer(v.type)) {
  9122. v = lb_address_from_load_or_generate_local(p, v);
  9123. }
  9124. Type *src_type = type_deref(v.type);
  9125. Type *dst_type = type;
  9126. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  9127. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  9128. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  9129. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9130. args[0] = ok;
  9131. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9132. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9133. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9134. args[4] = lb_typeid(p->module, src_type);
  9135. args[5] = lb_typeid(p->module, dst_type);
  9136. lb_emit_runtime_call(p, "type_assertion_check", args);
  9137. lbValue data_ptr = v;
  9138. return lb_emit_conv(p, data_ptr, tv.type);
  9139. } else if (is_type_any(t)) {
  9140. lbValue v = e;
  9141. if (is_type_pointer(v.type)) {
  9142. v = lb_emit_load(p, v);
  9143. }
  9144. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  9145. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  9146. lbValue id = lb_typeid(p->module, type);
  9147. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  9148. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9149. args[0] = ok;
  9150. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9151. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9152. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9153. args[4] = any_id;
  9154. args[5] = id;
  9155. lb_emit_runtime_call(p, "type_assertion_check", args);
  9156. return lb_emit_conv(p, data_ptr, tv.type);
  9157. } else {
  9158. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  9159. }
  9160. }
  9161. return lb_build_addr_ptr(p, ue->expr);
  9162. }
  9163. default:
  9164. {
  9165. lbValue v = lb_build_expr(p, ue->expr);
  9166. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  9167. }
  9168. }
  9169. case_end;
  9170. case_ast_node(be, BinaryExpr, expr);
  9171. return lb_build_binary_expr(p, expr);
  9172. case_end;
  9173. case_ast_node(pl, ProcLit, expr);
  9174. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  9175. case_end;
  9176. case_ast_node(cl, CompoundLit, expr);
  9177. return lb_addr_load(p, lb_build_addr(p, expr));
  9178. case_end;
  9179. case_ast_node(ce, CallExpr, expr);
  9180. lbValue res = lb_build_call_expr(p, expr);
  9181. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  9182. GB_ASSERT(is_type_tuple(res.type));
  9183. GB_ASSERT(res.type->Tuple.variables.count == 2);
  9184. return lb_emit_struct_ev(p, res, 0);
  9185. }
  9186. return res;
  9187. case_end;
  9188. case_ast_node(se, SliceExpr, expr);
  9189. return lb_addr_load(p, lb_build_addr(p, expr));
  9190. case_end;
  9191. case_ast_node(ie, IndexExpr, expr);
  9192. return lb_addr_load(p, lb_build_addr(p, expr));
  9193. case_end;
  9194. case_ast_node(ia, InlineAsmExpr, expr);
  9195. Type *t = type_of_expr(expr);
  9196. GB_ASSERT(is_type_asm_proc(t));
  9197. String asm_string = {};
  9198. String constraints_string = {};
  9199. TypeAndValue tav;
  9200. tav = type_and_value_of_expr(ia->asm_string);
  9201. GB_ASSERT(is_type_string(tav.type));
  9202. GB_ASSERT(tav.value.kind == ExactValue_String);
  9203. asm_string = tav.value.value_string;
  9204. tav = type_and_value_of_expr(ia->constraints_string);
  9205. GB_ASSERT(is_type_string(tav.type));
  9206. GB_ASSERT(tav.value.kind == ExactValue_String);
  9207. constraints_string = tav.value.value_string;
  9208. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  9209. switch (ia->dialect) {
  9210. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  9211. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  9212. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  9213. default: GB_PANIC("Unhandled inline asm dialect"); break;
  9214. }
  9215. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  9216. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  9217. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  9218. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  9219. ia->has_side_effects, ia->is_align_stack, dialect
  9220. );
  9221. GB_ASSERT(the_asm != nullptr);
  9222. return {the_asm, t};
  9223. case_end;
  9224. }
  9225. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  9226. return {};
  9227. }
  9228. lbAddr lb_get_soa_variable_addr(lbProcedure *p, Entity *e) {
  9229. lbAddr *found = map_get(&p->module->soa_values, hash_entity(e));
  9230. GB_ASSERT(found != nullptr);
  9231. return *found;
  9232. }
  9233. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  9234. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  9235. String name = e->token.string;
  9236. Entity *parent = e->using_parent;
  9237. Selection sel = lookup_field(parent->type, name, false);
  9238. GB_ASSERT(sel.entity != nullptr);
  9239. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  9240. lbValue v = {};
  9241. if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) {
  9242. // NOTE(bill): using SOA value (probably from for-in statement)
  9243. lbAddr parent_addr = lb_get_soa_variable_addr(p, parent);
  9244. v = lb_addr_get_ptr(p, parent_addr);
  9245. } else if (pv != nullptr) {
  9246. v = *pv;
  9247. } else {
  9248. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  9249. v = lb_build_addr_ptr(p, e->using_expr);
  9250. }
  9251. GB_ASSERT(v.value != nullptr);
  9252. GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type));
  9253. lbValue ptr = lb_emit_deep_field_gep(p, v, sel);
  9254. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  9255. return ptr;
  9256. }
  9257. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  9258. GB_ASSERT(e != nullptr);
  9259. if (e->kind == Entity_Constant) {
  9260. Type *t = default_type(type_of_expr(expr));
  9261. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  9262. lbAddr g = lb_add_global_generated(p->module, t, v);
  9263. return g;
  9264. }
  9265. lbValue v = {};
  9266. lbValue *found = map_get(&p->module->values, hash_entity(e));
  9267. if (found) {
  9268. v = *found;
  9269. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  9270. // NOTE(bill): Calculate the using variable every time
  9271. v = lb_get_using_variable(p, e);
  9272. } else if (e->flags & EntityFlag_SoaPtrField) {
  9273. return lb_get_soa_variable_addr(p, e);
  9274. }
  9275. if (v.value == nullptr) {
  9276. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  9277. LIT(p->name),
  9278. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  9279. GB_PANIC("Unknown value");
  9280. }
  9281. return lb_addr(v);
  9282. }
  9283. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  9284. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  9285. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  9286. map_type = base_type(map_type);
  9287. GB_ASSERT(map_type->kind == Type_Map);
  9288. Type *key_type = map_type->Map.key;
  9289. Type *val_type = map_type->Map.value;
  9290. // NOTE(bill): Removes unnecessary allocation if split gep
  9291. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  9292. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  9293. lb_emit_store(p, gep0, m);
  9294. i64 entry_size = type_size_of (map_type->Map.entry_type);
  9295. i64 entry_align = type_align_of (map_type->Map.entry_type);
  9296. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  9297. i64 key_size = type_size_of (map_type->Map.key);
  9298. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  9299. i64 value_size = type_size_of (map_type->Map.value);
  9300. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  9301. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  9302. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  9303. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  9304. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  9305. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  9306. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  9307. return lb_addr_load(p, h);
  9308. }
  9309. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  9310. if (true) {
  9311. return {};
  9312. }
  9313. lbValue hashed_key = {};
  9314. if (lb_is_const(key)) {
  9315. u64 hash = 0xcbf29ce484222325;
  9316. if (is_type_cstring(key_type)) {
  9317. size_t length = 0;
  9318. char const *text = LLVMGetAsString(key.value, &length);
  9319. hash = fnv64a(text, cast(isize)length);
  9320. } else if (is_type_string(key_type)) {
  9321. unsigned data_indices[] = {0};
  9322. unsigned len_indices[] = {1};
  9323. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  9324. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  9325. isize length = LLVMConstIntGetSExtValue(len);
  9326. char const *text = nullptr;
  9327. if (false && length != 0) {
  9328. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  9329. return {};
  9330. }
  9331. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  9332. size_t ulength = 0;
  9333. text = LLVMGetAsString(data, &ulength);
  9334. gb_printf_err("%td %td %s\n", length, ulength, text);
  9335. length = gb_min(length, cast(isize)ulength);
  9336. }
  9337. hash = fnv64a(text, cast(isize)length);
  9338. } else {
  9339. return {};
  9340. }
  9341. // TODO(bill): other const hash types
  9342. if (build_context.word_size == 4) {
  9343. hash &= 0xffffffffull;
  9344. }
  9345. hashed_key = lb_const_int(m, t_uintptr, hash);
  9346. }
  9347. return hashed_key;
  9348. }
  9349. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  9350. Type *hash_type = t_u64;
  9351. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  9352. lbValue vp = lb_addr_get_ptr(p, v);
  9353. Type *t = base_type(key.type);
  9354. key = lb_emit_conv(p, key, key_type);
  9355. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  9356. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  9357. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  9358. if (hashed_key.value == nullptr) {
  9359. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  9360. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9361. args[0] = key_ptr;
  9362. args[1] = lb_const_int(p->module, t_uintptr, 0);
  9363. hashed_key = lb_emit_call(p, hasher, args);
  9364. }
  9365. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  9366. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  9367. return lb_addr_load(p, v);
  9368. }
  9369. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  9370. lbValue map_key, lbValue map_value, Ast *node) {
  9371. map_type = base_type(map_type);
  9372. GB_ASSERT(map_type->kind == Type_Map);
  9373. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  9374. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  9375. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  9376. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  9377. lb_addr_store(p, value_addr, v);
  9378. auto args = array_make<lbValue>(permanent_allocator(), 4);
  9379. args[0] = h;
  9380. args[1] = key;
  9381. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  9382. args[3] = lb_emit_source_code_location(p, node);
  9383. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  9384. }
  9385. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  9386. expr = unparen_expr(expr);
  9387. switch (expr->kind) {
  9388. case_ast_node(i, Implicit, expr);
  9389. lbAddr v = {};
  9390. switch (i->kind) {
  9391. case Token_context:
  9392. v = lb_find_or_generate_context_ptr(p);
  9393. break;
  9394. }
  9395. GB_ASSERT(v.addr.value != nullptr);
  9396. return v;
  9397. case_end;
  9398. case_ast_node(i, Ident, expr);
  9399. if (is_blank_ident(expr)) {
  9400. lbAddr val = {};
  9401. return val;
  9402. }
  9403. String name = i->token.string;
  9404. Entity *e = entity_of_node(expr);
  9405. return lb_build_addr_from_entity(p, e, expr);
  9406. case_end;
  9407. case_ast_node(se, SelectorExpr, expr);
  9408. Ast *sel = unparen_expr(se->selector);
  9409. if (sel->kind == Ast_Ident) {
  9410. String selector = sel->Ident.token.string;
  9411. TypeAndValue tav = type_and_value_of_expr(se->expr);
  9412. if (tav.mode == Addressing_Invalid) {
  9413. // NOTE(bill): Imports
  9414. Entity *imp = entity_of_node(se->expr);
  9415. if (imp != nullptr) {
  9416. GB_ASSERT(imp->kind == Entity_ImportName);
  9417. }
  9418. return lb_build_addr(p, unparen_expr(se->selector));
  9419. }
  9420. Type *type = base_type(tav.type);
  9421. if (tav.mode == Addressing_Type) { // Addressing_Type
  9422. Selection sel = lookup_field(type, selector, true);
  9423. Entity *e = sel.entity;
  9424. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  9425. GB_ASSERT(e->flags & EntityFlag_TypeField);
  9426. String name = e->token.string;
  9427. /*if (name == "names") {
  9428. lbValue ti_ptr = lb_type_info(m, type);
  9429. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  9430. lbValue names_ptr = nullptr;
  9431. if (is_type_enum(type)) {
  9432. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  9433. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  9434. } else if (type->kind == Type_Struct) {
  9435. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  9436. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  9437. }
  9438. return ir_addr(names_ptr);
  9439. } else */{
  9440. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  9441. }
  9442. GB_PANIC("Unreachable");
  9443. }
  9444. Selection sel = lookup_field(type, selector, false);
  9445. GB_ASSERT(sel.entity != nullptr);
  9446. {
  9447. lbAddr addr = lb_build_addr(p, se->expr);
  9448. if (addr.kind == lbAddr_Map) {
  9449. lbValue v = lb_addr_load(p, addr);
  9450. lbValue a = lb_address_from_load_or_generate_local(p, v);
  9451. a = lb_emit_deep_field_gep(p, a, sel);
  9452. return lb_addr(a);
  9453. } else if (addr.kind == lbAddr_Context) {
  9454. GB_ASSERT(sel.index.count > 0);
  9455. if (addr.ctx.sel.index.count >= 0) {
  9456. sel = selection_combine(addr.ctx.sel, sel);
  9457. }
  9458. addr.ctx.sel = sel;
  9459. addr.kind = lbAddr_Context;
  9460. return addr;
  9461. } else if (addr.kind == lbAddr_SoaVariable) {
  9462. lbValue index = addr.soa.index;
  9463. i32 first_index = sel.index[0];
  9464. Selection sub_sel = sel;
  9465. sub_sel.index.data += 1;
  9466. sub_sel.index.count -= 1;
  9467. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  9468. Type *t = base_type(type_deref(addr.addr.type));
  9469. GB_ASSERT(is_type_soa_struct(t));
  9470. // TODO(bill): Bounds check
  9471. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  9472. lbValue len = lb_soa_struct_len(p, addr.addr);
  9473. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  9474. }
  9475. lbValue item = {};
  9476. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9477. item = lb_emit_array_ep(p, arr, index);
  9478. } else {
  9479. item = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  9480. }
  9481. if (sub_sel.index.count > 0) {
  9482. item = lb_emit_deep_field_gep(p, item, sub_sel);
  9483. }
  9484. return lb_addr(item);
  9485. }
  9486. lbValue a = lb_addr_get_ptr(p, addr);
  9487. a = lb_emit_deep_field_gep(p, a, sel);
  9488. return lb_addr(a);
  9489. }
  9490. } else {
  9491. GB_PANIC("Unsupported selector expression");
  9492. }
  9493. case_end;
  9494. case_ast_node(se, SelectorCallExpr, expr);
  9495. GB_ASSERT(se->modified_call);
  9496. TypeAndValue tav = type_and_value_of_expr(expr);
  9497. GB_ASSERT(tav.mode != Addressing_Invalid);
  9498. return lb_build_addr(p, se->call);
  9499. case_end;
  9500. case_ast_node(ta, TypeAssertion, expr);
  9501. TokenPos pos = ast_token(expr).pos;
  9502. lbValue e = lb_build_expr(p, ta->expr);
  9503. Type *t = type_deref(e.type);
  9504. if (is_type_union(t)) {
  9505. Type *type = type_of_expr(expr);
  9506. lbAddr v = lb_add_local_generated(p, type, false);
  9507. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  9508. return v;
  9509. } else if (is_type_any(t)) {
  9510. Type *type = type_of_expr(expr);
  9511. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  9512. } else {
  9513. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  9514. }
  9515. case_end;
  9516. case_ast_node(ue, UnaryExpr, expr);
  9517. switch (ue->op.kind) {
  9518. case Token_And: {
  9519. return lb_build_addr(p, ue->expr);
  9520. }
  9521. default:
  9522. GB_PANIC("Invalid unary expression for lb_build_addr");
  9523. }
  9524. case_end;
  9525. case_ast_node(be, BinaryExpr, expr);
  9526. lbValue v = lb_build_expr(p, expr);
  9527. Type *t = v.type;
  9528. if (is_type_pointer(t)) {
  9529. return lb_addr(v);
  9530. }
  9531. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  9532. case_end;
  9533. case_ast_node(ie, IndexExpr, expr);
  9534. Type *t = base_type(type_of_expr(ie->expr));
  9535. bool deref = is_type_pointer(t);
  9536. t = base_type(type_deref(t));
  9537. if (is_type_soa_struct(t)) {
  9538. // SOA STRUCTURES!!!!
  9539. lbValue val = lb_build_addr_ptr(p, ie->expr);
  9540. if (deref) {
  9541. val = lb_emit_load(p, val);
  9542. }
  9543. lbValue index = lb_build_expr(p, ie->index);
  9544. return lb_addr_soa_variable(val, index, ie->index);
  9545. }
  9546. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  9547. // SOA Structures for slices/dynamic arrays
  9548. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  9549. lbValue field = lb_build_expr(p, ie->expr);
  9550. lbValue index = lb_build_expr(p, ie->index);
  9551. if (!build_context.no_bounds_check) {
  9552. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  9553. // GB_ASSERT(LLVMIsALoadInst(field.value));
  9554. // lbValue a = {};
  9555. // a.value = LLVMGetOperand(field.value, 0);
  9556. // a.type = alloc_type_pointer(field.type);
  9557. // irInstr *b = &a->Instr;
  9558. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  9559. // lbValue base_struct = b->StructElementPtr.address;
  9560. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  9561. // lbValue len = ir_soa_struct_len(p, base_struct);
  9562. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9563. }
  9564. lbValue val = lb_emit_ptr_offset(p, field, index);
  9565. return lb_addr(val);
  9566. }
  9567. if (!is_type_indexable(t)) {
  9568. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9569. if (found != nullptr) {
  9570. if (found->kind == TypeAtomOp_index_get) {
  9571. return lb_build_addr(p, found->node);
  9572. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  9573. return lb_addr(lb_build_expr(p, found->node));
  9574. } else if (found->kind == TypeAtomOp_index_set) {
  9575. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  9576. if (deref) {
  9577. ptr = lb_emit_load(p, ptr);
  9578. }
  9579. lbAddr addr = {lbAddr_AtomOp_index_set};
  9580. addr.addr = ptr;
  9581. addr.index_set.index = lb_build_expr(p, ie->index);
  9582. addr.index_set.node = found->node;
  9583. return addr;
  9584. }
  9585. }
  9586. }
  9587. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  9588. if (is_type_map(t)) {
  9589. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  9590. if (deref) {
  9591. map_val = lb_emit_load(p, map_val);
  9592. }
  9593. lbValue key = lb_build_expr(p, ie->index);
  9594. key = lb_emit_conv(p, key, t->Map.key);
  9595. Type *result_type = type_of_expr(expr);
  9596. return lb_addr_map(map_val, key, t, result_type);
  9597. }
  9598. switch (t->kind) {
  9599. case Type_Array: {
  9600. lbValue array = {};
  9601. array = lb_build_addr_ptr(p, ie->expr);
  9602. if (deref) {
  9603. array = lb_emit_load(p, array);
  9604. }
  9605. lbValue index = lb_build_expr(p, ie->index);
  9606. index = lb_emit_conv(p, index, t_int);
  9607. lbValue elem = lb_emit_array_ep(p, array, index);
  9608. auto index_tv = type_and_value_of_expr(ie->index);
  9609. if (index_tv.mode != Addressing_Constant) {
  9610. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  9611. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9612. }
  9613. return lb_addr(elem);
  9614. }
  9615. case Type_EnumeratedArray: {
  9616. lbValue array = {};
  9617. array = lb_build_addr_ptr(p, ie->expr);
  9618. if (deref) {
  9619. array = lb_emit_load(p, array);
  9620. }
  9621. Type *index_type = t->EnumeratedArray.index;
  9622. auto index_tv = type_and_value_of_expr(ie->index);
  9623. lbValue index = {};
  9624. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  9625. if (index_tv.mode == Addressing_Constant) {
  9626. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  9627. index = lb_const_value(p->module, index_type, idx);
  9628. } else {
  9629. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9630. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  9631. }
  9632. } else {
  9633. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9634. }
  9635. lbValue elem = lb_emit_array_ep(p, array, index);
  9636. if (index_tv.mode != Addressing_Constant) {
  9637. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  9638. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9639. }
  9640. return lb_addr(elem);
  9641. }
  9642. case Type_Slice: {
  9643. lbValue slice = {};
  9644. slice = lb_build_expr(p, ie->expr);
  9645. if (deref) {
  9646. slice = lb_emit_load(p, slice);
  9647. }
  9648. lbValue elem = lb_slice_elem(p, slice);
  9649. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9650. lbValue len = lb_slice_len(p, slice);
  9651. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9652. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9653. return lb_addr(v);
  9654. }
  9655. case Type_RelativeSlice: {
  9656. lbAddr slice_addr = {};
  9657. if (deref) {
  9658. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  9659. } else {
  9660. slice_addr = lb_build_addr(p, ie->expr);
  9661. }
  9662. lbValue slice = lb_addr_load(p, slice_addr);
  9663. lbValue elem = lb_slice_elem(p, slice);
  9664. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9665. lbValue len = lb_slice_len(p, slice);
  9666. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9667. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9668. return lb_addr(v);
  9669. }
  9670. case Type_DynamicArray: {
  9671. lbValue dynamic_array = {};
  9672. dynamic_array = lb_build_expr(p, ie->expr);
  9673. if (deref) {
  9674. dynamic_array = lb_emit_load(p, dynamic_array);
  9675. }
  9676. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  9677. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  9678. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9679. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9680. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9681. return lb_addr(v);
  9682. }
  9683. case Type_Basic: { // Basic_string
  9684. lbValue str;
  9685. lbValue elem;
  9686. lbValue len;
  9687. lbValue index;
  9688. str = lb_build_expr(p, ie->expr);
  9689. if (deref) {
  9690. str = lb_emit_load(p, str);
  9691. }
  9692. elem = lb_string_elem(p, str);
  9693. len = lb_string_len(p, str);
  9694. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9695. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9696. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  9697. }
  9698. }
  9699. case_end;
  9700. case_ast_node(se, SliceExpr, expr);
  9701. lbValue low = lb_const_int(p->module, t_int, 0);
  9702. lbValue high = {};
  9703. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  9704. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  9705. bool no_indices = se->low == nullptr && se->high == nullptr;
  9706. {
  9707. Type *type = base_type(type_of_expr(se->expr));
  9708. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  9709. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  9710. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  9711. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9712. if (found) {
  9713. lbValue base = lb_build_expr(p, found->node);
  9714. Type *slice_type = base.type;
  9715. lbValue len = lb_slice_len(p, base);
  9716. if (high.value == nullptr) high = len;
  9717. if (!no_indices) {
  9718. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9719. }
  9720. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9721. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9722. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9723. lb_fill_slice(p, slice, elem, new_len);
  9724. return slice;
  9725. }
  9726. }
  9727. }
  9728. }
  9729. lbAddr addr = lb_build_addr(p, se->expr);
  9730. lbValue base = lb_addr_load(p, addr);
  9731. Type *type = base_type(base.type);
  9732. if (is_type_pointer(type)) {
  9733. type = base_type(type_deref(type));
  9734. addr = lb_addr(base);
  9735. base = lb_addr_load(p, addr);
  9736. }
  9737. switch (type->kind) {
  9738. case Type_Slice: {
  9739. Type *slice_type = type;
  9740. lbValue len = lb_slice_len(p, base);
  9741. if (high.value == nullptr) high = len;
  9742. if (!no_indices) {
  9743. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9744. }
  9745. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9746. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9747. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9748. lb_fill_slice(p, slice, elem, new_len);
  9749. return slice;
  9750. }
  9751. case Type_RelativeSlice:
  9752. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  9753. break;
  9754. case Type_DynamicArray: {
  9755. Type *elem_type = type->DynamicArray.elem;
  9756. Type *slice_type = alloc_type_slice(elem_type);
  9757. lbValue len = lb_dynamic_array_len(p, base);
  9758. if (high.value == nullptr) high = len;
  9759. if (!no_indices) {
  9760. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9761. }
  9762. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  9763. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9764. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9765. lb_fill_slice(p, slice, elem, new_len);
  9766. return slice;
  9767. }
  9768. case Type_Array: {
  9769. Type *slice_type = alloc_type_slice(type->Array.elem);
  9770. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  9771. if (high.value == nullptr) high = len;
  9772. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  9773. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  9774. if (!low_const || !high_const) {
  9775. if (!no_indices) {
  9776. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9777. }
  9778. }
  9779. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  9780. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9781. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9782. lb_fill_slice(p, slice, elem, new_len);
  9783. return slice;
  9784. }
  9785. case Type_Basic: {
  9786. GB_ASSERT(type == t_string);
  9787. lbValue len = lb_string_len(p, base);
  9788. if (high.value == nullptr) high = len;
  9789. if (!no_indices) {
  9790. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9791. }
  9792. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  9793. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9794. lbAddr str = lb_add_local_generated(p, t_string, false);
  9795. lb_fill_string(p, str, elem, new_len);
  9796. return str;
  9797. }
  9798. case Type_Struct:
  9799. if (is_type_soa_struct(type)) {
  9800. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  9801. if (high.value == nullptr) high = len;
  9802. if (!no_indices) {
  9803. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9804. }
  9805. #if 1
  9806. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  9807. if (type->Struct.soa_kind == StructSoa_Fixed) {
  9808. i32 field_count = cast(i32)type->Struct.fields.count;
  9809. for (i32 i = 0; i < field_count; i++) {
  9810. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9811. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  9812. field_src = lb_emit_array_ep(p, field_src, low);
  9813. lb_emit_store(p, field_dst, field_src);
  9814. }
  9815. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9816. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9817. lb_emit_store(p, len_dst, new_len);
  9818. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  9819. if (no_indices) {
  9820. lb_addr_store(p, dst, base);
  9821. } else {
  9822. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  9823. for (i32 i = 0; i < field_count; i++) {
  9824. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9825. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9826. field_src = lb_emit_ptr_offset(p, field_src, low);
  9827. lb_emit_store(p, field_dst, field_src);
  9828. }
  9829. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9830. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9831. lb_emit_store(p, len_dst, new_len);
  9832. }
  9833. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  9834. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  9835. for (i32 i = 0; i < field_count; i++) {
  9836. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9837. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9838. field_src = lb_emit_ptr_offset(p, field_src, low);
  9839. lb_emit_store(p, field_dst, field_src);
  9840. }
  9841. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9842. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9843. lb_emit_store(p, len_dst, new_len);
  9844. }
  9845. return dst;
  9846. #endif
  9847. }
  9848. break;
  9849. }
  9850. GB_PANIC("Unknown slicable type");
  9851. case_end;
  9852. case_ast_node(de, DerefExpr, expr);
  9853. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  9854. lbAddr addr = lb_build_addr(p, de->expr);
  9855. addr.relative.deref = true;
  9856. return addr;
  9857. }
  9858. lbValue addr = lb_build_expr(p, de->expr);
  9859. return lb_addr(addr);
  9860. case_end;
  9861. case_ast_node(ce, CallExpr, expr);
  9862. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  9863. lbValue e = lb_build_expr(p, expr);
  9864. lbAddr v = lb_add_local_generated(p, e.type, false);
  9865. lb_addr_store(p, v, e);
  9866. return v;
  9867. case_end;
  9868. case_ast_node(cl, CompoundLit, expr);
  9869. Type *type = type_of_expr(expr);
  9870. Type *bt = base_type(type);
  9871. lbAddr v = lb_add_local_generated(p, type, true);
  9872. Type *et = nullptr;
  9873. switch (bt->kind) {
  9874. case Type_Array: et = bt->Array.elem; break;
  9875. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  9876. case Type_Slice: et = bt->Slice.elem; break;
  9877. case Type_BitSet: et = bt->BitSet.elem; break;
  9878. case Type_SimdVector: et = bt->SimdVector.elem; break;
  9879. }
  9880. String proc_name = {};
  9881. if (p->entity) {
  9882. proc_name = p->entity->token.string;
  9883. }
  9884. TokenPos pos = ast_token(expr).pos;
  9885. switch (bt->kind) {
  9886. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  9887. case Type_Struct: {
  9888. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  9889. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  9890. bool is_raw_union = is_type_raw_union(bt);
  9891. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  9892. TypeStruct *st = &bt->Struct;
  9893. if (cl->elems.count > 0) {
  9894. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9895. for_array(field_index, cl->elems) {
  9896. Ast *elem = cl->elems[field_index];
  9897. lbValue field_expr = {};
  9898. Entity *field = nullptr;
  9899. isize index = field_index;
  9900. if (elem->kind == Ast_FieldValue) {
  9901. ast_node(fv, FieldValue, elem);
  9902. String name = fv->field->Ident.token.string;
  9903. Selection sel = lookup_field(bt, name, false);
  9904. index = sel.index[0];
  9905. elem = fv->value;
  9906. TypeAndValue tav = type_and_value_of_expr(elem);
  9907. } else {
  9908. TypeAndValue tav = type_and_value_of_expr(elem);
  9909. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  9910. index = sel.index[0];
  9911. }
  9912. field = st->fields[index];
  9913. Type *ft = field->type;
  9914. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  9915. continue;
  9916. }
  9917. field_expr = lb_build_expr(p, elem);
  9918. Type *fet = field_expr.type;
  9919. GB_ASSERT(fet->kind != Type_Tuple);
  9920. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  9921. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  9922. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  9923. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9924. lb_emit_store_union_variant(p, gep, field_expr, fet);
  9925. } else {
  9926. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9927. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9928. lb_emit_store(p, gep, fv);
  9929. }
  9930. }
  9931. }
  9932. break;
  9933. }
  9934. case Type_Map: {
  9935. if (cl->elems.count == 0) {
  9936. break;
  9937. }
  9938. {
  9939. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9940. args[0] = lb_gen_map_header(p, v.addr, type);
  9941. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  9942. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  9943. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  9944. }
  9945. for_array(field_index, cl->elems) {
  9946. Ast *elem = cl->elems[field_index];
  9947. ast_node(fv, FieldValue, elem);
  9948. lbValue key = lb_build_expr(p, fv->field);
  9949. lbValue value = lb_build_expr(p, fv->value);
  9950. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  9951. }
  9952. break;
  9953. }
  9954. case Type_Array: {
  9955. if (cl->elems.count > 0) {
  9956. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9957. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9958. // NOTE(bill): Separate value, gep, store into their own chunks
  9959. for_array(i, cl->elems) {
  9960. Ast *elem = cl->elems[i];
  9961. if (elem->kind == Ast_FieldValue) {
  9962. ast_node(fv, FieldValue, elem);
  9963. if (lb_is_elem_const(fv->value, et)) {
  9964. continue;
  9965. }
  9966. if (is_ast_range(fv->field)) {
  9967. ast_node(ie, BinaryExpr, fv->field);
  9968. TypeAndValue lo_tav = ie->left->tav;
  9969. TypeAndValue hi_tav = ie->right->tav;
  9970. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9971. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9972. TokenKind op = ie->op.kind;
  9973. i64 lo = exact_value_to_i64(lo_tav.value);
  9974. i64 hi = exact_value_to_i64(hi_tav.value);
  9975. if (op == Token_Ellipsis) {
  9976. hi += 1;
  9977. }
  9978. lbValue value = lb_build_expr(p, fv->value);
  9979. for (i64 k = lo; k < hi; k++) {
  9980. lbCompoundLitElemTempData data = {};
  9981. data.value = value;
  9982. data.elem_index = cast(i32)k;
  9983. array_add(&temp_data, data);
  9984. }
  9985. } else {
  9986. auto tav = fv->field->tav;
  9987. GB_ASSERT(tav.mode == Addressing_Constant);
  9988. i64 index = exact_value_to_i64(tav.value);
  9989. lbValue value = lb_build_expr(p, fv->value);
  9990. lbCompoundLitElemTempData data = {};
  9991. data.value = lb_emit_conv(p, value, et);
  9992. data.expr = fv->value;
  9993. data.elem_index = cast(i32)index;
  9994. array_add(&temp_data, data);
  9995. }
  9996. } else {
  9997. if (lb_is_elem_const(elem, et)) {
  9998. continue;
  9999. }
  10000. lbCompoundLitElemTempData data = {};
  10001. data.expr = elem;
  10002. data.elem_index = cast(i32)i;
  10003. array_add(&temp_data, data);
  10004. }
  10005. }
  10006. for_array(i, temp_data) {
  10007. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  10008. }
  10009. for_array(i, temp_data) {
  10010. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  10011. auto return_ptr_hint_value = p->return_ptr_hint_value;
  10012. auto return_ptr_hint_used = p->return_ptr_hint_used;
  10013. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  10014. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  10015. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  10016. lbValue field_expr = temp_data[i].value;
  10017. Ast *expr = temp_data[i].expr;
  10018. p->return_ptr_hint_value = temp_data[i].gep;
  10019. p->return_ptr_hint_ast = unparen_expr(expr);
  10020. if (field_expr.value == nullptr) {
  10021. field_expr = lb_build_expr(p, expr);
  10022. }
  10023. Type *t = field_expr.type;
  10024. GB_ASSERT(t->kind != Type_Tuple);
  10025. lbValue ev = lb_emit_conv(p, field_expr, et);
  10026. if (!p->return_ptr_hint_used) {
  10027. temp_data[i].value = ev;
  10028. }
  10029. }
  10030. for_array(i, temp_data) {
  10031. if (temp_data[i].value.value != nullptr) {
  10032. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10033. }
  10034. }
  10035. }
  10036. break;
  10037. }
  10038. case Type_EnumeratedArray: {
  10039. if (cl->elems.count > 0) {
  10040. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10041. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10042. // NOTE(bill): Separate value, gep, store into their own chunks
  10043. for_array(i, cl->elems) {
  10044. Ast *elem = cl->elems[i];
  10045. if (elem->kind == Ast_FieldValue) {
  10046. ast_node(fv, FieldValue, elem);
  10047. if (lb_is_elem_const(fv->value, et)) {
  10048. continue;
  10049. }
  10050. if (is_ast_range(fv->field)) {
  10051. ast_node(ie, BinaryExpr, fv->field);
  10052. TypeAndValue lo_tav = ie->left->tav;
  10053. TypeAndValue hi_tav = ie->right->tav;
  10054. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10055. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10056. TokenKind op = ie->op.kind;
  10057. i64 lo = exact_value_to_i64(lo_tav.value);
  10058. i64 hi = exact_value_to_i64(hi_tav.value);
  10059. if (op == Token_Ellipsis) {
  10060. hi += 1;
  10061. }
  10062. lbValue value = lb_build_expr(p, fv->value);
  10063. for (i64 k = lo; k < hi; k++) {
  10064. lbCompoundLitElemTempData data = {};
  10065. data.value = value;
  10066. data.elem_index = cast(i32)k;
  10067. array_add(&temp_data, data);
  10068. }
  10069. } else {
  10070. auto tav = fv->field->tav;
  10071. GB_ASSERT(tav.mode == Addressing_Constant);
  10072. i64 index = exact_value_to_i64(tav.value);
  10073. lbValue value = lb_build_expr(p, fv->value);
  10074. lbCompoundLitElemTempData data = {};
  10075. data.value = lb_emit_conv(p, value, et);
  10076. data.expr = fv->value;
  10077. data.elem_index = cast(i32)index;
  10078. array_add(&temp_data, data);
  10079. }
  10080. } else {
  10081. if (lb_is_elem_const(elem, et)) {
  10082. continue;
  10083. }
  10084. lbCompoundLitElemTempData data = {};
  10085. data.expr = elem;
  10086. data.elem_index = cast(i32)i;
  10087. array_add(&temp_data, data);
  10088. }
  10089. }
  10090. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  10091. for_array(i, temp_data) {
  10092. i32 index = temp_data[i].elem_index - index_offset;
  10093. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  10094. }
  10095. for_array(i, temp_data) {
  10096. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  10097. auto return_ptr_hint_value = p->return_ptr_hint_value;
  10098. auto return_ptr_hint_used = p->return_ptr_hint_used;
  10099. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  10100. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  10101. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  10102. lbValue field_expr = temp_data[i].value;
  10103. Ast *expr = temp_data[i].expr;
  10104. p->return_ptr_hint_value = temp_data[i].gep;
  10105. p->return_ptr_hint_ast = unparen_expr(expr);
  10106. if (field_expr.value == nullptr) {
  10107. field_expr = lb_build_expr(p, expr);
  10108. }
  10109. Type *t = field_expr.type;
  10110. GB_ASSERT(t->kind != Type_Tuple);
  10111. lbValue ev = lb_emit_conv(p, field_expr, et);
  10112. if (!p->return_ptr_hint_used) {
  10113. temp_data[i].value = ev;
  10114. }
  10115. }
  10116. for_array(i, temp_data) {
  10117. if (temp_data[i].value.value != nullptr) {
  10118. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10119. }
  10120. }
  10121. }
  10122. break;
  10123. }
  10124. case Type_Slice: {
  10125. if (cl->elems.count > 0) {
  10126. Type *elem_type = bt->Slice.elem;
  10127. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  10128. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  10129. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  10130. lbValue data = lb_slice_elem(p, slice);
  10131. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10132. for_array(i, cl->elems) {
  10133. Ast *elem = cl->elems[i];
  10134. if (elem->kind == Ast_FieldValue) {
  10135. ast_node(fv, FieldValue, elem);
  10136. if (lb_is_elem_const(fv->value, et)) {
  10137. continue;
  10138. }
  10139. if (is_ast_range(fv->field)) {
  10140. ast_node(ie, BinaryExpr, fv->field);
  10141. TypeAndValue lo_tav = ie->left->tav;
  10142. TypeAndValue hi_tav = ie->right->tav;
  10143. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10144. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10145. TokenKind op = ie->op.kind;
  10146. i64 lo = exact_value_to_i64(lo_tav.value);
  10147. i64 hi = exact_value_to_i64(hi_tav.value);
  10148. if (op == Token_Ellipsis) {
  10149. hi += 1;
  10150. }
  10151. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10152. for (i64 k = lo; k < hi; k++) {
  10153. lbCompoundLitElemTempData data = {};
  10154. data.value = value;
  10155. data.elem_index = cast(i32)k;
  10156. array_add(&temp_data, data);
  10157. }
  10158. } else {
  10159. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10160. i64 index = exact_value_to_i64(fv->field->tav.value);
  10161. lbValue field_expr = lb_build_expr(p, fv->value);
  10162. GB_ASSERT(!is_type_tuple(field_expr.type));
  10163. lbValue ev = lb_emit_conv(p, field_expr, et);
  10164. lbCompoundLitElemTempData data = {};
  10165. data.value = ev;
  10166. data.elem_index = cast(i32)index;
  10167. array_add(&temp_data, data);
  10168. }
  10169. } else {
  10170. if (lb_is_elem_const(elem, et)) {
  10171. continue;
  10172. }
  10173. lbValue field_expr = lb_build_expr(p, elem);
  10174. GB_ASSERT(!is_type_tuple(field_expr.type));
  10175. lbValue ev = lb_emit_conv(p, field_expr, et);
  10176. lbCompoundLitElemTempData data = {};
  10177. data.value = ev;
  10178. data.elem_index = cast(i32)i;
  10179. array_add(&temp_data, data);
  10180. }
  10181. }
  10182. for_array(i, temp_data) {
  10183. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  10184. }
  10185. for_array(i, temp_data) {
  10186. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10187. }
  10188. {
  10189. lbValue count = {};
  10190. count.type = t_int;
  10191. if (lb_is_const(slice)) {
  10192. unsigned indices[1] = {1};
  10193. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  10194. } else {
  10195. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  10196. }
  10197. lb_fill_slice(p, v, data, count);
  10198. }
  10199. }
  10200. break;
  10201. }
  10202. case Type_DynamicArray: {
  10203. if (cl->elems.count == 0) {
  10204. break;
  10205. }
  10206. Type *et = bt->DynamicArray.elem;
  10207. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  10208. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  10209. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  10210. {
  10211. auto args = array_make<lbValue>(permanent_allocator(), 5);
  10212. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  10213. args[1] = size;
  10214. args[2] = align;
  10215. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  10216. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  10217. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  10218. }
  10219. lbValue items = lb_generate_local_array(p, et, item_count);
  10220. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  10221. for_array(i, cl->elems) {
  10222. Ast *elem = cl->elems[i];
  10223. if (elem->kind == Ast_FieldValue) {
  10224. ast_node(fv, FieldValue, elem);
  10225. if (is_ast_range(fv->field)) {
  10226. ast_node(ie, BinaryExpr, fv->field);
  10227. TypeAndValue lo_tav = ie->left->tav;
  10228. TypeAndValue hi_tav = ie->right->tav;
  10229. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10230. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10231. TokenKind op = ie->op.kind;
  10232. i64 lo = exact_value_to_i64(lo_tav.value);
  10233. i64 hi = exact_value_to_i64(hi_tav.value);
  10234. if (op == Token_Ellipsis) {
  10235. hi += 1;
  10236. }
  10237. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10238. for (i64 k = lo; k < hi; k++) {
  10239. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  10240. lb_emit_store(p, ep, value);
  10241. }
  10242. } else {
  10243. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10244. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  10245. lbValue ev = lb_build_expr(p, fv->value);
  10246. lbValue value = lb_emit_conv(p, ev, et);
  10247. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  10248. lb_emit_store(p, ep, value);
  10249. }
  10250. } else {
  10251. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  10252. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  10253. lb_emit_store(p, ep, value);
  10254. }
  10255. }
  10256. {
  10257. auto args = array_make<lbValue>(permanent_allocator(), 6);
  10258. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  10259. args[1] = size;
  10260. args[2] = align;
  10261. args[3] = lb_emit_conv(p, items, t_rawptr);
  10262. args[4] = lb_const_int(p->module, t_int, item_count);
  10263. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  10264. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  10265. }
  10266. break;
  10267. }
  10268. case Type_Basic: {
  10269. GB_ASSERT(is_type_any(bt));
  10270. if (cl->elems.count > 0) {
  10271. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10272. String field_names[2] = {
  10273. str_lit("data"),
  10274. str_lit("id"),
  10275. };
  10276. Type *field_types[2] = {
  10277. t_rawptr,
  10278. t_typeid,
  10279. };
  10280. for_array(field_index, cl->elems) {
  10281. Ast *elem = cl->elems[field_index];
  10282. lbValue field_expr = {};
  10283. isize index = field_index;
  10284. if (elem->kind == Ast_FieldValue) {
  10285. ast_node(fv, FieldValue, elem);
  10286. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  10287. index = sel.index[0];
  10288. elem = fv->value;
  10289. } else {
  10290. TypeAndValue tav = type_and_value_of_expr(elem);
  10291. Selection sel = lookup_field(bt, field_names[field_index], false);
  10292. index = sel.index[0];
  10293. }
  10294. field_expr = lb_build_expr(p, elem);
  10295. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  10296. Type *ft = field_types[index];
  10297. lbValue fv = lb_emit_conv(p, field_expr, ft);
  10298. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10299. lb_emit_store(p, gep, fv);
  10300. }
  10301. }
  10302. break;
  10303. }
  10304. case Type_BitSet: {
  10305. i64 sz = type_size_of(type);
  10306. if (cl->elems.count > 0 && sz > 0) {
  10307. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10308. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  10309. for_array(i, cl->elems) {
  10310. Ast *elem = cl->elems[i];
  10311. GB_ASSERT(elem->kind != Ast_FieldValue);
  10312. if (lb_is_elem_const(elem, et)) {
  10313. continue;
  10314. }
  10315. lbValue expr = lb_build_expr(p, elem);
  10316. GB_ASSERT(expr.type->kind != Type_Tuple);
  10317. Type *it = bit_set_to_int(bt);
  10318. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  10319. lbValue e = lb_emit_conv(p, expr, it);
  10320. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  10321. e = lb_emit_arith(p, Token_Shl, one, e, it);
  10322. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  10323. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  10324. new_value = lb_emit_transmute(p, new_value, type);
  10325. lb_addr_store(p, v, new_value);
  10326. }
  10327. }
  10328. break;
  10329. }
  10330. }
  10331. return v;
  10332. case_end;
  10333. case_ast_node(tc, TypeCast, expr);
  10334. Type *type = type_of_expr(expr);
  10335. lbValue x = lb_build_expr(p, tc->expr);
  10336. lbValue e = {};
  10337. switch (tc->token.kind) {
  10338. case Token_cast:
  10339. e = lb_emit_conv(p, x, type);
  10340. break;
  10341. case Token_transmute:
  10342. e = lb_emit_transmute(p, x, type);
  10343. break;
  10344. default:
  10345. GB_PANIC("Invalid AST TypeCast");
  10346. }
  10347. lbAddr v = lb_add_local_generated(p, type, false);
  10348. lb_addr_store(p, v, e);
  10349. return v;
  10350. case_end;
  10351. case_ast_node(ac, AutoCast, expr);
  10352. return lb_build_addr(p, ac->expr);
  10353. case_end;
  10354. }
  10355. TokenPos token_pos = ast_token(expr).pos;
  10356. GB_PANIC("Unexpected address expression\n"
  10357. "\tAst: %.*s @ "
  10358. "%s\n",
  10359. LIT(ast_strings[expr->kind]),
  10360. token_pos_to_string(token_pos));
  10361. return {};
  10362. }
  10363. void lb_init_module(lbModule *m, Checker *c) {
  10364. m->info = &c->info;
  10365. m->ctx = LLVMGetGlobalContext();
  10366. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  10367. // m->debug_builder = nullptr;
  10368. if (build_context.ODIN_DEBUG) {
  10369. enum {DEBUG_METADATA_VERSION = 3};
  10370. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  10371. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  10372. if (build_context.metrics.os == TargetOs_windows) {
  10373. LLVMMetadataRef ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true));
  10374. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "CodeView", 8, ref);
  10375. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  10376. }
  10377. }
  10378. m->state_flags = 0;
  10379. m->state_flags |= StateFlag_bounds_check;
  10380. gb_mutex_init(&m->mutex);
  10381. gbAllocator a = heap_allocator();
  10382. map_init(&m->types, a);
  10383. map_init(&m->llvm_types, a);
  10384. map_init(&m->values, a);
  10385. map_init(&m->soa_values, a);
  10386. string_map_init(&m->members, a);
  10387. map_init(&m->procedure_values, a);
  10388. string_map_init(&m->procedures, a);
  10389. string_map_init(&m->const_strings, a);
  10390. map_init(&m->anonymous_proc_lits, a);
  10391. map_init(&m->function_type_map, a);
  10392. map_init(&m->equal_procs, a);
  10393. map_init(&m->hasher_procs, a);
  10394. array_init(&m->procedures_to_generate, a, 0, 1024);
  10395. array_init(&m->foreign_library_paths, a, 0, 1024);
  10396. map_init(&m->debug_values, a);
  10397. array_init(&m->debug_incomplete_types, a, 0, 1024);
  10398. }
  10399. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  10400. if (global_error_collector.count != 0) {
  10401. return false;
  10402. }
  10403. isize tc = c->parser->total_token_count;
  10404. if (tc < 2) {
  10405. return false;
  10406. }
  10407. String init_fullpath = c->parser->init_fullpath;
  10408. if (build_context.out_filepath.len == 0) {
  10409. gen->output_name = remove_directory_from_path(init_fullpath);
  10410. gen->output_name = remove_extension_from_path(gen->output_name);
  10411. gen->output_name = string_trim_whitespace(gen->output_name);
  10412. if (gen->output_name.len == 0) {
  10413. gen->output_name = c->info.init_scope->pkg->name;
  10414. }
  10415. gen->output_base = gen->output_name;
  10416. } else {
  10417. gen->output_name = build_context.out_filepath;
  10418. gen->output_name = string_trim_whitespace(gen->output_name);
  10419. if (gen->output_name.len == 0) {
  10420. gen->output_name = c->info.init_scope->pkg->name;
  10421. }
  10422. isize pos = string_extension_position(gen->output_name);
  10423. if (pos < 0) {
  10424. gen->output_base = gen->output_name;
  10425. } else {
  10426. gen->output_base = substring(gen->output_name, 0, pos);
  10427. }
  10428. }
  10429. gbAllocator ha = heap_allocator();
  10430. array_init(&gen->output_object_paths, ha);
  10431. gen->output_base = path_to_full_path(ha, gen->output_base);
  10432. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  10433. output_file_path = gb_string_appendc(output_file_path, ".obj");
  10434. defer (gb_string_free(output_file_path));
  10435. gen->info = &c->info;
  10436. lb_init_module(&gen->module, c);
  10437. return true;
  10438. }
  10439. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  10440. GB_ASSERT(type != nullptr);
  10441. type = default_type(type);
  10442. isize max_len = 7+8+1;
  10443. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  10444. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  10445. m->global_generated_index++;
  10446. String name = make_string(str, len-1);
  10447. Scope *scope = nullptr;
  10448. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  10449. lbValue g = {};
  10450. g.type = alloc_type_pointer(type);
  10451. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  10452. if (value.value != nullptr) {
  10453. GB_ASSERT(LLVMIsConstant(value.value));
  10454. LLVMSetInitializer(g.value, value.value);
  10455. } else {
  10456. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  10457. }
  10458. lb_add_entity(m, e, g);
  10459. lb_add_member(m, name, g);
  10460. return lb_addr(g);
  10461. }
  10462. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  10463. AstPackage *p = m->info->runtime_package;
  10464. Entity *e = scope_lookup_current(p->scope, name);
  10465. lbValue *found = map_get(&m->values, hash_entity(e));
  10466. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  10467. lbValue value = *found;
  10468. return value;
  10469. }
  10470. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  10471. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  10472. lbValue *found = map_get(&m->values, hash_entity(e));
  10473. GB_ASSERT_MSG(found != nullptr, "Unable to find value '%.*s.%.*s'", LIT(pkg), LIT(name));
  10474. lbValue value = *found;
  10475. return value;
  10476. }
  10477. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  10478. i32 index = cast(i32)lb_type_info_index(m->info, type);
  10479. GB_ASSERT(index >= 0);
  10480. // gb_printf_err("%d %s\n", index, type_to_string(type));
  10481. LLVMValueRef indices[2] = {
  10482. LLVMConstInt(lb_type(m, t_int), 0, false),
  10483. LLVMConstInt(lb_type(m, t_int), index, false),
  10484. };
  10485. lbValue res = {};
  10486. res.type = t_type_info_ptr;
  10487. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  10488. return res;
  10489. }
  10490. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  10491. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  10492. lb_global_type_info_member_types_index += cast(i32)count;
  10493. return offset;
  10494. }
  10495. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  10496. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  10497. lb_global_type_info_member_names_index += cast(i32)count;
  10498. return offset;
  10499. }
  10500. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  10501. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  10502. lb_global_type_info_member_offsets_index += cast(i32)count;
  10503. return offset;
  10504. }
  10505. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  10506. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  10507. lb_global_type_info_member_usings_index += cast(i32)count;
  10508. return offset;
  10509. }
  10510. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  10511. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  10512. lb_global_type_info_member_tags_index += cast(i32)count;
  10513. return offset;
  10514. }
  10515. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  10516. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  10517. return lb_addr_get_ptr(p, addr);
  10518. }
  10519. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  10520. Token token = {Token_Ident};
  10521. isize name_len = prefix.len + 1 + 20;
  10522. auto suffix_id = cast(unsigned long long)id;
  10523. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  10524. gb_snprintf(text, name_len,
  10525. "%.*s-%llu", LIT(prefix), suffix_id);
  10526. text[name_len] = 0;
  10527. String s = make_string_c(text);
  10528. Type *t = alloc_type_array(elem_type, count);
  10529. lbValue g = {};
  10530. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  10531. g.type = alloc_type_pointer(t);
  10532. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  10533. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  10534. string_map_set(&m->members, s, g);
  10535. return g;
  10536. }
  10537. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  10538. lbModule *m = p->module;
  10539. LLVMContextRef ctx = m->ctx;
  10540. CheckerInfo *info = m->info;
  10541. {
  10542. // NOTE(bill): Set the type_table slice with the global backing array
  10543. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  10544. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  10545. GB_ASSERT(is_type_array(type));
  10546. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  10547. LLVMValueRef values[2] = {
  10548. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  10549. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  10550. };
  10551. LLVMValueRef slice = llvm_const_named_struct(llvm_addr_type(global_type_table), values, gb_count_of(values));
  10552. LLVMSetInitializer(global_type_table.value, slice);
  10553. }
  10554. // Useful types
  10555. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  10556. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  10557. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  10558. Type *t_type_info_flags = type_info_flags_entity->type;
  10559. i32 type_info_member_types_index = 0;
  10560. i32 type_info_member_names_index = 0;
  10561. i32 type_info_member_offsets_index = 0;
  10562. for_array(type_info_type_index, info->type_info_types) {
  10563. Type *t = info->type_info_types[type_info_type_index];
  10564. if (t == nullptr || t == t_invalid) {
  10565. continue;
  10566. }
  10567. isize entry_index = lb_type_info_index(info, t, false);
  10568. if (entry_index <= 0) {
  10569. continue;
  10570. }
  10571. lbValue tag = {};
  10572. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  10573. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  10574. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  10575. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  10576. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  10577. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  10578. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  10579. switch (t->kind) {
  10580. case Type_Named: {
  10581. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  10582. LLVMValueRef pkg_name = nullptr;
  10583. if (t->Named.type_name->pkg) {
  10584. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  10585. } else {
  10586. pkg_name = LLVMConstNull(lb_type(m, t_string));
  10587. }
  10588. String proc_name = {};
  10589. if (t->Named.type_name->parent_proc_decl) {
  10590. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  10591. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  10592. proc_name = decl->entity->token.string;
  10593. }
  10594. }
  10595. TokenPos pos = t->Named.type_name->token.pos;
  10596. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  10597. LLVMValueRef vals[4] = {
  10598. lb_const_string(p->module, t->Named.type_name->token.string).value,
  10599. lb_get_type_info_ptr(m, t->Named.base).value,
  10600. pkg_name,
  10601. loc.value
  10602. };
  10603. lbValue res = {};
  10604. res.type = type_deref(tag.type);
  10605. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10606. lb_emit_store(p, tag, res);
  10607. break;
  10608. }
  10609. case Type_Basic:
  10610. switch (t->Basic.kind) {
  10611. case Basic_bool:
  10612. case Basic_b8:
  10613. case Basic_b16:
  10614. case Basic_b32:
  10615. case Basic_b64:
  10616. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  10617. break;
  10618. case Basic_i8:
  10619. case Basic_u8:
  10620. case Basic_i16:
  10621. case Basic_u16:
  10622. case Basic_i32:
  10623. case Basic_u32:
  10624. case Basic_i64:
  10625. case Basic_u64:
  10626. case Basic_i128:
  10627. case Basic_u128:
  10628. case Basic_i16le:
  10629. case Basic_u16le:
  10630. case Basic_i32le:
  10631. case Basic_u32le:
  10632. case Basic_i64le:
  10633. case Basic_u64le:
  10634. case Basic_i128le:
  10635. case Basic_u128le:
  10636. case Basic_i16be:
  10637. case Basic_u16be:
  10638. case Basic_i32be:
  10639. case Basic_u32be:
  10640. case Basic_i64be:
  10641. case Basic_u64be:
  10642. case Basic_i128be:
  10643. case Basic_u128be:
  10644. case Basic_int:
  10645. case Basic_uint:
  10646. case Basic_uintptr: {
  10647. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  10648. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  10649. // NOTE(bill): This is matches the runtime layout
  10650. u8 endianness_value = 0;
  10651. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10652. endianness_value = 1;
  10653. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10654. endianness_value = 2;
  10655. }
  10656. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10657. LLVMValueRef vals[2] = {
  10658. is_signed.value,
  10659. endianness.value,
  10660. };
  10661. lbValue res = {};
  10662. res.type = type_deref(tag.type);
  10663. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10664. lb_emit_store(p, tag, res);
  10665. break;
  10666. }
  10667. case Basic_rune:
  10668. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  10669. break;
  10670. // case Basic_f16:
  10671. case Basic_f32:
  10672. case Basic_f64:
  10673. case Basic_f32le:
  10674. case Basic_f64le:
  10675. case Basic_f32be:
  10676. case Basic_f64be:
  10677. {
  10678. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  10679. // NOTE(bill): This is matches the runtime layout
  10680. u8 endianness_value = 0;
  10681. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10682. endianness_value = 1;
  10683. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10684. endianness_value = 2;
  10685. }
  10686. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10687. LLVMValueRef vals[1] = {
  10688. endianness.value,
  10689. };
  10690. lbValue res = {};
  10691. res.type = type_deref(tag.type);
  10692. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10693. lb_emit_store(p, tag, res);
  10694. }
  10695. break;
  10696. // case Basic_complex32:
  10697. case Basic_complex64:
  10698. case Basic_complex128:
  10699. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  10700. break;
  10701. case Basic_quaternion128:
  10702. case Basic_quaternion256:
  10703. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  10704. break;
  10705. case Basic_rawptr:
  10706. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10707. break;
  10708. case Basic_string:
  10709. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10710. break;
  10711. case Basic_cstring:
  10712. {
  10713. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10714. LLVMValueRef vals[1] = {
  10715. lb_const_bool(m, t_bool, true).value,
  10716. };
  10717. lbValue res = {};
  10718. res.type = type_deref(tag.type);
  10719. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10720. lb_emit_store(p, tag, res);
  10721. }
  10722. break;
  10723. case Basic_any:
  10724. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  10725. break;
  10726. case Basic_typeid:
  10727. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  10728. break;
  10729. }
  10730. break;
  10731. case Type_Pointer: {
  10732. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10733. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  10734. LLVMValueRef vals[1] = {
  10735. gep.value,
  10736. };
  10737. lbValue res = {};
  10738. res.type = type_deref(tag.type);
  10739. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10740. lb_emit_store(p, tag, res);
  10741. break;
  10742. }
  10743. case Type_Array: {
  10744. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  10745. i64 ez = type_size_of(t->Array.elem);
  10746. LLVMValueRef vals[3] = {
  10747. lb_get_type_info_ptr(m, t->Array.elem).value,
  10748. lb_const_int(m, t_int, ez).value,
  10749. lb_const_int(m, t_int, t->Array.count).value,
  10750. };
  10751. lbValue res = {};
  10752. res.type = type_deref(tag.type);
  10753. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10754. lb_emit_store(p, tag, res);
  10755. break;
  10756. }
  10757. case Type_EnumeratedArray: {
  10758. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  10759. LLVMValueRef vals[6] = {
  10760. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  10761. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  10762. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  10763. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  10764. // Unions
  10765. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10766. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10767. };
  10768. lbValue res = {};
  10769. res.type = type_deref(tag.type);
  10770. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10771. lb_emit_store(p, tag, res);
  10772. // NOTE(bill): Union assignment
  10773. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  10774. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  10775. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  10776. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  10777. lb_emit_store(p, min_value, min_v);
  10778. lb_emit_store(p, max_value, max_v);
  10779. break;
  10780. }
  10781. case Type_DynamicArray: {
  10782. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  10783. LLVMValueRef vals[2] = {
  10784. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  10785. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  10786. };
  10787. lbValue res = {};
  10788. res.type = type_deref(tag.type);
  10789. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10790. lb_emit_store(p, tag, res);
  10791. break;
  10792. }
  10793. case Type_Slice: {
  10794. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  10795. LLVMValueRef vals[2] = {
  10796. lb_get_type_info_ptr(m, t->Slice.elem).value,
  10797. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  10798. };
  10799. lbValue res = {};
  10800. res.type = type_deref(tag.type);
  10801. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10802. lb_emit_store(p, tag, res);
  10803. break;
  10804. }
  10805. case Type_Proc: {
  10806. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  10807. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10808. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10809. if (t->Proc.params != nullptr) {
  10810. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  10811. }
  10812. if (t->Proc.results != nullptr) {
  10813. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  10814. }
  10815. LLVMValueRef vals[4] = {
  10816. params,
  10817. results,
  10818. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  10819. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  10820. };
  10821. lbValue res = {};
  10822. res.type = type_deref(tag.type);
  10823. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10824. lb_emit_store(p, tag, res);
  10825. break;
  10826. }
  10827. case Type_Tuple: {
  10828. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  10829. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  10830. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  10831. for_array(i, t->Tuple.variables) {
  10832. // NOTE(bill): offset is not used for tuples
  10833. Entity *f = t->Tuple.variables[i];
  10834. lbValue index = lb_const_int(m, t_int, i);
  10835. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10836. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  10837. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10838. if (f->token.string.len > 0) {
  10839. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10840. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10841. }
  10842. }
  10843. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  10844. LLVMValueRef types_slice = llvm_const_slice(m, memory_types, count);
  10845. LLVMValueRef names_slice = llvm_const_slice(m, memory_names, count);
  10846. LLVMValueRef vals[2] = {
  10847. types_slice,
  10848. names_slice,
  10849. };
  10850. lbValue res = {};
  10851. res.type = type_deref(tag.type);
  10852. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10853. lb_emit_store(p, tag, res);
  10854. break;
  10855. }
  10856. case Type_Enum:
  10857. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  10858. {
  10859. GB_ASSERT(t->Enum.base_type != nullptr);
  10860. // 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));
  10861. LLVMValueRef vals[3] = {};
  10862. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  10863. if (t->Enum.fields.count > 0) {
  10864. auto fields = t->Enum.fields;
  10865. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  10866. str_lit("$enum_names"), cast(i64)entry_index);
  10867. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  10868. str_lit("$enum_values"), cast(i64)entry_index);
  10869. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10870. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10871. GB_ASSERT(is_type_integer(t->Enum.base_type));
  10872. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  10873. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  10874. for_array(i, fields) {
  10875. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  10876. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  10877. }
  10878. LLVMValueRef name_init = llvm_const_array(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  10879. LLVMValueRef value_init = llvm_const_array(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  10880. LLVMSetInitializer(name_array.value, name_init);
  10881. LLVMSetInitializer(value_array.value, value_init);
  10882. lbValue v_count = lb_const_int(m, t_int, fields.count);
  10883. vals[1] = llvm_const_slice(m, lb_array_elem(p, name_array), v_count);
  10884. vals[2] = llvm_const_slice(m, lb_array_elem(p, value_array), v_count);
  10885. } else {
  10886. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  10887. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  10888. }
  10889. lbValue res = {};
  10890. res.type = type_deref(tag.type);
  10891. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10892. lb_emit_store(p, tag, res);
  10893. }
  10894. break;
  10895. case Type_Union: {
  10896. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  10897. {
  10898. LLVMValueRef vals[6] = {};
  10899. isize variant_count = gb_max(0, t->Union.variants.count);
  10900. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  10901. // NOTE(bill): Zeroth is nil so ignore it
  10902. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  10903. Type *vt = t->Union.variants[variant_index];
  10904. lbValue tip = lb_get_type_info_ptr(m, vt);
  10905. lbValue index = lb_const_int(m, t_int, variant_index);
  10906. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10907. lb_emit_store(p, type_info, lb_type_info(m, vt));
  10908. }
  10909. lbValue count = lb_const_int(m, t_int, variant_count);
  10910. vals[0] = llvm_const_slice(m, memory_types, count);
  10911. i64 tag_size = union_tag_size(t);
  10912. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  10913. if (tag_size > 0) {
  10914. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  10915. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  10916. } else {
  10917. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  10918. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10919. }
  10920. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  10921. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  10922. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  10923. lbValue res = {};
  10924. res.type = type_deref(tag.type);
  10925. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10926. lb_emit_store(p, tag, res);
  10927. }
  10928. break;
  10929. }
  10930. case Type_Struct: {
  10931. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  10932. LLVMValueRef vals[12] = {};
  10933. {
  10934. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  10935. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  10936. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  10937. vals[5] = is_packed.value;
  10938. vals[6] = is_raw_union.value;
  10939. vals[7] = is_custom_align.value;
  10940. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  10941. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  10942. }
  10943. if (t->Struct.soa_kind != StructSoa_None) {
  10944. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  10945. Type *kind_type = type_deref(kind.type);
  10946. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  10947. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  10948. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  10949. vals[9] = soa_kind.value;
  10950. vals[10] = soa_type.value;
  10951. vals[11] = soa_len.value;
  10952. }
  10953. }
  10954. isize count = t->Struct.fields.count;
  10955. if (count > 0) {
  10956. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  10957. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  10958. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  10959. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  10960. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  10961. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  10962. for (isize source_index = 0; source_index < count; source_index++) {
  10963. // TODO(bill): Order fields in source order not layout order
  10964. Entity *f = t->Struct.fields[source_index];
  10965. lbValue tip = lb_get_type_info_ptr(m, f->type);
  10966. i64 foffset = 0;
  10967. if (!t->Struct.is_raw_union) {
  10968. foffset = t->Struct.offsets[f->Variable.field_index];
  10969. }
  10970. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  10971. lbValue index = lb_const_int(m, t_int, source_index);
  10972. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10973. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  10974. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  10975. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10976. if (f->token.string.len > 0) {
  10977. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10978. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10979. }
  10980. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  10981. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  10982. if (t->Struct.tags.count > 0) {
  10983. String tag_string = t->Struct.tags[source_index];
  10984. if (tag_string.len > 0) {
  10985. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  10986. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  10987. }
  10988. }
  10989. }
  10990. lbValue cv = lb_const_int(m, t_int, count);
  10991. vals[0] = llvm_const_slice(m, memory_types, cv);
  10992. vals[1] = llvm_const_slice(m, memory_names, cv);
  10993. vals[2] = llvm_const_slice(m, memory_offsets, cv);
  10994. vals[3] = llvm_const_slice(m, memory_usings, cv);
  10995. vals[4] = llvm_const_slice(m, memory_tags, cv);
  10996. }
  10997. for (isize i = 0; i < gb_count_of(vals); i++) {
  10998. if (vals[i] == nullptr) {
  10999. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  11000. }
  11001. }
  11002. lbValue res = {};
  11003. res.type = type_deref(tag.type);
  11004. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11005. lb_emit_store(p, tag, res);
  11006. break;
  11007. }
  11008. case Type_Map: {
  11009. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  11010. init_map_internal_types(t);
  11011. LLVMValueRef vals[5] = {
  11012. lb_get_type_info_ptr(m, t->Map.key).value,
  11013. lb_get_type_info_ptr(m, t->Map.value).value,
  11014. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  11015. lb_get_equal_proc_for_type(m, t->Map.key).value,
  11016. lb_get_hasher_proc_for_type(m, t->Map.key).value
  11017. };
  11018. lbValue res = {};
  11019. res.type = type_deref(tag.type);
  11020. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11021. lb_emit_store(p, tag, res);
  11022. break;
  11023. }
  11024. case Type_BitSet:
  11025. {
  11026. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  11027. GB_ASSERT(is_type_typed(t->BitSet.elem));
  11028. LLVMValueRef vals[4] = {
  11029. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  11030. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  11031. lb_const_int(m, t_i64, t->BitSet.lower).value,
  11032. lb_const_int(m, t_i64, t->BitSet.upper).value,
  11033. };
  11034. if (t->BitSet.underlying != nullptr) {
  11035. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  11036. }
  11037. lbValue res = {};
  11038. res.type = type_deref(tag.type);
  11039. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11040. lb_emit_store(p, tag, res);
  11041. }
  11042. break;
  11043. case Type_SimdVector:
  11044. {
  11045. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  11046. LLVMValueRef vals[4] = {};
  11047. if (t->SimdVector.is_x86_mmx) {
  11048. vals[3] = lb_const_bool(m, t_bool, true).value;
  11049. } else {
  11050. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  11051. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  11052. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  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_RelativePointer:
  11061. {
  11062. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  11063. LLVMValueRef vals[2] = {
  11064. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  11065. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  11066. };
  11067. lbValue res = {};
  11068. res.type = type_deref(tag.type);
  11069. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11070. lb_emit_store(p, tag, res);
  11071. }
  11072. break;
  11073. case Type_RelativeSlice:
  11074. {
  11075. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  11076. LLVMValueRef vals[2] = {
  11077. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  11078. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  11079. };
  11080. lbValue res = {};
  11081. res.type = type_deref(tag.type);
  11082. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11083. lb_emit_store(p, tag, res);
  11084. }
  11085. break;
  11086. }
  11087. if (tag.value != nullptr) {
  11088. Type *tag_type = type_deref(tag.type);
  11089. GB_ASSERT(is_type_named(tag_type));
  11090. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  11091. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  11092. } else {
  11093. if (t != t_llvm_bool) {
  11094. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  11095. }
  11096. }
  11097. }
  11098. }
  11099. void lb_generate_code(lbGenerator *gen) {
  11100. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  11101. TIME_SECTION("LLVM Initializtion");
  11102. lbModule *m = &gen->module;
  11103. LLVMModuleRef mod = gen->module.mod;
  11104. CheckerInfo *info = gen->info;
  11105. auto *min_dep_set = &info->minimum_dependency_set;
  11106. LLVMInitializeAllTargetInfos();
  11107. LLVMInitializeAllTargets();
  11108. LLVMInitializeAllTargetMCs();
  11109. LLVMInitializeAllAsmPrinters();
  11110. LLVMInitializeAllAsmParsers();
  11111. LLVMInitializeAllDisassemblers();
  11112. LLVMInitializeNativeTarget();
  11113. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  11114. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  11115. LLVMSetTarget(mod, target_triple);
  11116. LLVMTargetRef target = {};
  11117. char *llvm_error = nullptr;
  11118. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  11119. GB_ASSERT(target != nullptr);
  11120. TIME_SECTION("LLVM Create Target Machine");
  11121. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  11122. if (build_context.metrics.arch == TargetArch_wasm32) {
  11123. code_mode = LLVMCodeModelJITDefault;
  11124. }
  11125. char const *host_cpu_name = LLVMGetHostCPUName();
  11126. char const *llvm_cpu = "generic";
  11127. char const *llvm_features = "";
  11128. if (build_context.microarch.len != 0) {
  11129. if (build_context.microarch == "native") {
  11130. llvm_cpu = host_cpu_name;
  11131. } else {
  11132. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  11133. }
  11134. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  11135. llvm_features = LLVMGetHostCPUFeatures();
  11136. }
  11137. }
  11138. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  11139. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  11140. switch (build_context.optimization_level) {
  11141. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  11142. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  11143. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  11144. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  11145. }
  11146. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, llvm_cpu, llvm_features, code_gen_level, LLVMRelocDefault, code_mode);
  11147. defer (LLVMDisposeTargetMachine(target_machine));
  11148. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  11149. if (m->debug_builder) { // Debug Info
  11150. for_array(i, info->files.entries) {
  11151. AstFile *f = info->files.entries[i].value;
  11152. String fullpath = f->fullpath;
  11153. String filename = remove_directory_from_path(fullpath);
  11154. String directory = directory_from_path(fullpath);
  11155. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  11156. cast(char const *)filename.text, filename.len,
  11157. cast(char const *)directory.text, directory.len);
  11158. lb_set_llvm_metadata(m, f, res);
  11159. }
  11160. gbString producer = gb_string_make(heap_allocator(), "odin");
  11161. producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  11162. #ifdef NIGHTLY
  11163. producer = gb_string_appendc(producer, "-nightly");
  11164. #endif
  11165. #ifdef GIT_SHA
  11166. producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  11167. #endif
  11168. gbString split_name = gb_string_make(heap_allocator(), "");
  11169. LLVMBool is_optimized = build_context.optimization_level > 0;
  11170. AstFile *init_file = m->info->init_package->files[0];
  11171. if (m->info->entry_point && m->info->entry_point->identifier && m->info->entry_point->identifier->file) {
  11172. init_file = m->info->entry_point->identifier->file;
  11173. }
  11174. LLVMBool split_debug_inlining = false;
  11175. LLVMBool debug_info_for_profiling = false;
  11176. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  11177. lb_get_llvm_metadata(m, init_file),
  11178. producer, gb_string_length(producer),
  11179. is_optimized, "", 0,
  11180. 1, split_name, gb_string_length(split_name),
  11181. LLVMDWARFEmissionFull,
  11182. 0, split_debug_inlining,
  11183. debug_info_for_profiling,
  11184. "", 0, // sys_root
  11185. "", 0 // SDK
  11186. );
  11187. GB_ASSERT(m->debug_compile_unit != nullptr);
  11188. }
  11189. TIME_SECTION("LLVM Global Variables");
  11190. {
  11191. { // Add type info data
  11192. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  11193. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  11194. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  11195. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  11196. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11197. LLVMSetLinkage(g, LLVMInternalLinkage);
  11198. lbValue value = {};
  11199. value.value = g;
  11200. value.type = alloc_type_pointer(t);
  11201. lb_global_type_info_data = lb_addr(value);
  11202. }
  11203. { // Type info member buffer
  11204. // NOTE(bill): Removes need for heap allocation by making it global memory
  11205. isize count = 0;
  11206. for_array(entry_index, m->info->type_info_types) {
  11207. Type *t = m->info->type_info_types[entry_index];
  11208. isize index = lb_type_info_index(m->info, t, false);
  11209. if (index < 0) {
  11210. continue;
  11211. }
  11212. switch (t->kind) {
  11213. case Type_Union:
  11214. count += t->Union.variants.count;
  11215. break;
  11216. case Type_Struct:
  11217. count += t->Struct.fields.count;
  11218. break;
  11219. case Type_Tuple:
  11220. count += t->Tuple.variables.count;
  11221. break;
  11222. }
  11223. }
  11224. if (count > 0) {
  11225. {
  11226. char const *name = LB_TYPE_INFO_TYPES_NAME;
  11227. Type *t = alloc_type_array(t_type_info_ptr, count);
  11228. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11229. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11230. LLVMSetLinkage(g, LLVMInternalLinkage);
  11231. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  11232. }
  11233. {
  11234. char const *name = LB_TYPE_INFO_NAMES_NAME;
  11235. Type *t = alloc_type_array(t_string, count);
  11236. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11237. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11238. LLVMSetLinkage(g, LLVMInternalLinkage);
  11239. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  11240. }
  11241. {
  11242. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  11243. Type *t = alloc_type_array(t_uintptr, count);
  11244. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11245. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11246. LLVMSetLinkage(g, LLVMInternalLinkage);
  11247. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  11248. }
  11249. {
  11250. char const *name = LB_TYPE_INFO_USINGS_NAME;
  11251. Type *t = alloc_type_array(t_bool, count);
  11252. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11253. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11254. LLVMSetLinkage(g, LLVMInternalLinkage);
  11255. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  11256. }
  11257. {
  11258. char const *name = LB_TYPE_INFO_TAGS_NAME;
  11259. Type *t = alloc_type_array(t_string, count);
  11260. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11261. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11262. LLVMSetLinkage(g, LLVMInternalLinkage);
  11263. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  11264. }
  11265. }
  11266. }
  11267. }
  11268. isize global_variable_max_count = 0;
  11269. Entity *entry_point = info->entry_point;
  11270. bool has_dll_main = false;
  11271. bool has_win_main = false;
  11272. for_array(i, info->entities) {
  11273. Entity *e = info->entities[i];
  11274. String name = e->token.string;
  11275. bool is_global = e->pkg != nullptr;
  11276. if (e->kind == Entity_Variable) {
  11277. global_variable_max_count++;
  11278. } else if (e->kind == Entity_Procedure && !is_global) {
  11279. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  11280. GB_ASSERT(e == entry_point);
  11281. // entry_point = e;
  11282. }
  11283. if (e->Procedure.is_export ||
  11284. (e->Procedure.link_name.len > 0) ||
  11285. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  11286. if (!has_dll_main && name == "DllMain") {
  11287. has_dll_main = true;
  11288. } else if (!has_win_main && name == "WinMain") {
  11289. has_win_main = true;
  11290. }
  11291. }
  11292. }
  11293. }
  11294. struct GlobalVariable {
  11295. lbValue var;
  11296. lbValue init;
  11297. DeclInfo *decl;
  11298. bool is_initialized;
  11299. };
  11300. auto global_variables = array_make<GlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  11301. for_array(i, info->variable_init_order) {
  11302. DeclInfo *d = info->variable_init_order[i];
  11303. Entity *e = d->entity;
  11304. if ((e->scope->flags & ScopeFlag_File) == 0) {
  11305. continue;
  11306. }
  11307. if (!ptr_set_exists(min_dep_set, e)) {
  11308. continue;
  11309. }
  11310. DeclInfo *decl = decl_info_of_entity(e);
  11311. if (decl == nullptr) {
  11312. continue;
  11313. }
  11314. GB_ASSERT(e->kind == Entity_Variable);
  11315. bool is_foreign = e->Variable.is_foreign;
  11316. bool is_export = e->Variable.is_export;
  11317. String name = lb_get_entity_name(m, e);
  11318. lbValue g = {};
  11319. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  11320. g.type = alloc_type_pointer(e->type);
  11321. if (e->Variable.thread_local_model != "") {
  11322. LLVMSetThreadLocal(g.value, true);
  11323. String m = e->Variable.thread_local_model;
  11324. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  11325. if (m == "default") {
  11326. mode = LLVMGeneralDynamicTLSModel;
  11327. } else if (m == "localdynamic") {
  11328. mode = LLVMLocalDynamicTLSModel;
  11329. } else if (m == "initialexec") {
  11330. mode = LLVMInitialExecTLSModel;
  11331. } else if (m == "localexec") {
  11332. mode = LLVMLocalExecTLSModel;
  11333. } else {
  11334. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  11335. }
  11336. LLVMSetThreadLocalMode(g.value, mode);
  11337. }
  11338. if (is_foreign) {
  11339. LLVMSetExternallyInitialized(g.value, true);
  11340. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  11341. } else {
  11342. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  11343. }
  11344. if (is_export) {
  11345. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  11346. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  11347. }
  11348. if (e->flags & EntityFlag_Static) {
  11349. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  11350. }
  11351. GlobalVariable var = {};
  11352. var.var = g;
  11353. var.decl = decl;
  11354. if (decl->init_expr != nullptr) {
  11355. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  11356. if (!is_type_any(e->type)) {
  11357. if (tav.mode != Addressing_Invalid) {
  11358. if (tav.value.kind != ExactValue_Invalid) {
  11359. ExactValue v = tav.value;
  11360. lbValue init = lb_const_value(m, tav.type, v);
  11361. LLVMSetInitializer(g.value, init.value);
  11362. var.is_initialized = true;
  11363. }
  11364. }
  11365. }
  11366. if (!var.is_initialized &&
  11367. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  11368. var.is_initialized = true;
  11369. }
  11370. }
  11371. array_add(&global_variables, var);
  11372. lb_add_entity(m, e, g);
  11373. lb_add_member(m, name, g);
  11374. if (m->debug_builder) {
  11375. String global_name = e->token.string;
  11376. if (global_name.len != 0 && global_name != "_") {
  11377. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  11378. LLVMMetadataRef llvm_scope = llvm_file;
  11379. LLVMBool local_to_unit = e->flags & EntityFlag_Static;
  11380. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  11381. LLVMMetadataRef llvm_decl = nullptr;
  11382. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  11383. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  11384. m->debug_builder, llvm_scope,
  11385. cast(char const *)global_name.text, global_name.len,
  11386. "", 0, // linkage
  11387. llvm_file, e->token.pos.line,
  11388. lb_debug_type(m, e->type),
  11389. local_to_unit,
  11390. llvm_expr,
  11391. llvm_decl,
  11392. align_in_bits
  11393. );
  11394. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  11395. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  11396. }
  11397. }
  11398. }
  11399. TIME_SECTION("LLVM Global Procedures and Types");
  11400. for_array(i, info->entities) {
  11401. Entity *e = info->entities[i];
  11402. String name = e->token.string;
  11403. DeclInfo *decl = e->decl_info;
  11404. Scope * scope = e->scope;
  11405. if ((scope->flags & ScopeFlag_File) == 0) {
  11406. continue;
  11407. }
  11408. Scope *package_scope = scope->parent;
  11409. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  11410. switch (e->kind) {
  11411. case Entity_Variable:
  11412. // NOTE(bill): Handled above as it requires a specific load order
  11413. continue;
  11414. case Entity_ProcGroup:
  11415. continue;
  11416. case Entity_TypeName:
  11417. case Entity_Procedure:
  11418. break;
  11419. }
  11420. bool polymorphic_struct = false;
  11421. if (e->type != nullptr && e->kind == Entity_TypeName) {
  11422. Type *bt = base_type(e->type);
  11423. if (bt->kind == Type_Struct) {
  11424. polymorphic_struct = is_type_polymorphic(bt);
  11425. }
  11426. }
  11427. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  11428. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  11429. continue;
  11430. }
  11431. String mangled_name = lb_get_entity_name(m, e);
  11432. switch (e->kind) {
  11433. case Entity_TypeName:
  11434. lb_type(m, e->type);
  11435. break;
  11436. case Entity_Procedure:
  11437. {
  11438. lbProcedure *p = lb_create_procedure(m, e);
  11439. array_add(&m->procedures_to_generate, p);
  11440. }
  11441. break;
  11442. }
  11443. }
  11444. TIME_SECTION("LLVM Registry Initializtion");
  11445. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  11446. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  11447. defer (LLVMDisposePassManager(default_function_pass_manager));
  11448. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  11449. lb_populate_function_pass_manager(default_function_pass_manager, false);
  11450. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  11451. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  11452. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  11453. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  11454. lb_populate_function_pass_manager(default_function_pass_manager_without_memcpy, true);
  11455. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  11456. TIME_SECTION("LLVM Runtime Type Information Creation");
  11457. lbProcedure *startup_type_info = nullptr;
  11458. lbProcedure *startup_runtime = nullptr;
  11459. { // Startup Type Info
  11460. Type *params = alloc_type_tuple();
  11461. Type *results = alloc_type_tuple();
  11462. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11463. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  11464. p->is_startup = true;
  11465. startup_type_info = p;
  11466. lb_begin_procedure_body(p);
  11467. lb_setup_type_info_data(p);
  11468. lb_end_procedure_body(p);
  11469. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11470. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11471. LLVMDumpValue(p->value);
  11472. gb_printf_err("\n\n\n\n");
  11473. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11474. }
  11475. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11476. }
  11477. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  11478. { // Startup Runtime
  11479. Type *params = alloc_type_tuple();
  11480. Type *results = alloc_type_tuple();
  11481. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11482. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  11483. p->is_startup = true;
  11484. startup_runtime = p;
  11485. lb_begin_procedure_body(p);
  11486. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  11487. for_array(i, global_variables) {
  11488. auto *var = &global_variables[i];
  11489. if (var->is_initialized) {
  11490. continue;
  11491. }
  11492. Entity *e = var->decl->entity;
  11493. GB_ASSERT(e->kind == Entity_Variable);
  11494. if (var->decl->init_expr != nullptr) {
  11495. // gb_printf_err("%s\n", expr_to_string(var->decl->init_expr));
  11496. lbValue init = lb_build_expr(p, var->decl->init_expr);
  11497. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  11498. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  11499. if (lb_is_const_or_global(init)) {
  11500. if (!var->is_initialized) {
  11501. LLVMSetInitializer(var->var.value, init.value);
  11502. var->is_initialized = true;
  11503. continue;
  11504. }
  11505. } else {
  11506. var->init = init;
  11507. }
  11508. }
  11509. if (var->init.value != nullptr) {
  11510. GB_ASSERT(!var->is_initialized);
  11511. Type *t = type_deref(var->var.type);
  11512. if (is_type_any(t)) {
  11513. // NOTE(bill): Edge case for 'any' type
  11514. Type *var_type = default_type(var->init.type);
  11515. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  11516. lb_addr_store(p, g, var->init);
  11517. lbValue gp = lb_addr_get_ptr(p, g);
  11518. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  11519. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  11520. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  11521. lb_emit_store(p, ti, lb_type_info(m, var_type));
  11522. } else {
  11523. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  11524. LLVMTypeRef vt = LLVMGetElementType(pvt);
  11525. lbValue src0 = lb_emit_conv(p, var->init, t);
  11526. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  11527. LLVMValueRef dst = var->var.value;
  11528. LLVMBuildStore(p->builder, src, dst);
  11529. }
  11530. var->is_initialized = true;
  11531. }
  11532. }
  11533. lb_end_procedure_body(p);
  11534. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11535. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11536. LLVMDumpValue(p->value);
  11537. gb_printf_err("\n\n\n\n");
  11538. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11539. }
  11540. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11541. /*{
  11542. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  11543. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  11544. instr != last_instr;
  11545. instr = LLVMGetNextInstruction(instr)) {
  11546. if (LLVMIsAAllocaInst(instr)) {
  11547. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  11548. LLVMValueRef sz_val = LLVMSizeOf(type);
  11549. GB_ASSERT(LLVMIsConstant(sz_val));
  11550. gb_printf_err(">> 0x%p\n", sz_val);
  11551. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  11552. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  11553. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  11554. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  11555. gb_printf_err(">> %ll\n", sz);
  11556. }
  11557. }
  11558. }*/
  11559. }
  11560. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  11561. TIME_SECTION("LLVM DLL main");
  11562. Type *params = alloc_type_tuple();
  11563. Type *results = alloc_type_tuple();
  11564. String name = str_lit("main");
  11565. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  11566. name = str_lit("mainCRTStartup");
  11567. } else {
  11568. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  11569. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  11570. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  11571. }
  11572. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  11573. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  11574. Type *proc_type = alloc_type_proc(nullptr,
  11575. params, params->Tuple.variables.count,
  11576. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  11577. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  11578. p->is_startup = true;
  11579. lb_begin_procedure_body(p);
  11580. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  11581. if (build_context.command_kind == Command_test) {
  11582. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  11583. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  11584. Type *slice_type = alloc_type_slice(t_Internal_Test);
  11585. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  11586. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  11587. LLVMTypeRef lbt_Internal_Test = lb_type(m, t_Internal_Test);
  11588. LLVMValueRef indices[2] = {};
  11589. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  11590. for_array(i, m->info->testing_procedures) {
  11591. Entity *testing_proc = m->info->testing_procedures[i];
  11592. String name = testing_proc->token.string;
  11593. lbValue *found = map_get(&m->values, hash_entity(testing_proc));
  11594. GB_ASSERT(found != nullptr);
  11595. String pkg_name = {};
  11596. if (testing_proc->pkg != nullptr) {
  11597. pkg_name = testing_proc->pkg->name;
  11598. }
  11599. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  11600. lbValue v_name = lb_find_or_add_entity_string(m, name);
  11601. lbValue v_proc = *found;
  11602. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  11603. LLVMValueRef vals[3] = {};
  11604. vals[0] = v_pkg.value;
  11605. vals[1] = v_name.value;
  11606. vals[2] = v_proc.value;
  11607. GB_ASSERT(LLVMIsConstant(vals[0]));
  11608. GB_ASSERT(LLVMIsConstant(vals[1]));
  11609. GB_ASSERT(LLVMIsConstant(vals[2]));
  11610. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  11611. LLVMValueRef src = llvm_const_named_struct(lbt_Internal_Test, vals, gb_count_of(vals));
  11612. LLVMBuildStore(p->builder, src, dst);
  11613. }
  11614. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  11615. lb_fill_slice(p, all_tests_slice,
  11616. lb_array_elem(p, all_tests_array),
  11617. lb_const_int(m, t_int, m->info->testing_procedures.count));
  11618. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  11619. auto args = array_make<lbValue>(heap_allocator(), 1);
  11620. args[0] = lb_addr_load(p, all_tests_slice);
  11621. lb_emit_call(p, runner, args);
  11622. } else {
  11623. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  11624. GB_ASSERT(found != nullptr);
  11625. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  11626. }
  11627. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  11628. lb_end_procedure_body(p);
  11629. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11630. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11631. LLVMDumpValue(p->value);
  11632. gb_printf_err("\n\n\n\n");
  11633. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11634. }
  11635. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11636. }
  11637. String filepath_ll = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".ll"));
  11638. TIME_SECTION("LLVM Procedure Generation");
  11639. for_array(i, m->procedures_to_generate) {
  11640. lbProcedure *p = m->procedures_to_generate[i];
  11641. if (p->is_done) {
  11642. continue;
  11643. }
  11644. if (p->body != nullptr) { // Build Procedure
  11645. m->curr_procedure = p;
  11646. lb_begin_procedure_body(p);
  11647. lb_build_stmt(p, p->body);
  11648. lb_end_procedure_body(p);
  11649. p->is_done = true;
  11650. m->curr_procedure = nullptr;
  11651. }
  11652. lb_end_procedure(p);
  11653. // Add Flags
  11654. if (p->body != nullptr) {
  11655. if (p->name == "memcpy" || p->name == "memmove" ||
  11656. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  11657. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  11658. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  11659. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  11660. }
  11661. }
  11662. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11663. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  11664. LLVMDumpValue(p->value);
  11665. gb_printf_err("\n\n\n\n");
  11666. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11667. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11668. }
  11669. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  11670. gb_exit(1);
  11671. }
  11672. }
  11673. if (m->debug_builder != nullptr) {
  11674. TIME_SECTION("LLVM Debug Info Complete Types");
  11675. lb_debug_complete_types(m);
  11676. TIME_SECTION("LLVM Print Module to File");
  11677. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11678. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11679. gb_exit(1);
  11680. return;
  11681. }
  11682. TIME_SECTION("LLVM Debug Info Builder Finalize");
  11683. LLVMDIBuilderFinalize(m->debug_builder);
  11684. }
  11685. TIME_SECTION("LLVM Function Pass");
  11686. {
  11687. for_array(i, m->procedures_to_generate) {
  11688. lbProcedure *p = m->procedures_to_generate[i];
  11689. if (p->body != nullptr) { // Build Procedure
  11690. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  11691. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  11692. } else {
  11693. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11694. }
  11695. }
  11696. }
  11697. for_array(i, m->equal_procs.entries) {
  11698. lbProcedure *p = m->equal_procs.entries[i].value;
  11699. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11700. }
  11701. for_array(i, m->hasher_procs.entries) {
  11702. lbProcedure *p = m->hasher_procs.entries[i].value;
  11703. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11704. }
  11705. }
  11706. TIME_SECTION("LLVM Module Pass");
  11707. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  11708. defer (LLVMDisposePassManager(module_pass_manager));
  11709. lb_populate_module_pass_manager(target_machine, module_pass_manager);
  11710. LLVMRunPassManager(module_pass_manager, mod);
  11711. llvm_error = nullptr;
  11712. defer (LLVMDisposeMessage(llvm_error));
  11713. String filepath_obj = {};
  11714. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  11715. if (build_context.build_mode == BuildMode_Assembly) {
  11716. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".S"));
  11717. code_gen_file_type = LLVMAssemblyFile;
  11718. } else {
  11719. switch (build_context.metrics.os) {
  11720. case TargetOs_windows:
  11721. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".obj"));
  11722. break;
  11723. case TargetOs_darwin:
  11724. case TargetOs_linux:
  11725. case TargetOs_essence:
  11726. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".o"));
  11727. break;
  11728. case TargetOs_js:
  11729. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  11730. break;
  11731. }
  11732. }
  11733. if (LLVMVerifyModule(mod, LLVMReturnStatusAction, &llvm_error)) {
  11734. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  11735. if (build_context.keep_temp_files) {
  11736. TIME_SECTION("LLVM Print Module to File");
  11737. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11738. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11739. gb_exit(1);
  11740. return;
  11741. }
  11742. }
  11743. gb_exit(1);
  11744. return;
  11745. }
  11746. llvm_error = nullptr;
  11747. if (build_context.keep_temp_files) {
  11748. TIME_SECTION("LLVM Print Module to File");
  11749. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11750. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11751. gb_exit(1);
  11752. return;
  11753. }
  11754. }
  11755. TIME_SECTION("LLVM Object Generation");
  11756. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  11757. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11758. gb_exit(1);
  11759. return;
  11760. }
  11761. array_add(&gen->output_object_paths, filepath_obj);
  11762. for_array(i, m->info->required_foreign_imports_through_force) {
  11763. Entity *e = m->info->required_foreign_imports_through_force[i];
  11764. lb_add_foreign_library_path(m, e);
  11765. }
  11766. #undef TIME_SECTION
  11767. }