llvm_backend.cpp 458 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592
  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->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->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. lbAddr old_addr = lb_find_or_generate_context_ptr(p);
  323. // IMPORTANT NOTE(bill, 2021-04-22): reuse unused 'context' variables to minimize stack usage
  324. // This has to be done manually since the optimizer cannot determine when this is possible
  325. bool create_new = true;
  326. for_array(i, p->context_stack) {
  327. lbContextData *ctx_data = &p->context_stack[i];
  328. if (ctx_data->ctx.addr.value == old_addr.addr.value) {
  329. if (ctx_data->uses > 0) {
  330. create_new = true;
  331. } else if (p->scope_index > ctx_data->scope_index) {
  332. create_new = true;
  333. } else {
  334. // gb_printf_err("%.*s (curr:%td) (ctx:%td) (uses:%td)\n", LIT(p->name), p->scope_index, ctx_data->scope_index, ctx_data->uses);
  335. create_new = false;
  336. }
  337. break;
  338. }
  339. }
  340. lbValue next = {};
  341. if (create_new) {
  342. lbValue old = lb_addr_load(p, old_addr);
  343. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  344. lb_addr_store(p, next_addr, old);
  345. lb_push_context_onto_stack(p, next_addr);
  346. next = next_addr.addr;
  347. } else {
  348. next = old_addr.addr;
  349. }
  350. if (addr.ctx.sel.index.count > 0) {
  351. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  352. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  353. lb_emit_store(p, lhs, rhs);
  354. } else {
  355. lbValue lhs = next;
  356. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  357. lb_emit_store(p, lhs, rhs);
  358. }
  359. return;
  360. } else if (addr.kind == lbAddr_SoaVariable) {
  361. Type *t = type_deref(addr.addr.type);
  362. t = base_type(t);
  363. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  364. Type *elem_type = t->Struct.soa_elem;
  365. value = lb_emit_conv(p, value, elem_type);
  366. elem_type = base_type(elem_type);
  367. lbValue index = addr.soa.index;
  368. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  369. Type *t = base_type(type_deref(addr.addr.type));
  370. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  371. lbValue len = lb_soa_struct_len(p, addr.addr);
  372. if (addr.soa.index_expr != nullptr) {
  373. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  374. }
  375. }
  376. isize field_count = 0;
  377. switch (elem_type->kind) {
  378. case Type_Struct:
  379. field_count = elem_type->Struct.fields.count;
  380. break;
  381. case Type_Array:
  382. field_count = elem_type->Array.count;
  383. break;
  384. }
  385. for (isize i = 0; i < field_count; i++) {
  386. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  387. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  388. if (t->Struct.soa_kind == StructSoa_Fixed) {
  389. dst = lb_emit_array_ep(p, dst, index);
  390. lb_emit_store(p, dst, src);
  391. } else {
  392. lbValue field = lb_emit_load(p, dst);
  393. dst = lb_emit_ptr_offset(p, field, index);
  394. lb_emit_store(p, dst, src);
  395. }
  396. }
  397. return;
  398. }
  399. GB_ASSERT(value.value != nullptr);
  400. value = lb_emit_conv(p, value, lb_addr_type(addr));
  401. // if (lb_is_const_or_global(value)) {
  402. // // NOTE(bill): Just bypass the actual storage and set the initializer
  403. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  404. // LLVMValueRef dst = addr.addr.value;
  405. // LLVMValueRef src = value.value;
  406. // LLVMSetInitializer(dst, src);
  407. // return;
  408. // }
  409. // }
  410. lb_emit_store(p, addr.addr, value);
  411. }
  412. void lb_const_store(lbValue ptr, lbValue value) {
  413. GB_ASSERT(lb_is_const(ptr));
  414. GB_ASSERT(lb_is_const(value));
  415. GB_ASSERT(is_type_pointer(ptr.type));
  416. LLVMSetInitializer(ptr.value, value.value);
  417. }
  418. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  419. GB_ASSERT(value.value != nullptr);
  420. Type *a = type_deref(ptr.type);
  421. if (is_type_boolean(a)) {
  422. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  423. value = lb_emit_conv(p, value, a);
  424. }
  425. Type *ca = core_type(a);
  426. if (ca->kind == Type_Basic) {
  427. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  428. }
  429. if (is_type_proc(a)) {
  430. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  431. // stored as regular pointer with no procedure information
  432. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  433. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  434. LLVMBuildStore(p->builder, v, ptr.value);
  435. } else {
  436. Type *ca = core_type(a);
  437. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  438. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  439. } else {
  440. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  441. }
  442. LLVMBuildStore(p->builder, value.value, ptr.value);
  443. }
  444. }
  445. LLVMTypeRef llvm_addr_type(lbValue addr_val) {
  446. return LLVMGetElementType(LLVMTypeOf(addr_val.value));
  447. }
  448. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  449. lbModule *m = p->module;
  450. GB_ASSERT(value.value != nullptr);
  451. GB_ASSERT(is_type_pointer(value.type));
  452. Type *t = type_deref(value.type);
  453. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  454. return lbValue{v, t};
  455. }
  456. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  457. GB_ASSERT(addr.addr.value != nullptr);
  458. if (addr.kind == lbAddr_RelativePointer) {
  459. Type *rel_ptr = base_type(lb_addr_type(addr));
  460. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  461. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  462. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  463. offset = lb_emit_load(p, offset);
  464. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  465. offset = lb_emit_conv(p, offset, t_i64);
  466. }
  467. offset = lb_emit_conv(p, offset, t_uintptr);
  468. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  469. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  470. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  471. // NOTE(bill): nil check
  472. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  473. lbValue final_ptr = {};
  474. final_ptr.type = absolute_ptr.type;
  475. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  476. return lb_emit_load(p, final_ptr);
  477. } else if (addr.kind == lbAddr_RelativeSlice) {
  478. Type *rel_ptr = base_type(lb_addr_type(addr));
  479. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  480. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  481. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  482. lbValue offset = lb_emit_load(p, offset_ptr);
  483. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  484. offset = lb_emit_conv(p, offset, t_i64);
  485. }
  486. offset = lb_emit_conv(p, offset, t_uintptr);
  487. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  488. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  489. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  490. Type *slice_elem = slice_type->Slice.elem;
  491. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  492. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  493. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  494. // NOTE(bill): nil check
  495. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  496. lbValue data = {};
  497. data.type = absolute_ptr.type;
  498. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  499. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  500. len = lb_emit_conv(p, len, t_int);
  501. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  502. lb_fill_slice(p, slice, data, len);
  503. return lb_addr_load(p, slice);
  504. } else if (addr.kind == lbAddr_Map) {
  505. Type *map_type = base_type(addr.map.type);
  506. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  507. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  508. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  509. auto args = array_make<lbValue>(permanent_allocator(), 2);
  510. args[0] = h;
  511. args[1] = key;
  512. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  513. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  514. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  515. lbBlock *then = lb_create_block(p, "map.get.then");
  516. lbBlock *done = lb_create_block(p, "map.get.done");
  517. lb_emit_if(p, ok, then, done);
  518. lb_start_block(p, then);
  519. {
  520. // TODO(bill): mem copy it instead?
  521. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  522. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  523. lb_emit_store(p, gep0, lb_emit_load(p, value));
  524. }
  525. lb_emit_jump(p, done);
  526. lb_start_block(p, done);
  527. if (is_type_tuple(addr.map.result)) {
  528. return lb_addr_load(p, v);
  529. } else {
  530. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  531. return lb_emit_load(p, single);
  532. }
  533. } else if (addr.kind == lbAddr_Context) {
  534. lbValue a = addr.addr;
  535. for_array(i, p->context_stack) {
  536. lbContextData *ctx_data = &p->context_stack[i];
  537. if (ctx_data->ctx.addr.value == a.value) {
  538. ctx_data->uses += 1;
  539. break;
  540. }
  541. }
  542. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  543. if (addr.ctx.sel.index.count > 0) {
  544. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  545. return lb_emit_load(p, b);
  546. } else {
  547. return lb_emit_load(p, a);
  548. }
  549. } else if (addr.kind == lbAddr_SoaVariable) {
  550. Type *t = type_deref(addr.addr.type);
  551. t = base_type(t);
  552. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  553. Type *elem = t->Struct.soa_elem;
  554. lbValue len = {};
  555. if (t->Struct.soa_kind == StructSoa_Fixed) {
  556. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  557. } else {
  558. lbValue v = lb_emit_load(p, addr.addr);
  559. len = lb_soa_struct_len(p, v);
  560. }
  561. lbAddr res = lb_add_local_generated(p, elem, true);
  562. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  563. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  564. }
  565. if (t->Struct.soa_kind == StructSoa_Fixed) {
  566. for_array(i, t->Struct.fields) {
  567. Entity *field = t->Struct.fields[i];
  568. Type *base_type = field->type;
  569. GB_ASSERT(base_type->kind == Type_Array);
  570. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  571. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  572. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  573. lbValue src = lb_emit_load(p, src_ptr);
  574. lb_emit_store(p, dst, src);
  575. }
  576. } else {
  577. isize field_count = t->Struct.fields.count;
  578. if (t->Struct.soa_kind == StructSoa_Slice) {
  579. field_count -= 1;
  580. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  581. field_count -= 3;
  582. }
  583. for (isize i = 0; i < field_count; i++) {
  584. Entity *field = t->Struct.fields[i];
  585. Type *base_type = field->type;
  586. GB_ASSERT(base_type->kind == Type_Pointer);
  587. Type *elem = base_type->Pointer.elem;
  588. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  589. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  590. lbValue src = lb_emit_load(p, src_ptr);
  591. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  592. src = lb_emit_load(p, src);
  593. lb_emit_store(p, dst, src);
  594. }
  595. }
  596. return lb_addr_load(p, res);
  597. }
  598. if (is_type_proc(addr.addr.type)) {
  599. return addr.addr;
  600. }
  601. return lb_emit_load(p, addr.addr);
  602. }
  603. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  604. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  605. }
  606. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  607. Type *t = u.type;
  608. GB_ASSERT_MSG(is_type_pointer(t) &&
  609. is_type_union(type_deref(t)), "%s", type_to_string(t));
  610. Type *ut = type_deref(t);
  611. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  612. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  613. GB_ASSERT(type_size_of(ut) > 0);
  614. Type *tag_type = union_tag_type(ut);
  615. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  616. unsigned element_count = LLVMCountStructElementTypes(uvt);
  617. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  618. lbValue tag_ptr = {};
  619. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  620. tag_ptr.type = alloc_type_pointer(tag_type);
  621. return tag_ptr;
  622. }
  623. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  624. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  625. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  626. return lb_emit_load(p, tag_ptr);
  627. }
  628. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  629. Type *t = type_deref(parent.type);
  630. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  631. // No tag needed!
  632. } else {
  633. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  634. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  635. }
  636. }
  637. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  638. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  639. lb_emit_store(p, underlying, variant);
  640. lb_emit_store_union_variant_tag(p, parent, variant_type);
  641. }
  642. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  643. unsigned field_count = LLVMCountStructElementTypes(src);
  644. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  645. LLVMGetStructElementTypes(src, fields);
  646. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  647. }
  648. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  649. switch (alignment) {
  650. case 1:
  651. return LLVMArrayType(lb_type(m, t_u8), 0);
  652. case 2:
  653. return LLVMArrayType(lb_type(m, t_u16), 0);
  654. case 4:
  655. return LLVMArrayType(lb_type(m, t_u32), 0);
  656. case 8:
  657. return LLVMArrayType(lb_type(m, t_u64), 0);
  658. case 16:
  659. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  660. default:
  661. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  662. break;
  663. }
  664. return nullptr;
  665. }
  666. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  667. if (!elem_type_can_be_constant(elem_type)) {
  668. return false;
  669. }
  670. if (elem->kind == Ast_FieldValue) {
  671. elem = elem->FieldValue.value;
  672. }
  673. TypeAndValue tav = type_and_value_of_expr(elem);
  674. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  675. return tav.value.kind != ExactValue_Invalid;
  676. }
  677. String lb_mangle_name(lbModule *m, Entity *e) {
  678. String name = e->token.string;
  679. AstPackage *pkg = e->pkg;
  680. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  681. String pkgn = pkg->name;
  682. GB_ASSERT(!rune_is_digit(pkgn[0]));
  683. if (pkgn == "llvm") {
  684. pkgn = str_lit("llvm$");
  685. }
  686. isize max_len = pkgn.len + 1 + name.len + 1;
  687. bool require_suffix_id = is_type_polymorphic(e->type, true);
  688. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  689. require_suffix_id = true;
  690. } else if (is_blank_ident(e->token)) {
  691. require_suffix_id = true;
  692. }if (e->flags & EntityFlag_NotExported) {
  693. require_suffix_id = true;
  694. }
  695. if (require_suffix_id) {
  696. max_len += 21;
  697. }
  698. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  699. isize new_name_len = gb_snprintf(
  700. new_name, max_len,
  701. "%.*s.%.*s", LIT(pkgn), LIT(name)
  702. );
  703. if (require_suffix_id) {
  704. char *str = new_name + new_name_len-1;
  705. isize len = max_len-new_name_len;
  706. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  707. new_name_len += extra-1;
  708. }
  709. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  710. return mangled_name;
  711. }
  712. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  713. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  714. // and as a result, the declaration does not have time to determine what it should be
  715. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  716. if (e->TypeName.ir_mangled_name.len != 0) {
  717. return e->TypeName.ir_mangled_name;
  718. }
  719. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  720. if (p == nullptr) {
  721. Entity *proc = nullptr;
  722. if (e->parent_proc_decl != nullptr) {
  723. proc = e->parent_proc_decl->entity;
  724. } else {
  725. Scope *scope = e->scope;
  726. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  727. scope = scope->parent;
  728. }
  729. GB_ASSERT(scope != nullptr);
  730. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  731. proc = scope->procedure_entity;
  732. }
  733. GB_ASSERT(proc->kind == Entity_Procedure);
  734. if (proc->code_gen_procedure != nullptr) {
  735. p = proc->code_gen_procedure;
  736. }
  737. }
  738. // NOTE(bill): Generate a new name
  739. // parent_proc.name-guid
  740. String ts_name = e->token.string;
  741. if (p != nullptr) {
  742. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  743. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  744. u32 guid = ++p->module->nested_type_name_guid;
  745. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  746. String name = make_string(cast(u8 *)name_text, name_len-1);
  747. e->TypeName.ir_mangled_name = name;
  748. return name;
  749. } else {
  750. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  751. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  752. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  753. static u32 guid = 0;
  754. guid += 1;
  755. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  756. String name = make_string(cast(u8 *)name_text, name_len-1);
  757. e->TypeName.ir_mangled_name = name;
  758. return name;
  759. }
  760. }
  761. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  762. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  763. return e->TypeName.ir_mangled_name;
  764. }
  765. GB_ASSERT(e != nullptr);
  766. if (e->pkg == nullptr) {
  767. return e->token.string;
  768. }
  769. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  770. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  771. }
  772. String name = {};
  773. bool no_name_mangle = false;
  774. if (e->kind == Entity_Variable) {
  775. bool is_foreign = e->Variable.is_foreign;
  776. bool is_export = e->Variable.is_export;
  777. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  778. if (e->Variable.link_name.len > 0) {
  779. return e->Variable.link_name;
  780. }
  781. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  782. return e->Procedure.link_name;
  783. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  784. no_name_mangle = true;
  785. }
  786. if (!no_name_mangle) {
  787. name = lb_mangle_name(m, e);
  788. }
  789. if (name.len == 0) {
  790. name = e->token.string;
  791. }
  792. if (e->kind == Entity_TypeName) {
  793. e->TypeName.ir_mangled_name = name;
  794. } else if (e->kind == Entity_Procedure) {
  795. e->Procedure.link_name = name;
  796. }
  797. return name;
  798. }
  799. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  800. Type *original_type = type;
  801. LLVMContextRef ctx = m->ctx;
  802. i64 size = type_size_of(type); // Check size
  803. GB_ASSERT(type != t_invalid);
  804. switch (type->kind) {
  805. case Type_Basic:
  806. switch (type->Basic.kind) {
  807. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  808. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  809. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  810. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  811. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  812. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  813. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  814. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  815. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  816. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  817. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  818. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  819. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  820. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  821. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  822. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  823. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  824. case Basic_f16: return LLVMHalfTypeInContext(ctx);
  825. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  826. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  827. case Basic_f16le: return LLVMHalfTypeInContext(ctx);
  828. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  829. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  830. case Basic_f16be: return LLVMHalfTypeInContext(ctx);
  831. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  832. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  833. case Basic_complex32:
  834. {
  835. char const *name = "..complex32";
  836. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  837. if (type != nullptr) {
  838. return type;
  839. }
  840. type = LLVMStructCreateNamed(ctx, name);
  841. LLVMTypeRef fields[2] = {
  842. lb_type(m, t_f16),
  843. lb_type(m, t_f16),
  844. };
  845. LLVMStructSetBody(type, fields, 2, false);
  846. return type;
  847. }
  848. case Basic_complex64:
  849. {
  850. char const *name = "..complex64";
  851. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  852. if (type != nullptr) {
  853. return type;
  854. }
  855. type = LLVMStructCreateNamed(ctx, name);
  856. LLVMTypeRef fields[2] = {
  857. lb_type(m, t_f32),
  858. lb_type(m, t_f32),
  859. };
  860. LLVMStructSetBody(type, fields, 2, false);
  861. return type;
  862. }
  863. case Basic_complex128:
  864. {
  865. char const *name = "..complex128";
  866. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  867. if (type != nullptr) {
  868. return type;
  869. }
  870. type = LLVMStructCreateNamed(ctx, name);
  871. LLVMTypeRef fields[2] = {
  872. lb_type(m, t_f64),
  873. lb_type(m, t_f64),
  874. };
  875. LLVMStructSetBody(type, fields, 2, false);
  876. return type;
  877. }
  878. case Basic_quaternion64:
  879. {
  880. char const *name = "..quaternion64";
  881. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  882. if (type != nullptr) {
  883. return type;
  884. }
  885. type = LLVMStructCreateNamed(ctx, name);
  886. LLVMTypeRef fields[4] = {
  887. lb_type(m, t_f16),
  888. lb_type(m, t_f16),
  889. lb_type(m, t_f16),
  890. lb_type(m, t_f16),
  891. };
  892. LLVMStructSetBody(type, fields, 4, false);
  893. return type;
  894. }
  895. case Basic_quaternion128:
  896. {
  897. char const *name = "..quaternion128";
  898. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  899. if (type != nullptr) {
  900. return type;
  901. }
  902. type = LLVMStructCreateNamed(ctx, name);
  903. LLVMTypeRef fields[4] = {
  904. lb_type(m, t_f32),
  905. lb_type(m, t_f32),
  906. lb_type(m, t_f32),
  907. lb_type(m, t_f32),
  908. };
  909. LLVMStructSetBody(type, fields, 4, false);
  910. return type;
  911. }
  912. case Basic_quaternion256:
  913. {
  914. char const *name = "..quaternion256";
  915. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  916. if (type != nullptr) {
  917. return type;
  918. }
  919. type = LLVMStructCreateNamed(ctx, name);
  920. LLVMTypeRef fields[4] = {
  921. lb_type(m, t_f64),
  922. lb_type(m, t_f64),
  923. lb_type(m, t_f64),
  924. lb_type(m, t_f64),
  925. };
  926. LLVMStructSetBody(type, fields, 4, false);
  927. return type;
  928. }
  929. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  930. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  931. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  932. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  933. case Basic_string:
  934. {
  935. char const *name = "..string";
  936. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  937. if (type != nullptr) {
  938. return type;
  939. }
  940. type = LLVMStructCreateNamed(ctx, name);
  941. LLVMTypeRef fields[2] = {
  942. LLVMPointerType(lb_type(m, t_u8), 0),
  943. lb_type(m, t_int),
  944. };
  945. LLVMStructSetBody(type, fields, 2, false);
  946. return type;
  947. }
  948. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  949. case Basic_any:
  950. {
  951. char const *name = "..any";
  952. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  953. if (type != nullptr) {
  954. return type;
  955. }
  956. type = LLVMStructCreateNamed(ctx, name);
  957. LLVMTypeRef fields[2] = {
  958. lb_type(m, t_rawptr),
  959. lb_type(m, t_typeid),
  960. };
  961. LLVMStructSetBody(type, fields, 2, false);
  962. return type;
  963. }
  964. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  965. // Endian Specific Types
  966. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  967. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  968. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  969. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  970. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  971. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  972. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  973. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  974. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  975. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  976. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  977. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  978. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  979. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  980. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  981. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  982. // Untyped types
  983. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  984. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  985. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  986. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  987. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  988. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  989. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  990. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  991. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  992. }
  993. break;
  994. case Type_Named:
  995. {
  996. Type *base = base_type(type->Named.base);
  997. switch (base->kind) {
  998. case Type_Basic:
  999. return lb_type_internal(m, base);
  1000. case Type_Named:
  1001. case Type_Generic:
  1002. GB_PANIC("INVALID TYPE");
  1003. break;
  1004. case Type_Pointer:
  1005. case Type_Array:
  1006. case Type_EnumeratedArray:
  1007. case Type_Slice:
  1008. case Type_DynamicArray:
  1009. case Type_Map:
  1010. case Type_Enum:
  1011. case Type_BitSet:
  1012. case Type_SimdVector:
  1013. return lb_type_internal(m, base);
  1014. // TODO(bill): Deal with this correctly. Can this be named?
  1015. case Type_Proc:
  1016. return lb_type_internal(m, base);
  1017. case Type_Tuple:
  1018. return lb_type_internal(m, base);
  1019. }
  1020. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1021. if (found) {
  1022. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1023. if (kind == LLVMStructTypeKind) {
  1024. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1025. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1026. if (llvm_type != nullptr) {
  1027. return llvm_type;
  1028. }
  1029. llvm_type = LLVMStructCreateNamed(ctx, name);
  1030. map_set(&m->types, hash_type(type), llvm_type);
  1031. lb_clone_struct_type(llvm_type, *found);
  1032. return llvm_type;
  1033. }
  1034. }
  1035. switch (base->kind) {
  1036. case Type_Struct:
  1037. case Type_Union:
  1038. {
  1039. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1040. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1041. if (llvm_type != nullptr) {
  1042. return llvm_type;
  1043. }
  1044. llvm_type = LLVMStructCreateNamed(ctx, name);
  1045. map_set(&m->types, hash_type(type), llvm_type);
  1046. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1047. return llvm_type;
  1048. }
  1049. }
  1050. return lb_type_internal(m, base);
  1051. }
  1052. case Type_Pointer:
  1053. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1054. case Type_Array: {
  1055. m->internal_type_level -= 1;
  1056. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1057. m->internal_type_level += 1;
  1058. return t;
  1059. }
  1060. case Type_EnumeratedArray: {
  1061. m->internal_type_level -= 1;
  1062. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1063. m->internal_type_level += 1;
  1064. return t;
  1065. }
  1066. case Type_Slice:
  1067. {
  1068. LLVMTypeRef fields[2] = {
  1069. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1070. lb_type(m, t_int), // len
  1071. };
  1072. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1073. }
  1074. break;
  1075. case Type_DynamicArray:
  1076. {
  1077. LLVMTypeRef fields[4] = {
  1078. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1079. lb_type(m, t_int), // len
  1080. lb_type(m, t_int), // cap
  1081. lb_type(m, t_allocator), // allocator
  1082. };
  1083. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1084. }
  1085. break;
  1086. case Type_Map:
  1087. return lb_type(m, type->Map.internal_type);
  1088. case Type_Struct:
  1089. {
  1090. if (type->Struct.is_raw_union) {
  1091. unsigned field_count = 2;
  1092. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1093. i64 alignment = type_align_of(type);
  1094. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1095. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1096. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1097. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1098. }
  1099. isize offset = 0;
  1100. if (type->Struct.custom_align > 0) {
  1101. offset = 1;
  1102. }
  1103. m->internal_type_level += 1;
  1104. defer (m->internal_type_level -= 1);
  1105. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1106. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1107. for_array(i, type->Struct.fields) {
  1108. Entity *field = type->Struct.fields[i];
  1109. fields[i+offset] = lb_type(m, field->type);
  1110. }
  1111. if (type->Struct.custom_align > 0) {
  1112. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1113. }
  1114. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1115. }
  1116. break;
  1117. case Type_Union:
  1118. if (type->Union.variants.count == 0) {
  1119. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1120. } else {
  1121. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1122. // LLVM takes the first element's alignment as the entire alignment (like C)
  1123. i64 align = type_align_of(type);
  1124. i64 size = type_size_of(type);
  1125. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1126. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1127. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1128. }
  1129. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1130. LLVMTypeRef fields[3] = {};
  1131. unsigned field_count = 1;
  1132. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1133. if (is_type_union_maybe_pointer(type)) {
  1134. field_count += 1;
  1135. fields[1] = lb_type(m, type->Union.variants[0]);
  1136. } else {
  1137. field_count += 2;
  1138. if (block_size == align) {
  1139. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1140. } else {
  1141. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1142. }
  1143. fields[2] = lb_type(m, union_tag_type(type));
  1144. }
  1145. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1146. }
  1147. break;
  1148. case Type_Enum:
  1149. return lb_type(m, base_enum_type(type));
  1150. case Type_Tuple:
  1151. if (type->Tuple.variables.count == 1) {
  1152. return lb_type(m, type->Tuple.variables[0]->type);
  1153. } else {
  1154. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1155. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1156. for_array(i, type->Tuple.variables) {
  1157. Entity *field = type->Tuple.variables[i];
  1158. LLVMTypeRef param_type = nullptr;
  1159. param_type = lb_type(m, field->type);
  1160. fields[i] = param_type;
  1161. }
  1162. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1163. }
  1164. case Type_Proc:
  1165. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1166. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1167. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1168. } else {
  1169. unsigned param_count = 0;
  1170. if (type->Proc.calling_convention == ProcCC_Odin) {
  1171. param_count += 1;
  1172. }
  1173. if (type->Proc.param_count != 0) {
  1174. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1175. for_array(i, type->Proc.params->Tuple.variables) {
  1176. Entity *e = type->Proc.params->Tuple.variables[i];
  1177. if (e->kind != Entity_Variable) {
  1178. continue;
  1179. }
  1180. if (e->flags & EntityFlag_CVarArg) {
  1181. continue;
  1182. }
  1183. param_count += 1;
  1184. }
  1185. }
  1186. m->internal_type_level += 1;
  1187. defer (m->internal_type_level -= 1);
  1188. LLVMTypeRef ret = nullptr;
  1189. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1190. if (type->Proc.result_count != 0) {
  1191. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1192. ret = lb_type(m, single_ret);
  1193. if (ret != nullptr) {
  1194. if (is_type_boolean(single_ret) &&
  1195. is_calling_convention_none(type->Proc.calling_convention) &&
  1196. type_size_of(single_ret) <= 1) {
  1197. ret = LLVMInt1TypeInContext(m->ctx);
  1198. }
  1199. }
  1200. }
  1201. isize param_index = 0;
  1202. if (type->Proc.param_count != 0) {
  1203. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1204. for_array(i, type->Proc.params->Tuple.variables) {
  1205. Entity *e = type->Proc.params->Tuple.variables[i];
  1206. if (e->kind != Entity_Variable) {
  1207. continue;
  1208. }
  1209. if (e->flags & EntityFlag_CVarArg) {
  1210. continue;
  1211. }
  1212. Type *e_type = reduce_tuple_to_single_type(e->type);
  1213. LLVMTypeRef param_type = nullptr;
  1214. if (is_type_boolean(e_type) &&
  1215. type_size_of(e_type) <= 1) {
  1216. param_type = LLVMInt1TypeInContext(m->ctx);
  1217. } else {
  1218. if (is_type_proc(e_type)) {
  1219. param_type = lb_type(m, t_rawptr);
  1220. } else {
  1221. param_type = lb_type(m, e_type);
  1222. }
  1223. }
  1224. params[param_index++] = param_type;
  1225. }
  1226. }
  1227. if (param_index < param_count) {
  1228. params[param_index++] = lb_type(m, t_rawptr);
  1229. // params[param_index++] = lb_type(m, t_context_ptr);
  1230. }
  1231. GB_ASSERT(param_index == param_count);
  1232. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1233. map_set(&m->function_type_map, hash_type(type), ft);
  1234. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1235. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1236. // LLVMTypeRef new_ret = LLVMGetReturnType(new_abi_fn_type);
  1237. // LLVMTypeRef old_ret = LLVMGetReturnType(old_abi_fn_type);
  1238. // unsigned new_count = LLVMCountParamTypes(new_abi_fn_type);
  1239. // unsigned old_count = LLVMCountParamTypes(old_abi_fn_type);
  1240. // 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));
  1241. return new_abi_fn_ptr_type;
  1242. }
  1243. break;
  1244. case Type_BitSet:
  1245. {
  1246. Type *ut = bit_set_to_int(type);
  1247. return lb_type(m, ut);
  1248. }
  1249. case Type_SimdVector:
  1250. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1251. case Type_RelativePointer:
  1252. return lb_type_internal(m, type->RelativePointer.base_integer);
  1253. case Type_RelativeSlice:
  1254. {
  1255. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1256. unsigned field_count = 2;
  1257. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1258. fields[0] = base_integer;
  1259. fields[1] = base_integer;
  1260. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1261. }
  1262. }
  1263. GB_PANIC("Invalid type %s", type_to_string(type));
  1264. return LLVMInt32TypeInContext(ctx);
  1265. }
  1266. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1267. type = default_type(type);
  1268. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1269. if (found) {
  1270. return *found;
  1271. }
  1272. LLVMTypeRef llvm_type = nullptr;
  1273. m->internal_type_level += 1;
  1274. llvm_type = lb_type_internal(m, type);
  1275. m->internal_type_level -= 1;
  1276. if (m->internal_type_level == 0) {
  1277. map_set(&m->types, hash_type(type), llvm_type);
  1278. if (is_type_named(type)) {
  1279. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1280. }
  1281. }
  1282. return llvm_type;
  1283. }
  1284. LLVMMetadataRef lb_get_llvm_metadata(lbModule *m, void *key) {
  1285. if (key == nullptr) {
  1286. return nullptr;
  1287. }
  1288. auto found = map_get(&m->debug_values, hash_pointer(key));
  1289. if (found) {
  1290. return *found;
  1291. }
  1292. return nullptr;
  1293. }
  1294. void lb_set_llvm_metadata(lbModule *m, void *key, LLVMMetadataRef value) {
  1295. if (key != nullptr) {
  1296. map_set(&m->debug_values, hash_pointer(key), value);
  1297. }
  1298. }
  1299. LLVMMetadataRef lb_get_llvm_file_metadata_from_node(lbModule *m, Ast *node) {
  1300. if (node == nullptr) {
  1301. return nullptr;
  1302. }
  1303. return lb_get_llvm_metadata(m, node->file);
  1304. }
  1305. LLVMMetadataRef lb_get_current_debug_scope(lbProcedure *p) {
  1306. GB_ASSERT_MSG(p->debug_info != nullptr, "missing debug information for %.*s", LIT(p->name));
  1307. for (isize i = p->scope_stack.count-1; i >= 0; i--) {
  1308. Scope *s = p->scope_stack[i];
  1309. LLVMMetadataRef md = lb_get_llvm_metadata(p->module, s);
  1310. if (md) {
  1311. return md;
  1312. }
  1313. }
  1314. return p->debug_info;
  1315. }
  1316. LLVMMetadataRef lb_debug_location_from_token_pos(lbProcedure *p, TokenPos pos) {
  1317. LLVMMetadataRef scope = lb_get_current_debug_scope(p);
  1318. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  1319. return LLVMDIBuilderCreateDebugLocation(p->module->ctx, cast(unsigned)pos.line, cast(unsigned)pos.column, scope, nullptr);
  1320. }
  1321. LLVMMetadataRef lb_debug_location_from_ast(lbProcedure *p, Ast *node) {
  1322. GB_ASSERT(node != nullptr);
  1323. return lb_debug_location_from_token_pos(p, ast_token(node).pos);
  1324. }
  1325. LLVMMetadataRef lb_debug_type_internal_proc(lbModule *m, Type *type) {
  1326. Type *original_type = type;
  1327. LLVMContextRef ctx = m->ctx;
  1328. i64 size = type_size_of(type); // Check size
  1329. GB_ASSERT(type != t_invalid);
  1330. unsigned const word_size = cast(unsigned)build_context.word_size;
  1331. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1332. GB_ASSERT(type->kind == Type_Proc);
  1333. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1334. unsigned parameter_count = 1;
  1335. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1336. Entity *e = type->Proc.params->Tuple.variables[i];
  1337. if (e->kind == Entity_Variable) {
  1338. parameter_count += 1;
  1339. }
  1340. }
  1341. LLVMMetadataRef *parameters = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, parameter_count);
  1342. unsigned param_index = 0;
  1343. if (type->Proc.result_count == 0) {
  1344. parameters[param_index++] = nullptr;
  1345. } else {
  1346. parameters[param_index++] = lb_debug_type(m, type->Proc.results);
  1347. }
  1348. LLVMMetadataRef parent_scope = nullptr;
  1349. LLVMMetadataRef scope = nullptr;
  1350. LLVMMetadataRef file = nullptr;
  1351. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1352. Entity *e = type->Proc.params->Tuple.variables[i];
  1353. if (e->kind != Entity_Variable) {
  1354. continue;
  1355. }
  1356. parameters[param_index] = lb_debug_type(m, e->type);
  1357. param_index += 1;
  1358. }
  1359. LLVMDIFlags flags = LLVMDIFlagZero;
  1360. if (type->Proc.diverging) {
  1361. flags = LLVMDIFlagNoReturn;
  1362. }
  1363. return LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, parameters, parameter_count, flags);
  1364. }
  1365. LLVMMetadataRef lb_debug_struct_field(lbModule *m, String const &name, Type *type, u64 offset_in_bits) {
  1366. unsigned field_line = 1;
  1367. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1368. AstPackage *pkg = m->info->runtime_package;
  1369. GB_ASSERT(pkg->files.count != 0);
  1370. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1371. LLVMMetadataRef scope = file;
  1372. return LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1373. 8*cast(u64)type_size_of(type), 8*cast(u32)type_align_of(type), offset_in_bits,
  1374. field_flags, lb_debug_type(m, type)
  1375. );
  1376. }
  1377. LLVMMetadataRef lb_debug_basic_struct(lbModule *m, String const &name, u64 size_in_bits, u32 align_in_bits, LLVMMetadataRef *elements, unsigned element_count) {
  1378. AstPackage *pkg = m->info->runtime_package;
  1379. GB_ASSERT(pkg->files.count != 0);
  1380. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1381. LLVMMetadataRef scope = file;
  1382. 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);
  1383. }
  1384. LLVMMetadataRef lb_debug_type_basic_type(lbModule *m, String const &name, u64 size_in_bits, LLVMDWARFTypeEncoding encoding, LLVMDIFlags flags = LLVMDIFlagZero) {
  1385. LLVMMetadataRef basic_type = LLVMDIBuilderCreateBasicType(m->debug_builder, cast(char const *)name.text, name.len, size_in_bits, encoding, flags);
  1386. #if 1
  1387. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, basic_type, cast(char const *)name.text, name.len, nullptr, 0, nullptr, cast(u32)size_in_bits);
  1388. return final_decl;
  1389. #else
  1390. return basic_type;
  1391. #endif
  1392. }
  1393. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1394. Type *original_type = type;
  1395. LLVMContextRef ctx = m->ctx;
  1396. i64 size = type_size_of(type); // Check size
  1397. GB_ASSERT(type != t_invalid);
  1398. unsigned const word_size = cast(unsigned)build_context.word_size;
  1399. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1400. switch (type->kind) {
  1401. case Type_Basic:
  1402. switch (type->Basic.kind) {
  1403. case Basic_llvm_bool: return lb_debug_type_basic_type(m, str_lit("llvm bool"), 1, LLVMDWARFTypeEncoding_Boolean);
  1404. case Basic_bool: return lb_debug_type_basic_type(m, str_lit("bool"), 8, LLVMDWARFTypeEncoding_Boolean);
  1405. case Basic_b8: return lb_debug_type_basic_type(m, str_lit("b8"), 8, LLVMDWARFTypeEncoding_Boolean);
  1406. case Basic_b16: return lb_debug_type_basic_type(m, str_lit("b16"), 16, LLVMDWARFTypeEncoding_Boolean);
  1407. case Basic_b32: return lb_debug_type_basic_type(m, str_lit("b32"), 32, LLVMDWARFTypeEncoding_Boolean);
  1408. case Basic_b64: return lb_debug_type_basic_type(m, str_lit("b64"), 64, LLVMDWARFTypeEncoding_Boolean);
  1409. case Basic_i8: return lb_debug_type_basic_type(m, str_lit("i8"), 8, LLVMDWARFTypeEncoding_Signed);
  1410. case Basic_u8: return lb_debug_type_basic_type(m, str_lit("u8"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1411. case Basic_i16: return lb_debug_type_basic_type(m, str_lit("i16"), 16, LLVMDWARFTypeEncoding_Signed);
  1412. case Basic_u16: return lb_debug_type_basic_type(m, str_lit("u16"), 16, LLVMDWARFTypeEncoding_Unsigned);
  1413. case Basic_i32: return lb_debug_type_basic_type(m, str_lit("i32"), 32, LLVMDWARFTypeEncoding_Signed);
  1414. case Basic_u32: return lb_debug_type_basic_type(m, str_lit("u32"), 32, LLVMDWARFTypeEncoding_Unsigned);
  1415. case Basic_i64: return lb_debug_type_basic_type(m, str_lit("i64"), 64, LLVMDWARFTypeEncoding_Signed);
  1416. case Basic_u64: return lb_debug_type_basic_type(m, str_lit("u64"), 64, LLVMDWARFTypeEncoding_Unsigned);
  1417. case Basic_i128: return lb_debug_type_basic_type(m, str_lit("i128"), 128, LLVMDWARFTypeEncoding_Signed);
  1418. case Basic_u128: return lb_debug_type_basic_type(m, str_lit("u128"), 128, LLVMDWARFTypeEncoding_Unsigned);
  1419. case Basic_rune: return lb_debug_type_basic_type(m, str_lit("rune"), 32, LLVMDWARFTypeEncoding_Utf);
  1420. case Basic_f16: return lb_debug_type_basic_type(m, str_lit("f16"), 16, LLVMDWARFTypeEncoding_Float);
  1421. case Basic_f32: return lb_debug_type_basic_type(m, str_lit("f32"), 32, LLVMDWARFTypeEncoding_Float);
  1422. case Basic_f64: return lb_debug_type_basic_type(m, str_lit("f64"), 64, LLVMDWARFTypeEncoding_Float);
  1423. case Basic_int: return lb_debug_type_basic_type(m, str_lit("int"), word_bits, LLVMDWARFTypeEncoding_Signed);
  1424. case Basic_uint: return lb_debug_type_basic_type(m, str_lit("uint"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1425. case Basic_uintptr: return lb_debug_type_basic_type(m, str_lit("uintptr"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1426. case Basic_typeid:
  1427. return lb_debug_type_basic_type(m, str_lit("typeid"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1428. // Endian Specific Types
  1429. case Basic_i16le: return lb_debug_type_basic_type(m, str_lit("i16le"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1430. case Basic_u16le: return lb_debug_type_basic_type(m, str_lit("u16le"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1431. case Basic_i32le: return lb_debug_type_basic_type(m, str_lit("i32le"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1432. case Basic_u32le: return lb_debug_type_basic_type(m, str_lit("u32le"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1433. case Basic_i64le: return lb_debug_type_basic_type(m, str_lit("i64le"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1434. case Basic_u64le: return lb_debug_type_basic_type(m, str_lit("u64le"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1435. case Basic_i128le: return lb_debug_type_basic_type(m, str_lit("i128le"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1436. case Basic_u128le: return lb_debug_type_basic_type(m, str_lit("u128le"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1437. case Basic_f16le: return lb_debug_type_basic_type(m, str_lit("f16le"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1438. case Basic_f32le: return lb_debug_type_basic_type(m, str_lit("f32le"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1439. case Basic_f64le: return lb_debug_type_basic_type(m, str_lit("f64le"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1440. case Basic_i16be: return lb_debug_type_basic_type(m, str_lit("i16be"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1441. case Basic_u16be: return lb_debug_type_basic_type(m, str_lit("u16be"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1442. case Basic_i32be: return lb_debug_type_basic_type(m, str_lit("i32be"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1443. case Basic_u32be: return lb_debug_type_basic_type(m, str_lit("u32be"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1444. case Basic_i64be: return lb_debug_type_basic_type(m, str_lit("i64be"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1445. case Basic_u64be: return lb_debug_type_basic_type(m, str_lit("u64be"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1446. case Basic_i128be: return lb_debug_type_basic_type(m, str_lit("i128be"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1447. case Basic_u128be: return lb_debug_type_basic_type(m, str_lit("u128be"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1448. case Basic_f16be: return lb_debug_type_basic_type(m, str_lit("f16be"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1449. case Basic_f32be: return lb_debug_type_basic_type(m, str_lit("f32be"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1450. case Basic_f64be: return lb_debug_type_basic_type(m, str_lit("f64be"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1451. case Basic_complex32:
  1452. {
  1453. LLVMMetadataRef elements[2] = {};
  1454. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f16, 0);
  1455. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 4);
  1456. return lb_debug_basic_struct(m, str_lit("complex32"), 64, 32, elements, gb_count_of(elements));
  1457. }
  1458. case Basic_complex64:
  1459. {
  1460. LLVMMetadataRef elements[2] = {};
  1461. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f32, 0);
  1462. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 4);
  1463. return lb_debug_basic_struct(m, str_lit("complex64"), 64, 32, elements, gb_count_of(elements));
  1464. }
  1465. case Basic_complex128:
  1466. {
  1467. LLVMMetadataRef elements[2] = {};
  1468. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f64, 0);
  1469. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 8);
  1470. return lb_debug_basic_struct(m, str_lit("complex128"), 128, 64, elements, gb_count_of(elements));
  1471. }
  1472. case Basic_quaternion64:
  1473. {
  1474. LLVMMetadataRef elements[4] = {};
  1475. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 0);
  1476. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f16, 4);
  1477. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f16, 8);
  1478. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f16, 12);
  1479. return lb_debug_basic_struct(m, str_lit("quaternion64"), 128, 32, elements, gb_count_of(elements));
  1480. }
  1481. case Basic_quaternion128:
  1482. {
  1483. LLVMMetadataRef elements[4] = {};
  1484. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 0);
  1485. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f32, 4);
  1486. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f32, 8);
  1487. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f32, 12);
  1488. return lb_debug_basic_struct(m, str_lit("quaternion128"), 128, 32, elements, gb_count_of(elements));
  1489. }
  1490. case Basic_quaternion256:
  1491. {
  1492. LLVMMetadataRef elements[4] = {};
  1493. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 0);
  1494. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f64, 8);
  1495. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f64, 16);
  1496. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f64, 24);
  1497. return lb_debug_basic_struct(m, str_lit("quaternion256"), 256, 32, elements, gb_count_of(elements));
  1498. }
  1499. case Basic_rawptr:
  1500. {
  1501. LLVMMetadataRef void_type = lb_debug_type_basic_type(m, str_lit("void"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1502. return LLVMDIBuilderCreatePointerType(m->debug_builder, void_type, word_bits, word_bits, LLVMDWARFTypeEncoding_Address, "rawptr", 6);
  1503. }
  1504. case Basic_string:
  1505. {
  1506. LLVMMetadataRef elements[2] = {};
  1507. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_u8_ptr, 0);
  1508. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, word_bits);
  1509. return lb_debug_basic_struct(m, str_lit("string"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1510. }
  1511. case Basic_cstring:
  1512. {
  1513. LLVMMetadataRef char_type = lb_debug_type_basic_type(m, str_lit("char"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1514. return LLVMDIBuilderCreatePointerType(m->debug_builder, char_type, word_bits, word_bits, 0, "cstring", 7);
  1515. }
  1516. case Basic_any:
  1517. {
  1518. LLVMMetadataRef elements[2] = {};
  1519. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_rawptr, 0);
  1520. elements[1] = lb_debug_struct_field(m, str_lit("id"), t_typeid, word_bits);
  1521. return lb_debug_basic_struct(m, str_lit("any"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1522. }
  1523. // Untyped types
  1524. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1525. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1526. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1527. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1528. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1529. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1530. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1531. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1532. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1533. default: GB_PANIC("Basic Unhandled"); break;
  1534. }
  1535. break;
  1536. case Type_Named:
  1537. GB_PANIC("Type_Named should be handled in lb_debug_type separately");
  1538. case Type_Pointer:
  1539. return LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, type->Pointer.elem), word_bits, word_bits, 0, nullptr, 0);
  1540. case Type_Array:
  1541. return LLVMDIBuilderCreateArrayType(m->debug_builder,
  1542. type->Array.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->Array.elem), nullptr, 0);
  1543. case Type_EnumeratedArray: {
  1544. LLVMMetadataRef array_type = LLVMDIBuilderCreateArrayType(m->debug_builder,
  1545. type->EnumeratedArray.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->EnumeratedArray.elem), nullptr, 0);
  1546. gbString name = type_to_string(type, temporary_allocator());
  1547. return LLVMDIBuilderCreateTypedef(m->debug_builder, array_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1548. }
  1549. case Type_Struct:
  1550. case Type_Union:
  1551. case Type_Slice:
  1552. case Type_DynamicArray:
  1553. case Type_Map:
  1554. case Type_BitSet:
  1555. {
  1556. unsigned tag = DW_TAG_structure_type;
  1557. if (is_type_raw_union(type) || is_type_union(type)) {
  1558. tag = DW_TAG_union_type;
  1559. }
  1560. u64 size_in_bits = cast(u64)(8*type_size_of(type));
  1561. u32 align_in_bits = cast(u32)(8*type_size_of(type));
  1562. LLVMDIFlags flags = LLVMDIFlagZero;
  1563. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1564. m->debug_builder, tag, "", 0, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1565. );
  1566. lbIncompleteDebugType idt = {};
  1567. idt.type = type;
  1568. idt.metadata = temp_forward_decl;
  1569. array_add(&m->debug_incomplete_types, idt);
  1570. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1571. return temp_forward_decl;
  1572. }
  1573. case Type_Enum:
  1574. {
  1575. LLVMMetadataRef scope = nullptr;
  1576. LLVMMetadataRef file = nullptr;
  1577. unsigned line = 0;
  1578. unsigned element_count = cast(unsigned)type->Enum.fields.count;
  1579. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1580. Type *bt = base_enum_type(type);
  1581. LLVMBool is_unsigned = is_type_unsigned(bt);
  1582. for (unsigned i = 0; i < element_count; i++) {
  1583. Entity *f = type->Enum.fields[i];
  1584. GB_ASSERT(f->kind == Entity_Constant);
  1585. String name = f->token.string;
  1586. i64 value = exact_value_to_i64(f->Constant.value);
  1587. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1588. }
  1589. LLVMMetadataRef class_type = lb_debug_type(m, bt);
  1590. 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);
  1591. }
  1592. case Type_Tuple:
  1593. if (type->Tuple.variables.count == 1) {
  1594. return lb_debug_type(m, type->Tuple.variables[0]->type);
  1595. } else {
  1596. type_set_offsets(type);
  1597. LLVMMetadataRef parent_scope = nullptr;
  1598. LLVMMetadataRef scope = nullptr;
  1599. LLVMMetadataRef file = nullptr;
  1600. unsigned line = 0;
  1601. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1602. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1603. LLVMDIFlags flags = LLVMDIFlagZero;
  1604. unsigned element_count = cast(unsigned)type->Tuple.variables.count;
  1605. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1606. for (unsigned i = 0; i < element_count; i++) {
  1607. Entity *f = type->Tuple.variables[i];
  1608. GB_ASSERT(f->kind == Entity_Variable);
  1609. String name = f->token.string;
  1610. unsigned field_line = 0;
  1611. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1612. u64 offset_in_bits = 8*cast(u64)type->Tuple.offsets[i];
  1613. elements[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1614. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type), offset_in_bits,
  1615. field_flags, lb_debug_type(m, f->type)
  1616. );
  1617. }
  1618. return LLVMDIBuilderCreateStructType(m->debug_builder, parent_scope, "", 0, file, line,
  1619. size_in_bits, align_in_bits, flags,
  1620. nullptr, elements, element_count, 0, nullptr,
  1621. "", 0
  1622. );
  1623. }
  1624. case Type_Proc:
  1625. {
  1626. LLVMMetadataRef proc_underlying_type = lb_debug_type_internal_proc(m, type);
  1627. LLVMMetadataRef pointer_type = LLVMDIBuilderCreatePointerType(m->debug_builder, proc_underlying_type, word_bits, word_bits, 0, nullptr, 0);
  1628. gbString name = type_to_string(type, temporary_allocator());
  1629. return LLVMDIBuilderCreateTypedef(m->debug_builder, pointer_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1630. }
  1631. break;
  1632. case Type_SimdVector:
  1633. 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);
  1634. case Type_RelativePointer: {
  1635. LLVMMetadataRef base_integer = lb_debug_type(m, type->RelativePointer.base_integer);
  1636. gbString name = type_to_string(type, temporary_allocator());
  1637. return LLVMDIBuilderCreateTypedef(m->debug_builder, base_integer, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1638. }
  1639. case Type_RelativeSlice:
  1640. {
  1641. unsigned element_count = 0;
  1642. LLVMMetadataRef elements[2] = {};
  1643. Type *base_integer = type->RelativeSlice.base_integer;
  1644. elements[0] = lb_debug_struct_field(m, str_lit("data_offset"), base_integer, 0);
  1645. elements[1] = lb_debug_struct_field(m, str_lit("len"), base_integer, 8*type_size_of(base_integer));
  1646. gbString name = type_to_string(type, temporary_allocator());
  1647. 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);
  1648. }
  1649. }
  1650. GB_PANIC("Invalid type %s", type_to_string(type));
  1651. return nullptr;
  1652. }
  1653. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1654. GB_ASSERT(type != nullptr);
  1655. LLVMMetadataRef found = lb_get_llvm_metadata(m, type);
  1656. if (found != nullptr) {
  1657. return found;
  1658. }
  1659. if (type->kind == Type_Named) {
  1660. LLVMMetadataRef file = nullptr;
  1661. unsigned line = 0;
  1662. LLVMMetadataRef scope = nullptr;
  1663. if (type->Named.type_name != nullptr) {
  1664. Entity *e = type->Named.type_name;
  1665. scope = lb_get_llvm_metadata(m, e->scope);
  1666. if (scope != nullptr) {
  1667. file = LLVMDIScopeGetFile(scope);
  1668. }
  1669. line = cast(unsigned)e->token.pos.line;
  1670. }
  1671. // TODO(bill): location data for Type_Named
  1672. u64 size_in_bits = 8*type_size_of(type);
  1673. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1674. String name = type->Named.name;
  1675. char const *name_text = cast(char const *)name.text;
  1676. size_t name_len = cast(size_t)name.len;
  1677. unsigned tag = DW_TAG_structure_type;
  1678. if (is_type_raw_union(type) || is_type_union(type)) {
  1679. tag = DW_TAG_union_type;
  1680. }
  1681. LLVMDIFlags flags = LLVMDIFlagZero;
  1682. Type *bt = base_type(type->Named.base);
  1683. lbIncompleteDebugType idt = {};
  1684. idt.type = type;
  1685. switch (bt->kind) {
  1686. case Type_Enum:
  1687. {
  1688. LLVMMetadataRef scope = nullptr;
  1689. LLVMMetadataRef file = nullptr;
  1690. unsigned line = 0;
  1691. unsigned element_count = cast(unsigned)bt->Enum.fields.count;
  1692. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1693. Type *ct = base_enum_type(type);
  1694. LLVMBool is_unsigned = is_type_unsigned(ct);
  1695. for (unsigned i = 0; i < element_count; i++) {
  1696. Entity *f = bt->Enum.fields[i];
  1697. GB_ASSERT(f->kind == Entity_Constant);
  1698. String name = f->token.string;
  1699. i64 value = exact_value_to_i64(f->Constant.value);
  1700. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1701. }
  1702. LLVMMetadataRef class_type = lb_debug_type(m, ct);
  1703. 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);
  1704. }
  1705. case Type_Basic:
  1706. case Type_Pointer:
  1707. case Type_Array:
  1708. case Type_EnumeratedArray:
  1709. case Type_Tuple:
  1710. case Type_Proc:
  1711. case Type_SimdVector:
  1712. case Type_RelativePointer:
  1713. case Type_RelativeSlice:
  1714. {
  1715. LLVMMetadataRef debug_bt = lb_debug_type(m, bt);
  1716. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, debug_bt, name_text, name_len, file, line, scope, align_in_bits);
  1717. lb_set_llvm_metadata(m, type, final_decl);
  1718. return final_decl;
  1719. }
  1720. case Type_Slice:
  1721. case Type_DynamicArray:
  1722. case Type_Map:
  1723. case Type_Struct:
  1724. case Type_Union:
  1725. case Type_BitSet:
  1726. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1727. m->debug_builder, tag, name_text, name_len, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1728. );
  1729. idt.metadata = temp_forward_decl;
  1730. array_add(&m->debug_incomplete_types, idt);
  1731. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1732. return temp_forward_decl;
  1733. }
  1734. }
  1735. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1736. lb_set_llvm_metadata(m, type, dt);
  1737. return dt;
  1738. }
  1739. void lb_debug_complete_types(lbModule *m) {
  1740. unsigned const word_size = cast(unsigned)build_context.word_size;
  1741. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1742. for_array(debug_incomplete_type_index, m->debug_incomplete_types) {
  1743. auto const &idt = m->debug_incomplete_types[debug_incomplete_type_index];
  1744. GB_ASSERT(idt.type != nullptr);
  1745. GB_ASSERT(idt.metadata != nullptr);
  1746. Type *t = idt.type;
  1747. Type *bt = base_type(t);
  1748. LLVMMetadataRef parent_scope = nullptr;
  1749. LLVMMetadataRef file = nullptr;
  1750. unsigned line_number = 0;
  1751. u64 size_in_bits = 8*type_size_of(t);
  1752. u32 align_in_bits = cast(u32)(8*type_align_of(t));
  1753. LLVMDIFlags flags = LLVMDIFlagZero;
  1754. LLVMMetadataRef derived_from = nullptr;
  1755. LLVMMetadataRef *elements = nullptr;
  1756. unsigned element_count = 0;
  1757. unsigned runtime_lang = 0; // Objective-C runtime version
  1758. char const *unique_id = "";
  1759. LLVMMetadataRef vtable_holder = nullptr;
  1760. size_t unique_id_len = 0;
  1761. LLVMMetadataRef record_scope = nullptr;
  1762. switch (bt->kind) {
  1763. case Type_Slice:
  1764. case Type_DynamicArray:
  1765. case Type_Map:
  1766. case Type_Struct:
  1767. case Type_Union:
  1768. case Type_BitSet: {
  1769. bool is_union = is_type_raw_union(bt) || is_type_union(bt);
  1770. String name = str_lit("<anonymous-struct>");
  1771. if (t->kind == Type_Named) {
  1772. name = t->Named.name;
  1773. if (t->Named.type_name && t->Named.type_name->pkg && t->Named.type_name->pkg->name.len != 0) {
  1774. name = concatenate3_strings(temporary_allocator(), t->Named.type_name->pkg->name, str_lit("."), t->Named.name);
  1775. }
  1776. LLVMMetadataRef file = nullptr;
  1777. unsigned line = 0;
  1778. LLVMMetadataRef file_scope = nullptr;
  1779. if (t->Named.type_name != nullptr) {
  1780. Entity *e = t->Named.type_name;
  1781. file_scope = lb_get_llvm_metadata(m, e->scope);
  1782. if (file_scope != nullptr) {
  1783. file = LLVMDIScopeGetFile(file_scope);
  1784. }
  1785. line = cast(unsigned)e->token.pos.line;
  1786. }
  1787. // TODO(bill): location data for Type_Named
  1788. } else {
  1789. name = make_string_c(type_to_string(t, temporary_allocator()));
  1790. }
  1791. switch (bt->kind) {
  1792. case Type_Slice:
  1793. element_count = 2;
  1794. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1795. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->Slice.elem), 0*word_bits);
  1796. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1797. break;
  1798. case Type_DynamicArray:
  1799. element_count = 4;
  1800. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1801. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->DynamicArray.elem), 0*word_bits);
  1802. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1803. elements[2] = lb_debug_struct_field(m, str_lit("cap"), t_int, 2*word_bits);
  1804. elements[3] = lb_debug_struct_field(m, str_lit("allocator"), t_allocator, 3*word_bits);
  1805. break;
  1806. case Type_Map:
  1807. bt = bt->Map.internal_type;
  1808. /*fallthrough*/
  1809. case Type_Struct:
  1810. if (file == nullptr) {
  1811. if (bt->Struct.node) {
  1812. file = lb_get_llvm_metadata(m, bt->Struct.node->file);
  1813. line_number = cast(unsigned)ast_token(bt->Struct.node).pos.line;
  1814. }
  1815. }
  1816. type_set_offsets(bt);
  1817. {
  1818. isize element_offset = 0;
  1819. record_scope = lb_get_llvm_metadata(m, bt->Struct.scope);
  1820. switch (bt->Struct.soa_kind) {
  1821. case StructSoa_Slice: element_offset = 1; break;
  1822. case StructSoa_Dynamic: element_offset = 3; break;
  1823. }
  1824. element_count = cast(unsigned)(bt->Struct.fields.count + element_offset);
  1825. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1826. switch (bt->Struct.soa_kind) {
  1827. case StructSoa_Slice:
  1828. elements[0] = LLVMDIBuilderCreateMemberType(
  1829. m->debug_builder, record_scope,
  1830. ".len", 4,
  1831. file, 0,
  1832. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1833. 8*type_size_of(bt)-word_bits,
  1834. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1835. );
  1836. break;
  1837. case StructSoa_Dynamic:
  1838. elements[0] = LLVMDIBuilderCreateMemberType(
  1839. m->debug_builder, record_scope,
  1840. ".len", 4,
  1841. file, 0,
  1842. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1843. 8*type_size_of(bt)-word_bits + 0*word_bits,
  1844. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1845. );
  1846. elements[1] = LLVMDIBuilderCreateMemberType(
  1847. m->debug_builder, record_scope,
  1848. ".cap", 4,
  1849. file, 0,
  1850. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1851. 8*type_size_of(bt)-word_bits + 1*word_bits,
  1852. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1853. );
  1854. elements[3] = LLVMDIBuilderCreateMemberType(
  1855. m->debug_builder, record_scope,
  1856. ".allocator", 12,
  1857. file, 0,
  1858. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1859. 8*type_size_of(bt)-word_bits + 2*word_bits,
  1860. LLVMDIFlagZero, lb_debug_type(m, t_allocator)
  1861. );
  1862. break;
  1863. }
  1864. for_array(j, bt->Struct.fields) {
  1865. Entity *f = bt->Struct.fields[j];
  1866. String fname = f->token.string;
  1867. unsigned field_line = 0;
  1868. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1869. u64 offset_in_bits = 8*cast(u64)bt->Struct.offsets[j];
  1870. elements[element_offset+j] = LLVMDIBuilderCreateMemberType(
  1871. m->debug_builder, record_scope,
  1872. cast(char const *)fname.text, cast(size_t)fname.len,
  1873. file, field_line,
  1874. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type),
  1875. offset_in_bits,
  1876. field_flags, lb_debug_type(m, f->type)
  1877. );
  1878. }
  1879. }
  1880. break;
  1881. case Type_Union:
  1882. {
  1883. if (file == nullptr) {
  1884. GB_ASSERT(bt->Union.node != nullptr);
  1885. file = lb_get_llvm_metadata(m, bt->Union.node->file);
  1886. line_number = cast(unsigned)ast_token(bt->Union.node).pos.line;
  1887. }
  1888. isize index_offset = 1;
  1889. if (is_type_union_maybe_pointer(bt)) {
  1890. index_offset = 0;
  1891. }
  1892. record_scope = lb_get_llvm_metadata(m, bt->Union.scope);
  1893. element_count = cast(unsigned)bt->Union.variants.count;
  1894. if (index_offset > 0) {
  1895. element_count += 1;
  1896. }
  1897. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1898. if (index_offset > 0) {
  1899. Type *tag_type = union_tag_type(bt);
  1900. unsigned field_line = 0;
  1901. u64 offset_in_bits = 8*cast(u64)bt->Union.variant_block_size;
  1902. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1903. elements[0] = LLVMDIBuilderCreateMemberType(
  1904. m->debug_builder, record_scope,
  1905. "tag", 3,
  1906. file, field_line,
  1907. 8*cast(u64)type_size_of(tag_type), 8*cast(u32)type_align_of(tag_type),
  1908. offset_in_bits,
  1909. field_flags, lb_debug_type(m, tag_type)
  1910. );
  1911. }
  1912. for_array(j, bt->Union.variants) {
  1913. Type *variant = bt->Union.variants[j];
  1914. unsigned field_index = cast(unsigned)(index_offset+j);
  1915. char name[16] = {};
  1916. gb_snprintf(name, gb_size_of(name), "v%u", field_index);
  1917. isize name_len = gb_strlen(name);
  1918. unsigned field_line = 0;
  1919. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1920. u64 offset_in_bits = 0;
  1921. elements[field_index] = LLVMDIBuilderCreateMemberType(
  1922. m->debug_builder, record_scope,
  1923. name, name_len,
  1924. file, field_line,
  1925. 8*cast(u64)type_size_of(variant), 8*cast(u32)type_align_of(variant),
  1926. offset_in_bits,
  1927. field_flags, lb_debug_type(m, variant)
  1928. );
  1929. }
  1930. }
  1931. break;
  1932. case Type_BitSet:
  1933. {
  1934. if (file == nullptr) {
  1935. GB_ASSERT(bt->BitSet.node != nullptr);
  1936. file = lb_get_llvm_metadata(m, bt->BitSet.node->file);
  1937. line_number = cast(unsigned)ast_token(bt->BitSet.node).pos.line;
  1938. }
  1939. LLVMMetadataRef bit_set_field_type = lb_debug_type(m, t_bool);
  1940. LLVMMetadataRef scope = file;
  1941. Type *elem = base_type(bt->BitSet.elem);
  1942. if (elem->kind == Type_Enum) {
  1943. element_count = cast(unsigned)elem->Enum.fields.count;
  1944. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1945. for_array(i, elem->Enum.fields) {
  1946. Entity *f = elem->Enum.fields[i];
  1947. GB_ASSERT(f->kind == Entity_Constant);
  1948. i64 val = exact_value_to_i64(f->Constant.value);
  1949. String name = f->token.string;
  1950. u64 offset_in_bits = cast(u64)(val - bt->BitSet.lower);
  1951. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  1952. m->debug_builder,
  1953. scope,
  1954. cast(char const *)name.text, name.len,
  1955. file, line_number,
  1956. 1,
  1957. offset_in_bits,
  1958. 0,
  1959. LLVMDIFlagZero,
  1960. bit_set_field_type
  1961. );
  1962. }
  1963. } else {
  1964. char name[32] = {};
  1965. GB_ASSERT(is_type_integer(elem));
  1966. i64 count = bt->BitSet.upper - bt->BitSet.lower + 1;
  1967. GB_ASSERT(0 <= count);
  1968. element_count = cast(unsigned)count;
  1969. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1970. for (unsigned i = 0; i < element_count; i++) {
  1971. u64 offset_in_bits = i;
  1972. i64 val = bt->BitSet.lower + cast(i64)i;
  1973. gb_snprintf(name, gb_count_of(name), "%lld", cast(long long)val);
  1974. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  1975. m->debug_builder,
  1976. scope,
  1977. name, gb_strlen(name),
  1978. file, line_number,
  1979. 1,
  1980. offset_in_bits,
  1981. 0,
  1982. LLVMDIFlagZero,
  1983. bit_set_field_type
  1984. );
  1985. }
  1986. }
  1987. }
  1988. }
  1989. LLVMMetadataRef final_metadata = nullptr;
  1990. if (is_union) {
  1991. final_metadata = LLVMDIBuilderCreateUnionType(
  1992. m->debug_builder,
  1993. parent_scope,
  1994. cast(char const *)name.text, cast(size_t)name.len,
  1995. file, line_number,
  1996. size_in_bits, align_in_bits,
  1997. flags,
  1998. elements, element_count,
  1999. runtime_lang,
  2000. unique_id, unique_id_len
  2001. );
  2002. } else {
  2003. final_metadata = LLVMDIBuilderCreateStructType(
  2004. m->debug_builder,
  2005. parent_scope,
  2006. cast(char const *)name.text, cast(size_t)name.len,
  2007. file, line_number,
  2008. size_in_bits, align_in_bits,
  2009. flags,
  2010. derived_from,
  2011. elements, element_count,
  2012. runtime_lang,
  2013. vtable_holder,
  2014. unique_id, unique_id_len
  2015. );
  2016. }
  2017. LLVMMetadataReplaceAllUsesWith(idt.metadata, final_metadata);
  2018. lb_set_llvm_metadata(m, idt.type, final_metadata);
  2019. } break;
  2020. default:
  2021. GB_PANIC("invalid incomplete debug type");
  2022. break;
  2023. }
  2024. }
  2025. array_clear(&m->debug_incomplete_types);
  2026. }
  2027. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  2028. if (e != nullptr) {
  2029. map_set(&m->values, hash_entity(e), val);
  2030. }
  2031. }
  2032. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  2033. if (name.len > 0) {
  2034. string_map_set(&m->members, name, val);
  2035. }
  2036. }
  2037. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  2038. string_map_set(&m->members, key, val);
  2039. }
  2040. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  2041. if (p->entity != nullptr) {
  2042. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  2043. }
  2044. string_map_set(&m->procedures, p->name, p);
  2045. }
  2046. LLVMValueRef llvm_const_cast(LLVMValueRef val, LLVMTypeRef dst) {
  2047. LLVMTypeRef src = LLVMTypeOf(val);
  2048. if (src == dst) {
  2049. return val;
  2050. }
  2051. if (LLVMIsNull(val)) {
  2052. return LLVMConstNull(dst);
  2053. }
  2054. GB_ASSERT(LLVMSizeOf(dst) == LLVMSizeOf(src));
  2055. LLVMTypeKind kind = LLVMGetTypeKind(dst);
  2056. switch (kind) {
  2057. case LLVMPointerTypeKind:
  2058. return LLVMConstPointerCast(val, dst);
  2059. case LLVMStructTypeKind:
  2060. return LLVMConstBitCast(val, dst);
  2061. default:
  2062. GB_PANIC("Unhandled const cast %s to %s", LLVMPrintTypeToString(src), LLVMPrintTypeToString(dst));
  2063. }
  2064. return val;
  2065. }
  2066. LLVMValueRef llvm_const_named_struct(LLVMTypeRef t, LLVMValueRef *values, isize value_count_) {
  2067. unsigned value_count = cast(unsigned)value_count_;
  2068. unsigned elem_count = LLVMCountStructElementTypes(t);
  2069. GB_ASSERT(value_count == elem_count);
  2070. for (unsigned i = 0; i < elem_count; i++) {
  2071. LLVMTypeRef elem_type = LLVMStructGetTypeAtIndex(t, i);
  2072. values[i] = llvm_const_cast(values[i], elem_type);
  2073. }
  2074. return LLVMConstNamedStruct(t, values, value_count);
  2075. }
  2076. LLVMValueRef llvm_const_array(LLVMTypeRef elem_type, LLVMValueRef *values, isize value_count_) {
  2077. unsigned value_count = cast(unsigned)value_count_;
  2078. for (unsigned i = 0; i < value_count; i++) {
  2079. values[i] = llvm_const_cast(values[i], elem_type);
  2080. }
  2081. return LLVMConstArray(elem_type, values, value_count);
  2082. }
  2083. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  2084. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  2085. LLVMValueRef values[2] = {
  2086. str_elem.value,
  2087. str_len.value,
  2088. };
  2089. lbValue res = {};
  2090. res.type = t_string;
  2091. res.value = llvm_const_named_struct(lb_type(p->module, t_string), values, gb_count_of(values));
  2092. return res;
  2093. } else {
  2094. lbAddr res = lb_add_local_generated(p, t_string, false);
  2095. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  2096. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  2097. return lb_addr_load(p, res);
  2098. }
  2099. }
  2100. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  2101. String s = make_string_c(name);
  2102. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2103. // and the current LLVM C API does not expose this functionality yet.
  2104. // It is better to ignore the attributes for the time being
  2105. if (s == "byval") {
  2106. return nullptr;
  2107. } else if (s == "byref") {
  2108. return nullptr;
  2109. } else if (s == "preallocated") {
  2110. return nullptr;
  2111. } else if (s == "sret") {
  2112. return nullptr;
  2113. }
  2114. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2115. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2116. return LLVMCreateEnumAttribute(ctx, kind, value);
  2117. }
  2118. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  2119. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  2120. GB_ASSERT(attr != nullptr);
  2121. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  2122. }
  2123. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  2124. lb_add_proc_attribute_at_index(p, index, name, 0);
  2125. }
  2126. void lb_add_attribute_to_proc(lbModule *m, LLVMValueRef proc_value, char const *name, u64 value=0) {
  2127. LLVMAddAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(m->ctx, name, value));
  2128. }
  2129. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  2130. if (p->abi_function_type != nullptr) {
  2131. return;
  2132. }
  2133. auto hash = hash_type(p->type);
  2134. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  2135. if (ft_found == nullptr) {
  2136. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  2137. ft_found = map_get(&m->function_type_map, hash);
  2138. }
  2139. GB_ASSERT(ft_found != nullptr);
  2140. p->abi_function_type = *ft_found;
  2141. GB_ASSERT(p->abi_function_type != nullptr);
  2142. }
  2143. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  2144. GB_ASSERT(entity != nullptr);
  2145. String link_name = lb_get_entity_name(m, entity);
  2146. {
  2147. StringHashKey key = string_hash_string(link_name);
  2148. lbValue *found = string_map_get(&m->members, key);
  2149. if (found) {
  2150. lb_add_entity(m, entity, *found);
  2151. lbProcedure **p_found = string_map_get(&m->procedures, key);
  2152. GB_ASSERT(p_found != nullptr);
  2153. return *p_found;
  2154. }
  2155. }
  2156. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2157. p->module = m;
  2158. entity->code_gen_module = m;
  2159. entity->code_gen_procedure = p;
  2160. p->entity = entity;
  2161. p->name = link_name;
  2162. DeclInfo *decl = entity->decl_info;
  2163. ast_node(pl, ProcLit, decl->proc_lit);
  2164. Type *pt = base_type(entity->type);
  2165. GB_ASSERT(pt->kind == Type_Proc);
  2166. p->type = entity->type;
  2167. p->type_expr = decl->type_expr;
  2168. p->body = pl->body;
  2169. p->inlining = pl->inlining;
  2170. p->is_foreign = entity->Procedure.is_foreign;
  2171. p->is_export = entity->Procedure.is_export;
  2172. p->is_entry_point = false;
  2173. gbAllocator a = heap_allocator();
  2174. p->children.allocator = a;
  2175. p->params.allocator = a;
  2176. p->defer_stmts.allocator = a;
  2177. p->blocks.allocator = a;
  2178. p->branch_blocks.allocator = a;
  2179. p->context_stack.allocator = a;
  2180. p->scope_stack.allocator = a;
  2181. if (p->is_foreign) {
  2182. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  2183. }
  2184. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2185. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2186. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2187. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2188. lb_ensure_abi_function_type(m, p);
  2189. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  2190. if (false) {
  2191. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2192. // TODO(bill): Clean up this logic
  2193. if (build_context.metrics.os != TargetOs_js) {
  2194. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2195. }
  2196. LLVMSetFunctionCallConv(p->value, cc_kind);
  2197. }
  2198. if (pt->Proc.diverging) {
  2199. lb_add_attribute_to_proc(m, p->value, "noreturn");
  2200. }
  2201. if (pt->Proc.calling_convention == ProcCC_Naked) {
  2202. lb_add_attribute_to_proc(m, p->value, "naked");
  2203. }
  2204. switch (p->inlining) {
  2205. case ProcInlining_inline:
  2206. lb_add_attribute_to_proc(m, p->value, "alwaysinline");
  2207. break;
  2208. case ProcInlining_no_inline:
  2209. lb_add_attribute_to_proc(m, p->value, "noinline");
  2210. break;
  2211. }
  2212. if (entity->flags & EntityFlag_Cold) {
  2213. lb_add_attribute_to_proc(m, p->value, "cold");
  2214. }
  2215. switch (entity->Procedure.optimization_mode) {
  2216. case ProcedureOptimizationMode_None:
  2217. lb_add_attribute_to_proc(m, p->value, "optnone");
  2218. break;
  2219. case ProcedureOptimizationMode_Minimal:
  2220. lb_add_attribute_to_proc(m, p->value, "optnone");
  2221. break;
  2222. case ProcedureOptimizationMode_Size:
  2223. lb_add_attribute_to_proc(m, p->value, "optsize");
  2224. break;
  2225. case ProcedureOptimizationMode_Speed:
  2226. // TODO(bill): handle this correctly
  2227. lb_add_attribute_to_proc(m, p->value, "optsize");
  2228. break;
  2229. }
  2230. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2231. // // TODO(bill): Clean up this logic
  2232. // if (build_context.metrics.os != TargetOs_js) {
  2233. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2234. // }
  2235. // LLVMSetFunctionCallConv(p->value, cc_kind);
  2236. lbValue proc_value = {p->value, p->type};
  2237. lb_add_entity(m, entity, proc_value);
  2238. lb_add_member(m, p->name, proc_value);
  2239. lb_add_procedure_value(m, p);
  2240. if (p->is_export) {
  2241. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  2242. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  2243. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  2244. if (build_context.metrics.os == TargetOs_js) {
  2245. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  2246. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  2247. }
  2248. }
  2249. if (p->is_foreign) {
  2250. if (build_context.metrics.os == TargetOs_js) {
  2251. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  2252. char const *module_name = "env";
  2253. if (entity->Procedure.foreign_library != nullptr) {
  2254. Entity *foreign_library = entity->Procedure.foreign_library;
  2255. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  2256. if (foreign_library->LibraryName.paths.count > 0) {
  2257. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  2258. }
  2259. }
  2260. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  2261. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  2262. }
  2263. }
  2264. // NOTE(bill): offset==0 is the return value
  2265. isize offset = 1;
  2266. if (pt->Proc.return_by_pointer) {
  2267. offset = 2;
  2268. }
  2269. isize parameter_index = 0;
  2270. if (pt->Proc.param_count) {
  2271. TypeTuple *params = &pt->Proc.params->Tuple;
  2272. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2273. Entity *e = params->variables[i];
  2274. Type *original_type = e->type;
  2275. if (e->kind != Entity_Variable) continue;
  2276. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2277. continue;
  2278. }
  2279. if (e->flags&EntityFlag_NoAlias) {
  2280. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2281. }
  2282. parameter_index += 1;
  2283. }
  2284. }
  2285. if (m->debug_builder) { // Debug Information
  2286. Type *bt = base_type(p->type);
  2287. unsigned line = cast(unsigned)entity->token.pos.line;
  2288. LLVMMetadataRef scope = nullptr;
  2289. LLVMMetadataRef file = nullptr;
  2290. LLVMMetadataRef type = nullptr;
  2291. scope = p->module->debug_compile_unit;
  2292. type = lb_debug_type_internal_proc(m, bt);
  2293. if (entity->file != nullptr) {
  2294. file = lb_get_llvm_metadata(m, entity->file);
  2295. scope = file;
  2296. } else if (entity->identifier != nullptr && entity->identifier->file != nullptr) {
  2297. file = lb_get_llvm_metadata(m, entity->identifier->file);
  2298. scope = file;
  2299. } else if (entity->scope != nullptr) {
  2300. file = lb_get_llvm_metadata(m, entity->scope->file);
  2301. scope = file;
  2302. }
  2303. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  2304. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  2305. LLVMBool is_local_to_unit = false;
  2306. LLVMBool is_definition = p->body != nullptr;
  2307. unsigned scope_line = line;
  2308. u32 flags = LLVMDIFlagStaticMember;
  2309. LLVMBool is_optimized = false;
  2310. if (bt->Proc.diverging) {
  2311. flags |= LLVMDIFlagNoReturn;
  2312. }
  2313. if (p->body == nullptr) {
  2314. flags |= LLVMDIFlagPrototyped;
  2315. is_optimized = false;
  2316. }
  2317. if (p->body != nullptr) {
  2318. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  2319. cast(char const *)entity->token.string.text, entity->token.string.len,
  2320. cast(char const *)p->name.text, p->name.len,
  2321. file, line, type,
  2322. is_local_to_unit, is_definition,
  2323. scope_line, cast(LLVMDIFlags)flags, is_optimized
  2324. );
  2325. GB_ASSERT(p->debug_info != nullptr);
  2326. LLVMSetSubprogram(p->value, p->debug_info);
  2327. lb_set_llvm_metadata(m, p, p->debug_info);
  2328. }
  2329. }
  2330. return p;
  2331. }
  2332. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  2333. {
  2334. lbValue *found = string_map_get(&m->members, link_name);
  2335. GB_ASSERT(found == nullptr);
  2336. }
  2337. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2338. p->module = m;
  2339. p->name = link_name;
  2340. p->type = type;
  2341. p->type_expr = nullptr;
  2342. p->body = nullptr;
  2343. p->tags = 0;
  2344. p->inlining = ProcInlining_none;
  2345. p->is_foreign = false;
  2346. p->is_export = false;
  2347. p->is_entry_point = false;
  2348. gbAllocator a = permanent_allocator();
  2349. p->children.allocator = a;
  2350. p->params.allocator = a;
  2351. p->defer_stmts.allocator = a;
  2352. p->blocks.allocator = a;
  2353. p->branch_blocks.allocator = a;
  2354. p->context_stack.allocator = a;
  2355. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2356. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2357. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2358. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2359. Type *pt = p->type;
  2360. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2361. // TODO(bill): Clean up this logic
  2362. if (build_context.metrics.os != TargetOs_js) {
  2363. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2364. }
  2365. LLVMSetFunctionCallConv(p->value, cc_kind);
  2366. lbValue proc_value = {p->value, p->type};
  2367. lb_add_member(m, p->name, proc_value);
  2368. lb_add_procedure_value(m, p);
  2369. // NOTE(bill): offset==0 is the return value
  2370. isize offset = 1;
  2371. if (pt->Proc.return_by_pointer) {
  2372. lb_add_proc_attribute_at_index(p, 1, "sret");
  2373. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2374. offset = 2;
  2375. }
  2376. isize parameter_index = 0;
  2377. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2378. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2379. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2380. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2381. }
  2382. return p;
  2383. }
  2384. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2385. lbParamPasskind kind = lbParamPass_Value;
  2386. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2387. if (is_type_pointer(abi_type)) {
  2388. GB_ASSERT(e->kind == Entity_Variable);
  2389. Type *av = core_type(type_deref(abi_type));
  2390. if (are_types_identical(av, core_type(e->type))) {
  2391. kind = lbParamPass_Pointer;
  2392. if (e->flags&EntityFlag_Value) {
  2393. kind = lbParamPass_ConstRef;
  2394. }
  2395. } else {
  2396. kind = lbParamPass_BitCast;
  2397. }
  2398. } else if (is_type_integer(abi_type)) {
  2399. kind = lbParamPass_Integer;
  2400. } else if (abi_type == t_llvm_bool) {
  2401. kind = lbParamPass_Value;
  2402. } else if (is_type_boolean(abi_type)) {
  2403. kind = lbParamPass_Integer;
  2404. } else if (is_type_simd_vector(abi_type)) {
  2405. kind = lbParamPass_BitCast;
  2406. } else if (is_type_float(abi_type)) {
  2407. kind = lbParamPass_BitCast;
  2408. } else if (is_type_tuple(abi_type)) {
  2409. kind = lbParamPass_Tuple;
  2410. } else if (is_type_proc(abi_type)) {
  2411. kind = lbParamPass_Value;
  2412. } else {
  2413. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2414. }
  2415. }
  2416. if (kind_) *kind_ = kind;
  2417. lbValue res = {};
  2418. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2419. res.type = abi_type;
  2420. return res;
  2421. }
  2422. Type *struct_type_from_systemv_distribute_struct_fields(Type *abi_type) {
  2423. GB_ASSERT(is_type_tuple(abi_type));
  2424. Type *final_type = alloc_type_struct();
  2425. final_type->Struct.fields = abi_type->Tuple.variables;
  2426. return final_type;
  2427. }
  2428. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  2429. lbParamPasskind kind = lbParamPass_Value;
  2430. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  2431. array_add(&p->params, v);
  2432. lbValue res = {};
  2433. switch (kind) {
  2434. case lbParamPass_Value: {
  2435. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2436. lbValue x = v;
  2437. if (abi_type == t_llvm_bool) {
  2438. x = lb_emit_conv(p, x, t_bool);
  2439. }
  2440. lb_addr_store(p, l, x);
  2441. return x;
  2442. }
  2443. case lbParamPass_Pointer:
  2444. lb_add_entity(p->module, e, v);
  2445. return lb_emit_load(p, v);
  2446. case lbParamPass_Integer: {
  2447. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2448. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  2449. lb_emit_store(p, iptr, v);
  2450. return lb_addr_load(p, l);
  2451. }
  2452. case lbParamPass_ConstRef:
  2453. lb_add_entity(p->module, e, v);
  2454. return lb_emit_load(p, v);
  2455. case lbParamPass_BitCast: {
  2456. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2457. lbValue x = lb_emit_transmute(p, v, e->type);
  2458. lb_addr_store(p, l, x);
  2459. return x;
  2460. }
  2461. case lbParamPass_Tuple: {
  2462. lbAddr l = lb_add_local(p, e->type, e, true, index);
  2463. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2464. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  2465. if (abi_type->Tuple.variables.count > 0) {
  2466. array_pop(&p->params);
  2467. }
  2468. for_array(i, abi_type->Tuple.variables) {
  2469. Type *t = abi_type->Tuple.variables[i]->type;
  2470. GB_ASSERT(!is_type_tuple(t));
  2471. lbParamPasskind elem_kind = lbParamPass_Value;
  2472. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  2473. array_add(&p->params, elem);
  2474. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2475. lb_emit_store(p, dst, elem);
  2476. }
  2477. return lb_addr_load(p, l);
  2478. }
  2479. }
  2480. GB_PANIC("Unreachable");
  2481. return {};
  2482. }
  2483. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2484. GB_ASSERT(b != nullptr);
  2485. if (!b->appended) {
  2486. b->appended = true;
  2487. LLVMAppendExistingBasicBlock(p->value, b->block);
  2488. }
  2489. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2490. p->curr_block = b;
  2491. }
  2492. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2493. LLVMContextRef ctx = p->module->ctx;
  2494. LLVMTypeRef src_type = LLVMTypeOf(val);
  2495. if (src_type == dst_type) {
  2496. return val;
  2497. }
  2498. i64 src_size = lb_sizeof(src_type);
  2499. i64 dst_size = lb_sizeof(dst_type);
  2500. i64 src_align = lb_alignof(src_type);
  2501. i64 dst_align = lb_alignof(dst_type);
  2502. if (LLVMIsALoadInst(val)) {
  2503. src_align = gb_min(src_align, LLVMGetAlignment(val));
  2504. }
  2505. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2506. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2507. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2508. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2509. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2510. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2511. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2512. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2513. }
  2514. if (src_size != dst_size) {
  2515. if ((lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2516. // Okay
  2517. } else {
  2518. goto general_end;
  2519. }
  2520. }
  2521. if (src_kind == dst_kind) {
  2522. if (src_kind == LLVMPointerTypeKind) {
  2523. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2524. } else if (src_kind == LLVMArrayTypeKind) {
  2525. // ignore
  2526. } else if (src_kind != LLVMStructTypeKind) {
  2527. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2528. }
  2529. } else {
  2530. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2531. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2532. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2533. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2534. }
  2535. }
  2536. general_end:;
  2537. // make the alignment big if necessary
  2538. if (LLVMIsALoadInst(val) && src_align < dst_align) {
  2539. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2540. if (LLVMGetInstructionOpcode(val_ptr) == LLVMAlloca) {
  2541. src_align = gb_max(LLVMGetAlignment(val_ptr), dst_align);
  2542. LLVMSetAlignment(val_ptr, cast(unsigned)src_align);
  2543. }
  2544. }
  2545. src_size = align_formula(src_size, src_align);
  2546. dst_size = align_formula(dst_size, dst_align);
  2547. if (LLVMIsALoadInst(val) && (src_size >= dst_size && src_align >= dst_align)) {
  2548. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2549. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2550. LLVMValueRef loaded_val = LLVMBuildLoad(p->builder, val_ptr, "");
  2551. // LLVMSetAlignment(loaded_val, gb_min(src_align, dst_align));
  2552. return loaded_val;
  2553. } else {
  2554. GB_ASSERT(p->decl_block != p->curr_block);
  2555. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2556. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2557. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2558. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2559. max_align = gb_max(max_align, 4);
  2560. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2561. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2562. LLVMBuildStore(p->builder, val, nptr);
  2563. return LLVMBuildLoad(p->builder, ptr, "");
  2564. }
  2565. }
  2566. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token) {
  2567. if (p->debug_info == nullptr) {
  2568. return;
  2569. }
  2570. if (type == nullptr) {
  2571. return;
  2572. }
  2573. if (type == t_invalid) {
  2574. return;
  2575. }
  2576. if (p->body == nullptr) {
  2577. return;
  2578. }
  2579. lbModule *m = p->module;
  2580. String const &name = token.string;
  2581. if (name == "" || name == "_") {
  2582. return;
  2583. }
  2584. if (lb_get_llvm_metadata(m, ptr) != nullptr) {
  2585. // Already been set
  2586. return;
  2587. }
  2588. AstFile *file = p->body->file;
  2589. LLVMMetadataRef llvm_scope = lb_get_current_debug_scope(p);
  2590. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, file);
  2591. GB_ASSERT(llvm_scope != nullptr);
  2592. if (llvm_file == nullptr) {
  2593. llvm_file = LLVMDIScopeGetFile(llvm_scope);
  2594. }
  2595. if (llvm_file == nullptr) {
  2596. return;
  2597. }
  2598. unsigned alignment_in_bits = cast(unsigned)(8*type_align_of(type));
  2599. LLVMDIFlags flags = LLVMDIFlagZero;
  2600. LLVMBool always_preserve = build_context.optimization_level == 0;
  2601. LLVMMetadataRef debug_type = lb_debug_type(m, type);
  2602. LLVMMetadataRef var_info = LLVMDIBuilderCreateAutoVariable(
  2603. m->debug_builder, llvm_scope,
  2604. cast(char const *)name.text, cast(size_t)name.len,
  2605. llvm_file, token.pos.line,
  2606. debug_type,
  2607. always_preserve, flags, alignment_in_bits
  2608. );
  2609. LLVMValueRef storage = ptr;
  2610. LLVMValueRef instr = ptr;
  2611. LLVMMetadataRef llvm_debug_loc = lb_debug_location_from_token_pos(p, token.pos);
  2612. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2613. lb_set_llvm_metadata(m, ptr, llvm_expr);
  2614. LLVMDIBuilderInsertDeclareBefore(m->debug_builder, storage, var_info, llvm_expr, llvm_debug_loc, instr);
  2615. }
  2616. void lb_add_debug_context_variable(lbProcedure *p, lbAddr const &ctx) {
  2617. if (!p->debug_info || !p->body) {
  2618. return;
  2619. }
  2620. LLVMMetadataRef loc = LLVMGetCurrentDebugLocation2(p->builder);
  2621. if (!loc) {
  2622. return;
  2623. }
  2624. TokenPos pos = {};
  2625. pos.file_id = p->body->file ? p->body->file->id : 0;
  2626. pos.line = LLVMDILocationGetLine(loc);
  2627. pos.column = LLVMDILocationGetColumn(loc);
  2628. Token token = {};
  2629. token.kind = Token_context;
  2630. token.string = str_lit("context");
  2631. token.pos = pos;
  2632. lb_add_debug_local_variable(p, ctx.addr.value, t_context, token);
  2633. }
  2634. void lb_begin_procedure_body(lbProcedure *p) {
  2635. DeclInfo *decl = decl_info_of_entity(p->entity);
  2636. if (decl != nullptr) {
  2637. for_array(i, decl->labels) {
  2638. BlockLabel bl = decl->labels[i];
  2639. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2640. array_add(&p->branch_blocks, bb);
  2641. }
  2642. }
  2643. p->builder = LLVMCreateBuilder();
  2644. p->decl_block = lb_create_block(p, "decls", true);
  2645. p->entry_block = lb_create_block(p, "entry", true);
  2646. lb_start_block(p, p->entry_block);
  2647. GB_ASSERT(p->type != nullptr);
  2648. lb_ensure_abi_function_type(p->module, p);
  2649. {
  2650. lbFunctionType *ft = p->abi_function_type;
  2651. unsigned param_offset = 0;
  2652. lbValue return_ptr_value = {};
  2653. if (ft->ret.kind == lbArg_Indirect) {
  2654. // NOTE(bill): this must be parameter 0
  2655. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2656. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2657. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2658. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2659. return_ptr_value.type = ptr_type;
  2660. p->return_ptr = lb_addr(return_ptr_value);
  2661. lb_add_entity(p->module, e, return_ptr_value);
  2662. param_offset += 1;
  2663. }
  2664. if (p->type->Proc.params != nullptr) {
  2665. TypeTuple *params = &p->type->Proc.params->Tuple;
  2666. unsigned param_index = 0;
  2667. for_array(i, params->variables) {
  2668. Entity *e = params->variables[i];
  2669. if (e->kind != Entity_Variable) {
  2670. continue;
  2671. }
  2672. lbArgType *arg_type = &ft->args[param_index];
  2673. if (arg_type->kind == lbArg_Ignore) {
  2674. continue;
  2675. } else if (arg_type->kind == lbArg_Direct) {
  2676. lbParamPasskind kind = lbParamPass_Value;
  2677. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2678. if (param_type != arg_type->type) {
  2679. kind = lbParamPass_BitCast;
  2680. }
  2681. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2682. value = OdinLLVMBuildTransmute(p, value, param_type);
  2683. lbValue param = {};
  2684. param.value = value;
  2685. param.type = e->type;
  2686. array_add(&p->params, param);
  2687. if (e->token.string.len != 0) {
  2688. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2689. lb_addr_store(p, l, param);
  2690. }
  2691. param_index += 1;
  2692. } else if (arg_type->kind == lbArg_Indirect) {
  2693. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2694. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2695. lbValue param = {};
  2696. param.value = value;
  2697. param.type = e->type;
  2698. array_add(&p->params, param);
  2699. lbValue ptr = {};
  2700. ptr.value = value_ptr;
  2701. ptr.type = alloc_type_pointer(e->type);
  2702. lb_add_entity(p->module, e, ptr);
  2703. param_index += 1;
  2704. }
  2705. }
  2706. }
  2707. if (p->type->Proc.has_named_results) {
  2708. GB_ASSERT(p->type->Proc.result_count > 0);
  2709. TypeTuple *results = &p->type->Proc.results->Tuple;
  2710. for_array(i, results->variables) {
  2711. Entity *e = results->variables[i];
  2712. GB_ASSERT(e->kind == Entity_Variable);
  2713. if (e->token.string != "") {
  2714. GB_ASSERT(!is_blank_ident(e->token));
  2715. lbAddr res = {};
  2716. if (return_ptr_value.value) {
  2717. lbValue ptr = return_ptr_value;
  2718. if (results->variables.count != 1) {
  2719. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2720. }
  2721. res = lb_addr(ptr);
  2722. lb_add_entity(p->module, e, ptr);
  2723. } else {
  2724. res = lb_add_local(p, e->type, e);
  2725. }
  2726. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2727. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2728. lb_addr_store(p, res, c);
  2729. }
  2730. }
  2731. }
  2732. }
  2733. }
  2734. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2735. lb_push_context_onto_stack_from_implicit_parameter(p);
  2736. }
  2737. lb_start_block(p, p->entry_block);
  2738. if (p->debug_info != nullptr) {
  2739. TokenPos pos = {};
  2740. if (p->body != nullptr) {
  2741. pos = ast_token(p->body).pos;
  2742. } else if (p->type_expr != nullptr) {
  2743. pos = ast_token(p->type_expr).pos;
  2744. } else if (p->entity != nullptr) {
  2745. pos = p->entity->token.pos;
  2746. }
  2747. if (pos.file_id != 0) {
  2748. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  2749. }
  2750. if (p->context_stack.count != 0) {
  2751. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  2752. }
  2753. }
  2754. }
  2755. void lb_end_procedure_body(lbProcedure *p) {
  2756. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2757. LLVMBuildBr(p->builder, p->entry_block->block);
  2758. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2759. // Make sure there is a "ret void" at the end of a procedure with no return type
  2760. if (p->type->Proc.result_count == 0) {
  2761. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2762. if (!lb_is_instr_terminating(instr)) {
  2763. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2764. LLVMBuildRetVoid(p->builder);
  2765. }
  2766. }
  2767. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  2768. LLVMBasicBlockRef block = nullptr;
  2769. // Make sure every block terminates, and if not, make it unreachable
  2770. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2771. LLVMValueRef instr = LLVMGetLastInstruction(block);
  2772. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  2773. LLVMPositionBuilderAtEnd(p->builder, block);
  2774. LLVMBuildUnreachable(p->builder);
  2775. }
  2776. }
  2777. p->curr_block = nullptr;
  2778. p->state_flags = 0;
  2779. }
  2780. void lb_end_procedure(lbProcedure *p) {
  2781. LLVMDisposeBuilder(p->builder);
  2782. }
  2783. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2784. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2785. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2786. array_add(&from->succs, to);
  2787. array_add(&to->preds, from);
  2788. }
  2789. }
  2790. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2791. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2792. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2793. b->appended = false;
  2794. if (append) {
  2795. b->appended = true;
  2796. LLVMAppendExistingBasicBlock(p->value, b->block);
  2797. }
  2798. b->scope = p->curr_scope;
  2799. b->scope_index = p->scope_index;
  2800. b->preds.allocator = heap_allocator();
  2801. b->succs.allocator = heap_allocator();
  2802. array_add(&p->blocks, b);
  2803. return b;
  2804. }
  2805. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2806. if (p->curr_block == nullptr) {
  2807. return;
  2808. }
  2809. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2810. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2811. return;
  2812. }
  2813. lb_add_edge(p->curr_block, target_block);
  2814. LLVMBuildBr(p->builder, target_block->block);
  2815. p->curr_block = nullptr;
  2816. }
  2817. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2818. lbBlock *b = p->curr_block;
  2819. if (b == nullptr) {
  2820. return;
  2821. }
  2822. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2823. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2824. return;
  2825. }
  2826. lb_add_edge(b, true_block);
  2827. lb_add_edge(b, false_block);
  2828. LLVMValueRef cv = cond.value;
  2829. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2830. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2831. }
  2832. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2833. GB_ASSERT(cond != nullptr);
  2834. GB_ASSERT(true_block != nullptr);
  2835. GB_ASSERT(false_block != nullptr);
  2836. switch (cond->kind) {
  2837. case_ast_node(pe, ParenExpr, cond);
  2838. return lb_build_cond(p, pe->expr, true_block, false_block);
  2839. case_end;
  2840. case_ast_node(ue, UnaryExpr, cond);
  2841. if (ue->op.kind == Token_Not) {
  2842. return lb_build_cond(p, ue->expr, false_block, true_block);
  2843. }
  2844. case_end;
  2845. case_ast_node(be, BinaryExpr, cond);
  2846. if (be->op.kind == Token_CmpAnd) {
  2847. lbBlock *block = lb_create_block(p, "cmp.and");
  2848. lb_build_cond(p, be->left, block, false_block);
  2849. lb_start_block(p, block);
  2850. return lb_build_cond(p, be->right, true_block, false_block);
  2851. } else if (be->op.kind == Token_CmpOr) {
  2852. lbBlock *block = lb_create_block(p, "cmp.or");
  2853. lb_build_cond(p, be->left, true_block, block);
  2854. lb_start_block(p, block);
  2855. return lb_build_cond(p, be->right, true_block, false_block);
  2856. }
  2857. case_end;
  2858. }
  2859. lbValue v = lb_build_expr(p, cond);
  2860. // v = lb_emit_conv(p, v, t_bool);
  2861. v = lb_emit_conv(p, v, t_llvm_bool);
  2862. lb_emit_if(p, v, true_block, false_block);
  2863. return v;
  2864. }
  2865. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2866. GB_ASSERT(p->decl_block != p->curr_block);
  2867. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2868. char const *name = "";
  2869. if (e != nullptr) {
  2870. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2871. }
  2872. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2873. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2874. // unsigned alignment = 16; // TODO(bill): Make this configurable
  2875. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  2876. LLVMSetAlignment(ptr, alignment);
  2877. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2878. if (zero_init) {
  2879. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2880. switch (kind) {
  2881. case LLVMStructTypeKind:
  2882. case LLVMArrayTypeKind:
  2883. {
  2884. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  2885. LLVMTypeRef type_i8 = LLVMInt8TypeInContext(p->module->ctx);
  2886. LLVMTypeRef type_i32 = LLVMInt32TypeInContext(p->module->ctx);
  2887. i32 sz = cast(i32)type_size_of(type);
  2888. LLVMBuildMemSet(p->builder, ptr, LLVMConstNull(type_i8), LLVMConstInt(type_i32, sz, false), alignment);
  2889. }
  2890. break;
  2891. default:
  2892. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2893. break;
  2894. }
  2895. }
  2896. lbValue val = {};
  2897. val.value = ptr;
  2898. val.type = alloc_type_pointer(type);
  2899. if (e != nullptr) {
  2900. lb_add_entity(p->module, e, val);
  2901. lb_add_debug_local_variable(p, ptr, type, e->token);
  2902. }
  2903. return lb_addr(val);
  2904. }
  2905. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2906. return lb_add_local(p, type, nullptr, zero_init);
  2907. }
  2908. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2909. GB_ASSERT(pd->body != nullptr);
  2910. lbModule *m = p->module;
  2911. auto *min_dep_set = &m->info->minimum_dependency_set;
  2912. if (ptr_set_exists(min_dep_set, e) == false) {
  2913. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2914. return;
  2915. }
  2916. // NOTE(bill): Generate a new name
  2917. // parent.name-guid
  2918. String original_name = e->token.string;
  2919. String pd_name = original_name;
  2920. if (e->Procedure.link_name.len > 0) {
  2921. pd_name = e->Procedure.link_name;
  2922. }
  2923. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2924. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2925. i32 guid = cast(i32)p->children.count;
  2926. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2927. String name = make_string(cast(u8 *)name_text, name_len-1);
  2928. e->Procedure.link_name = name;
  2929. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2930. e->code_gen_procedure = nested_proc;
  2931. lbValue value = {};
  2932. value.value = nested_proc->value;
  2933. value.type = nested_proc->type;
  2934. lb_add_entity(m, e, value);
  2935. array_add(&p->children, nested_proc);
  2936. array_add(&m->procedures_to_generate, nested_proc);
  2937. }
  2938. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2939. if (e == nullptr) {
  2940. return;
  2941. }
  2942. GB_ASSERT(e->kind == Entity_LibraryName);
  2943. GB_ASSERT(e->flags & EntityFlag_Used);
  2944. for_array(i, e->LibraryName.paths) {
  2945. String library_path = e->LibraryName.paths[i];
  2946. if (library_path.len == 0) {
  2947. continue;
  2948. }
  2949. bool ok = true;
  2950. for_array(path_index, m->foreign_library_paths) {
  2951. String path = m->foreign_library_paths[path_index];
  2952. #if defined(GB_SYSTEM_WINDOWS)
  2953. if (str_eq_ignore_case(path, library_path)) {
  2954. #else
  2955. if (str_eq(path, library_path)) {
  2956. #endif
  2957. ok = false;
  2958. break;
  2959. }
  2960. }
  2961. if (ok) {
  2962. array_add(&m->foreign_library_paths, library_path);
  2963. }
  2964. }
  2965. }
  2966. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2967. if (vd == nullptr || vd->is_mutable) {
  2968. return;
  2969. }
  2970. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2971. static i32 global_guid = 0;
  2972. for_array(i, vd->names) {
  2973. Ast *ident = vd->names[i];
  2974. GB_ASSERT(ident->kind == Ast_Ident);
  2975. Entity *e = entity_of_node(ident);
  2976. GB_ASSERT(e != nullptr);
  2977. if (e->kind != Entity_TypeName) {
  2978. continue;
  2979. }
  2980. bool polymorphic_struct = false;
  2981. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2982. Type *bt = base_type(e->type);
  2983. if (bt->kind == Type_Struct) {
  2984. polymorphic_struct = bt->Struct.is_polymorphic;
  2985. }
  2986. }
  2987. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2988. continue;
  2989. }
  2990. if (e->TypeName.ir_mangled_name.len != 0) {
  2991. // NOTE(bill): Already set
  2992. continue;
  2993. }
  2994. lb_set_nested_type_name_ir_mangled_name(e, p);
  2995. }
  2996. for_array(i, vd->names) {
  2997. Ast *ident = vd->names[i];
  2998. GB_ASSERT(ident->kind == Ast_Ident);
  2999. Entity *e = entity_of_node(ident);
  3000. GB_ASSERT(e != nullptr);
  3001. if (e->kind != Entity_Procedure) {
  3002. continue;
  3003. }
  3004. GB_ASSERT (vd->values[i] != nullptr);
  3005. Ast *value = unparen_expr(vd->values[i]);
  3006. if (value->kind != Ast_ProcLit) {
  3007. continue; // It's an alias
  3008. }
  3009. CheckerInfo *info = p->module->info;
  3010. DeclInfo *decl = decl_info_of_entity(e);
  3011. ast_node(pl, ProcLit, decl->proc_lit);
  3012. if (pl->body != nullptr) {
  3013. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  3014. if (found) {
  3015. auto procs = *found;
  3016. for_array(i, procs) {
  3017. Entity *e = procs[i];
  3018. if (!ptr_set_exists(min_dep_set, e)) {
  3019. continue;
  3020. }
  3021. DeclInfo *d = decl_info_of_entity(e);
  3022. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  3023. }
  3024. } else {
  3025. lb_build_nested_proc(p, pl, e);
  3026. }
  3027. } else {
  3028. // FFI - Foreign function interace
  3029. String original_name = e->token.string;
  3030. String name = original_name;
  3031. if (e->Procedure.is_foreign) {
  3032. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  3033. }
  3034. if (e->Procedure.link_name.len > 0) {
  3035. name = e->Procedure.link_name;
  3036. }
  3037. lbValue *prev_value = string_map_get(&p->module->members, name);
  3038. if (prev_value != nullptr) {
  3039. // NOTE(bill): Don't do mutliple declarations in the IR
  3040. return;
  3041. }
  3042. e->Procedure.link_name = name;
  3043. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  3044. lbValue value = {};
  3045. value.value = nested_proc->value;
  3046. value.type = nested_proc->type;
  3047. array_add(&p->module->procedures_to_generate, nested_proc);
  3048. if (p != nullptr) {
  3049. array_add(&p->children, nested_proc);
  3050. } else {
  3051. string_map_set(&p->module->members, name, value);
  3052. }
  3053. }
  3054. }
  3055. }
  3056. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  3057. for_array(i, stmts) {
  3058. Ast *stmt = stmts[i];
  3059. switch (stmt->kind) {
  3060. case_ast_node(vd, ValueDecl, stmt);
  3061. lb_build_constant_value_decl(p, vd);
  3062. case_end;
  3063. case_ast_node(fb, ForeignBlockDecl, stmt);
  3064. ast_node(block, BlockStmt, fb->body);
  3065. lb_build_stmt_list(p, block->stmts);
  3066. case_end;
  3067. }
  3068. }
  3069. for_array(i, stmts) {
  3070. lb_build_stmt(p, stmts[i]);
  3071. }
  3072. }
  3073. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  3074. GB_ASSERT(ident->kind == Ast_Ident);
  3075. Entity *e = entity_of_node(ident);
  3076. GB_ASSERT(e->kind == Entity_Label);
  3077. for_array(i, p->branch_blocks) {
  3078. lbBranchBlocks *b = &p->branch_blocks[i];
  3079. if (b->label == e->Label.node) {
  3080. return *b;
  3081. }
  3082. }
  3083. GB_PANIC("Unreachable");
  3084. lbBranchBlocks empty = {};
  3085. return empty;
  3086. }
  3087. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  3088. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  3089. tl->prev = p->target_list;
  3090. tl->break_ = break_;
  3091. tl->continue_ = continue_;
  3092. tl->fallthrough_ = fallthrough_;
  3093. p->target_list = tl;
  3094. if (label != nullptr) { // Set label blocks
  3095. GB_ASSERT(label->kind == Ast_Label);
  3096. for_array(i, p->branch_blocks) {
  3097. lbBranchBlocks *b = &p->branch_blocks[i];
  3098. GB_ASSERT(b->label != nullptr && label != nullptr);
  3099. GB_ASSERT(b->label->kind == Ast_Label);
  3100. if (b->label == label) {
  3101. b->break_ = break_;
  3102. b->continue_ = continue_;
  3103. return tl;
  3104. }
  3105. }
  3106. GB_PANIC("Unreachable");
  3107. }
  3108. return tl;
  3109. }
  3110. void lb_pop_target_list(lbProcedure *p) {
  3111. p->target_list = p->target_list->prev;
  3112. }
  3113. void lb_open_scope(lbProcedure *p, Scope *s) {
  3114. lbModule *m = p->module;
  3115. if (m->debug_builder) {
  3116. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  3117. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  3118. Token token = ast_token(s->node);
  3119. unsigned line = cast(unsigned)token.pos.line;
  3120. unsigned column = cast(unsigned)token.pos.column;
  3121. LLVMMetadataRef file = nullptr;
  3122. if (s->node->file != nullptr) {
  3123. file = lb_get_llvm_metadata(m, s->node->file);
  3124. }
  3125. LLVMMetadataRef scope = nullptr;
  3126. if (p->scope_stack.count > 0) {
  3127. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  3128. }
  3129. if (scope == nullptr) {
  3130. scope = lb_get_llvm_metadata(m, p);
  3131. }
  3132. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  3133. if (m->debug_builder) {
  3134. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  3135. file, line, column
  3136. );
  3137. lb_set_llvm_metadata(m, s, res);
  3138. }
  3139. }
  3140. }
  3141. p->scope_index += 1;
  3142. array_add(&p->scope_stack, s);
  3143. }
  3144. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  3145. lb_emit_defer_stmts(p, kind, block);
  3146. GB_ASSERT(p->scope_index > 0);
  3147. // NOTE(bill): Remove `context`s made in that scope
  3148. while (p->context_stack.count > 0) {
  3149. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  3150. if (ctx->scope_index >= p->scope_index) {
  3151. array_pop(&p->context_stack);
  3152. } else {
  3153. break;
  3154. }
  3155. }
  3156. p->scope_index -= 1;
  3157. array_pop(&p->scope_stack);
  3158. }
  3159. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  3160. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  3161. GB_ASSERT(is_type_boolean(tv.type));
  3162. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  3163. if (tv.value.value_bool) {
  3164. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  3165. } else if (ws->else_stmt) {
  3166. switch (ws->else_stmt->kind) {
  3167. case Ast_BlockStmt:
  3168. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  3169. break;
  3170. case Ast_WhenStmt:
  3171. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  3172. break;
  3173. default:
  3174. GB_PANIC("Invalid 'else' statement in 'when' statement");
  3175. break;
  3176. }
  3177. }
  3178. }
  3179. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  3180. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3181. lbModule *m = p->module;
  3182. lbValue count = {};
  3183. Type *expr_type = base_type(type_deref(expr.type));
  3184. switch (expr_type->kind) {
  3185. case Type_Array:
  3186. count = lb_const_int(m, t_int, expr_type->Array.count);
  3187. break;
  3188. }
  3189. lbValue val = {};
  3190. lbValue idx = {};
  3191. lbBlock *loop = nullptr;
  3192. lbBlock *done = nullptr;
  3193. lbBlock *body = nullptr;
  3194. lbAddr index = lb_add_local_generated(p, t_int, false);
  3195. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  3196. loop = lb_create_block(p, "for.index.loop");
  3197. lb_emit_jump(p, loop);
  3198. lb_start_block(p, loop);
  3199. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  3200. lb_addr_store(p, index, incr);
  3201. body = lb_create_block(p, "for.index.body");
  3202. done = lb_create_block(p, "for.index.done");
  3203. if (count.value == nullptr) {
  3204. GB_ASSERT(count_ptr.value != nullptr);
  3205. count = lb_emit_load(p, count_ptr);
  3206. }
  3207. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3208. lb_emit_if(p, cond, body, done);
  3209. lb_start_block(p, body);
  3210. idx = lb_addr_load(p, index);
  3211. switch (expr_type->kind) {
  3212. case Type_Array: {
  3213. if (val_type != nullptr) {
  3214. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3215. }
  3216. break;
  3217. }
  3218. case Type_EnumeratedArray: {
  3219. if (val_type != nullptr) {
  3220. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3221. // NOTE(bill): Override the idx value for the enumeration
  3222. Type *index_type = expr_type->EnumeratedArray.index;
  3223. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  3224. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  3225. }
  3226. }
  3227. break;
  3228. }
  3229. case Type_Slice: {
  3230. if (val_type != nullptr) {
  3231. lbValue elem = lb_slice_elem(p, expr);
  3232. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3233. }
  3234. break;
  3235. }
  3236. case Type_DynamicArray: {
  3237. if (val_type != nullptr) {
  3238. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  3239. elem = lb_emit_load(p, elem);
  3240. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3241. }
  3242. break;
  3243. }
  3244. case Type_Map: {
  3245. lbValue entries = lb_map_entries_ptr(p, expr);
  3246. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  3247. elem = lb_emit_load(p, elem);
  3248. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  3249. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  3250. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  3251. break;
  3252. }
  3253. case Type_Struct: {
  3254. GB_ASSERT(is_type_soa_struct(expr_type));
  3255. break;
  3256. }
  3257. default:
  3258. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  3259. break;
  3260. }
  3261. if (val_) *val_ = val;
  3262. if (idx_) *idx_ = idx;
  3263. if (loop_) *loop_ = loop;
  3264. if (done_) *done_ = done;
  3265. }
  3266. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  3267. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3268. lbModule *m = p->module;
  3269. lbValue count = lb_const_int(m, t_int, 0);
  3270. Type *expr_type = base_type(expr.type);
  3271. switch (expr_type->kind) {
  3272. case Type_Basic:
  3273. count = lb_string_len(p, expr);
  3274. break;
  3275. default:
  3276. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  3277. break;
  3278. }
  3279. lbValue val = {};
  3280. lbValue idx = {};
  3281. lbBlock *loop = nullptr;
  3282. lbBlock *done = nullptr;
  3283. lbBlock *body = nullptr;
  3284. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3285. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3286. loop = lb_create_block(p, "for.string.loop");
  3287. lb_emit_jump(p, loop);
  3288. lb_start_block(p, loop);
  3289. body = lb_create_block(p, "for.string.body");
  3290. done = lb_create_block(p, "for.string.done");
  3291. lbValue offset = lb_addr_load(p, offset_);
  3292. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  3293. lb_emit_if(p, cond, body, done);
  3294. lb_start_block(p, body);
  3295. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  3296. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  3297. auto args = array_make<lbValue>(permanent_allocator(), 1);
  3298. args[0] = lb_emit_string(p, str_elem, str_len);
  3299. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  3300. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  3301. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  3302. idx = offset;
  3303. if (val_type != nullptr) {
  3304. val = lb_emit_struct_ev(p, rune_and_len, 0);
  3305. }
  3306. if (val_) *val_ = val;
  3307. if (idx_) *idx_ = idx;
  3308. if (loop_) *loop_ = loop;
  3309. if (done_) *done_ = done;
  3310. }
  3311. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  3312. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3313. lbModule *m = p->module;
  3314. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  3315. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  3316. lbValue lower = lb_build_expr(p, node->left);
  3317. lbValue upper = {};
  3318. lbValue val = {};
  3319. lbValue idx = {};
  3320. lbBlock *loop = nullptr;
  3321. lbBlock *done = nullptr;
  3322. lbBlock *body = nullptr;
  3323. if (val_type == nullptr) {
  3324. val_type = lower.type;
  3325. }
  3326. lbAddr value = lb_add_local_generated(p, val_type, false);
  3327. lb_addr_store(p, value, lower);
  3328. lbAddr index = lb_add_local_generated(p, t_int, false);
  3329. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  3330. loop = lb_create_block(p, "for.interval.loop");
  3331. lb_emit_jump(p, loop);
  3332. lb_start_block(p, loop);
  3333. body = lb_create_block(p, "for.interval.body");
  3334. done = lb_create_block(p, "for.interval.done");
  3335. TokenKind op = Token_Lt;
  3336. switch (node->op.kind) {
  3337. case Token_Ellipsis: op = Token_LtEq; break;
  3338. case Token_RangeHalf: op = Token_Lt; break;
  3339. default: GB_PANIC("Invalid interval operator"); break;
  3340. }
  3341. upper = lb_build_expr(p, node->right);
  3342. lbValue curr_value = lb_addr_load(p, value);
  3343. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  3344. lb_emit_if(p, cond, body, done);
  3345. lb_start_block(p, body);
  3346. val = lb_addr_load(p, value);
  3347. idx = lb_addr_load(p, index);
  3348. lb_emit_increment(p, value.addr);
  3349. lb_emit_increment(p, index.addr);
  3350. if (val_) *val_ = val;
  3351. if (idx_) *idx_ = idx;
  3352. if (loop_) *loop_ = loop;
  3353. if (done_) *done_ = done;
  3354. }
  3355. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3356. lbModule *m = p->module;
  3357. Type *t = enum_type;
  3358. GB_ASSERT(is_type_enum(t));
  3359. Type *enum_ptr = alloc_type_pointer(t);
  3360. t = base_type(t);
  3361. Type *core_elem = core_type(t);
  3362. GB_ASSERT(t->kind == Type_Enum);
  3363. i64 enum_count = t->Enum.fields.count;
  3364. lbValue max_count = lb_const_int(m, t_int, enum_count);
  3365. lbValue ti = lb_type_info(m, t);
  3366. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  3367. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  3368. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  3369. lbValue values_data = lb_slice_elem(p, values);
  3370. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3371. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3372. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  3373. lb_emit_jump(p, loop);
  3374. lb_start_block(p, loop);
  3375. lbBlock *body = lb_create_block(p, "for.enum.body");
  3376. lbBlock *done = lb_create_block(p, "for.enum.done");
  3377. lbValue offset = lb_addr_load(p, offset_);
  3378. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  3379. lb_emit_if(p, cond, body, done);
  3380. lb_start_block(p, body);
  3381. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  3382. lb_emit_increment(p, offset_.addr);
  3383. lbValue val = {};
  3384. if (val_type != nullptr) {
  3385. GB_ASSERT(are_types_identical(enum_type, val_type));
  3386. if (is_type_integer(core_elem)) {
  3387. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  3388. val = lb_emit_conv(p, i, t);
  3389. } else {
  3390. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  3391. }
  3392. }
  3393. if (val_) *val_ = val;
  3394. if (idx_) *idx_ = offset;
  3395. if (loop_) *loop_ = loop;
  3396. if (done_) *done_ = done;
  3397. }
  3398. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  3399. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  3400. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  3401. lb_emit_jump(p, loop);
  3402. lb_start_block(p, loop);
  3403. lbBlock *body = lb_create_block(p, "for.tuple.body");
  3404. lbBlock *done = lb_create_block(p, "for.tuple.done");
  3405. lbValue tuple_value = lb_build_expr(p, expr);
  3406. Type *tuple = tuple_value.type;
  3407. GB_ASSERT(tuple->kind == Type_Tuple);
  3408. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  3409. i32 cond_index = tuple_count-1;
  3410. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  3411. lb_emit_if(p, cond, body, done);
  3412. lb_start_block(p, body);
  3413. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  3414. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  3415. if (loop_) *loop_ = loop;
  3416. if (done_) *done_ = done;
  3417. }
  3418. void lb_build_range_stmt_struct_soa(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3419. Ast *expr = unparen_expr(rs->expr);
  3420. TypeAndValue tav = type_and_value_of_expr(expr);
  3421. lbBlock *loop = nullptr;
  3422. lbBlock *body = nullptr;
  3423. lbBlock *done = nullptr;
  3424. lb_open_scope(p, scope);
  3425. Type *val_types[2] = {};
  3426. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3427. val_types[0] = type_of_expr(rs->vals[0]);
  3428. }
  3429. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3430. val_types[1] = type_of_expr(rs->vals[1]);
  3431. }
  3432. lbAddr array = lb_build_addr(p, expr);
  3433. if (is_type_pointer(type_deref(lb_addr_type(array)))) {
  3434. array = lb_addr(lb_addr_load(p, array));
  3435. }
  3436. lbValue count = lb_soa_struct_len(p, lb_addr_load(p, array));
  3437. lbAddr index = lb_add_local_generated(p, t_int, false);
  3438. lb_addr_store(p, index, lb_const_int(p->module, t_int, cast(u64)-1));
  3439. loop = lb_create_block(p, "for.soa.loop");
  3440. lb_emit_jump(p, loop);
  3441. lb_start_block(p, loop);
  3442. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  3443. lb_addr_store(p, index, incr);
  3444. body = lb_create_block(p, "for.soa.body");
  3445. done = lb_create_block(p, "for.soa.done");
  3446. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3447. lb_emit_if(p, cond, body, done);
  3448. lb_start_block(p, body);
  3449. if (val_types[0]) {
  3450. Entity *e = entity_of_node(rs->vals[0]);
  3451. if (e != nullptr) {
  3452. lbAddr soa_val = lb_addr_soa_variable(array.addr, lb_addr_load(p, index), nullptr);
  3453. map_set(&p->module->soa_values, hash_entity(e), soa_val);
  3454. }
  3455. }
  3456. if (val_types[1]) {
  3457. lb_store_range_stmt_val(p, rs->vals[1], lb_addr_load(p, index));
  3458. }
  3459. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3460. lb_build_stmt(p, rs->body);
  3461. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3462. lb_pop_target_list(p);
  3463. lb_emit_jump(p, loop);
  3464. lb_start_block(p, done);
  3465. }
  3466. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3467. Ast *expr = unparen_expr(rs->expr);
  3468. Type *expr_type = type_of_expr(expr);
  3469. if (expr_type != nullptr) {
  3470. Type *et = base_type(type_deref(expr_type));
  3471. if (is_type_soa_struct(et)) {
  3472. lb_build_range_stmt_struct_soa(p, rs, scope);
  3473. return;
  3474. }
  3475. }
  3476. lb_open_scope(p, scope);
  3477. Type *val0_type = nullptr;
  3478. Type *val1_type = nullptr;
  3479. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3480. val0_type = type_of_expr(rs->vals[0]);
  3481. }
  3482. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3483. val1_type = type_of_expr(rs->vals[1]);
  3484. }
  3485. if (val0_type != nullptr) {
  3486. Entity *e = entity_of_node(rs->vals[0]);
  3487. lb_add_local(p, e->type, e, true);
  3488. }
  3489. if (val1_type != nullptr) {
  3490. Entity *e = entity_of_node(rs->vals[1]);
  3491. lb_add_local(p, e->type, e, true);
  3492. }
  3493. lbValue val = {};
  3494. lbValue key = {};
  3495. lbBlock *loop = nullptr;
  3496. lbBlock *done = nullptr;
  3497. bool is_map = false;
  3498. TypeAndValue tav = type_and_value_of_expr(expr);
  3499. if (is_ast_range(expr)) {
  3500. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  3501. } else if (tav.mode == Addressing_Type) {
  3502. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3503. } else {
  3504. Type *expr_type = type_of_expr(expr);
  3505. Type *et = base_type(type_deref(expr_type));
  3506. switch (et->kind) {
  3507. case Type_Map: {
  3508. is_map = true;
  3509. lbValue map = lb_build_addr_ptr(p, expr);
  3510. if (is_type_pointer(type_deref(map.type))) {
  3511. map = lb_emit_load(p, map);
  3512. }
  3513. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3514. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3515. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3516. break;
  3517. }
  3518. case Type_Array: {
  3519. lbValue array = lb_build_addr_ptr(p, expr);
  3520. if (is_type_pointer(type_deref(array.type))) {
  3521. array = lb_emit_load(p, array);
  3522. }
  3523. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3524. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3525. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3526. break;
  3527. }
  3528. case Type_EnumeratedArray: {
  3529. lbValue array = lb_build_addr_ptr(p, expr);
  3530. if (is_type_pointer(type_deref(array.type))) {
  3531. array = lb_emit_load(p, array);
  3532. }
  3533. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3534. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3535. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3536. break;
  3537. }
  3538. case Type_DynamicArray: {
  3539. lbValue count_ptr = {};
  3540. lbValue array = lb_build_addr_ptr(p, expr);
  3541. if (is_type_pointer(type_deref(array.type))) {
  3542. array = lb_emit_load(p, array);
  3543. }
  3544. count_ptr = lb_emit_struct_ep(p, array, 1);
  3545. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3546. break;
  3547. }
  3548. case Type_Slice: {
  3549. lbValue count_ptr = {};
  3550. lbValue slice = lb_build_expr(p, expr);
  3551. if (is_type_pointer(slice.type)) {
  3552. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3553. slice = lb_emit_load(p, slice);
  3554. } else {
  3555. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3556. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3557. }
  3558. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3559. break;
  3560. }
  3561. case Type_Basic: {
  3562. lbValue string = lb_build_expr(p, expr);
  3563. if (is_type_pointer(string.type)) {
  3564. string = lb_emit_load(p, string);
  3565. }
  3566. if (is_type_untyped(expr_type)) {
  3567. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3568. lb_addr_store(p, s, string);
  3569. string = lb_addr_load(p, s);
  3570. }
  3571. Type *t = base_type(string.type);
  3572. GB_ASSERT(!is_type_cstring(t));
  3573. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3574. break;
  3575. }
  3576. case Type_Tuple:
  3577. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3578. break;
  3579. default:
  3580. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3581. break;
  3582. }
  3583. }
  3584. if (is_map) {
  3585. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], key);
  3586. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], val);
  3587. } else {
  3588. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3589. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], key);
  3590. }
  3591. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3592. lb_build_stmt(p, rs->body);
  3593. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3594. lb_pop_target_list(p);
  3595. lb_emit_jump(p, loop);
  3596. lb_start_block(p, done);
  3597. }
  3598. void lb_build_inline_range_stmt(lbProcedure *p, AstUnrollRangeStmt *rs, Scope *scope) {
  3599. lbModule *m = p->module;
  3600. lb_open_scope(p, scope); // Open scope here
  3601. Type *val0_type = nullptr;
  3602. Type *val1_type = nullptr;
  3603. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3604. val0_type = type_of_expr(rs->val0);
  3605. }
  3606. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3607. val1_type = type_of_expr(rs->val1);
  3608. }
  3609. if (val0_type != nullptr) {
  3610. Entity *e = entity_of_node(rs->val0);
  3611. lb_add_local(p, e->type, e, true);
  3612. }
  3613. if (val1_type != nullptr) {
  3614. Entity *e = entity_of_node(rs->val1);
  3615. lb_add_local(p, e->type, e, true);
  3616. }
  3617. lbValue val = {};
  3618. lbValue key = {};
  3619. lbBlock *loop = nullptr;
  3620. lbBlock *done = nullptr;
  3621. Ast *expr = unparen_expr(rs->expr);
  3622. TypeAndValue tav = type_and_value_of_expr(expr);
  3623. if (is_ast_range(expr)) {
  3624. lbAddr val0_addr = {};
  3625. lbAddr val1_addr = {};
  3626. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3627. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3628. TokenKind op = expr->BinaryExpr.op.kind;
  3629. Ast *start_expr = expr->BinaryExpr.left;
  3630. Ast *end_expr = expr->BinaryExpr.right;
  3631. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3632. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3633. ExactValue start = start_expr->tav.value;
  3634. ExactValue end = end_expr->tav.value;
  3635. if (op == Token_Ellipsis) { // .. [start, end]
  3636. ExactValue index = exact_value_i64(0);
  3637. for (ExactValue val = start;
  3638. compare_exact_values(Token_LtEq, val, end);
  3639. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3640. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3641. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3642. lb_build_stmt(p, rs->body);
  3643. }
  3644. } else if (op == Token_RangeHalf) { // ..< [start, end)
  3645. ExactValue index = exact_value_i64(0);
  3646. for (ExactValue val = start;
  3647. compare_exact_values(Token_Lt, val, end);
  3648. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3649. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3650. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3651. lb_build_stmt(p, rs->body);
  3652. }
  3653. }
  3654. } else if (tav.mode == Addressing_Type) {
  3655. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3656. Type *et = type_deref(tav.type);
  3657. Type *bet = base_type(et);
  3658. lbAddr val0_addr = {};
  3659. lbAddr val1_addr = {};
  3660. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3661. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3662. for_array(i, bet->Enum.fields) {
  3663. Entity *field = bet->Enum.fields[i];
  3664. GB_ASSERT(field->kind == Entity_Constant);
  3665. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3666. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3667. lb_build_stmt(p, rs->body);
  3668. }
  3669. } else {
  3670. lbAddr val0_addr = {};
  3671. lbAddr val1_addr = {};
  3672. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3673. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3674. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3675. Type *t = base_type(expr->tav.type);
  3676. switch (t->kind) {
  3677. case Type_Basic:
  3678. GB_ASSERT(is_type_string(t));
  3679. {
  3680. ExactValue value = expr->tav.value;
  3681. GB_ASSERT(value.kind == ExactValue_String);
  3682. String str = value.value_string;
  3683. Rune codepoint = 0;
  3684. isize offset = 0;
  3685. do {
  3686. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3687. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3688. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3689. lb_build_stmt(p, rs->body);
  3690. offset += width;
  3691. } while (offset < str.len);
  3692. }
  3693. break;
  3694. case Type_Array:
  3695. if (t->Array.count > 0) {
  3696. lbValue val = lb_build_expr(p, expr);
  3697. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3698. for (i64 i = 0; i < t->Array.count; i++) {
  3699. if (val0_type) {
  3700. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3701. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3702. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3703. }
  3704. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3705. lb_build_stmt(p, rs->body);
  3706. }
  3707. }
  3708. break;
  3709. case Type_EnumeratedArray:
  3710. if (t->EnumeratedArray.count > 0) {
  3711. lbValue val = lb_build_expr(p, expr);
  3712. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3713. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3714. if (val0_type) {
  3715. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3716. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3717. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3718. }
  3719. if (val1_type) {
  3720. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3721. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3722. }
  3723. lb_build_stmt(p, rs->body);
  3724. }
  3725. }
  3726. break;
  3727. default:
  3728. GB_PANIC("Invalid '#unroll for' type");
  3729. break;
  3730. }
  3731. }
  3732. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3733. }
  3734. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  3735. lb_open_scope(p, scope);
  3736. if (ss->init != nullptr) {
  3737. lb_build_stmt(p, ss->init);
  3738. }
  3739. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3740. if (ss->tag != nullptr) {
  3741. tag = lb_build_expr(p, ss->tag);
  3742. }
  3743. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3744. ast_node(body, BlockStmt, ss->body);
  3745. Slice<Ast *> default_stmts = {};
  3746. lbBlock *default_fall = nullptr;
  3747. lbBlock *default_block = nullptr;
  3748. lbBlock *fall = nullptr;
  3749. isize case_count = body->stmts.count;
  3750. for_array(i, body->stmts) {
  3751. Ast *clause = body->stmts[i];
  3752. ast_node(cc, CaseClause, clause);
  3753. lbBlock *body = fall;
  3754. if (body == nullptr) {
  3755. body = lb_create_block(p, "switch.case.body");
  3756. }
  3757. fall = done;
  3758. if (i+1 < case_count) {
  3759. fall = lb_create_block(p, "switch.fall.body");
  3760. }
  3761. if (cc->list.count == 0) {
  3762. // default case
  3763. default_stmts = cc->stmts;
  3764. default_fall = fall;
  3765. default_block = body;
  3766. continue;
  3767. }
  3768. lbBlock *next_cond = nullptr;
  3769. for_array(j, cc->list) {
  3770. Ast *expr = unparen_expr(cc->list[j]);
  3771. next_cond = lb_create_block(p, "switch.case.next");
  3772. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3773. if (is_ast_range(expr)) {
  3774. ast_node(ie, BinaryExpr, expr);
  3775. TokenKind op = Token_Invalid;
  3776. switch (ie->op.kind) {
  3777. case Token_Ellipsis: op = Token_LtEq; break;
  3778. case Token_RangeHalf: op = Token_Lt; break;
  3779. default: GB_PANIC("Invalid interval operator"); break;
  3780. }
  3781. lbValue lhs = lb_build_expr(p, ie->left);
  3782. lbValue rhs = lb_build_expr(p, ie->right);
  3783. // TODO(bill): do short circuit here
  3784. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3785. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3786. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3787. } else {
  3788. if (expr->tav.mode == Addressing_Type) {
  3789. GB_ASSERT(is_type_typeid(tag.type));
  3790. lbValue e = lb_typeid(p->module, expr->tav.type);
  3791. e = lb_emit_conv(p, e, tag.type);
  3792. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3793. } else {
  3794. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3795. }
  3796. }
  3797. lb_emit_if(p, cond, body, next_cond);
  3798. lb_start_block(p, next_cond);
  3799. }
  3800. lb_start_block(p, body);
  3801. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3802. lb_open_scope(p, body->scope);
  3803. lb_build_stmt_list(p, cc->stmts);
  3804. lb_close_scope(p, lbDeferExit_Default, body);
  3805. lb_pop_target_list(p);
  3806. lb_emit_jump(p, done);
  3807. lb_start_block(p, next_cond);
  3808. }
  3809. if (default_block != nullptr) {
  3810. lb_emit_jump(p, default_block);
  3811. lb_start_block(p, default_block);
  3812. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3813. lb_open_scope(p, default_block->scope);
  3814. lb_build_stmt_list(p, default_stmts);
  3815. lb_close_scope(p, lbDeferExit_Default, default_block);
  3816. lb_pop_target_list(p);
  3817. }
  3818. lb_emit_jump(p, done);
  3819. lb_close_scope(p, lbDeferExit_Default, done);
  3820. lb_start_block(p, done);
  3821. }
  3822. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3823. Entity *e = implicit_entity_of_node(clause);
  3824. GB_ASSERT(e != nullptr);
  3825. if (e->flags & EntityFlag_Value) {
  3826. // by value
  3827. GB_ASSERT(are_types_identical(e->type, value.type));
  3828. lbAddr x = lb_add_local(p, e->type, e, false);
  3829. lb_addr_store(p, x, value);
  3830. } else {
  3831. // by reference
  3832. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3833. lb_add_entity(p->module, e, value);
  3834. }
  3835. }
  3836. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3837. Entity *e = entity_of_node(stmt_val);
  3838. if (e == nullptr) {
  3839. return {};
  3840. }
  3841. if ((e->flags & EntityFlag_Value) == 0) {
  3842. if (LLVMIsALoadInst(value.value)) {
  3843. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3844. lb_add_entity(p->module, e, ptr);
  3845. return lb_addr(ptr);
  3846. }
  3847. }
  3848. // by value
  3849. lbAddr addr = lb_add_local(p, e->type, e, false);
  3850. lb_addr_store(p, addr, value);
  3851. return addr;
  3852. }
  3853. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3854. ast_node(cc, CaseClause, clause);
  3855. lb_push_target_list(p, label, done, nullptr, nullptr);
  3856. lb_open_scope(p, body->scope);
  3857. lb_build_stmt_list(p, cc->stmts);
  3858. lb_close_scope(p, lbDeferExit_Default, body);
  3859. lb_pop_target_list(p);
  3860. lb_emit_jump(p, done);
  3861. }
  3862. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3863. lbModule *m = p->module;
  3864. ast_node(as, AssignStmt, ss->tag);
  3865. GB_ASSERT(as->lhs.count == 1);
  3866. GB_ASSERT(as->rhs.count == 1);
  3867. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3868. bool is_parent_ptr = is_type_pointer(parent.type);
  3869. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3870. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3871. lbValue parent_value = parent;
  3872. lbValue parent_ptr = parent;
  3873. if (!is_parent_ptr) {
  3874. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3875. }
  3876. lbValue tag_index = {};
  3877. lbValue union_data = {};
  3878. if (switch_kind == TypeSwitch_Union) {
  3879. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3880. if (is_type_union_maybe_pointer(type_deref(parent_ptr.type))) {
  3881. tag_index = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, union_data), t_int);
  3882. } else {
  3883. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3884. tag_index = lb_emit_load(p, tag_ptr);
  3885. }
  3886. }
  3887. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3888. lb_emit_jump(p, start_block);
  3889. lb_start_block(p, start_block);
  3890. // NOTE(bill): Append this later
  3891. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3892. Ast *default_ = nullptr;
  3893. ast_node(body, BlockStmt, ss->body);
  3894. gb_local_persist i32 weird_count = 0;
  3895. for_array(i, body->stmts) {
  3896. Ast *clause = body->stmts[i];
  3897. ast_node(cc, CaseClause, clause);
  3898. if (cc->list.count == 0) {
  3899. default_ = clause;
  3900. continue;
  3901. }
  3902. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3903. lbBlock *next = nullptr;
  3904. Type *case_type = nullptr;
  3905. for_array(type_index, cc->list) {
  3906. next = lb_create_block(p, "typeswitch.next");
  3907. case_type = type_of_expr(cc->list[type_index]);
  3908. lbValue cond = {};
  3909. if (switch_kind == TypeSwitch_Union) {
  3910. Type *ut = base_type(type_deref(parent.type));
  3911. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3912. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3913. } else if (switch_kind == TypeSwitch_Any) {
  3914. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3915. lbValue case_typeid = lb_typeid(m, case_type);
  3916. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3917. }
  3918. GB_ASSERT(cond.value != nullptr);
  3919. lb_emit_if(p, cond, body, next);
  3920. lb_start_block(p, next);
  3921. }
  3922. Entity *case_entity = implicit_entity_of_node(clause);
  3923. lbValue value = parent_value;
  3924. lb_start_block(p, body);
  3925. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3926. if (cc->list.count == 1) {
  3927. lbValue data = {};
  3928. if (switch_kind == TypeSwitch_Union) {
  3929. data = union_data;
  3930. } else if (switch_kind == TypeSwitch_Any) {
  3931. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3932. data = any_data;
  3933. }
  3934. Type *ct = case_entity->type;
  3935. Type *ct_ptr = alloc_type_pointer(ct);
  3936. value = lb_emit_conv(p, data, ct_ptr);
  3937. if (!by_reference) {
  3938. value = lb_emit_load(p, value);
  3939. }
  3940. }
  3941. lb_store_type_case_implicit(p, clause, value);
  3942. lb_type_case_body(p, ss->label, clause, body, done);
  3943. lb_start_block(p, next);
  3944. }
  3945. if (default_ != nullptr) {
  3946. lb_store_type_case_implicit(p, default_, parent_value);
  3947. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3948. } else {
  3949. lb_emit_jump(p, done);
  3950. }
  3951. lb_start_block(p, done);
  3952. }
  3953. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3954. lbModule *m = p->module;
  3955. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3956. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3957. type = default_type(type);
  3958. lbValue short_circuit = {};
  3959. if (op == Token_CmpAnd) {
  3960. lb_build_cond(p, left, rhs, done);
  3961. short_circuit = lb_const_bool(m, type, false);
  3962. } else if (op == Token_CmpOr) {
  3963. lb_build_cond(p, left, done, rhs);
  3964. short_circuit = lb_const_bool(m, type, true);
  3965. }
  3966. if (rhs->preds.count == 0) {
  3967. lb_start_block(p, done);
  3968. return short_circuit;
  3969. }
  3970. if (done->preds.count == 0) {
  3971. lb_start_block(p, rhs);
  3972. return lb_build_expr(p, right);
  3973. }
  3974. Array<LLVMValueRef> incoming_values = {};
  3975. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3976. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3977. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3978. for_array(i, done->preds) {
  3979. incoming_values[i] = short_circuit.value;
  3980. incoming_blocks[i] = done->preds[i]->block;
  3981. }
  3982. lb_start_block(p, rhs);
  3983. lbValue edge = lb_build_expr(p, right);
  3984. incoming_values[done->preds.count] = edge.value;
  3985. incoming_blocks[done->preds.count] = p->curr_block->block;
  3986. lb_emit_jump(p, done);
  3987. lb_start_block(p, done);
  3988. lbValue res = {};
  3989. res.type = type;
  3990. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3991. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3992. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3993. return res;
  3994. }
  3995. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3996. Ast *prev_stmt = p->curr_stmt;
  3997. defer (p->curr_stmt = prev_stmt);
  3998. p->curr_stmt = node;
  3999. if (p->curr_block != nullptr) {
  4000. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  4001. if (lb_is_instr_terminating(last_instr)) {
  4002. return;
  4003. }
  4004. }
  4005. LLVMMetadataRef prev_debug_location = nullptr;
  4006. if (p->debug_info != nullptr) {
  4007. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  4008. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  4009. }
  4010. defer (if (prev_debug_location != nullptr) {
  4011. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  4012. });
  4013. u16 prev_state_flags = p->state_flags;
  4014. defer (p->state_flags = prev_state_flags);
  4015. if (node->state_flags != 0) {
  4016. u16 in = node->state_flags;
  4017. u16 out = p->state_flags;
  4018. if (in & StateFlag_bounds_check) {
  4019. out |= StateFlag_bounds_check;
  4020. out &= ~StateFlag_no_bounds_check;
  4021. } else if (in & StateFlag_no_bounds_check) {
  4022. out |= StateFlag_no_bounds_check;
  4023. out &= ~StateFlag_bounds_check;
  4024. }
  4025. p->state_flags = out;
  4026. }
  4027. switch (node->kind) {
  4028. case_ast_node(bs, EmptyStmt, node);
  4029. case_end;
  4030. case_ast_node(us, UsingStmt, node);
  4031. case_end;
  4032. case_ast_node(ws, WhenStmt, node);
  4033. lb_build_when_stmt(p, ws);
  4034. case_end;
  4035. case_ast_node(bs, BlockStmt, node);
  4036. lbBlock *done = nullptr;
  4037. if (bs->label != nullptr) {
  4038. done = lb_create_block(p, "block.done");
  4039. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  4040. tl->is_block = true;
  4041. }
  4042. lb_open_scope(p, node->scope);
  4043. lb_build_stmt_list(p, bs->stmts);
  4044. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4045. if (done != nullptr) {
  4046. lb_emit_jump(p, done);
  4047. lb_start_block(p, done);
  4048. }
  4049. case_end;
  4050. case_ast_node(vd, ValueDecl, node);
  4051. if (!vd->is_mutable) {
  4052. return;
  4053. }
  4054. bool is_static = false;
  4055. if (vd->names.count > 0) {
  4056. Entity *e = entity_of_node(vd->names[0]);
  4057. if (e->flags & EntityFlag_Static) {
  4058. // NOTE(bill): If one of the entities is static, they all are
  4059. is_static = true;
  4060. }
  4061. }
  4062. if (is_static) {
  4063. for_array(i, vd->names) {
  4064. lbValue value = {};
  4065. if (vd->values.count > 0) {
  4066. GB_ASSERT(vd->names.count == vd->values.count);
  4067. Ast *ast_value = vd->values[i];
  4068. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  4069. ast_value->tav.mode == Addressing_Invalid);
  4070. bool allow_local = false;
  4071. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  4072. }
  4073. Ast *ident = vd->names[i];
  4074. GB_ASSERT(!is_blank_ident(ident));
  4075. Entity *e = entity_of_node(ident);
  4076. GB_ASSERT(e->flags & EntityFlag_Static);
  4077. String name = e->token.string;
  4078. String mangled_name = {};
  4079. {
  4080. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  4081. str = gb_string_appendc(str, "-");
  4082. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  4083. mangled_name.text = cast(u8 *)str;
  4084. mangled_name.len = gb_string_length(str);
  4085. }
  4086. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  4087. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  4088. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  4089. if (value.value != nullptr) {
  4090. LLVMSetInitializer(global, value.value);
  4091. } else {
  4092. }
  4093. if (e->Variable.thread_local_model != "") {
  4094. LLVMSetThreadLocal(global, true);
  4095. String m = e->Variable.thread_local_model;
  4096. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  4097. if (m == "default") {
  4098. mode = LLVMGeneralDynamicTLSModel;
  4099. } else if (m == "localdynamic") {
  4100. mode = LLVMLocalDynamicTLSModel;
  4101. } else if (m == "initialexec") {
  4102. mode = LLVMInitialExecTLSModel;
  4103. } else if (m == "localexec") {
  4104. mode = LLVMLocalExecTLSModel;
  4105. } else {
  4106. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  4107. }
  4108. LLVMSetThreadLocalMode(global, mode);
  4109. } else {
  4110. LLVMSetLinkage(global, LLVMInternalLinkage);
  4111. }
  4112. lbValue global_val = {global, alloc_type_pointer(e->type)};
  4113. lb_add_entity(p->module, e, global_val);
  4114. lb_add_member(p->module, mangled_name, global_val);
  4115. }
  4116. return;
  4117. }
  4118. if (vd->values.count == 0) { // declared and zero-initialized
  4119. for_array(i, vd->names) {
  4120. Ast *name = vd->names[i];
  4121. if (!is_blank_ident(name)) {
  4122. Entity *e = entity_of_node(name);
  4123. lb_add_local(p, e->type, e, true);
  4124. }
  4125. }
  4126. } else { // Tuple(s)
  4127. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  4128. auto inits = array_make<lbValue>(permanent_allocator(), 0, vd->names.count);
  4129. for_array(i, vd->names) {
  4130. Ast *name = vd->names[i];
  4131. lbAddr lval = {};
  4132. if (!is_blank_ident(name)) {
  4133. Entity *e = entity_of_node(name);
  4134. lval = lb_add_local(p, e->type, e, false);
  4135. }
  4136. array_add(&lvals, lval);
  4137. }
  4138. for_array(i, vd->values) {
  4139. lbValue init = lb_build_expr(p, vd->values[i]);
  4140. Type *t = init.type;
  4141. if (t->kind == Type_Tuple) {
  4142. for_array(i, t->Tuple.variables) {
  4143. Entity *e = t->Tuple.variables[i];
  4144. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4145. array_add(&inits, v);
  4146. }
  4147. } else {
  4148. array_add(&inits, init);
  4149. }
  4150. }
  4151. for_array(i, inits) {
  4152. lbAddr lval = lvals[i];
  4153. lbValue init = inits[i];
  4154. lb_addr_store(p, lval, init);
  4155. }
  4156. }
  4157. case_end;
  4158. case_ast_node(as, AssignStmt, node);
  4159. if (as->op.kind == Token_Eq) {
  4160. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  4161. for_array(i, as->lhs) {
  4162. Ast *lhs = as->lhs[i];
  4163. lbAddr lval = {};
  4164. if (!is_blank_ident(lhs)) {
  4165. lval = lb_build_addr(p, lhs);
  4166. }
  4167. array_add(&lvals, lval);
  4168. }
  4169. if (as->lhs.count == as->rhs.count) {
  4170. if (as->lhs.count == 1) {
  4171. lbAddr lval = lvals[0];
  4172. Ast *rhs = as->rhs[0];
  4173. lbValue init = lb_build_expr(p, rhs);
  4174. lb_addr_store(p, lvals[0], init);
  4175. } else {
  4176. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4177. for_array(i, as->rhs) {
  4178. lbValue init = lb_build_expr(p, as->rhs[i]);
  4179. array_add(&inits, init);
  4180. }
  4181. for_array(i, inits) {
  4182. lbAddr lval = lvals[i];
  4183. lbValue init = inits[i];
  4184. lb_addr_store(p, lval, init);
  4185. }
  4186. }
  4187. } else {
  4188. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4189. for_array(i, as->rhs) {
  4190. lbValue init = lb_build_expr(p, as->rhs[i]);
  4191. Type *t = init.type;
  4192. // TODO(bill): refactor for code reuse as this is repeated a bit
  4193. if (t->kind == Type_Tuple) {
  4194. for_array(i, t->Tuple.variables) {
  4195. Entity *e = t->Tuple.variables[i];
  4196. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4197. array_add(&inits, v);
  4198. }
  4199. } else {
  4200. array_add(&inits, init);
  4201. }
  4202. }
  4203. for_array(i, inits) {
  4204. lbAddr lval = lvals[i];
  4205. lbValue init = inits[i];
  4206. lb_addr_store(p, lval, init);
  4207. }
  4208. }
  4209. } else {
  4210. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  4211. // +=, -=, etc
  4212. i32 op = cast(i32)as->op.kind;
  4213. op += Token_Add - Token_AddEq; // Convert += to +
  4214. if (op == Token_CmpAnd || op == Token_CmpOr) {
  4215. Type *type = as->lhs[0]->tav.type;
  4216. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  4217. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4218. lb_addr_store(p, lhs, new_value);
  4219. } else {
  4220. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4221. lbValue value = lb_build_expr(p, as->rhs[0]);
  4222. lbValue old_value = lb_addr_load(p, lhs);
  4223. Type *type = old_value.type;
  4224. lbValue change = lb_emit_conv(p, value, type);
  4225. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  4226. lb_addr_store(p, lhs, new_value);
  4227. }
  4228. return;
  4229. }
  4230. case_end;
  4231. case_ast_node(es, ExprStmt, node);
  4232. lb_build_expr(p, es->expr);
  4233. case_end;
  4234. case_ast_node(ds, DeferStmt, node);
  4235. isize scope_index = p->scope_index;
  4236. lb_add_defer_node(p, scope_index, ds->stmt);
  4237. case_end;
  4238. case_ast_node(rs, ReturnStmt, node);
  4239. lbValue res = {};
  4240. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  4241. isize return_count = p->type->Proc.result_count;
  4242. isize res_count = rs->results.count;
  4243. if (return_count == 0) {
  4244. // No return values
  4245. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4246. LLVMBuildRetVoid(p->builder);
  4247. return;
  4248. } else if (return_count == 1) {
  4249. Entity *e = tuple->variables[0];
  4250. if (res_count == 0) {
  4251. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4252. GB_ASSERT(found);
  4253. res = lb_emit_load(p, *found);
  4254. } else {
  4255. res = lb_build_expr(p, rs->results[0]);
  4256. res = lb_emit_conv(p, res, e->type);
  4257. }
  4258. if (p->type->Proc.has_named_results) {
  4259. // NOTE(bill): store the named values before returning
  4260. if (e->token.string != "") {
  4261. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4262. GB_ASSERT(found != nullptr);
  4263. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  4264. }
  4265. }
  4266. } else {
  4267. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  4268. if (res_count != 0) {
  4269. for (isize res_index = 0; res_index < res_count; res_index++) {
  4270. lbValue res = lb_build_expr(p, rs->results[res_index]);
  4271. Type *t = res.type;
  4272. if (t->kind == Type_Tuple) {
  4273. for_array(i, t->Tuple.variables) {
  4274. Entity *e = t->Tuple.variables[i];
  4275. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  4276. array_add(&results, v);
  4277. }
  4278. } else {
  4279. array_add(&results, res);
  4280. }
  4281. }
  4282. } else {
  4283. for (isize res_index = 0; res_index < return_count; res_index++) {
  4284. Entity *e = tuple->variables[res_index];
  4285. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4286. GB_ASSERT(found);
  4287. lbValue res = lb_emit_load(p, *found);
  4288. array_add(&results, res);
  4289. }
  4290. }
  4291. GB_ASSERT(results.count == return_count);
  4292. if (p->type->Proc.has_named_results) {
  4293. // NOTE(bill): store the named values before returning
  4294. for_array(i, p->type->Proc.results->Tuple.variables) {
  4295. Entity *e = p->type->Proc.results->Tuple.variables[i];
  4296. if (e->kind != Entity_Variable) {
  4297. continue;
  4298. }
  4299. if (e->token.string == "") {
  4300. continue;
  4301. }
  4302. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4303. GB_ASSERT(found != nullptr);
  4304. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  4305. }
  4306. }
  4307. Type *ret_type = p->type->Proc.results;
  4308. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4309. res = lb_add_local_generated(p, ret_type, false).addr;
  4310. for_array(i, results) {
  4311. Entity *e = tuple->variables[i];
  4312. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  4313. lbValue val = lb_emit_conv(p, results[i], e->type);
  4314. lb_emit_store(p, field, val);
  4315. }
  4316. res = lb_emit_load(p, res);
  4317. }
  4318. lb_ensure_abi_function_type(p->module, p);
  4319. if (p->abi_function_type->ret.kind == lbArg_Indirect) {
  4320. if (res.value != nullptr) {
  4321. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  4322. } else {
  4323. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  4324. }
  4325. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4326. LLVMBuildRetVoid(p->builder);
  4327. } else {
  4328. LLVMValueRef ret_val = res.value;
  4329. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  4330. if (p->abi_function_type->ret.cast_type != nullptr) {
  4331. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  4332. }
  4333. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4334. LLVMBuildRet(p->builder, ret_val);
  4335. }
  4336. case_end;
  4337. case_ast_node(is, IfStmt, node);
  4338. lb_open_scope(p, node->scope); // Scope #1
  4339. if (is->init != nullptr) {
  4340. // TODO(bill): Should this have a separate block to begin with?
  4341. #if 1
  4342. lbBlock *init = lb_create_block(p, "if.init");
  4343. lb_emit_jump(p, init);
  4344. lb_start_block(p, init);
  4345. #endif
  4346. lb_build_stmt(p, is->init);
  4347. }
  4348. lbBlock *then = lb_create_block(p, "if.then");
  4349. lbBlock *done = lb_create_block(p, "if.done");
  4350. lbBlock *else_ = done;
  4351. if (is->else_stmt != nullptr) {
  4352. else_ = lb_create_block(p, "if.else");
  4353. }
  4354. lb_build_cond(p, is->cond, then, else_);
  4355. lb_start_block(p, then);
  4356. if (is->label != nullptr) {
  4357. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  4358. tl->is_block = true;
  4359. }
  4360. lb_build_stmt(p, is->body);
  4361. lb_emit_jump(p, done);
  4362. if (is->else_stmt != nullptr) {
  4363. lb_start_block(p, else_);
  4364. lb_open_scope(p, is->else_stmt->scope);
  4365. lb_build_stmt(p, is->else_stmt);
  4366. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4367. lb_emit_jump(p, done);
  4368. }
  4369. lb_start_block(p, done);
  4370. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4371. case_end;
  4372. case_ast_node(fs, ForStmt, node);
  4373. lb_open_scope(p, node->scope); // Open Scope here
  4374. if (fs->init != nullptr) {
  4375. #if 1
  4376. lbBlock *init = lb_create_block(p, "for.init");
  4377. lb_emit_jump(p, init);
  4378. lb_start_block(p, init);
  4379. #endif
  4380. lb_build_stmt(p, fs->init);
  4381. }
  4382. lbBlock *body = lb_create_block(p, "for.body");
  4383. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  4384. lbBlock *loop = body;
  4385. if (fs->cond != nullptr) {
  4386. loop = lb_create_block(p, "for.loop");
  4387. }
  4388. lbBlock *post = loop;
  4389. if (fs->post != nullptr) {
  4390. post = lb_create_block(p, "for.post");
  4391. }
  4392. lb_emit_jump(p, loop);
  4393. lb_start_block(p, loop);
  4394. if (loop != body) {
  4395. lb_build_cond(p, fs->cond, body, done);
  4396. lb_start_block(p, body);
  4397. }
  4398. lb_push_target_list(p, fs->label, done, post, nullptr);
  4399. lb_build_stmt(p, fs->body);
  4400. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4401. lb_pop_target_list(p);
  4402. lb_emit_jump(p, post);
  4403. if (fs->post != nullptr) {
  4404. lb_start_block(p, post);
  4405. lb_build_stmt(p, fs->post);
  4406. lb_emit_jump(p, loop);
  4407. }
  4408. lb_start_block(p, done);
  4409. case_end;
  4410. case_ast_node(rs, RangeStmt, node);
  4411. lb_build_range_stmt(p, rs, node->scope);
  4412. case_end;
  4413. case_ast_node(rs, UnrollRangeStmt, node);
  4414. lb_build_inline_range_stmt(p, rs, node->scope);
  4415. case_end;
  4416. case_ast_node(ss, SwitchStmt, node);
  4417. lb_build_switch_stmt(p, ss, node->scope);
  4418. case_end;
  4419. case_ast_node(ss, TypeSwitchStmt, node);
  4420. lb_build_type_switch_stmt(p, ss);
  4421. case_end;
  4422. case_ast_node(bs, BranchStmt, node);
  4423. lbBlock *block = nullptr;
  4424. if (bs->label != nullptr) {
  4425. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  4426. switch (bs->token.kind) {
  4427. case Token_break: block = bb.break_; break;
  4428. case Token_continue: block = bb.continue_; break;
  4429. case Token_fallthrough:
  4430. GB_PANIC("fallthrough cannot have a label");
  4431. break;
  4432. }
  4433. } else {
  4434. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  4435. if (t->is_block) {
  4436. continue;
  4437. }
  4438. switch (bs->token.kind) {
  4439. case Token_break: block = t->break_; break;
  4440. case Token_continue: block = t->continue_; break;
  4441. case Token_fallthrough: block = t->fallthrough_; break;
  4442. }
  4443. }
  4444. }
  4445. if (block != nullptr) {
  4446. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  4447. }
  4448. lb_emit_jump(p, block);
  4449. case_end;
  4450. }
  4451. }
  4452. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  4453. cond = lb_emit_conv(p, cond, t_llvm_bool);
  4454. lbValue res = {};
  4455. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  4456. res.type = x.type;
  4457. return res;
  4458. }
  4459. lbValue lb_const_nil(lbModule *m, Type *type) {
  4460. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  4461. return lbValue{v, type};
  4462. }
  4463. lbValue lb_const_undef(lbModule *m, Type *type) {
  4464. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  4465. return lbValue{v, type};
  4466. }
  4467. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  4468. lbValue res = {};
  4469. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  4470. res.type = type;
  4471. return res;
  4472. }
  4473. lbValue lb_const_string(lbModule *m, String const &value) {
  4474. return lb_const_value(m, t_string, exact_value_string(value));
  4475. }
  4476. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  4477. lbValue res = {};
  4478. res.value = LLVMConstInt(lb_type(m, type), value, false);
  4479. res.type = type;
  4480. return res;
  4481. }
  4482. LLVMValueRef lb_const_f16(lbModule *m, f32 f, Type *type=t_f16) {
  4483. GB_ASSERT(type_size_of(type) == 2);
  4484. u16 u = f32_to_f16(f);
  4485. if (is_type_different_to_arch_endianness(type)) {
  4486. u = gb_endian_swap16(u);
  4487. }
  4488. LLVMValueRef i = LLVMConstInt(LLVMInt16TypeInContext(m->ctx), u, false);
  4489. return LLVMConstBitCast(i, lb_type(m, type));
  4490. }
  4491. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  4492. GB_ASSERT(type_size_of(type) == 4);
  4493. u32 u = bit_cast<u32>(f);
  4494. if (is_type_different_to_arch_endianness(type)) {
  4495. u = gb_endian_swap32(u);
  4496. }
  4497. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  4498. return LLVMConstBitCast(i, lb_type(m, type));
  4499. }
  4500. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4501. x = lb_emit_conv(p, x, t);
  4502. y = lb_emit_conv(p, y, t);
  4503. if (is_type_float(t)) {
  4504. i64 sz = 8*type_size_of(t);
  4505. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4506. args[0] = x;
  4507. args[1] = y;
  4508. switch (sz) {
  4509. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  4510. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  4511. }
  4512. GB_PANIC("Unknown float type");
  4513. }
  4514. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  4515. }
  4516. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4517. x = lb_emit_conv(p, x, t);
  4518. y = lb_emit_conv(p, y, t);
  4519. if (is_type_float(t)) {
  4520. i64 sz = 8*type_size_of(t);
  4521. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4522. args[0] = x;
  4523. args[1] = y;
  4524. switch (sz) {
  4525. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  4526. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  4527. }
  4528. GB_PANIC("Unknown float type");
  4529. }
  4530. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  4531. }
  4532. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  4533. lbValue z = {};
  4534. z = lb_emit_max(p, t, x, min);
  4535. z = lb_emit_min(p, t, z, max);
  4536. return z;
  4537. }
  4538. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  4539. StringHashKey key = string_hash_string(str);
  4540. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  4541. if (found != nullptr) {
  4542. return *found;
  4543. } else {
  4544. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4545. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4546. cast(char const *)str.text,
  4547. cast(unsigned)str.len,
  4548. false);
  4549. isize max_len = 7+8+1;
  4550. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  4551. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4552. len -= 1;
  4553. m->global_array_index++;
  4554. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4555. LLVMSetInitializer(global_data, data);
  4556. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4557. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4558. string_map_set(&m->const_strings, key, ptr);
  4559. return ptr;
  4560. }
  4561. }
  4562. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  4563. LLVMValueRef ptr = nullptr;
  4564. if (str.len != 0) {
  4565. ptr = lb_find_or_add_entity_string_ptr(m, str);
  4566. } else {
  4567. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4568. }
  4569. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4570. LLVMValueRef values[2] = {ptr, str_len};
  4571. lbValue res = {};
  4572. res.value = llvm_const_named_struct(lb_type(m, t_string), values, 2);
  4573. res.type = t_string;
  4574. return res;
  4575. }
  4576. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  4577. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4578. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4579. cast(char const *)str.text,
  4580. cast(unsigned)str.len,
  4581. false);
  4582. char *name = nullptr;
  4583. {
  4584. isize max_len = 7+8+1;
  4585. name = gb_alloc_array(permanent_allocator(), char, max_len);
  4586. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4587. len -= 1;
  4588. m->global_array_index++;
  4589. }
  4590. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4591. LLVMSetInitializer(global_data, data);
  4592. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4593. LLVMValueRef ptr = nullptr;
  4594. if (str.len != 0) {
  4595. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4596. } else {
  4597. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4598. }
  4599. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4600. LLVMValueRef values[2] = {ptr, len};
  4601. lbValue res = {};
  4602. res.value = llvm_const_named_struct(lb_type(m, t_u8_slice), values, 2);
  4603. res.type = t_u8_slice;
  4604. return res;
  4605. }
  4606. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4607. isize index = type_info_index(info, type, false);
  4608. if (index >= 0) {
  4609. auto *set = &info->minimum_dependency_type_info_set;
  4610. for_array(i, set->entries) {
  4611. if (set->entries[i].ptr == index) {
  4612. return i+1;
  4613. }
  4614. }
  4615. }
  4616. if (err_on_not_found) {
  4617. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  4618. }
  4619. return -1;
  4620. }
  4621. lbValue lb_typeid(lbModule *m, Type *type) {
  4622. type = default_type(type);
  4623. u64 id = cast(u64)lb_type_info_index(m->info, type);
  4624. GB_ASSERT(id >= 0);
  4625. u64 kind = Typeid_Invalid;
  4626. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4627. u64 special = 0;
  4628. u64 reserved = 0;
  4629. Type *bt = base_type(type);
  4630. TypeKind tk = bt->kind;
  4631. switch (tk) {
  4632. case Type_Basic: {
  4633. u32 flags = bt->Basic.flags;
  4634. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4635. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4636. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4637. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4638. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4639. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4640. if (flags & BasicFlag_String) kind = Typeid_String;
  4641. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4642. } break;
  4643. case Type_Pointer: kind = Typeid_Pointer; break;
  4644. case Type_Array: kind = Typeid_Array; break;
  4645. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  4646. case Type_Slice: kind = Typeid_Slice; break;
  4647. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4648. case Type_Map: kind = Typeid_Map; break;
  4649. case Type_Struct: kind = Typeid_Struct; break;
  4650. case Type_Enum: kind = Typeid_Enum; break;
  4651. case Type_Union: kind = Typeid_Union; break;
  4652. case Type_Tuple: kind = Typeid_Tuple; break;
  4653. case Type_Proc: kind = Typeid_Procedure; break;
  4654. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4655. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  4656. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  4657. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  4658. }
  4659. if (is_type_cstring(type)) {
  4660. special = 1;
  4661. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4662. special = 1;
  4663. }
  4664. u64 data = 0;
  4665. if (build_context.word_size == 4) {
  4666. GB_ASSERT(id <= (1u<<24u));
  4667. data |= (id &~ (1u<<24)) << 0u; // index
  4668. data |= (kind &~ (1u<<5)) << 24u; // kind
  4669. data |= (named &~ (1u<<1)) << 29u; // kind
  4670. data |= (special &~ (1u<<1)) << 30u; // kind
  4671. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4672. } else {
  4673. GB_ASSERT(build_context.word_size == 8);
  4674. GB_ASSERT(id <= (1ull<<56u));
  4675. data |= (id &~ (1ull<<56)) << 0ul; // index
  4676. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4677. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4678. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4679. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4680. }
  4681. lbValue res = {};
  4682. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  4683. res.type = t_typeid;
  4684. return res;
  4685. }
  4686. lbValue lb_type_info(lbModule *m, Type *type) {
  4687. type = default_type(type);
  4688. isize index = lb_type_info_index(m->info, type);
  4689. GB_ASSERT(index >= 0);
  4690. LLVMTypeRef it = lb_type(m, t_int);
  4691. LLVMValueRef indices[2] = {
  4692. LLVMConstInt(it, 0, false),
  4693. LLVMConstInt(it, index, true),
  4694. };
  4695. lbValue value = {};
  4696. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  4697. value.type = t_type_info_ptr;
  4698. return value;
  4699. }
  4700. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  4701. bool is_local = allow_local && m->curr_procedure != nullptr;
  4702. bool is_const = true;
  4703. if (is_local) {
  4704. for (isize i = 0; i < count; i++) {
  4705. GB_ASSERT(values[i] != nullptr);
  4706. if (!LLVMIsConstant(values[i])) {
  4707. is_const = false;
  4708. break;
  4709. }
  4710. }
  4711. }
  4712. if (!is_const) {
  4713. lbProcedure *p = m->curr_procedure;
  4714. GB_ASSERT(p != nullptr);
  4715. lbAddr v = lb_add_local_generated(p, type, false);
  4716. lbValue ptr = lb_addr_get_ptr(p, v);
  4717. for (isize i = 0; i < count; i++) {
  4718. lbValue elem = lb_emit_array_epi(p, ptr, i);
  4719. LLVMBuildStore(p->builder, values[i], elem.value);
  4720. }
  4721. return lb_addr_load(p, v).value;
  4722. }
  4723. return llvm_const_array(lb_type(m, elem_type), values, cast(unsigned int)count);
  4724. }
  4725. lbValue lb_find_procedure_value_from_entity(lbModule *m, Entity *e) {
  4726. e = strip_entity_wrapping(e);
  4727. GB_ASSERT(e != nullptr);
  4728. auto *found = map_get(&m->values, hash_entity(e));
  4729. if (found) {
  4730. return *found;
  4731. }
  4732. // TODO(bill): this is
  4733. lbProcedure *missing_proc = lb_create_procedure(m, e);
  4734. found = map_get(&m->values, hash_entity(e));
  4735. if (found) {
  4736. return *found;
  4737. }
  4738. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  4739. return {};
  4740. }
  4741. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  4742. LLVMContextRef ctx = m->ctx;
  4743. type = default_type(type);
  4744. Type *original_type = type;
  4745. lbValue res = {};
  4746. res.type = original_type;
  4747. type = core_type(type);
  4748. value = convert_exact_value_for_type(value, type);
  4749. if (value.kind == ExactValue_Typeid) {
  4750. return lb_typeid(m, value.value_typeid);
  4751. }
  4752. if (value.kind == ExactValue_Invalid) {
  4753. return lb_const_nil(m, type);
  4754. }
  4755. if (value.kind == ExactValue_Procedure) {
  4756. Ast *expr = unparen_expr(value.value_procedure);
  4757. if (expr->kind == Ast_ProcLit) {
  4758. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4759. }
  4760. Entity *e = entity_from_expr(expr);
  4761. return lb_find_procedure_value_from_entity(m, e);
  4762. }
  4763. bool is_local = allow_local && m->curr_procedure != nullptr;
  4764. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  4765. if (is_type_slice(type)) {
  4766. if (value.kind == ExactValue_String) {
  4767. GB_ASSERT(is_type_u8_slice(type));
  4768. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  4769. return res;
  4770. } else {
  4771. ast_node(cl, CompoundLit, value.value_compound);
  4772. isize count = cl->elems.count;
  4773. if (count == 0) {
  4774. return lb_const_nil(m, type);
  4775. }
  4776. count = gb_max(cl->max_count, count);
  4777. Type *elem = base_type(type)->Slice.elem;
  4778. Type *t = alloc_type_array(elem, count);
  4779. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4780. LLVMValueRef array_data = nullptr;
  4781. if (is_local) {
  4782. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4783. // its backing data on the stack
  4784. lbProcedure *p = m->curr_procedure;
  4785. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4786. LLVMTypeRef llvm_type = lb_type(m, t);
  4787. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4788. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4789. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4790. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4791. {
  4792. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4793. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4794. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4795. lbAddr slice = lb_add_local_generated(p, type, false);
  4796. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4797. return lb_addr_load(p, slice);
  4798. }
  4799. } else {
  4800. isize max_len = 7+8+1;
  4801. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  4802. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4803. m->global_array_index++;
  4804. String name = make_string(cast(u8 *)str, len-1);
  4805. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4806. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4807. LLVMSetInitializer(array_data, backing_array.value);
  4808. lbValue g = {};
  4809. g.value = array_data;
  4810. g.type = t;
  4811. lb_add_entity(m, e, g);
  4812. lb_add_member(m, name, g);
  4813. {
  4814. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4815. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4816. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4817. LLVMValueRef values[2] = {ptr, len};
  4818. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4819. return res;
  4820. }
  4821. }
  4822. }
  4823. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4824. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  4825. i64 count = type->Array.count;
  4826. Type *elem = type->Array.elem;
  4827. LLVMTypeRef et = lb_type(m, elem);
  4828. Rune rune;
  4829. isize offset = 0;
  4830. isize width = 1;
  4831. String s = value.value_string;
  4832. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4833. for (i64 i = 0; i < count && offset < s.len; i++) {
  4834. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  4835. offset += width;
  4836. elems[i] = LLVMConstInt(et, rune, true);
  4837. }
  4838. GB_ASSERT(offset == s.len);
  4839. res.value = llvm_const_array(et, elems, cast(unsigned)count);
  4840. return res;
  4841. }
  4842. GB_PANIC("HERE!\n");
  4843. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4844. cast(char const *)value.value_string.text,
  4845. cast(unsigned)value.value_string.len,
  4846. false /*DontNullTerminate*/);
  4847. res.value = data;
  4848. return res;
  4849. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  4850. GB_ASSERT(type->Array.count == value.value_string.len);
  4851. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4852. cast(char const *)value.value_string.text,
  4853. cast(unsigned)value.value_string.len,
  4854. true /*DontNullTerminate*/);
  4855. res.value = data;
  4856. return res;
  4857. } else if (is_type_array(type) &&
  4858. value.kind != ExactValue_Invalid &&
  4859. value.kind != ExactValue_String &&
  4860. value.kind != ExactValue_Compound) {
  4861. i64 count = type->Array.count;
  4862. Type *elem = type->Array.elem;
  4863. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4864. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4865. for (i64 i = 0; i < count; i++) {
  4866. elems[i] = single_elem.value;
  4867. }
  4868. res.value = llvm_const_array(lb_type(m, elem), elems, cast(unsigned)count);
  4869. return res;
  4870. }
  4871. switch (value.kind) {
  4872. case ExactValue_Invalid:
  4873. res.value = LLVMConstNull(lb_type(m, original_type));
  4874. return res;
  4875. case ExactValue_Bool:
  4876. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4877. return res;
  4878. case ExactValue_String:
  4879. {
  4880. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4881. lbValue res = {};
  4882. res.type = default_type(original_type);
  4883. if (is_type_cstring(res.type)) {
  4884. res.value = ptr;
  4885. } else {
  4886. if (value.value_string.len == 0) {
  4887. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4888. }
  4889. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4890. LLVMValueRef values[2] = {ptr, str_len};
  4891. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4892. }
  4893. return res;
  4894. }
  4895. case ExactValue_Integer:
  4896. if (is_type_pointer(type)) {
  4897. unsigned len = cast(unsigned)value.value_integer.len;
  4898. LLVMTypeRef t = lb_type(m, original_type);
  4899. if (len == 0) {
  4900. res.value = LLVMConstNull(t);
  4901. } else {
  4902. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), len, big_int_ptr(&value.value_integer));
  4903. res.value = LLVMConstIntToPtr(i, t);
  4904. }
  4905. } else {
  4906. unsigned len = cast(unsigned)value.value_integer.len;
  4907. if (len == 0) {
  4908. res.value = LLVMConstNull(lb_type(m, original_type));
  4909. } else {
  4910. u64 *words = big_int_ptr(&value.value_integer);
  4911. if (is_type_different_to_arch_endianness(type)) {
  4912. // NOTE(bill): Swap byte order for different endianness
  4913. i64 sz = type_size_of(type);
  4914. isize byte_len = gb_size_of(u64)*len;
  4915. u8 *old_bytes = cast(u8 *)words;
  4916. // TODO(bill): Use a different allocator here for a temporary allocation
  4917. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  4918. for (i64 i = 0; i < sz; i++) {
  4919. new_bytes[i] = old_bytes[sz-1-i];
  4920. }
  4921. words = cast(u64 *)new_bytes;
  4922. }
  4923. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4924. if (value.value_integer.neg) {
  4925. res.value = LLVMConstNeg(res.value);
  4926. }
  4927. }
  4928. }
  4929. return res;
  4930. case ExactValue_Float:
  4931. if (is_type_different_to_arch_endianness(type)) {
  4932. u64 u = bit_cast<u64>(value.value_float);
  4933. u = gb_endian_swap64(u);
  4934. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4935. } else {
  4936. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4937. }
  4938. return res;
  4939. case ExactValue_Complex:
  4940. {
  4941. LLVMValueRef values[2] = {};
  4942. switch (8*type_size_of(type)) {
  4943. case 32:
  4944. values[0] = lb_const_f16(m, cast(f32)value.value_complex->real);
  4945. values[1] = lb_const_f16(m, cast(f32)value.value_complex->imag);
  4946. break;
  4947. case 64:
  4948. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  4949. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  4950. break;
  4951. case 128:
  4952. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  4953. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  4954. break;
  4955. }
  4956. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4957. return res;
  4958. }
  4959. break;
  4960. case ExactValue_Quaternion:
  4961. {
  4962. LLVMValueRef values[4] = {};
  4963. switch (8*type_size_of(type)) {
  4964. case 64:
  4965. // @QuaternionLayout
  4966. values[3] = lb_const_f16(m, cast(f32)value.value_quaternion->real);
  4967. values[0] = lb_const_f16(m, cast(f32)value.value_quaternion->imag);
  4968. values[1] = lb_const_f16(m, cast(f32)value.value_quaternion->jmag);
  4969. values[2] = lb_const_f16(m, cast(f32)value.value_quaternion->kmag);
  4970. break;
  4971. case 128:
  4972. // @QuaternionLayout
  4973. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  4974. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  4975. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  4976. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  4977. break;
  4978. case 256:
  4979. // @QuaternionLayout
  4980. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  4981. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  4982. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  4983. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  4984. break;
  4985. }
  4986. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 4);
  4987. return res;
  4988. }
  4989. break;
  4990. case ExactValue_Pointer:
  4991. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4992. return res;
  4993. case ExactValue_Compound:
  4994. if (is_type_slice(type)) {
  4995. return lb_const_value(m, type, value, allow_local);
  4996. } else if (is_type_array(type)) {
  4997. ast_node(cl, CompoundLit, value.value_compound);
  4998. Type *elem_type = type->Array.elem;
  4999. isize elem_count = cl->elems.count;
  5000. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5001. return lb_const_nil(m, original_type);
  5002. }
  5003. if (cl->elems[0]->kind == Ast_FieldValue) {
  5004. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5005. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  5006. isize value_index = 0;
  5007. for (i64 i = 0; i < type->Array.count; i++) {
  5008. bool found = false;
  5009. for (isize j = 0; j < elem_count; j++) {
  5010. Ast *elem = cl->elems[j];
  5011. ast_node(fv, FieldValue, elem);
  5012. if (is_ast_range(fv->field)) {
  5013. ast_node(ie, BinaryExpr, fv->field);
  5014. TypeAndValue lo_tav = ie->left->tav;
  5015. TypeAndValue hi_tav = ie->right->tav;
  5016. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5017. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5018. TokenKind op = ie->op.kind;
  5019. i64 lo = exact_value_to_i64(lo_tav.value);
  5020. i64 hi = exact_value_to_i64(hi_tav.value);
  5021. if (op == Token_Ellipsis) {
  5022. hi += 1;
  5023. }
  5024. if (lo == i) {
  5025. TypeAndValue tav = fv->value->tav;
  5026. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5027. for (i64 k = lo; k < hi; k++) {
  5028. values[value_index++] = val;
  5029. }
  5030. found = true;
  5031. i += (hi-lo-1);
  5032. break;
  5033. }
  5034. } else {
  5035. TypeAndValue index_tav = fv->field->tav;
  5036. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5037. i64 index = exact_value_to_i64(index_tav.value);
  5038. if (index == i) {
  5039. TypeAndValue tav = fv->value->tav;
  5040. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5041. values[value_index++] = val;
  5042. found = true;
  5043. break;
  5044. }
  5045. }
  5046. }
  5047. if (!found) {
  5048. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5049. }
  5050. }
  5051. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  5052. return res;
  5053. } else {
  5054. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  5055. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  5056. for (isize i = 0; i < elem_count; i++) {
  5057. TypeAndValue tav = cl->elems[i]->tav;
  5058. GB_ASSERT(tav.mode != Addressing_Invalid);
  5059. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5060. }
  5061. for (isize i = elem_count; i < type->Array.count; i++) {
  5062. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5063. }
  5064. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  5065. return res;
  5066. }
  5067. } else if (is_type_enumerated_array(type)) {
  5068. ast_node(cl, CompoundLit, value.value_compound);
  5069. Type *elem_type = type->EnumeratedArray.elem;
  5070. isize elem_count = cl->elems.count;
  5071. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5072. return lb_const_nil(m, original_type);
  5073. }
  5074. if (cl->elems[0]->kind == Ast_FieldValue) {
  5075. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5076. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  5077. isize value_index = 0;
  5078. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  5079. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  5080. for (i64 i = total_lo; i <= total_hi; i++) {
  5081. bool found = false;
  5082. for (isize j = 0; j < elem_count; j++) {
  5083. Ast *elem = cl->elems[j];
  5084. ast_node(fv, FieldValue, elem);
  5085. if (is_ast_range(fv->field)) {
  5086. ast_node(ie, BinaryExpr, fv->field);
  5087. TypeAndValue lo_tav = ie->left->tav;
  5088. TypeAndValue hi_tav = ie->right->tav;
  5089. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5090. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5091. TokenKind op = ie->op.kind;
  5092. i64 lo = exact_value_to_i64(lo_tav.value);
  5093. i64 hi = exact_value_to_i64(hi_tav.value);
  5094. if (op == Token_Ellipsis) {
  5095. hi += 1;
  5096. }
  5097. if (lo == i) {
  5098. TypeAndValue tav = fv->value->tav;
  5099. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5100. for (i64 k = lo; k < hi; k++) {
  5101. values[value_index++] = val;
  5102. }
  5103. found = true;
  5104. i += (hi-lo-1);
  5105. break;
  5106. }
  5107. } else {
  5108. TypeAndValue index_tav = fv->field->tav;
  5109. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5110. i64 index = exact_value_to_i64(index_tav.value);
  5111. if (index == i) {
  5112. TypeAndValue tav = fv->value->tav;
  5113. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5114. values[value_index++] = val;
  5115. found = true;
  5116. break;
  5117. }
  5118. }
  5119. }
  5120. if (!found) {
  5121. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5122. }
  5123. }
  5124. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  5125. return res;
  5126. } else {
  5127. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  5128. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  5129. for (isize i = 0; i < elem_count; i++) {
  5130. TypeAndValue tav = cl->elems[i]->tav;
  5131. GB_ASSERT(tav.mode != Addressing_Invalid);
  5132. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5133. }
  5134. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  5135. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5136. }
  5137. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  5138. return res;
  5139. }
  5140. } else if (is_type_simd_vector(type)) {
  5141. ast_node(cl, CompoundLit, value.value_compound);
  5142. Type *elem_type = type->SimdVector.elem;
  5143. isize elem_count = cl->elems.count;
  5144. if (elem_count == 0) {
  5145. return lb_const_nil(m, original_type);
  5146. }
  5147. GB_ASSERT(elem_type_can_be_constant(elem_type));
  5148. isize total_elem_count = type->SimdVector.count;
  5149. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  5150. for (isize i = 0; i < elem_count; i++) {
  5151. TypeAndValue tav = cl->elems[i]->tav;
  5152. GB_ASSERT(tav.mode != Addressing_Invalid);
  5153. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5154. }
  5155. LLVMTypeRef et = lb_type(m, elem_type);
  5156. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  5157. values[i] = LLVMConstNull(et);
  5158. }
  5159. for (isize i = 0; i< total_elem_count; i++) {
  5160. values[i] = llvm_const_cast(values[i], et);
  5161. }
  5162. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  5163. return res;
  5164. } else if (is_type_struct(type)) {
  5165. ast_node(cl, CompoundLit, value.value_compound);
  5166. if (cl->elems.count == 0) {
  5167. return lb_const_nil(m, original_type);
  5168. }
  5169. isize offset = 0;
  5170. if (type->Struct.custom_align > 0) {
  5171. offset = 1;
  5172. }
  5173. isize value_count = type->Struct.fields.count + offset;
  5174. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5175. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  5176. if (cl->elems.count > 0) {
  5177. if (cl->elems[0]->kind == Ast_FieldValue) {
  5178. isize elem_count = cl->elems.count;
  5179. for (isize i = 0; i < elem_count; i++) {
  5180. ast_node(fv, FieldValue, cl->elems[i]);
  5181. String name = fv->field->Ident.token.string;
  5182. TypeAndValue tav = fv->value->tav;
  5183. GB_ASSERT(tav.mode != Addressing_Invalid);
  5184. Selection sel = lookup_field(type, name, false);
  5185. Entity *f = type->Struct.fields[sel.index[0]];
  5186. if (elem_type_can_be_constant(f->type)) {
  5187. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  5188. visited[offset+f->Variable.field_index] = true;
  5189. }
  5190. }
  5191. } else {
  5192. for_array(i, cl->elems) {
  5193. Entity *f = type->Struct.fields[i];
  5194. TypeAndValue tav = cl->elems[i]->tav;
  5195. ExactValue val = {};
  5196. if (tav.mode != Addressing_Invalid) {
  5197. val = tav.value;
  5198. }
  5199. if (elem_type_can_be_constant(f->type)) {
  5200. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  5201. visited[offset+f->Variable.field_index] = true;
  5202. }
  5203. }
  5204. }
  5205. }
  5206. for (isize i = 0; i < type->Struct.fields.count; i++) {
  5207. if (!visited[offset+i]) {
  5208. GB_ASSERT(values[offset+i] == nullptr);
  5209. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  5210. }
  5211. }
  5212. if (type->Struct.custom_align > 0) {
  5213. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  5214. }
  5215. bool is_constant = true;
  5216. for (isize i = 0; i < value_count; i++) {
  5217. LLVMValueRef val = values[i];
  5218. if (!LLVMIsConstant(val)) {
  5219. GB_ASSERT(is_local);
  5220. GB_ASSERT(LLVMGetInstructionOpcode(val) == LLVMLoad);
  5221. is_constant = false;
  5222. }
  5223. }
  5224. if (is_constant) {
  5225. res.value = llvm_const_named_struct(lb_type(m, original_type), values, cast(unsigned)value_count);
  5226. return res;
  5227. } else {
  5228. // TODO(bill): THIS IS HACK BUT IT WORKS FOR WHAT I NEED
  5229. LLVMValueRef *old_values = values;
  5230. LLVMValueRef *new_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5231. for (isize i = 0; i < value_count; i++) {
  5232. LLVMValueRef old_value = old_values[i];
  5233. if (LLVMIsConstant(old_value)) {
  5234. new_values[i] = old_value;
  5235. } else {
  5236. new_values[i] = LLVMConstNull(LLVMTypeOf(old_value));
  5237. }
  5238. }
  5239. LLVMValueRef constant_value = llvm_const_named_struct(lb_type(m, original_type), new_values, cast(unsigned)value_count);
  5240. GB_ASSERT(is_local);
  5241. lbProcedure *p = m->curr_procedure;
  5242. lbAddr v = lb_add_local_generated(p, res.type, true);
  5243. LLVMBuildStore(p->builder, constant_value, v.addr.value);
  5244. for (isize i = 0; i < value_count; i++) {
  5245. LLVMValueRef val = old_values[i];
  5246. if (!LLVMIsConstant(val)) {
  5247. LLVMValueRef dst = LLVMBuildStructGEP(p->builder, v.addr.value, cast(unsigned)i, "");
  5248. LLVMBuildStore(p->builder, val, dst);
  5249. }
  5250. }
  5251. return lb_addr_load(p, v);
  5252. }
  5253. } else if (is_type_bit_set(type)) {
  5254. ast_node(cl, CompoundLit, value.value_compound);
  5255. if (cl->elems.count == 0) {
  5256. return lb_const_nil(m, original_type);
  5257. }
  5258. i64 sz = type_size_of(type);
  5259. if (sz == 0) {
  5260. return lb_const_nil(m, original_type);
  5261. }
  5262. u64 bits = 0;
  5263. for_array(i, cl->elems) {
  5264. Ast *e = cl->elems[i];
  5265. GB_ASSERT(e->kind != Ast_FieldValue);
  5266. TypeAndValue tav = e->tav;
  5267. if (tav.mode != Addressing_Constant) {
  5268. continue;
  5269. }
  5270. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  5271. i64 v = big_int_to_i64(&tav.value.value_integer);
  5272. i64 lower = type->BitSet.lower;
  5273. bits |= 1ull<<cast(u64)(v-lower);
  5274. }
  5275. if (is_type_different_to_arch_endianness(type)) {
  5276. i64 size = type_size_of(type);
  5277. switch (size) {
  5278. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  5279. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  5280. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  5281. }
  5282. }
  5283. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  5284. return res;
  5285. } else {
  5286. return lb_const_nil(m, original_type);
  5287. }
  5288. break;
  5289. case ExactValue_Procedure:
  5290. {
  5291. Ast *expr = value.value_procedure;
  5292. GB_ASSERT(expr != nullptr);
  5293. if (expr->kind == Ast_ProcLit) {
  5294. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5295. }
  5296. }
  5297. break;
  5298. case ExactValue_Typeid:
  5299. return lb_typeid(m, value.value_typeid);
  5300. }
  5301. return lb_const_nil(m, original_type);
  5302. }
  5303. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  5304. lbModule *m = p->module;
  5305. LLVMValueRef fields[4] = {};
  5306. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)).value;
  5307. fields[1]/*line*/ = lb_const_int(m, t_i32, pos.line).value;
  5308. fields[2]/*column*/ = lb_const_int(m, t_i32, pos.column).value;
  5309. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  5310. lbValue res = {};
  5311. res.value = llvm_const_named_struct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  5312. res.type = t_source_code_location;
  5313. return res;
  5314. }
  5315. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  5316. String proc_name = {};
  5317. if (p->entity) {
  5318. proc_name = p->entity->token.string;
  5319. }
  5320. TokenPos pos = {};
  5321. if (node) {
  5322. pos = ast_token(node).pos;
  5323. }
  5324. return lb_emit_source_code_location(p, proc_name, pos);
  5325. }
  5326. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  5327. switch (op) {
  5328. case Token_Add:
  5329. return x;
  5330. case Token_Not: // Boolean not
  5331. case Token_Xor: // Bitwise not
  5332. case Token_Sub: // Number negation
  5333. break;
  5334. case Token_Pointer:
  5335. GB_PANIC("This should be handled elsewhere");
  5336. break;
  5337. }
  5338. if (is_type_array(x.type)) {
  5339. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  5340. Type *tl = base_type(x.type);
  5341. lbValue val = lb_address_from_load_or_generate_local(p, x);
  5342. GB_ASSERT(is_type_array(type));
  5343. Type *elem_type = base_array_type(type);
  5344. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5345. lbAddr res_addr = lb_add_local_generated(p, type, false);
  5346. lbValue res = lb_addr_get_ptr(p, res_addr);
  5347. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5348. i32 count = cast(i32)tl->Array.count;
  5349. if (inline_array_arith) {
  5350. // inline
  5351. for (i32 i = 0; i < count; i++) {
  5352. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  5353. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5354. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  5355. }
  5356. } else {
  5357. auto loop_data = lb_loop_start(p, count, t_i32);
  5358. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  5359. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5360. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  5361. lb_loop_end(p, loop_data);
  5362. }
  5363. return lb_emit_load(p, res);
  5364. }
  5365. if (op == Token_Xor) {
  5366. lbValue cmp = {};
  5367. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  5368. cmp.type = x.type;
  5369. return lb_emit_conv(p, cmp, type);
  5370. }
  5371. if (op == Token_Not) {
  5372. lbValue cmp = {};
  5373. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  5374. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  5375. cmp.type = t_llvm_bool;
  5376. return lb_emit_conv(p, cmp, type);
  5377. }
  5378. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5379. Type *platform_type = integer_endian_type_to_platform_type(type);
  5380. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5381. lbValue res = {};
  5382. res.value = LLVMBuildNeg(p->builder, v.value, "");
  5383. res.type = platform_type;
  5384. return lb_emit_byte_swap(p, res, type);
  5385. }
  5386. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5387. Type *platform_type = integer_endian_type_to_platform_type(type);
  5388. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5389. lbValue res = {};
  5390. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  5391. res.type = platform_type;
  5392. return lb_emit_byte_swap(p, res, type);
  5393. }
  5394. lbValue res = {};
  5395. switch (op) {
  5396. case Token_Not: // Boolean not
  5397. case Token_Xor: // Bitwise not
  5398. res.value = LLVMBuildNot(p->builder, x.value, "");
  5399. res.type = x.type;
  5400. return res;
  5401. case Token_Sub: // Number negation
  5402. if (is_type_integer(x.type)) {
  5403. res.value = LLVMBuildNeg(p->builder, x.value, "");
  5404. } else if (is_type_float(x.type)) {
  5405. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  5406. } else if (is_type_complex(x.type)) {
  5407. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5408. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5409. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5410. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5411. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5412. return lb_addr_load(p, addr);
  5413. } else if (is_type_quaternion(x.type)) {
  5414. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5415. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5416. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  5417. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  5418. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5419. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5420. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5421. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  5422. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  5423. return lb_addr_load(p, addr);
  5424. } else {
  5425. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  5426. }
  5427. res.type = x.type;
  5428. return res;
  5429. }
  5430. return res;
  5431. }
  5432. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  5433. lbModule *m = p->module;
  5434. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  5435. lhs = lb_emit_conv(p, lhs, type);
  5436. rhs = lb_emit_conv(p, rhs, type);
  5437. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  5438. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  5439. GB_ASSERT(is_type_array(type));
  5440. Type *elem_type = base_array_type(type);
  5441. lbAddr res = lb_add_local_generated(p, type, false);
  5442. i64 count = base_type(type)->Array.count;
  5443. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5444. if (inline_array_arith) {
  5445. for (i64 i = 0; i < count; i++) {
  5446. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  5447. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  5448. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  5449. lbValue a = lb_emit_load(p, a_ptr);
  5450. lbValue b = lb_emit_load(p, b_ptr);
  5451. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5452. lb_emit_store(p, dst_ptr, c);
  5453. }
  5454. } else {
  5455. auto loop_data = lb_loop_start(p, count, t_i32);
  5456. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  5457. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  5458. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  5459. lbValue a = lb_emit_load(p, a_ptr);
  5460. lbValue b = lb_emit_load(p, b_ptr);
  5461. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5462. lb_emit_store(p, dst_ptr, c);
  5463. lb_loop_end(p, loop_data);
  5464. }
  5465. return lb_addr_load(p, res);
  5466. } else if (is_type_complex(type)) {
  5467. lhs = lb_emit_conv(p, lhs, type);
  5468. rhs = lb_emit_conv(p, rhs, type);
  5469. Type *ft = base_complex_elem_type(type);
  5470. if (op == Token_Quo) {
  5471. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5472. args[0] = lhs;
  5473. args[1] = rhs;
  5474. switch (type_size_of(ft)) {
  5475. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  5476. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  5477. default: GB_PANIC("Unknown float type"); break;
  5478. }
  5479. }
  5480. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5481. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  5482. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  5483. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  5484. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  5485. lbValue real = {};
  5486. lbValue imag = {};
  5487. switch (op) {
  5488. case Token_Add:
  5489. real = lb_emit_arith(p, Token_Add, a, c, ft);
  5490. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  5491. break;
  5492. case Token_Sub:
  5493. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  5494. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  5495. break;
  5496. case Token_Mul: {
  5497. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  5498. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  5499. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  5500. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  5501. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  5502. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  5503. break;
  5504. }
  5505. }
  5506. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  5507. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  5508. return lb_addr_load(p, res);
  5509. } else if (is_type_quaternion(type)) {
  5510. lhs = lb_emit_conv(p, lhs, type);
  5511. rhs = lb_emit_conv(p, rhs, type);
  5512. Type *ft = base_complex_elem_type(type);
  5513. if (op == Token_Add || op == Token_Sub) {
  5514. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5515. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  5516. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  5517. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  5518. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  5519. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  5520. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  5521. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  5522. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  5523. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  5524. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  5525. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  5526. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  5527. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  5528. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  5529. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  5530. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  5531. return lb_addr_load(p, res);
  5532. } else if (op == Token_Mul) {
  5533. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5534. args[0] = lhs;
  5535. args[1] = rhs;
  5536. switch (8*type_size_of(ft)) {
  5537. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  5538. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  5539. default: GB_PANIC("Unknown float type"); break;
  5540. }
  5541. } else if (op == Token_Quo) {
  5542. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5543. args[0] = lhs;
  5544. args[1] = rhs;
  5545. switch (8*type_size_of(ft)) {
  5546. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  5547. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  5548. default: GB_PANIC("Unknown float type"); break;
  5549. }
  5550. }
  5551. }
  5552. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5553. switch (op) {
  5554. case Token_AndNot:
  5555. case Token_And:
  5556. case Token_Or:
  5557. case Token_Xor:
  5558. goto handle_op;
  5559. }
  5560. Type *platform_type = integer_endian_type_to_platform_type(type);
  5561. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5562. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5563. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5564. return lb_emit_byte_swap(p, res, type);
  5565. }
  5566. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5567. Type *platform_type = integer_endian_type_to_platform_type(type);
  5568. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5569. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5570. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5571. return lb_emit_byte_swap(p, res, type);
  5572. }
  5573. handle_op:
  5574. lhs = lb_emit_conv(p, lhs, type);
  5575. rhs = lb_emit_conv(p, rhs, type);
  5576. lbValue res = {};
  5577. res.type = type;
  5578. // NOTE(bill): Bit Set Aliases for + and -
  5579. if (is_type_bit_set(type)) {
  5580. switch (op) {
  5581. case Token_Add: op = Token_Or; break;
  5582. case Token_Sub: op = Token_AndNot; break;
  5583. }
  5584. }
  5585. switch (op) {
  5586. case Token_Add:
  5587. if (is_type_float(type)) {
  5588. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  5589. return res;
  5590. }
  5591. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  5592. return res;
  5593. case Token_Sub:
  5594. if (is_type_float(type)) {
  5595. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  5596. return res;
  5597. }
  5598. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  5599. return res;
  5600. case Token_Mul:
  5601. if (is_type_float(type)) {
  5602. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  5603. return res;
  5604. }
  5605. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  5606. return res;
  5607. case Token_Quo:
  5608. if (is_type_float(type)) {
  5609. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  5610. return res;
  5611. } else if (is_type_unsigned(type)) {
  5612. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  5613. return res;
  5614. }
  5615. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  5616. return res;
  5617. case Token_Mod:
  5618. if (is_type_float(type)) {
  5619. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  5620. return res;
  5621. } else if (is_type_unsigned(type)) {
  5622. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5623. return res;
  5624. }
  5625. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5626. return res;
  5627. case Token_ModMod:
  5628. if (is_type_unsigned(type)) {
  5629. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5630. return res;
  5631. } else {
  5632. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5633. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  5634. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  5635. res.value = c;
  5636. return res;
  5637. }
  5638. case Token_And:
  5639. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  5640. return res;
  5641. case Token_Or:
  5642. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  5643. return res;
  5644. case Token_Xor:
  5645. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  5646. return res;
  5647. case Token_Shl:
  5648. {
  5649. rhs = lb_emit_conv(p, rhs, lhs.type);
  5650. LLVMValueRef lhsval = lhs.value;
  5651. LLVMValueRef bits = rhs.value;
  5652. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5653. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  5654. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  5655. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5656. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  5657. return res;
  5658. }
  5659. case Token_Shr:
  5660. {
  5661. rhs = lb_emit_conv(p, rhs, lhs.type);
  5662. LLVMValueRef lhsval = lhs.value;
  5663. LLVMValueRef bits = rhs.value;
  5664. bool is_unsigned = is_type_unsigned(type);
  5665. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5666. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  5667. if (is_unsigned) {
  5668. res.value = LLVMBuildLShr(p->builder, lhsval, bits, "");
  5669. } else {
  5670. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  5671. }
  5672. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5673. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  5674. return res;
  5675. }
  5676. case Token_AndNot:
  5677. {
  5678. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  5679. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  5680. return res;
  5681. }
  5682. break;
  5683. }
  5684. GB_PANIC("unhandled operator of lb_emit_arith");
  5685. return {};
  5686. }
  5687. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  5688. ast_node(be, BinaryExpr, expr);
  5689. TypeAndValue tv = type_and_value_of_expr(expr);
  5690. switch (be->op.kind) {
  5691. case Token_Add:
  5692. case Token_Sub:
  5693. case Token_Mul:
  5694. case Token_Quo:
  5695. case Token_Mod:
  5696. case Token_ModMod:
  5697. case Token_And:
  5698. case Token_Or:
  5699. case Token_Xor:
  5700. case Token_AndNot:
  5701. case Token_Shl:
  5702. case Token_Shr: {
  5703. Type *type = default_type(tv.type);
  5704. lbValue left = lb_build_expr(p, be->left);
  5705. lbValue right = lb_build_expr(p, be->right);
  5706. return lb_emit_arith(p, be->op.kind, left, right, type);
  5707. }
  5708. case Token_CmpEq:
  5709. case Token_NotEq:
  5710. case Token_Lt:
  5711. case Token_LtEq:
  5712. case Token_Gt:
  5713. case Token_GtEq:
  5714. {
  5715. lbValue left = {};
  5716. lbValue right = {};
  5717. if (be->left->tav.mode == Addressing_Type) {
  5718. left = lb_typeid(p->module, be->left->tav.type);
  5719. }
  5720. if (be->right->tav.mode == Addressing_Type) {
  5721. right = lb_typeid(p->module, be->right->tav.type);
  5722. }
  5723. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  5724. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  5725. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  5726. Type *type = default_type(tv.type);
  5727. return lb_emit_conv(p, cmp, type);
  5728. }
  5729. case Token_CmpAnd:
  5730. case Token_CmpOr:
  5731. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  5732. case Token_in:
  5733. case Token_not_in:
  5734. {
  5735. lbValue left = lb_build_expr(p, be->left);
  5736. Type *type = default_type(tv.type);
  5737. lbValue right = lb_build_expr(p, be->right);
  5738. Type *rt = base_type(right.type);
  5739. switch (rt->kind) {
  5740. case Type_Map:
  5741. {
  5742. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  5743. lbValue h = lb_gen_map_header(p, addr, rt);
  5744. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  5745. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5746. args[0] = h;
  5747. args[1] = key;
  5748. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  5749. if (be->op.kind == Token_in) {
  5750. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  5751. } else {
  5752. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  5753. }
  5754. }
  5755. break;
  5756. case Type_BitSet:
  5757. {
  5758. Type *key_type = rt->BitSet.elem;
  5759. GB_ASSERT(are_types_identical(left.type, key_type));
  5760. Type *it = bit_set_to_int(rt);
  5761. left = lb_emit_conv(p, left, it);
  5762. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  5763. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  5764. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  5765. bit = lb_emit_conv(p, bit, it);
  5766. lbValue old_value = lb_emit_transmute(p, right, it);
  5767. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  5768. if (be->op.kind == Token_in) {
  5769. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5770. } else {
  5771. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5772. }
  5773. }
  5774. break;
  5775. default:
  5776. GB_PANIC("Invalid 'in' type");
  5777. }
  5778. break;
  5779. }
  5780. break;
  5781. default:
  5782. GB_PANIC("Invalid binary expression");
  5783. break;
  5784. }
  5785. return {};
  5786. }
  5787. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  5788. Type *prev_src = src;
  5789. // Type *prev_dst = dst;
  5790. src = base_type(type_deref(src));
  5791. // dst = base_type(type_deref(dst));
  5792. bool src_is_ptr = src != prev_src;
  5793. // bool dst_is_ptr = dst != prev_dst;
  5794. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  5795. for_array(i, src->Struct.fields) {
  5796. Entity *f = src->Struct.fields[i];
  5797. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  5798. if (are_types_identical(dst, f->type)) {
  5799. return f->token.string;
  5800. }
  5801. if (src_is_ptr && is_type_pointer(dst)) {
  5802. if (are_types_identical(type_deref(dst), f->type)) {
  5803. return f->token.string;
  5804. }
  5805. }
  5806. if (is_type_struct(f->type)) {
  5807. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  5808. if (name.len > 0) {
  5809. return name;
  5810. }
  5811. }
  5812. }
  5813. }
  5814. return str_lit("");
  5815. }
  5816. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  5817. GB_ASSERT(is_type_pointer(value.type));
  5818. GB_ASSERT(is_type_pointer(t));
  5819. GB_ASSERT(lb_is_const(value));
  5820. lbValue res = {};
  5821. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  5822. res.type = t;
  5823. return res;
  5824. }
  5825. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  5826. lbModule *m = p->module;
  5827. t = reduce_tuple_to_single_type(t);
  5828. Type *src_type = value.type;
  5829. if (are_types_identical(t, src_type)) {
  5830. return value;
  5831. }
  5832. Type *src = core_type(src_type);
  5833. Type *dst = core_type(t);
  5834. GB_ASSERT(src != nullptr);
  5835. GB_ASSERT(dst != nullptr);
  5836. if (is_type_untyped_nil(src)) {
  5837. return lb_const_nil(m, t);
  5838. }
  5839. if (is_type_untyped_undef(src)) {
  5840. return lb_const_undef(m, t);
  5841. }
  5842. if (LLVMIsConstant(value.value)) {
  5843. if (is_type_any(dst)) {
  5844. Type *st = default_type(src_type);
  5845. lbAddr default_value = lb_add_local_generated(p, st, false);
  5846. lb_addr_store(p, default_value, value);
  5847. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  5848. lbValue id = lb_typeid(m, st);
  5849. lbAddr res = lb_add_local_generated(p, t, false);
  5850. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  5851. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  5852. lb_emit_store(p, a0, data);
  5853. lb_emit_store(p, a1, id);
  5854. return lb_addr_load(p, res);
  5855. } else if (dst->kind == Type_Basic) {
  5856. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5857. String str = lb_get_const_string(m, value);
  5858. lbValue res = {};
  5859. res.type = t;
  5860. res.value = llvm_cstring(m, str);
  5861. return res;
  5862. }
  5863. // if (is_type_float(dst)) {
  5864. // return value;
  5865. // } else if (is_type_integer(dst)) {
  5866. // return value;
  5867. // }
  5868. // ExactValue ev = value->Constant.value;
  5869. // if (is_type_float(dst)) {
  5870. // ev = exact_value_to_float(ev);
  5871. // } else if (is_type_complex(dst)) {
  5872. // ev = exact_value_to_complex(ev);
  5873. // } else if (is_type_quaternion(dst)) {
  5874. // ev = exact_value_to_quaternion(ev);
  5875. // } else if (is_type_string(dst)) {
  5876. // // Handled elsewhere
  5877. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5878. // } else if (is_type_integer(dst)) {
  5879. // ev = exact_value_to_integer(ev);
  5880. // } else if (is_type_pointer(dst)) {
  5881. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5882. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5883. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5884. // }
  5885. // return lb_const_value(p->module, t, ev);
  5886. }
  5887. }
  5888. if (are_types_identical(src, dst)) {
  5889. if (!are_types_identical(src_type, t)) {
  5890. return lb_emit_transmute(p, value, t);
  5891. }
  5892. return value;
  5893. }
  5894. // bool <-> llvm bool
  5895. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5896. lbValue res = {};
  5897. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5898. res.type = dst;
  5899. return res;
  5900. }
  5901. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5902. lbValue res = {};
  5903. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5904. res.type = dst;
  5905. return res;
  5906. }
  5907. // integer -> integer
  5908. if (is_type_integer(src) && is_type_integer(dst)) {
  5909. GB_ASSERT(src->kind == Type_Basic &&
  5910. dst->kind == Type_Basic);
  5911. i64 sz = type_size_of(default_type(src));
  5912. i64 dz = type_size_of(default_type(dst));
  5913. if (sz == dz) {
  5914. if (dz > 1 && !types_have_same_internal_endian(src, dst)) {
  5915. return lb_emit_byte_swap(p, value, t);
  5916. }
  5917. lbValue res = {};
  5918. res.value = value.value;
  5919. res.type = t;
  5920. return res;
  5921. }
  5922. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5923. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5924. value = lb_emit_byte_swap(p, value, platform_src_type);
  5925. }
  5926. LLVMOpcode op = LLVMTrunc;
  5927. if (dz < sz) {
  5928. op = LLVMTrunc;
  5929. } else if (dz == sz) {
  5930. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5931. // NOTE(bill): Copy the value just for type correctness
  5932. op = LLVMBitCast;
  5933. } else if (dz > sz) {
  5934. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5935. }
  5936. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5937. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5938. lbValue res = {};
  5939. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5940. res.type = t;
  5941. return lb_emit_byte_swap(p, res, t);
  5942. } else {
  5943. lbValue res = {};
  5944. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5945. res.type = t;
  5946. return res;
  5947. }
  5948. }
  5949. // boolean -> boolean/integer
  5950. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5951. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5952. lbValue res = {};
  5953. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5954. res.type = t;
  5955. return res;
  5956. }
  5957. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5958. return lb_emit_transmute(p, value, dst);
  5959. }
  5960. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5961. return lb_emit_transmute(p, value, dst);
  5962. }
  5963. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5964. return lb_emit_transmute(p, value, dst);
  5965. }
  5966. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5967. return lb_emit_transmute(p, value, dst);
  5968. }
  5969. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5970. lbValue c = lb_emit_conv(p, value, t_cstring);
  5971. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5972. args[0] = c;
  5973. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5974. return lb_emit_conv(p, s, dst);
  5975. }
  5976. // integer -> boolean
  5977. if (is_type_integer(src) && is_type_boolean(dst)) {
  5978. lbValue res = {};
  5979. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5980. res.type = t_llvm_bool;
  5981. return lb_emit_conv(p, res, t);
  5982. }
  5983. // float -> float
  5984. if (is_type_float(src) && is_type_float(dst)) {
  5985. i64 sz = type_size_of(src);
  5986. i64 dz = type_size_of(dst);
  5987. if (dz == sz) {
  5988. if (types_have_same_internal_endian(src, dst)) {
  5989. lbValue res = {};
  5990. res.type = t;
  5991. res.value = value.value;
  5992. return res;
  5993. } else {
  5994. return lb_emit_byte_swap(p, value, t);
  5995. }
  5996. }
  5997. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5998. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5999. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6000. lbValue res = {};
  6001. res = lb_emit_conv(p, value, platform_src_type);
  6002. res = lb_emit_conv(p, res, platform_dst_type);
  6003. if (is_type_different_to_arch_endianness(dst)) {
  6004. res = lb_emit_byte_swap(p, res, t);
  6005. }
  6006. return lb_emit_conv(p, res, t);
  6007. }
  6008. lbValue res = {};
  6009. res.type = t;
  6010. if (dz >= sz) {
  6011. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  6012. } else {
  6013. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  6014. }
  6015. return res;
  6016. }
  6017. if (is_type_complex(src) && is_type_complex(dst)) {
  6018. Type *ft = base_complex_elem_type(dst);
  6019. lbAddr gen = lb_add_local_generated(p, dst, false);
  6020. lbValue gp = lb_addr_get_ptr(p, gen);
  6021. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6022. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6023. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6024. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  6025. return lb_addr_load(p, gen);
  6026. }
  6027. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  6028. // @QuaternionLayout
  6029. Type *ft = base_complex_elem_type(dst);
  6030. lbAddr gen = lb_add_local_generated(p, dst, false);
  6031. lbValue gp = lb_addr_get_ptr(p, gen);
  6032. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6033. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6034. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  6035. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  6036. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  6037. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  6038. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  6039. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  6040. return lb_addr_load(p, gen);
  6041. }
  6042. if (is_type_float(src) && is_type_complex(dst)) {
  6043. Type *ft = base_complex_elem_type(dst);
  6044. lbAddr gen = lb_add_local_generated(p, dst, true);
  6045. lbValue gp = lb_addr_get_ptr(p, gen);
  6046. lbValue real = lb_emit_conv(p, value, ft);
  6047. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6048. return lb_addr_load(p, gen);
  6049. }
  6050. if (is_type_float(src) && is_type_quaternion(dst)) {
  6051. Type *ft = base_complex_elem_type(dst);
  6052. lbAddr gen = lb_add_local_generated(p, dst, true);
  6053. lbValue gp = lb_addr_get_ptr(p, gen);
  6054. lbValue real = lb_emit_conv(p, value, ft);
  6055. // @QuaternionLayout
  6056. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6057. return lb_addr_load(p, gen);
  6058. }
  6059. if (is_type_complex(src) && is_type_quaternion(dst)) {
  6060. Type *ft = base_complex_elem_type(dst);
  6061. lbAddr gen = lb_add_local_generated(p, dst, true);
  6062. lbValue gp = lb_addr_get_ptr(p, gen);
  6063. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6064. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6065. // @QuaternionLayout
  6066. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6067. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  6068. return lb_addr_load(p, gen);
  6069. }
  6070. // float <-> integer
  6071. if (is_type_float(src) && is_type_integer(dst)) {
  6072. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6073. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6074. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6075. lbValue res = {};
  6076. res = lb_emit_conv(p, value, platform_src_type);
  6077. res = lb_emit_conv(p, res, platform_dst_type);
  6078. if (is_type_different_to_arch_endianness(dst)) {
  6079. res = lb_emit_byte_swap(p, res, t);
  6080. }
  6081. return lb_emit_conv(p, res, t);
  6082. }
  6083. lbValue res = {};
  6084. res.type = t;
  6085. if (is_type_unsigned(dst)) {
  6086. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  6087. } else {
  6088. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  6089. }
  6090. return res;
  6091. }
  6092. if (is_type_integer(src) && is_type_float(dst)) {
  6093. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6094. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6095. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6096. lbValue res = {};
  6097. res = lb_emit_conv(p, value, platform_src_type);
  6098. res = lb_emit_conv(p, res, platform_dst_type);
  6099. if (is_type_different_to_arch_endianness(dst)) {
  6100. res = lb_emit_byte_swap(p, res, t);
  6101. }
  6102. return lb_emit_conv(p, res, t);
  6103. }
  6104. lbValue res = {};
  6105. res.type = t;
  6106. if (is_type_unsigned(src)) {
  6107. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  6108. } else {
  6109. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  6110. }
  6111. return res;
  6112. }
  6113. // Pointer <-> uintptr
  6114. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6115. lbValue res = {};
  6116. res.type = t;
  6117. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6118. return res;
  6119. }
  6120. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6121. lbValue res = {};
  6122. res.type = t;
  6123. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6124. return res;
  6125. }
  6126. #if 1
  6127. if (is_type_union(dst)) {
  6128. for_array(i, dst->Union.variants) {
  6129. Type *vt = dst->Union.variants[i];
  6130. if (are_types_identical(vt, src_type)) {
  6131. lbAddr parent = lb_add_local_generated(p, t, true);
  6132. lb_emit_store_union_variant(p, parent.addr, value, vt);
  6133. return lb_addr_load(p, parent);
  6134. }
  6135. }
  6136. }
  6137. #endif
  6138. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  6139. // subtype polymorphism casting
  6140. if (check_is_assignable_to_using_subtype(src_type, t)) {
  6141. Type *st = type_deref(src_type);
  6142. Type *pst = st;
  6143. st = type_deref(st);
  6144. bool st_is_ptr = is_type_pointer(src_type);
  6145. st = base_type(st);
  6146. Type *dt = t;
  6147. bool dt_is_ptr = type_deref(dt) != dt;
  6148. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  6149. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  6150. if (field_name.len > 0) {
  6151. // NOTE(bill): It can be casted
  6152. Selection sel = lookup_field(st, field_name, false, true);
  6153. if (sel.entity != nullptr) {
  6154. if (st_is_ptr) {
  6155. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  6156. Type *rt = res.type;
  6157. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6158. res = lb_emit_load(p, res);
  6159. }
  6160. return res;
  6161. } else {
  6162. if (is_type_pointer(value.type)) {
  6163. Type *rt = value.type;
  6164. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6165. value = lb_emit_load(p, value);
  6166. } else {
  6167. value = lb_emit_deep_field_gep(p, value, sel);
  6168. return lb_emit_load(p, value);
  6169. }
  6170. }
  6171. return lb_emit_deep_field_ev(p, value, sel);
  6172. }
  6173. } else {
  6174. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  6175. }
  6176. }
  6177. }
  6178. // Pointer <-> Pointer
  6179. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6180. lbValue res = {};
  6181. res.type = t;
  6182. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6183. return res;
  6184. }
  6185. // proc <-> proc
  6186. if (is_type_proc(src) && is_type_proc(dst)) {
  6187. lbValue res = {};
  6188. res.type = t;
  6189. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6190. return res;
  6191. }
  6192. // pointer -> proc
  6193. if (is_type_pointer(src) && is_type_proc(dst)) {
  6194. lbValue res = {};
  6195. res.type = t;
  6196. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6197. return res;
  6198. }
  6199. // proc -> pointer
  6200. if (is_type_proc(src) && is_type_pointer(dst)) {
  6201. lbValue res = {};
  6202. res.type = t;
  6203. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6204. return res;
  6205. }
  6206. // []byte/[]u8 <-> string
  6207. if (is_type_u8_slice(src) && is_type_string(dst)) {
  6208. return lb_emit_transmute(p, value, t);
  6209. }
  6210. if (is_type_string(src) && is_type_u8_slice(dst)) {
  6211. return lb_emit_transmute(p, value, t);
  6212. }
  6213. if (is_type_array(dst)) {
  6214. Type *elem = dst->Array.elem;
  6215. lbValue e = lb_emit_conv(p, value, elem);
  6216. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6217. lbAddr v = lb_add_local_generated(p, t, false);
  6218. isize index_count = cast(isize)dst->Array.count;
  6219. for (isize i = 0; i < index_count; i++) {
  6220. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  6221. lb_emit_store(p, elem, e);
  6222. }
  6223. return lb_addr_load(p, v);
  6224. }
  6225. if (is_type_any(dst)) {
  6226. if (is_type_untyped_nil(src)) {
  6227. return lb_const_nil(p->module, t);
  6228. }
  6229. if (is_type_untyped_undef(src)) {
  6230. return lb_const_undef(p->module, t);
  6231. }
  6232. lbAddr result = lb_add_local_generated(p, t, true);
  6233. Type *st = default_type(src_type);
  6234. lbValue data = lb_address_from_load_or_generate_local(p, value);
  6235. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  6236. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  6237. data = lb_emit_conv(p, data, t_rawptr);
  6238. lbValue id = lb_typeid(p->module, st);
  6239. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  6240. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  6241. lb_emit_store(p, any_data, data);
  6242. lb_emit_store(p, any_id, id);
  6243. return lb_addr_load(p, result);
  6244. }
  6245. i64 src_sz = type_size_of(src);
  6246. i64 dst_sz = type_size_of(dst);
  6247. if (src_sz == dst_sz) {
  6248. // bit_set <-> integer
  6249. if (is_type_integer(src) && is_type_bit_set(dst)) {
  6250. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  6251. res.type = dst;
  6252. return res;
  6253. }
  6254. if (is_type_bit_set(src) && is_type_integer(dst)) {
  6255. lbValue bs = value;
  6256. bs.type = bit_set_to_int(src);
  6257. return lb_emit_conv(p, bs, dst);
  6258. }
  6259. // typeid <-> integer
  6260. if (is_type_integer(src) && is_type_typeid(dst)) {
  6261. return lb_emit_transmute(p, value, dst);
  6262. }
  6263. if (is_type_typeid(src) && is_type_integer(dst)) {
  6264. return lb_emit_transmute(p, value, dst);
  6265. }
  6266. }
  6267. if (is_type_untyped(src)) {
  6268. if (is_type_string(src) && is_type_string(dst)) {
  6269. lbAddr result = lb_add_local_generated(p, t, false);
  6270. lb_addr_store(p, result, value);
  6271. return lb_addr_load(p, result);
  6272. }
  6273. }
  6274. gb_printf_err("%.*s\n", LIT(p->name));
  6275. gb_printf_err("lb_emit_conv: src -> dst\n");
  6276. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  6277. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  6278. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  6279. gb_printf_err("Not Identical %p != %p\n", src, dst);
  6280. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  6281. type_to_string(src_type), type_to_string(t),
  6282. LIT(p->name));
  6283. return {};
  6284. }
  6285. bool lb_is_type_aggregate(Type *t) {
  6286. t = base_type(t);
  6287. switch (t->kind) {
  6288. case Type_Basic:
  6289. switch (t->Basic.kind) {
  6290. case Basic_string:
  6291. case Basic_any:
  6292. return true;
  6293. case Basic_complex32:
  6294. case Basic_complex64:
  6295. case Basic_complex128:
  6296. case Basic_quaternion64:
  6297. case Basic_quaternion128:
  6298. case Basic_quaternion256:
  6299. return true;
  6300. }
  6301. break;
  6302. case Type_Pointer:
  6303. return false;
  6304. case Type_Array:
  6305. case Type_Slice:
  6306. case Type_Struct:
  6307. case Type_Union:
  6308. case Type_Tuple:
  6309. case Type_DynamicArray:
  6310. case Type_Map:
  6311. case Type_SimdVector:
  6312. return true;
  6313. case Type_Named:
  6314. return lb_is_type_aggregate(t->Named.base);
  6315. }
  6316. return false;
  6317. }
  6318. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  6319. Type *src_type = value.type;
  6320. if (are_types_identical(t, src_type)) {
  6321. return value;
  6322. }
  6323. lbValue res = {};
  6324. res.type = t;
  6325. Type *src = base_type(src_type);
  6326. Type *dst = base_type(t);
  6327. lbModule *m = p->module;
  6328. i64 sz = type_size_of(src);
  6329. i64 dz = type_size_of(dst);
  6330. if (sz != dz) {
  6331. LLVMTypeRef s = lb_type(m, src);
  6332. LLVMTypeRef d = lb_type(m, dst);
  6333. i64 llvm_sz = lb_sizeof(s);
  6334. i64 llvm_dz = lb_sizeof(d);
  6335. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  6336. }
  6337. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  6338. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  6339. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6340. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6341. return res;
  6342. }
  6343. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6344. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6345. return res;
  6346. }
  6347. if (is_type_uintptr(src) && is_type_proc(dst)) {
  6348. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6349. return res;
  6350. }
  6351. if (is_type_proc(src) && is_type_uintptr(dst)) {
  6352. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6353. return res;
  6354. }
  6355. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  6356. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6357. return res;
  6358. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  6359. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6360. return res;
  6361. }
  6362. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6363. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  6364. return res;
  6365. }
  6366. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  6367. lbValue s = lb_address_from_load_or_generate_local(p, value);
  6368. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  6369. return lb_emit_load(p, d);
  6370. }
  6371. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  6372. // GB_PANIC("lb_emit_transmute");
  6373. return res;
  6374. }
  6375. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  6376. GB_ASSERT(addr.kind == lbAddr_Context);
  6377. GB_ASSERT(addr.ctx.sel.index.count == 0);
  6378. lbModule *m = p->module;
  6379. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6380. args[0] = addr.addr;
  6381. lb_emit_runtime_call(p, "__init_context", args);
  6382. }
  6383. lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  6384. Type *pt = base_type(p->type);
  6385. GB_ASSERT(pt->kind == Type_Proc);
  6386. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  6387. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  6388. e->flags |= EntityFlag_NoAlias;
  6389. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  6390. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  6391. lbValue param = {context_ptr, e->type};
  6392. lb_add_entity(p->module, e, param);
  6393. lbAddr ctx_addr = {};
  6394. ctx_addr.kind = lbAddr_Context;
  6395. ctx_addr.addr = param;
  6396. lbContextData *cd = array_add_and_get(&p->context_stack);
  6397. cd->ctx = ctx_addr;
  6398. cd->scope_index = -1;
  6399. cd->uses = +1; // make sure it has been used already
  6400. return cd;
  6401. }
  6402. lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  6403. ctx.kind = lbAddr_Context;
  6404. lbContextData *cd = array_add_and_get(&p->context_stack);
  6405. cd->ctx = ctx;
  6406. cd->scope_index = p->scope_index;
  6407. return cd;
  6408. }
  6409. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  6410. if (p->context_stack.count > 0) {
  6411. return p->context_stack[p->context_stack.count-1].ctx;
  6412. }
  6413. Type *pt = base_type(p->type);
  6414. GB_ASSERT(pt->kind == Type_Proc);
  6415. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  6416. lbAddr c = lb_add_local_generated(p, t_context, true);
  6417. c.kind = lbAddr_Context;
  6418. lb_emit_init_context(p, c);
  6419. lb_push_context_onto_stack(p, c);
  6420. lb_add_debug_context_variable(p, c);
  6421. return c;
  6422. }
  6423. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  6424. if (LLVMIsALoadInst(value.value)) {
  6425. lbValue res = {};
  6426. res.value = LLVMGetOperand(value.value, 0);
  6427. res.type = alloc_type_pointer(value.type);
  6428. return res;
  6429. }
  6430. GB_ASSERT(is_type_typed(value.type));
  6431. lbAddr res = lb_add_local_generated(p, value.type, false);
  6432. lb_addr_store(p, res, value);
  6433. return res.addr;
  6434. }
  6435. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  6436. if (LLVMIsALoadInst(value.value)) {
  6437. lbValue res = {};
  6438. res.value = LLVMGetOperand(value.value, 0);
  6439. res.type = alloc_type_pointer(value.type);
  6440. return res;
  6441. }
  6442. GB_PANIC("lb_address_from_load");
  6443. return {};
  6444. }
  6445. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  6446. i64 type_alignment = type_align_of(new_type);
  6447. if (alignment < type_alignment) {
  6448. alignment = type_alignment;
  6449. }
  6450. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  6451. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  6452. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  6453. lb_addr_store(p, ptr, val);
  6454. // ptr.kind = lbAddr_Context;
  6455. return ptr.addr;
  6456. }
  6457. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  6458. GB_ASSERT(is_type_pointer(s.type));
  6459. Type *t = base_type(type_deref(s.type));
  6460. Type *result_type = nullptr;
  6461. if (is_type_relative_pointer(t)) {
  6462. s = lb_addr_get_ptr(p, lb_addr(s));
  6463. }
  6464. if (is_type_struct(t)) {
  6465. result_type = get_struct_field_type(t, index);
  6466. } else if (is_type_union(t)) {
  6467. GB_ASSERT(index == -1);
  6468. return lb_emit_union_tag_ptr(p, s);
  6469. } else if (is_type_tuple(t)) {
  6470. GB_ASSERT(t->Tuple.variables.count > 0);
  6471. result_type = t->Tuple.variables[index]->type;
  6472. } else if (is_type_complex(t)) {
  6473. Type *ft = base_complex_elem_type(t);
  6474. switch (index) {
  6475. case 0: result_type = ft; break;
  6476. case 1: result_type = ft; break;
  6477. }
  6478. } else if (is_type_quaternion(t)) {
  6479. Type *ft = base_complex_elem_type(t);
  6480. switch (index) {
  6481. case 0: result_type = ft; break;
  6482. case 1: result_type = ft; break;
  6483. case 2: result_type = ft; break;
  6484. case 3: result_type = ft; break;
  6485. }
  6486. } else if (is_type_slice(t)) {
  6487. switch (index) {
  6488. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6489. case 1: result_type = t_int; break;
  6490. }
  6491. } else if (is_type_string(t)) {
  6492. switch (index) {
  6493. case 0: result_type = t_u8_ptr; break;
  6494. case 1: result_type = t_int; break;
  6495. }
  6496. } else if (is_type_any(t)) {
  6497. switch (index) {
  6498. case 0: result_type = t_rawptr; break;
  6499. case 1: result_type = t_typeid; break;
  6500. }
  6501. } else if (is_type_dynamic_array(t)) {
  6502. switch (index) {
  6503. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6504. case 1: result_type = t_int; break;
  6505. case 2: result_type = t_int; break;
  6506. case 3: result_type = t_allocator; break;
  6507. }
  6508. } else if (is_type_map(t)) {
  6509. init_map_internal_types(t);
  6510. Type *itp = alloc_type_pointer(t->Map.internal_type);
  6511. s = lb_emit_transmute(p, s, itp);
  6512. Type *gst = t->Map.internal_type;
  6513. GB_ASSERT(gst->kind == Type_Struct);
  6514. switch (index) {
  6515. case 0: result_type = get_struct_field_type(gst, 0); break;
  6516. case 1: result_type = get_struct_field_type(gst, 1); break;
  6517. }
  6518. } else if (is_type_array(t)) {
  6519. return lb_emit_array_epi(p, s, index);
  6520. } else if (is_type_relative_slice(t)) {
  6521. switch (index) {
  6522. case 0: result_type = t->RelativeSlice.base_integer; break;
  6523. case 1: result_type = t->RelativeSlice.base_integer; break;
  6524. }
  6525. } else {
  6526. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  6527. }
  6528. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  6529. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6530. index += 1;
  6531. }
  6532. if (lb_is_const(s)) {
  6533. lbModule *m = p->module;
  6534. lbValue res = {};
  6535. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  6536. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6537. res.type = alloc_type_pointer(result_type);
  6538. return res;
  6539. } else {
  6540. lbValue res = {};
  6541. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  6542. res.type = alloc_type_pointer(result_type);
  6543. return res;
  6544. }
  6545. }
  6546. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  6547. if (LLVMIsALoadInst(s.value)) {
  6548. lbValue res = {};
  6549. res.value = LLVMGetOperand(s.value, 0);
  6550. res.type = alloc_type_pointer(s.type);
  6551. lbValue ptr = lb_emit_struct_ep(p, res, index);
  6552. return lb_emit_load(p, ptr);
  6553. }
  6554. Type *t = base_type(s.type);
  6555. Type *result_type = nullptr;
  6556. switch (t->kind) {
  6557. case Type_Basic:
  6558. switch (t->Basic.kind) {
  6559. case Basic_string:
  6560. switch (index) {
  6561. case 0: result_type = t_u8_ptr; break;
  6562. case 1: result_type = t_int; break;
  6563. }
  6564. break;
  6565. case Basic_any:
  6566. switch (index) {
  6567. case 0: result_type = t_rawptr; break;
  6568. case 1: result_type = t_typeid; break;
  6569. }
  6570. break;
  6571. case Basic_complex32:
  6572. case Basic_complex64:
  6573. case Basic_complex128:
  6574. {
  6575. Type *ft = base_complex_elem_type(t);
  6576. switch (index) {
  6577. case 0: result_type = ft; break;
  6578. case 1: result_type = ft; break;
  6579. }
  6580. break;
  6581. }
  6582. case Basic_quaternion64:
  6583. case Basic_quaternion128:
  6584. case Basic_quaternion256:
  6585. {
  6586. Type *ft = base_complex_elem_type(t);
  6587. switch (index) {
  6588. case 0: result_type = ft; break;
  6589. case 1: result_type = ft; break;
  6590. case 2: result_type = ft; break;
  6591. case 3: result_type = ft; break;
  6592. }
  6593. break;
  6594. }
  6595. }
  6596. break;
  6597. case Type_Struct:
  6598. result_type = get_struct_field_type(t, index);
  6599. break;
  6600. case Type_Union:
  6601. GB_ASSERT(index == -1);
  6602. // return lb_emit_union_tag_value(p, s);
  6603. GB_PANIC("lb_emit_union_tag_value");
  6604. case Type_Tuple:
  6605. GB_ASSERT(t->Tuple.variables.count > 0);
  6606. result_type = t->Tuple.variables[index]->type;
  6607. if (t->Tuple.variables.count == 1) {
  6608. return s;
  6609. }
  6610. break;
  6611. case Type_Slice:
  6612. switch (index) {
  6613. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6614. case 1: result_type = t_int; break;
  6615. }
  6616. break;
  6617. case Type_DynamicArray:
  6618. switch (index) {
  6619. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6620. case 1: result_type = t_int; break;
  6621. case 2: result_type = t_int; break;
  6622. case 3: result_type = t_allocator; break;
  6623. }
  6624. break;
  6625. case Type_Map:
  6626. {
  6627. init_map_internal_types(t);
  6628. Type *gst = t->Map.generated_struct_type;
  6629. switch (index) {
  6630. case 0: result_type = get_struct_field_type(gst, 0); break;
  6631. case 1: result_type = get_struct_field_type(gst, 1); break;
  6632. }
  6633. }
  6634. break;
  6635. case Type_Array:
  6636. result_type = t->Array.elem;
  6637. break;
  6638. default:
  6639. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  6640. break;
  6641. }
  6642. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  6643. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6644. index += 1;
  6645. }
  6646. lbValue res = {};
  6647. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  6648. res.type = result_type;
  6649. return res;
  6650. }
  6651. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  6652. GB_ASSERT(sel.index.count > 0);
  6653. Type *type = type_deref(e.type);
  6654. for_array(i, sel.index) {
  6655. i32 index = cast(i32)sel.index[i];
  6656. if (is_type_pointer(type)) {
  6657. type = type_deref(type);
  6658. e = lb_emit_load(p, e);
  6659. }
  6660. type = core_type(type);
  6661. if (is_type_quaternion(type)) {
  6662. e = lb_emit_struct_ep(p, e, index);
  6663. } else if (is_type_raw_union(type)) {
  6664. type = get_struct_field_type(type, index);
  6665. GB_ASSERT(is_type_pointer(e.type));
  6666. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  6667. } else if (is_type_struct(type)) {
  6668. type = get_struct_field_type(type, index);
  6669. e = lb_emit_struct_ep(p, e, index);
  6670. } else if (type->kind == Type_Union) {
  6671. GB_ASSERT(index == -1);
  6672. type = t_type_info_ptr;
  6673. e = lb_emit_struct_ep(p, e, index);
  6674. } else if (type->kind == Type_Tuple) {
  6675. type = type->Tuple.variables[index]->type;
  6676. e = lb_emit_struct_ep(p, e, index);
  6677. } else if (type->kind == Type_Basic) {
  6678. switch (type->Basic.kind) {
  6679. case Basic_any: {
  6680. if (index == 0) {
  6681. type = t_rawptr;
  6682. } else if (index == 1) {
  6683. type = t_type_info_ptr;
  6684. }
  6685. e = lb_emit_struct_ep(p, e, index);
  6686. break;
  6687. }
  6688. case Basic_string:
  6689. e = lb_emit_struct_ep(p, e, index);
  6690. break;
  6691. default:
  6692. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6693. break;
  6694. }
  6695. } else if (type->kind == Type_Slice) {
  6696. e = lb_emit_struct_ep(p, e, index);
  6697. } else if (type->kind == Type_DynamicArray) {
  6698. e = lb_emit_struct_ep(p, e, index);
  6699. } else if (type->kind == Type_Array) {
  6700. e = lb_emit_array_epi(p, e, index);
  6701. } else if (type->kind == Type_Map) {
  6702. e = lb_emit_struct_ep(p, e, index);
  6703. } else if (type->kind == Type_RelativePointer) {
  6704. e = lb_emit_struct_ep(p, e, index);
  6705. } else {
  6706. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6707. }
  6708. }
  6709. return e;
  6710. }
  6711. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  6712. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  6713. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  6714. return lb_emit_load(p, res);
  6715. }
  6716. void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  6717. // NOTE(bill): The prev block may defer injection before it's terminator
  6718. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  6719. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  6720. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  6721. return;
  6722. }
  6723. isize prev_context_stack_count = p->context_stack.count;
  6724. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  6725. defer (p->context_stack.count = prev_context_stack_count);
  6726. p->context_stack.count = d.context_stack_count;
  6727. lbBlock *b = lb_create_block(p, "defer");
  6728. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6729. lb_emit_jump(p, b);
  6730. }
  6731. lb_start_block(p, b);
  6732. if (d.kind == lbDefer_Node) {
  6733. lb_build_stmt(p, d.stmt);
  6734. } else if (d.kind == lbDefer_Instr) {
  6735. // NOTE(bill): Need to make a new copy
  6736. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  6737. LLVMInsertIntoBuilder(p->builder, instr);
  6738. } else if (d.kind == lbDefer_Proc) {
  6739. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  6740. }
  6741. }
  6742. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  6743. isize count = p->defer_stmts.count;
  6744. isize i = count;
  6745. while (i --> 0) {
  6746. lbDefer const &d = p->defer_stmts[i];
  6747. if (kind == lbDeferExit_Default) {
  6748. if (p->scope_index == d.scope_index &&
  6749. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  6750. lb_build_defer_stmt(p, d);
  6751. array_pop(&p->defer_stmts);
  6752. continue;
  6753. } else {
  6754. break;
  6755. }
  6756. } else if (kind == lbDeferExit_Return) {
  6757. lb_build_defer_stmt(p, d);
  6758. } else if (kind == lbDeferExit_Branch) {
  6759. GB_ASSERT(block != nullptr);
  6760. isize lower_limit = block->scope_index;
  6761. if (lower_limit < d.scope_index) {
  6762. lb_build_defer_stmt(p, d);
  6763. }
  6764. }
  6765. }
  6766. }
  6767. void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  6768. Type *pt = base_type(p->type);
  6769. GB_ASSERT(pt->kind == Type_Proc);
  6770. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6771. GB_ASSERT(p->context_stack.count != 0);
  6772. }
  6773. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6774. d->kind = lbDefer_Node;
  6775. d->scope_index = scope_index;
  6776. d->context_stack_count = p->context_stack.count;
  6777. d->block = p->curr_block;
  6778. d->stmt = stmt;
  6779. }
  6780. void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  6781. Type *pt = base_type(p->type);
  6782. GB_ASSERT(pt->kind == Type_Proc);
  6783. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6784. GB_ASSERT(p->context_stack.count != 0);
  6785. }
  6786. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6787. d->kind = lbDefer_Proc;
  6788. d->scope_index = p->scope_index;
  6789. d->block = p->curr_block;
  6790. d->context_stack_count = p->context_stack.count;
  6791. d->proc.deferred = deferred;
  6792. d->proc.result_as_args = result_as_args;
  6793. }
  6794. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  6795. Array<lbValue> array = {};
  6796. Type *t = base_type(value.type);
  6797. if (t == nullptr) {
  6798. // Do nothing
  6799. } else if (is_type_tuple(t)) {
  6800. GB_ASSERT(t->kind == Type_Tuple);
  6801. auto *rt = &t->Tuple;
  6802. if (rt->variables.count > 0) {
  6803. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  6804. for_array(i, rt->variables) {
  6805. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  6806. array[i] = elem;
  6807. }
  6808. }
  6809. } else {
  6810. array = array_make<lbValue>(permanent_allocator(), 1);
  6811. array[0] = value;
  6812. }
  6813. return array;
  6814. }
  6815. 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) {
  6816. unsigned arg_count = cast(unsigned)processed_args.count;
  6817. if (return_ptr.value != nullptr) {
  6818. arg_count += 1;
  6819. }
  6820. if (context_ptr.addr.value != nullptr) {
  6821. arg_count += 1;
  6822. }
  6823. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  6824. isize arg_index = 0;
  6825. if (return_ptr.value != nullptr) {
  6826. args[arg_index++] = return_ptr.value;
  6827. }
  6828. for_array(i, processed_args) {
  6829. lbValue arg = processed_args[i];
  6830. args[arg_index++] = arg.value;
  6831. }
  6832. if (context_ptr.addr.value != nullptr) {
  6833. LLVMValueRef cp = context_ptr.addr.value;
  6834. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  6835. args[arg_index++] = cp;
  6836. }
  6837. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  6838. GB_ASSERT(curr_block != p->decl_block->block);
  6839. {
  6840. LLVMTypeRef ftp = lb_type(p->module, value.type);
  6841. LLVMTypeRef ft = LLVMGetElementType(ftp);
  6842. LLVMValueRef fn = value.value;
  6843. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  6844. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  6845. }
  6846. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  6847. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  6848. {
  6849. unsigned param_count = LLVMCountParamTypes(fnp);
  6850. GB_ASSERT(arg_count >= param_count);
  6851. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  6852. LLVMGetParamTypes(fnp, param_types);
  6853. for (unsigned i = 0; i < param_count; i++) {
  6854. LLVMTypeRef param_type = param_types[i];
  6855. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  6856. GB_ASSERT_MSG(
  6857. arg_type == param_type,
  6858. "Parameter types do not match: %s != %s, argument: %s",
  6859. LLVMPrintTypeToString(arg_type),
  6860. LLVMPrintTypeToString(param_type),
  6861. LLVMPrintValueToString(args[i])
  6862. );
  6863. }
  6864. }
  6865. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  6866. switch (inlining) {
  6867. case ProcInlining_none:
  6868. break;
  6869. case ProcInlining_inline:
  6870. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  6871. break;
  6872. case ProcInlining_no_inline:
  6873. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  6874. break;
  6875. }
  6876. lbValue res = {};
  6877. res.value = ret;
  6878. res.type = abi_rt;
  6879. return res;
  6880. }
  6881. }
  6882. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  6883. // LLVMMetadataRef curr_loc = LLVMGetCurrentDebugLocation2(p->builder);
  6884. // LLVMSetCurrentDebugLocation2(p->builder, nullptr);
  6885. // defer (if (curr_loc) {
  6886. // LLVMSetCurrentDebugLocation2(p->builder, curr_loc);
  6887. // });
  6888. String name = make_string_c(c_name);
  6889. AstPackage *pkg = p->module->info->runtime_package;
  6890. Entity *e = scope_lookup_current(pkg->scope, name);
  6891. lbValue *found = nullptr;
  6892. if (p->module != e->code_gen_module) {
  6893. gb_mutex_lock(&p->module->mutex);
  6894. }
  6895. GB_ASSERT(e->code_gen_module != nullptr);
  6896. found = map_get(&e->code_gen_module->values, hash_entity(e));
  6897. if (p->module != e->code_gen_module) {
  6898. gb_mutex_unlock(&p->module->mutex);
  6899. }
  6900. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  6901. return lb_emit_call(p, *found, args);
  6902. }
  6903. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  6904. lbModule *m = p->module;
  6905. Type *pt = base_type(value.type);
  6906. GB_ASSERT(pt->kind == Type_Proc);
  6907. Type *results = pt->Proc.results;
  6908. if (p->entity != nullptr) {
  6909. if (p->entity->flags & EntityFlag_Disabled) {
  6910. return {};
  6911. }
  6912. }
  6913. lbAddr context_ptr = {};
  6914. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6915. context_ptr = lb_find_or_generate_context_ptr(p);
  6916. }
  6917. defer (if (pt->Proc.diverging) {
  6918. LLVMBuildUnreachable(p->builder);
  6919. });
  6920. bool is_c_vararg = pt->Proc.c_vararg;
  6921. isize param_count = pt->Proc.param_count;
  6922. if (is_c_vararg) {
  6923. GB_ASSERT(param_count-1 <= args.count);
  6924. param_count -= 1;
  6925. } else {
  6926. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  6927. }
  6928. lbValue result = {};
  6929. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  6930. {
  6931. lbFunctionType **ft_found = nullptr;
  6932. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6933. if (!ft_found) {
  6934. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  6935. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6936. }
  6937. GB_ASSERT(ft_found != nullptr);
  6938. lbFunctionType *ft = *ft_found;
  6939. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  6940. unsigned param_index = 0;
  6941. for (isize i = 0; i < param_count; i++) {
  6942. Entity *e = pt->Proc.params->Tuple.variables[i];
  6943. if (e->kind != Entity_Variable) {
  6944. continue;
  6945. }
  6946. GB_ASSERT(e->flags & EntityFlag_Param);
  6947. Type *original_type = e->type;
  6948. lbArgType *arg = &ft->args[param_index];
  6949. if (arg->kind == lbArg_Ignore) {
  6950. continue;
  6951. }
  6952. lbValue x = lb_emit_conv(p, args[i], original_type);
  6953. LLVMTypeRef xt = lb_type(p->module, x.type);
  6954. if (arg->kind == lbArg_Direct) {
  6955. LLVMTypeRef abi_type = arg->cast_type;
  6956. if (!abi_type) {
  6957. abi_type = arg->type;
  6958. }
  6959. if (xt == abi_type) {
  6960. array_add(&processed_args, x);
  6961. } else {
  6962. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  6963. array_add(&processed_args, x);
  6964. }
  6965. } else if (arg->kind == lbArg_Indirect) {
  6966. lbValue ptr = {};
  6967. if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  6968. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  6969. // i.e. `T const &` in C++
  6970. ptr = lb_address_from_load_or_generate_local(p, x);
  6971. } else {
  6972. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  6973. }
  6974. array_add(&processed_args, ptr);
  6975. }
  6976. param_index += 1;
  6977. }
  6978. if (inlining == ProcInlining_none) {
  6979. inlining = p->inlining;
  6980. }
  6981. Type *rt = reduce_tuple_to_single_type(results);
  6982. if (return_by_pointer) {
  6983. lbValue return_ptr = {};
  6984. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6985. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6986. return_ptr = p->return_ptr_hint_value;
  6987. p->return_ptr_hint_used = true;
  6988. }
  6989. }
  6990. if (return_ptr.value == nullptr) {
  6991. lbAddr r = lb_add_local_generated(p, rt, true);
  6992. return_ptr = r.addr;
  6993. }
  6994. GB_ASSERT(is_type_pointer(return_ptr.type));
  6995. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6996. result = lb_emit_load(p, return_ptr);
  6997. } else if (rt != nullptr) {
  6998. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  6999. if (ft->ret.cast_type) {
  7000. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  7001. }
  7002. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  7003. result.type = rt;
  7004. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  7005. result.type = t_llvm_bool;
  7006. }
  7007. if (!is_type_tuple(rt)) {
  7008. result = lb_emit_conv(p, result, rt);
  7009. }
  7010. } else {
  7011. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  7012. }
  7013. }
  7014. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  7015. if (found != nullptr) {
  7016. Entity *e = *found;
  7017. if (e != nullptr && entity_has_deferred_procedure(e)) {
  7018. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  7019. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  7020. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  7021. GB_ASSERT(deferred_found != nullptr);
  7022. lbValue deferred = *deferred_found;
  7023. auto in_args = args;
  7024. Array<lbValue> result_as_args = {};
  7025. switch (kind) {
  7026. case DeferredProcedure_none:
  7027. break;
  7028. case DeferredProcedure_in:
  7029. result_as_args = in_args;
  7030. break;
  7031. case DeferredProcedure_out:
  7032. result_as_args = lb_value_to_array(p, result);
  7033. break;
  7034. case DeferredProcedure_in_out:
  7035. {
  7036. auto out_args = lb_value_to_array(p, result);
  7037. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  7038. array_copy(&result_as_args, in_args, 0);
  7039. array_copy(&result_as_args, out_args, in_args.count);
  7040. }
  7041. break;
  7042. }
  7043. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  7044. }
  7045. }
  7046. return result;
  7047. }
  7048. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  7049. Type *t = s.type;
  7050. GB_ASSERT(is_type_pointer(t));
  7051. Type *st = base_type(type_deref(t));
  7052. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7053. GB_ASSERT_MSG(is_type_integer(core_type(index.type)), "%s", type_to_string(index.type));
  7054. LLVMValueRef indices[2] = {};
  7055. indices[0] = llvm_zero(p->module);
  7056. indices[1] = lb_emit_conv(p, index, t_int).value;
  7057. Type *ptr = base_array_type(st);
  7058. lbValue res = {};
  7059. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  7060. res.type = alloc_type_pointer(ptr);
  7061. return res;
  7062. }
  7063. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  7064. Type *t = s.type;
  7065. GB_ASSERT(is_type_pointer(t));
  7066. Type *st = base_type(type_deref(t));
  7067. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7068. GB_ASSERT(0 <= index);
  7069. Type *ptr = base_array_type(st);
  7070. LLVMValueRef indices[2] = {
  7071. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  7072. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  7073. };
  7074. lbValue res = {};
  7075. if (lb_is_const(s)) {
  7076. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  7077. } else {
  7078. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  7079. }
  7080. res.type = alloc_type_pointer(ptr);
  7081. return res;
  7082. }
  7083. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  7084. LLVMValueRef indices[1] = {index.value};
  7085. lbValue res = {};
  7086. res.type = ptr.type;
  7087. if (lb_is_const(ptr) && lb_is_const(index)) {
  7088. res.value = LLVMConstGEP(ptr.value, indices, 1);
  7089. } else {
  7090. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  7091. }
  7092. return res;
  7093. }
  7094. LLVMValueRef llvm_const_slice(lbModule *m, lbValue data, lbValue len) {
  7095. GB_ASSERT(is_type_pointer(data.type));
  7096. GB_ASSERT(are_types_identical(len.type, t_int));
  7097. LLVMValueRef vals[2] = {
  7098. data.value,
  7099. len.value,
  7100. };
  7101. return LLVMConstStructInContext(m->ctx, vals, gb_count_of(vals), false);
  7102. }
  7103. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  7104. Type *t = lb_addr_type(slice);
  7105. GB_ASSERT(is_type_slice(t));
  7106. lbValue ptr = lb_addr_get_ptr(p, slice);
  7107. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7108. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7109. }
  7110. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  7111. Type *t = lb_addr_type(string);
  7112. GB_ASSERT(is_type_string(t));
  7113. lbValue ptr = lb_addr_get_ptr(p, string);
  7114. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7115. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7116. }
  7117. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  7118. Type *t = base_type(string.type);
  7119. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  7120. return lb_emit_struct_ev(p, string, 0);
  7121. }
  7122. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  7123. Type *t = base_type(string.type);
  7124. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  7125. return lb_emit_struct_ev(p, string, 1);
  7126. }
  7127. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  7128. GB_ASSERT(is_type_cstring(value.type));
  7129. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7130. args[0] = lb_emit_conv(p, value, t_cstring);
  7131. return lb_emit_runtime_call(p, "cstring_len", args);
  7132. }
  7133. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  7134. Type *t = type_deref(array_ptr.type);
  7135. GB_ASSERT(is_type_array(t));
  7136. return lb_emit_struct_ep(p, array_ptr, 0);
  7137. }
  7138. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  7139. GB_ASSERT(is_type_slice(slice.type));
  7140. return lb_emit_struct_ev(p, slice, 0);
  7141. }
  7142. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  7143. GB_ASSERT(is_type_slice(slice.type));
  7144. return lb_emit_struct_ev(p, slice, 1);
  7145. }
  7146. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  7147. GB_ASSERT(is_type_dynamic_array(da.type));
  7148. return lb_emit_struct_ev(p, da, 0);
  7149. }
  7150. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  7151. GB_ASSERT(is_type_dynamic_array(da.type));
  7152. return lb_emit_struct_ev(p, da, 1);
  7153. }
  7154. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  7155. GB_ASSERT(is_type_dynamic_array(da.type));
  7156. return lb_emit_struct_ev(p, da, 2);
  7157. }
  7158. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  7159. GB_ASSERT(is_type_dynamic_array(da.type));
  7160. return lb_emit_struct_ev(p, da, 3);
  7161. }
  7162. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  7163. Type *t = base_type(value.type);
  7164. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7165. init_map_internal_types(t);
  7166. Type *gst = t->Map.generated_struct_type;
  7167. i32 index = 1;
  7168. lbValue entries = lb_emit_struct_ev(p, value, index);
  7169. return entries;
  7170. }
  7171. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  7172. Type *t = base_type(type_deref(value.type));
  7173. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7174. init_map_internal_types(t);
  7175. Type *gst = t->Map.generated_struct_type;
  7176. i32 index = 1;
  7177. lbValue entries = lb_emit_struct_ep(p, value, index);
  7178. return entries;
  7179. }
  7180. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  7181. lbValue entries = lb_map_entries(p, value);
  7182. return lb_dynamic_array_len(p, entries);
  7183. }
  7184. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  7185. lbValue entries = lb_map_entries(p, value);
  7186. return lb_dynamic_array_cap(p, entries);
  7187. }
  7188. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  7189. Type *t = base_type(value.type);
  7190. bool is_ptr = false;
  7191. if (is_type_pointer(t)) {
  7192. is_ptr = true;
  7193. t = base_type(type_deref(t));
  7194. }
  7195. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7196. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7197. }
  7198. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  7199. t->Struct.soa_kind == StructSoa_Dynamic);
  7200. isize n = 0;
  7201. Type *elem = base_type(t->Struct.soa_elem);
  7202. if (elem->kind == Type_Struct) {
  7203. n = elem->Struct.fields.count;
  7204. } else if (elem->kind == Type_Array) {
  7205. n = elem->Array.count;
  7206. } else {
  7207. GB_PANIC("Unreachable");
  7208. }
  7209. if (is_ptr) {
  7210. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7211. return lb_emit_load(p, v);
  7212. }
  7213. return lb_emit_struct_ev(p, value, cast(i32)n);
  7214. }
  7215. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  7216. Type *t = base_type(value.type);
  7217. bool is_ptr = false;
  7218. if (is_type_pointer(t)) {
  7219. is_ptr = true;
  7220. t = base_type(type_deref(t));
  7221. }
  7222. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7223. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7224. }
  7225. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  7226. isize n = 0;
  7227. Type *elem = base_type(t->Struct.soa_elem);
  7228. if (elem->kind == Type_Struct) {
  7229. n = elem->Struct.fields.count+1;
  7230. } else if (elem->kind == Type_Array) {
  7231. n = elem->Array.count+1;
  7232. } else {
  7233. GB_PANIC("Unreachable");
  7234. }
  7235. if (is_ptr) {
  7236. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7237. return lb_emit_load(p, v);
  7238. }
  7239. return lb_emit_struct_ev(p, value, cast(i32)n);
  7240. }
  7241. lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7242. GB_ASSERT(ce->args.count > 0);
  7243. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  7244. for_array(i, slices) {
  7245. Ast *arg = ce->args[i];
  7246. if (arg->kind == Ast_FieldValue) {
  7247. arg = arg->FieldValue.value;
  7248. }
  7249. slices[i] = lb_build_expr(p, arg);
  7250. }
  7251. lbValue len = lb_slice_len(p, slices[0]);
  7252. for (isize i = 1; i < slices.count; i++) {
  7253. lbValue other_len = lb_slice_len(p, slices[i]);
  7254. len = lb_emit_min(p, t_int, len, other_len);
  7255. }
  7256. GB_ASSERT(is_type_soa_struct(tv.type));
  7257. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7258. for_array(i, slices) {
  7259. lbValue src = lb_slice_elem(p, slices[i]);
  7260. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  7261. lb_emit_store(p, dst, src);
  7262. }
  7263. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  7264. lb_emit_store(p, len_dst, len);
  7265. return lb_addr_load(p, res);
  7266. }
  7267. lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7268. GB_ASSERT(ce->args.count == 1);
  7269. lbValue arg = lb_build_expr(p, ce->args[0]);
  7270. Type *t = base_type(arg.type);
  7271. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  7272. lbValue len = lb_soa_struct_len(p, arg);
  7273. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7274. if (is_type_tuple(tv.type)) {
  7275. lbValue rp = lb_addr_get_ptr(p, res);
  7276. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  7277. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  7278. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  7279. lb_fill_slice(p, dst, ptr, len);
  7280. }
  7281. } else {
  7282. GB_ASSERT(is_type_slice(tv.type));
  7283. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  7284. lb_fill_slice(p, res, ptr, len);
  7285. }
  7286. return lb_addr_load(p, res);
  7287. }
  7288. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  7289. ast_node(ce, CallExpr, expr);
  7290. switch (id) {
  7291. case BuiltinProc_DIRECTIVE: {
  7292. ast_node(bd, BasicDirective, ce->proc);
  7293. String name = bd->name;
  7294. GB_ASSERT(name == "location");
  7295. String procedure = p->entity->token.string;
  7296. TokenPos pos = ast_token(ce->proc).pos;
  7297. if (ce->args.count > 0) {
  7298. Ast *ident = unselector_expr(ce->args[0]);
  7299. GB_ASSERT(ident->kind == Ast_Ident);
  7300. Entity *e = entity_of_node(ident);
  7301. GB_ASSERT(e != nullptr);
  7302. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  7303. procedure = e->parent_proc_decl->entity->token.string;
  7304. } else {
  7305. procedure = str_lit("");
  7306. }
  7307. pos = e->token.pos;
  7308. }
  7309. return lb_emit_source_code_location(p, procedure, pos);
  7310. }
  7311. case BuiltinProc_type_info_of: {
  7312. Ast *arg = ce->args[0];
  7313. TypeAndValue tav = type_and_value_of_expr(arg);
  7314. if (tav.mode == Addressing_Type) {
  7315. Type *t = default_type(type_of_expr(arg));
  7316. return lb_type_info(p->module, t);
  7317. }
  7318. GB_ASSERT(is_type_typeid(tav.type));
  7319. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7320. args[0] = lb_build_expr(p, arg);
  7321. return lb_emit_runtime_call(p, "__type_info_of", args);
  7322. }
  7323. case BuiltinProc_typeid_of: {
  7324. Ast *arg = ce->args[0];
  7325. TypeAndValue tav = type_and_value_of_expr(arg);
  7326. GB_ASSERT(tav.mode == Addressing_Type);
  7327. Type *t = default_type(type_of_expr(arg));
  7328. return lb_typeid(p->module, t);
  7329. }
  7330. case BuiltinProc_len: {
  7331. lbValue v = lb_build_expr(p, ce->args[0]);
  7332. Type *t = base_type(v.type);
  7333. if (is_type_pointer(t)) {
  7334. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7335. v = lb_emit_load(p, v);
  7336. t = type_deref(t);
  7337. }
  7338. if (is_type_cstring(t)) {
  7339. return lb_cstring_len(p, v);
  7340. } else if (is_type_string(t)) {
  7341. return lb_string_len(p, v);
  7342. } else if (is_type_array(t)) {
  7343. GB_PANIC("Array lengths are constant");
  7344. } else if (is_type_slice(t)) {
  7345. return lb_slice_len(p, v);
  7346. } else if (is_type_dynamic_array(t)) {
  7347. return lb_dynamic_array_len(p, v);
  7348. } else if (is_type_map(t)) {
  7349. return lb_map_len(p, v);
  7350. } else if (is_type_soa_struct(t)) {
  7351. return lb_soa_struct_len(p, v);
  7352. }
  7353. GB_PANIC("Unreachable");
  7354. break;
  7355. }
  7356. case BuiltinProc_cap: {
  7357. lbValue v = lb_build_expr(p, ce->args[0]);
  7358. Type *t = base_type(v.type);
  7359. if (is_type_pointer(t)) {
  7360. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7361. v = lb_emit_load(p, v);
  7362. t = type_deref(t);
  7363. }
  7364. if (is_type_string(t)) {
  7365. GB_PANIC("Unreachable");
  7366. } else if (is_type_array(t)) {
  7367. GB_PANIC("Array lengths are constant");
  7368. } else if (is_type_slice(t)) {
  7369. return lb_slice_len(p, v);
  7370. } else if (is_type_dynamic_array(t)) {
  7371. return lb_dynamic_array_cap(p, v);
  7372. } else if (is_type_map(t)) {
  7373. return lb_map_cap(p, v);
  7374. } else if (is_type_soa_struct(t)) {
  7375. return lb_soa_struct_cap(p, v);
  7376. }
  7377. GB_PANIC("Unreachable");
  7378. break;
  7379. }
  7380. case BuiltinProc_swizzle: {
  7381. isize index_count = ce->args.count-1;
  7382. if (is_type_simd_vector(tv.type)) {
  7383. lbValue vec = lb_build_expr(p, ce->args[0]);
  7384. if (index_count == 0) {
  7385. return vec;
  7386. }
  7387. unsigned mask_len = cast(unsigned)index_count;
  7388. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  7389. for (isize i = 1; i < ce->args.count; i++) {
  7390. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7391. GB_ASSERT(is_type_integer(tv.type));
  7392. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7393. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  7394. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  7395. }
  7396. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  7397. LLVMValueRef v1 = vec.value;
  7398. LLVMValueRef v2 = vec.value;
  7399. lbValue res = {};
  7400. res.type = tv.type;
  7401. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  7402. return res;
  7403. }
  7404. lbAddr addr = lb_build_addr(p, ce->args[0]);
  7405. if (index_count == 0) {
  7406. return lb_addr_load(p, addr);
  7407. }
  7408. lbValue src = lb_addr_get_ptr(p, addr);
  7409. // TODO(bill): Should this be zeroed or not?
  7410. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  7411. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  7412. for (i32 i = 1; i < ce->args.count; i++) {
  7413. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7414. GB_ASSERT(is_type_integer(tv.type));
  7415. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7416. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  7417. i32 dst_index = i-1;
  7418. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  7419. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  7420. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  7421. }
  7422. return lb_addr_load(p, dst);
  7423. }
  7424. case BuiltinProc_complex: {
  7425. lbValue real = lb_build_expr(p, ce->args[0]);
  7426. lbValue imag = lb_build_expr(p, ce->args[1]);
  7427. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7428. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7429. Type *ft = base_complex_elem_type(tv.type);
  7430. real = lb_emit_conv(p, real, ft);
  7431. imag = lb_emit_conv(p, imag, ft);
  7432. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  7433. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  7434. return lb_emit_load(p, dst);
  7435. }
  7436. case BuiltinProc_quaternion: {
  7437. lbValue real = lb_build_expr(p, ce->args[0]);
  7438. lbValue imag = lb_build_expr(p, ce->args[1]);
  7439. lbValue jmag = lb_build_expr(p, ce->args[2]);
  7440. lbValue kmag = lb_build_expr(p, ce->args[3]);
  7441. // @QuaternionLayout
  7442. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7443. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7444. Type *ft = base_complex_elem_type(tv.type);
  7445. real = lb_emit_conv(p, real, ft);
  7446. imag = lb_emit_conv(p, imag, ft);
  7447. jmag = lb_emit_conv(p, jmag, ft);
  7448. kmag = lb_emit_conv(p, kmag, ft);
  7449. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  7450. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  7451. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  7452. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  7453. return lb_emit_load(p, dst);
  7454. }
  7455. case BuiltinProc_real: {
  7456. lbValue val = lb_build_expr(p, ce->args[0]);
  7457. if (is_type_complex(val.type)) {
  7458. lbValue real = lb_emit_struct_ev(p, val, 0);
  7459. return lb_emit_conv(p, real, tv.type);
  7460. } else if (is_type_quaternion(val.type)) {
  7461. // @QuaternionLayout
  7462. lbValue real = lb_emit_struct_ev(p, val, 3);
  7463. return lb_emit_conv(p, real, tv.type);
  7464. }
  7465. GB_PANIC("invalid type for real");
  7466. return {};
  7467. }
  7468. case BuiltinProc_imag: {
  7469. lbValue val = lb_build_expr(p, ce->args[0]);
  7470. if (is_type_complex(val.type)) {
  7471. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7472. return lb_emit_conv(p, imag, tv.type);
  7473. } else if (is_type_quaternion(val.type)) {
  7474. // @QuaternionLayout
  7475. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7476. return lb_emit_conv(p, imag, tv.type);
  7477. }
  7478. GB_PANIC("invalid type for imag");
  7479. return {};
  7480. }
  7481. case BuiltinProc_jmag: {
  7482. lbValue val = lb_build_expr(p, ce->args[0]);
  7483. if (is_type_quaternion(val.type)) {
  7484. // @QuaternionLayout
  7485. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7486. return lb_emit_conv(p, imag, tv.type);
  7487. }
  7488. GB_PANIC("invalid type for jmag");
  7489. return {};
  7490. }
  7491. case BuiltinProc_kmag: {
  7492. lbValue val = lb_build_expr(p, ce->args[0]);
  7493. if (is_type_quaternion(val.type)) {
  7494. // @QuaternionLayout
  7495. lbValue imag = lb_emit_struct_ev(p, val, 2);
  7496. return lb_emit_conv(p, imag, tv.type);
  7497. }
  7498. GB_PANIC("invalid type for kmag");
  7499. return {};
  7500. }
  7501. case BuiltinProc_conj: {
  7502. lbValue val = lb_build_expr(p, ce->args[0]);
  7503. lbValue res = {};
  7504. Type *t = val.type;
  7505. if (is_type_complex(t)) {
  7506. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7507. lbValue real = lb_emit_struct_ev(p, val, 0);
  7508. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7509. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7510. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  7511. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  7512. } else if (is_type_quaternion(t)) {
  7513. // @QuaternionLayout
  7514. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7515. lbValue real = lb_emit_struct_ev(p, val, 3);
  7516. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7517. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  7518. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  7519. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7520. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  7521. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  7522. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  7523. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  7524. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  7525. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  7526. }
  7527. return lb_emit_load(p, res);
  7528. }
  7529. case BuiltinProc_expand_to_tuple: {
  7530. lbValue val = lb_build_expr(p, ce->args[0]);
  7531. Type *t = base_type(val.type);
  7532. if (!is_type_tuple(tv.type)) {
  7533. if (t->kind == Type_Struct) {
  7534. GB_ASSERT(t->Struct.fields.count == 1);
  7535. return lb_emit_struct_ev(p, val, 0);
  7536. } else if (t->kind == Type_Array) {
  7537. GB_ASSERT(t->Array.count == 1);
  7538. return lb_emit_array_epi(p, val, 0);
  7539. } else {
  7540. GB_PANIC("Unknown type of expand_to_tuple");
  7541. }
  7542. }
  7543. GB_ASSERT(is_type_tuple(tv.type));
  7544. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  7545. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7546. if (t->kind == Type_Struct) {
  7547. for_array(src_index, t->Struct.fields) {
  7548. Entity *field = t->Struct.fields[src_index];
  7549. i32 field_index = field->Variable.field_index;
  7550. lbValue f = lb_emit_struct_ev(p, val, field_index);
  7551. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  7552. lb_emit_store(p, ep, f);
  7553. }
  7554. } else if (t->kind == Type_Array) {
  7555. // TODO(bill): Clean-up this code
  7556. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  7557. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  7558. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  7559. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  7560. lb_emit_store(p, ep, f);
  7561. }
  7562. } else {
  7563. GB_PANIC("Unknown type of expand_to_tuple");
  7564. }
  7565. return lb_emit_load(p, tuple);
  7566. }
  7567. case BuiltinProc_min: {
  7568. Type *t = type_of_expr(expr);
  7569. if (ce->args.count == 2) {
  7570. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7571. } else {
  7572. lbValue x = lb_build_expr(p, ce->args[0]);
  7573. for (isize i = 1; i < ce->args.count; i++) {
  7574. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  7575. }
  7576. return x;
  7577. }
  7578. }
  7579. case BuiltinProc_max: {
  7580. Type *t = type_of_expr(expr);
  7581. if (ce->args.count == 2) {
  7582. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7583. } else {
  7584. lbValue x = lb_build_expr(p, ce->args[0]);
  7585. for (isize i = 1; i < ce->args.count; i++) {
  7586. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  7587. }
  7588. return x;
  7589. }
  7590. }
  7591. case BuiltinProc_abs: {
  7592. lbValue x = lb_build_expr(p, ce->args[0]);
  7593. Type *t = x.type;
  7594. if (is_type_unsigned(t)) {
  7595. return x;
  7596. }
  7597. if (is_type_quaternion(t)) {
  7598. i64 sz = 8*type_size_of(t);
  7599. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7600. args[0] = x;
  7601. switch (sz) {
  7602. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  7603. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  7604. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  7605. }
  7606. GB_PANIC("Unknown complex type");
  7607. } else if (is_type_complex(t)) {
  7608. i64 sz = 8*type_size_of(t);
  7609. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7610. args[0] = x;
  7611. switch (sz) {
  7612. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  7613. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  7614. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  7615. }
  7616. GB_PANIC("Unknown complex type");
  7617. } else if (is_type_float(t)) {
  7618. i64 sz = 8*type_size_of(t);
  7619. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7620. args[0] = x;
  7621. switch (sz) {
  7622. case 16: return lb_emit_runtime_call(p, "abs_f16", args);
  7623. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  7624. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  7625. }
  7626. GB_PANIC("Unknown float type");
  7627. }
  7628. lbValue zero = lb_const_nil(p->module, t);
  7629. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  7630. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  7631. return lb_emit_select(p, cond, neg, x);
  7632. }
  7633. case BuiltinProc_clamp:
  7634. return lb_emit_clamp(p, type_of_expr(expr),
  7635. lb_build_expr(p, ce->args[0]),
  7636. lb_build_expr(p, ce->args[1]),
  7637. lb_build_expr(p, ce->args[2]));
  7638. case BuiltinProc_soa_zip:
  7639. return lb_soa_zip(p, ce, tv);
  7640. case BuiltinProc_soa_unzip:
  7641. return lb_soa_unzip(p, ce, tv);
  7642. // "Intrinsics"
  7643. case BuiltinProc_alloca:
  7644. {
  7645. lbValue sz = lb_build_expr(p, ce->args[0]);
  7646. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  7647. lbValue res = {};
  7648. res.type = t_u8_ptr;
  7649. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  7650. LLVMSetAlignment(res.value, cast(unsigned)al);
  7651. return res;
  7652. }
  7653. case BuiltinProc_cpu_relax:
  7654. if (build_context.metrics.arch == TargetArch_386 ||
  7655. build_context.metrics.arch == TargetArch_amd64) {
  7656. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7657. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7658. cast(char *)"pause", 5,
  7659. cast(char *)"", 0,
  7660. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7661. LLVMInlineAsmDialectATT
  7662. );
  7663. GB_ASSERT(the_asm != nullptr);
  7664. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7665. } else if (build_context.metrics.arch == TargetArch_arm64) {
  7666. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7667. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7668. cast(char *)"yield", 5,
  7669. cast(char *)"", 0,
  7670. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7671. LLVMInlineAsmDialectATT
  7672. );
  7673. GB_ASSERT(the_asm != nullptr);
  7674. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7675. }
  7676. return {};
  7677. case BuiltinProc_debug_trap:
  7678. case BuiltinProc_trap:
  7679. {
  7680. char const *name = nullptr;
  7681. switch (id) {
  7682. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  7683. case BuiltinProc_trap: name = "llvm.trap"; break;
  7684. }
  7685. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  7686. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  7687. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  7688. LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  7689. if (id == BuiltinProc_trap) {
  7690. LLVMBuildUnreachable(p->builder);
  7691. }
  7692. return {};
  7693. }
  7694. case BuiltinProc_read_cycle_counter:
  7695. {
  7696. char const *name = "llvm.readcyclecounter";
  7697. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  7698. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  7699. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  7700. lbValue res = {};
  7701. res.value = LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  7702. res.type = tv.type;
  7703. return res;
  7704. }
  7705. case BuiltinProc_count_trailing_zeros:
  7706. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  7707. case BuiltinProc_count_leading_zeros:
  7708. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  7709. case BuiltinProc_count_ones:
  7710. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  7711. case BuiltinProc_count_zeros:
  7712. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  7713. case BuiltinProc_reverse_bits:
  7714. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  7715. case BuiltinProc_byte_swap:
  7716. {
  7717. lbValue x = lb_build_expr(p, ce->args[0]);
  7718. x = lb_emit_conv(p, x, tv.type);
  7719. return lb_emit_byte_swap(p, x, tv.type);
  7720. }
  7721. case BuiltinProc_overflow_add:
  7722. case BuiltinProc_overflow_sub:
  7723. case BuiltinProc_overflow_mul:
  7724. {
  7725. Type *main_type = tv.type;
  7726. Type *type = main_type;
  7727. if (is_type_tuple(main_type)) {
  7728. type = main_type->Tuple.variables[0]->type;
  7729. }
  7730. lbValue x = lb_build_expr(p, ce->args[0]);
  7731. lbValue y = lb_build_expr(p, ce->args[1]);
  7732. x = lb_emit_conv(p, x, type);
  7733. y = lb_emit_conv(p, y, type);
  7734. char const *name = nullptr;
  7735. if (is_type_unsigned(type)) {
  7736. switch (id) {
  7737. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  7738. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  7739. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  7740. }
  7741. } else {
  7742. switch (id) {
  7743. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  7744. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  7745. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  7746. }
  7747. }
  7748. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  7749. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  7750. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  7751. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  7752. LLVMValueRef args[2] = {};
  7753. args[0] = x.value;
  7754. args[1] = y.value;
  7755. lbValue res = {};
  7756. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  7757. if (is_type_tuple(main_type)) {
  7758. Type *res_type = nullptr;
  7759. gbAllocator a = permanent_allocator();
  7760. res_type = alloc_type_tuple();
  7761. array_init(&res_type->Tuple.variables, a, 2);
  7762. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  7763. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  7764. res.type = res_type;
  7765. } else {
  7766. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  7767. res.type = type;
  7768. }
  7769. return res;
  7770. }
  7771. case BuiltinProc_atomic_fence:
  7772. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  7773. return {};
  7774. case BuiltinProc_atomic_fence_acq:
  7775. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  7776. return {};
  7777. case BuiltinProc_atomic_fence_rel:
  7778. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  7779. return {};
  7780. case BuiltinProc_atomic_fence_acqrel:
  7781. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  7782. return {};
  7783. case BuiltinProc_volatile_store:
  7784. case BuiltinProc_atomic_store:
  7785. case BuiltinProc_atomic_store_rel:
  7786. case BuiltinProc_atomic_store_relaxed:
  7787. case BuiltinProc_atomic_store_unordered: {
  7788. lbValue dst = lb_build_expr(p, ce->args[0]);
  7789. lbValue val = lb_build_expr(p, ce->args[1]);
  7790. val = lb_emit_conv(p, val, type_deref(dst.type));
  7791. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  7792. switch (id) {
  7793. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  7794. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7795. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  7796. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7797. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7798. }
  7799. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7800. return {};
  7801. }
  7802. case BuiltinProc_volatile_load:
  7803. case BuiltinProc_atomic_load:
  7804. case BuiltinProc_atomic_load_acq:
  7805. case BuiltinProc_atomic_load_relaxed:
  7806. case BuiltinProc_atomic_load_unordered: {
  7807. lbValue dst = lb_build_expr(p, ce->args[0]);
  7808. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  7809. switch (id) {
  7810. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  7811. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7812. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  7813. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7814. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7815. }
  7816. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7817. lbValue res = {};
  7818. res.value = instr;
  7819. res.type = type_deref(dst.type);
  7820. return res;
  7821. }
  7822. case BuiltinProc_atomic_add:
  7823. case BuiltinProc_atomic_add_acq:
  7824. case BuiltinProc_atomic_add_rel:
  7825. case BuiltinProc_atomic_add_acqrel:
  7826. case BuiltinProc_atomic_add_relaxed:
  7827. case BuiltinProc_atomic_sub:
  7828. case BuiltinProc_atomic_sub_acq:
  7829. case BuiltinProc_atomic_sub_rel:
  7830. case BuiltinProc_atomic_sub_acqrel:
  7831. case BuiltinProc_atomic_sub_relaxed:
  7832. case BuiltinProc_atomic_and:
  7833. case BuiltinProc_atomic_and_acq:
  7834. case BuiltinProc_atomic_and_rel:
  7835. case BuiltinProc_atomic_and_acqrel:
  7836. case BuiltinProc_atomic_and_relaxed:
  7837. case BuiltinProc_atomic_nand:
  7838. case BuiltinProc_atomic_nand_acq:
  7839. case BuiltinProc_atomic_nand_rel:
  7840. case BuiltinProc_atomic_nand_acqrel:
  7841. case BuiltinProc_atomic_nand_relaxed:
  7842. case BuiltinProc_atomic_or:
  7843. case BuiltinProc_atomic_or_acq:
  7844. case BuiltinProc_atomic_or_rel:
  7845. case BuiltinProc_atomic_or_acqrel:
  7846. case BuiltinProc_atomic_or_relaxed:
  7847. case BuiltinProc_atomic_xor:
  7848. case BuiltinProc_atomic_xor_acq:
  7849. case BuiltinProc_atomic_xor_rel:
  7850. case BuiltinProc_atomic_xor_acqrel:
  7851. case BuiltinProc_atomic_xor_relaxed:
  7852. case BuiltinProc_atomic_xchg:
  7853. case BuiltinProc_atomic_xchg_acq:
  7854. case BuiltinProc_atomic_xchg_rel:
  7855. case BuiltinProc_atomic_xchg_acqrel:
  7856. case BuiltinProc_atomic_xchg_relaxed: {
  7857. lbValue dst = lb_build_expr(p, ce->args[0]);
  7858. lbValue val = lb_build_expr(p, ce->args[1]);
  7859. val = lb_emit_conv(p, val, type_deref(dst.type));
  7860. LLVMAtomicRMWBinOp op = {};
  7861. LLVMAtomicOrdering ordering = {};
  7862. switch (id) {
  7863. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7864. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  7865. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  7866. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7867. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  7868. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7869. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  7870. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  7871. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7872. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  7873. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7874. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  7875. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  7876. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7877. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  7878. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7879. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  7880. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  7881. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7882. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  7883. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7884. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  7885. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  7886. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7887. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  7888. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7889. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  7890. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  7891. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7892. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  7893. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7894. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  7895. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  7896. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7897. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  7898. }
  7899. lbValue res = {};
  7900. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  7901. res.type = tv.type;
  7902. return res;
  7903. }
  7904. case BuiltinProc_atomic_cxchg:
  7905. case BuiltinProc_atomic_cxchg_acq:
  7906. case BuiltinProc_atomic_cxchg_rel:
  7907. case BuiltinProc_atomic_cxchg_acqrel:
  7908. case BuiltinProc_atomic_cxchg_relaxed:
  7909. case BuiltinProc_atomic_cxchg_failrelaxed:
  7910. case BuiltinProc_atomic_cxchg_failacq:
  7911. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  7912. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  7913. case BuiltinProc_atomic_cxchgweak:
  7914. case BuiltinProc_atomic_cxchgweak_acq:
  7915. case BuiltinProc_atomic_cxchgweak_rel:
  7916. case BuiltinProc_atomic_cxchgweak_acqrel:
  7917. case BuiltinProc_atomic_cxchgweak_relaxed:
  7918. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  7919. case BuiltinProc_atomic_cxchgweak_failacq:
  7920. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  7921. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  7922. Type *type = expr->tav.type;
  7923. lbValue address = lb_build_expr(p, ce->args[0]);
  7924. Type *elem = type_deref(address.type);
  7925. lbValue old_value = lb_build_expr(p, ce->args[1]);
  7926. lbValue new_value = lb_build_expr(p, ce->args[2]);
  7927. old_value = lb_emit_conv(p, old_value, elem);
  7928. new_value = lb_emit_conv(p, new_value, elem);
  7929. LLVMAtomicOrdering success_ordering = {};
  7930. LLVMAtomicOrdering failure_ordering = {};
  7931. LLVMBool weak = false;
  7932. switch (id) {
  7933. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7934. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7935. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7936. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7937. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7938. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7939. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  7940. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7941. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7942. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7943. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7944. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7945. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7946. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7947. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7948. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  7949. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7950. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7951. }
  7952. // TODO(bill): Figure out how to make it weak
  7953. LLVMBool single_threaded = weak;
  7954. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  7955. p->builder, address.value,
  7956. old_value.value, new_value.value,
  7957. success_ordering,
  7958. failure_ordering,
  7959. single_threaded
  7960. );
  7961. if (tv.type->kind == Type_Tuple) {
  7962. Type *fix_typed = alloc_type_tuple();
  7963. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  7964. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  7965. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  7966. lbValue res = {};
  7967. res.value = value;
  7968. res.type = fix_typed;
  7969. return res;
  7970. } else {
  7971. lbValue res = {};
  7972. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  7973. res.type = tv.type;
  7974. return res;
  7975. }
  7976. }
  7977. case BuiltinProc_type_equal_proc:
  7978. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  7979. case BuiltinProc_type_hasher_proc:
  7980. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  7981. case BuiltinProc_fixed_point_mul:
  7982. case BuiltinProc_fixed_point_div:
  7983. case BuiltinProc_fixed_point_mul_sat:
  7984. case BuiltinProc_fixed_point_div_sat:
  7985. {
  7986. bool do_bswap = is_type_different_to_arch_endianness(tv.type);
  7987. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  7988. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  7989. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  7990. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), platform_type);
  7991. char const *name = nullptr;
  7992. if (is_type_unsigned(tv.type)) {
  7993. switch (id) {
  7994. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  7995. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  7996. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  7997. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  7998. }
  7999. } else {
  8000. switch (id) {
  8001. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  8002. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  8003. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  8004. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  8005. }
  8006. }
  8007. GB_ASSERT(name != nullptr);
  8008. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  8009. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8010. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8011. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8012. lbValue res = {};
  8013. LLVMValueRef args[3] = {};
  8014. args[0] = x.value;
  8015. args[1] = y.value;
  8016. args[2] = scale.value;
  8017. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8018. res.type = platform_type;
  8019. return lb_emit_conv(p, res, tv.type);
  8020. }
  8021. case BuiltinProc_expect:
  8022. {
  8023. Type *t = default_type(tv.type);
  8024. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  8025. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  8026. char const *name = "llvm.expect";
  8027. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  8028. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8029. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8030. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8031. lbValue res = {};
  8032. LLVMValueRef args[2] = {};
  8033. args[0] = x.value;
  8034. args[1] = y.value;
  8035. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8036. res.type = t;
  8037. return lb_emit_conv(p, res, t);
  8038. }
  8039. }
  8040. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  8041. return {};
  8042. }
  8043. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  8044. switch (param_value.kind) {
  8045. case ParameterValue_Constant:
  8046. if (is_type_constant_type(parameter_type)) {
  8047. return lb_const_value(p->module, parameter_type, param_value.value);
  8048. } else {
  8049. ExactValue ev = param_value.value;
  8050. lbValue arg = {};
  8051. Type *type = type_of_expr(param_value.original_ast_expr);
  8052. if (type != nullptr) {
  8053. arg = lb_const_value(p->module, type, ev);
  8054. } else {
  8055. arg = lb_const_value(p->module, parameter_type, param_value.value);
  8056. }
  8057. return lb_emit_conv(p, arg, parameter_type);
  8058. }
  8059. case ParameterValue_Nil:
  8060. return lb_const_nil(p->module, parameter_type);
  8061. case ParameterValue_Location:
  8062. {
  8063. String proc_name = {};
  8064. if (p->entity != nullptr) {
  8065. proc_name = p->entity->token.string;
  8066. }
  8067. return lb_emit_source_code_location(p, proc_name, pos);
  8068. }
  8069. case ParameterValue_Value:
  8070. return lb_build_expr(p, param_value.ast_value);
  8071. }
  8072. return lb_const_nil(p->module, parameter_type);
  8073. }
  8074. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  8075. lbModule *m = p->module;
  8076. TypeAndValue tv = type_and_value_of_expr(expr);
  8077. ast_node(ce, CallExpr, expr);
  8078. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  8079. AddressingMode proc_mode = proc_tv.mode;
  8080. if (proc_mode == Addressing_Type) {
  8081. GB_ASSERT(ce->args.count == 1);
  8082. lbValue x = lb_build_expr(p, ce->args[0]);
  8083. lbValue y = lb_emit_conv(p, x, tv.type);
  8084. return y;
  8085. }
  8086. Ast *pexpr = unparen_expr(ce->proc);
  8087. if (proc_mode == Addressing_Builtin) {
  8088. Entity *e = entity_of_node(pexpr);
  8089. BuiltinProcId id = BuiltinProc_Invalid;
  8090. if (e != nullptr) {
  8091. id = cast(BuiltinProcId)e->Builtin.id;
  8092. } else {
  8093. id = BuiltinProc_DIRECTIVE;
  8094. }
  8095. return lb_build_builtin_proc(p, expr, tv, id);
  8096. }
  8097. // NOTE(bill): Regular call
  8098. lbValue value = {};
  8099. Ast *proc_expr = unparen_expr(ce->proc);
  8100. if (proc_expr->tav.mode == Addressing_Constant) {
  8101. ExactValue v = proc_expr->tav.value;
  8102. switch (v.kind) {
  8103. case ExactValue_Integer:
  8104. {
  8105. u64 u = big_int_to_u64(&v.value_integer);
  8106. lbValue x = {};
  8107. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  8108. x.type = t_uintptr;
  8109. x = lb_emit_conv(p, x, t_rawptr);
  8110. value = lb_emit_conv(p, x, proc_expr->tav.type);
  8111. break;
  8112. }
  8113. case ExactValue_Pointer:
  8114. {
  8115. u64 u = cast(u64)v.value_pointer;
  8116. lbValue x = {};
  8117. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  8118. x.type = t_uintptr;
  8119. x = lb_emit_conv(p, x, t_rawptr);
  8120. value = lb_emit_conv(p, x, proc_expr->tav.type);
  8121. break;
  8122. }
  8123. }
  8124. }
  8125. Entity *proc_entity = entity_of_node(proc_expr);
  8126. if (proc_entity != nullptr) {
  8127. if (proc_entity->flags & EntityFlag_Disabled) {
  8128. return {};
  8129. }
  8130. }
  8131. if (value.value == nullptr) {
  8132. value = lb_build_expr(p, proc_expr);
  8133. }
  8134. GB_ASSERT(value.value != nullptr);
  8135. Type *proc_type_ = base_type(value.type);
  8136. GB_ASSERT(proc_type_->kind == Type_Proc);
  8137. TypeProc *pt = &proc_type_->Proc;
  8138. if (is_call_expr_field_value(ce)) {
  8139. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  8140. for_array(arg_index, ce->args) {
  8141. Ast *arg = ce->args[arg_index];
  8142. ast_node(fv, FieldValue, arg);
  8143. GB_ASSERT(fv->field->kind == Ast_Ident);
  8144. String name = fv->field->Ident.token.string;
  8145. isize index = lookup_procedure_parameter(pt, name);
  8146. GB_ASSERT(index >= 0);
  8147. TypeAndValue tav = type_and_value_of_expr(fv->value);
  8148. if (tav.mode == Addressing_Type) {
  8149. args[index] = lb_const_nil(m, tav.type);
  8150. } else {
  8151. args[index] = lb_build_expr(p, fv->value);
  8152. }
  8153. }
  8154. TypeTuple *params = &pt->params->Tuple;
  8155. for (isize i = 0; i < args.count; i++) {
  8156. Entity *e = params->variables[i];
  8157. if (e->kind == Entity_TypeName) {
  8158. args[i] = lb_const_nil(m, e->type);
  8159. } else if (e->kind == Entity_Constant) {
  8160. continue;
  8161. } else {
  8162. GB_ASSERT(e->kind == Entity_Variable);
  8163. if (args[i].value == nullptr) {
  8164. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8165. } else {
  8166. args[i] = lb_emit_conv(p, args[i], e->type);
  8167. }
  8168. }
  8169. }
  8170. for (isize i = 0; i < args.count; i++) {
  8171. Entity *e = params->variables[i];
  8172. if (args[i].type == nullptr) {
  8173. continue;
  8174. } else if (is_type_untyped_nil(args[i].type)) {
  8175. args[i] = lb_const_nil(m, e->type);
  8176. } else if (is_type_untyped_undef(args[i].type)) {
  8177. args[i] = lb_const_undef(m, e->type);
  8178. }
  8179. }
  8180. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  8181. }
  8182. isize arg_index = 0;
  8183. isize arg_count = 0;
  8184. for_array(i, ce->args) {
  8185. Ast *arg = ce->args[i];
  8186. TypeAndValue tav = type_and_value_of_expr(arg);
  8187. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  8188. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  8189. Type *at = tav.type;
  8190. if (at->kind == Type_Tuple) {
  8191. arg_count += at->Tuple.variables.count;
  8192. } else {
  8193. arg_count++;
  8194. }
  8195. }
  8196. isize param_count = 0;
  8197. if (pt->params) {
  8198. GB_ASSERT(pt->params->kind == Type_Tuple);
  8199. param_count = pt->params->Tuple.variables.count;
  8200. }
  8201. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  8202. isize variadic_index = pt->variadic_index;
  8203. bool variadic = pt->variadic && variadic_index >= 0;
  8204. bool vari_expand = ce->ellipsis.pos.line != 0;
  8205. bool is_c_vararg = pt->c_vararg;
  8206. String proc_name = {};
  8207. if (p->entity != nullptr) {
  8208. proc_name = p->entity->token.string;
  8209. }
  8210. TokenPos pos = ast_token(ce->proc).pos;
  8211. TypeTuple *param_tuple = nullptr;
  8212. if (pt->params) {
  8213. GB_ASSERT(pt->params->kind == Type_Tuple);
  8214. param_tuple = &pt->params->Tuple;
  8215. }
  8216. for_array(i, ce->args) {
  8217. Ast *arg = ce->args[i];
  8218. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  8219. if (arg_tv.mode == Addressing_Type) {
  8220. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  8221. } else {
  8222. lbValue a = lb_build_expr(p, arg);
  8223. Type *at = a.type;
  8224. if (at->kind == Type_Tuple) {
  8225. for_array(i, at->Tuple.variables) {
  8226. Entity *e = at->Tuple.variables[i];
  8227. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  8228. args[arg_index++] = v;
  8229. }
  8230. } else {
  8231. args[arg_index++] = a;
  8232. }
  8233. }
  8234. }
  8235. if (param_count > 0) {
  8236. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  8237. GB_ASSERT(param_count < 1000000);
  8238. if (arg_count < param_count) {
  8239. isize end = cast(isize)param_count;
  8240. if (variadic) {
  8241. end = variadic_index;
  8242. }
  8243. while (arg_index < end) {
  8244. Entity *e = param_tuple->variables[arg_index];
  8245. GB_ASSERT(e->kind == Entity_Variable);
  8246. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8247. }
  8248. }
  8249. if (is_c_vararg) {
  8250. GB_ASSERT(variadic);
  8251. GB_ASSERT(!vari_expand);
  8252. isize i = 0;
  8253. for (; i < variadic_index; i++) {
  8254. Entity *e = param_tuple->variables[i];
  8255. if (e->kind == Entity_Variable) {
  8256. args[i] = lb_emit_conv(p, args[i], e->type);
  8257. }
  8258. }
  8259. Type *variadic_type = param_tuple->variables[i]->type;
  8260. GB_ASSERT(is_type_slice(variadic_type));
  8261. variadic_type = base_type(variadic_type)->Slice.elem;
  8262. if (!is_type_any(variadic_type)) {
  8263. for (; i < arg_count; i++) {
  8264. args[i] = lb_emit_conv(p, args[i], variadic_type);
  8265. }
  8266. } else {
  8267. for (; i < arg_count; i++) {
  8268. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  8269. }
  8270. }
  8271. } else if (variadic) {
  8272. isize i = 0;
  8273. for (; i < variadic_index; i++) {
  8274. Entity *e = param_tuple->variables[i];
  8275. if (e->kind == Entity_Variable) {
  8276. args[i] = lb_emit_conv(p, args[i], e->type);
  8277. }
  8278. }
  8279. if (!vari_expand) {
  8280. Type *variadic_type = param_tuple->variables[i]->type;
  8281. GB_ASSERT(is_type_slice(variadic_type));
  8282. variadic_type = base_type(variadic_type)->Slice.elem;
  8283. for (; i < arg_count; i++) {
  8284. args[i] = lb_emit_conv(p, args[i], variadic_type);
  8285. }
  8286. }
  8287. } else {
  8288. for (isize i = 0; i < param_count; i++) {
  8289. Entity *e = param_tuple->variables[i];
  8290. if (e->kind == Entity_Variable) {
  8291. if (args[i].value == nullptr) {
  8292. continue;
  8293. }
  8294. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  8295. args[i] = lb_emit_conv(p, args[i], e->type);
  8296. }
  8297. }
  8298. }
  8299. if (variadic && !vari_expand && !is_c_vararg) {
  8300. // variadic call argument generation
  8301. Type *slice_type = param_tuple->variables[variadic_index]->type;
  8302. Type *elem_type = base_type(slice_type)->Slice.elem;
  8303. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  8304. isize slice_len = arg_count+1 - (variadic_index+1);
  8305. if (slice_len > 0) {
  8306. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  8307. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  8308. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  8309. lb_emit_store(p, addr, args[i]);
  8310. }
  8311. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  8312. lbValue len = lb_const_int(m, t_int, slice_len);
  8313. lb_fill_slice(p, slice, base_elem, len);
  8314. }
  8315. arg_count = param_count;
  8316. args[variadic_index] = lb_addr_load(p, slice);
  8317. }
  8318. }
  8319. if (variadic && variadic_index+1 < param_count) {
  8320. for (isize i = variadic_index+1; i < param_count; i++) {
  8321. Entity *e = param_tuple->variables[i];
  8322. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  8323. }
  8324. }
  8325. isize final_count = param_count;
  8326. if (is_c_vararg) {
  8327. final_count = arg_count;
  8328. }
  8329. if (param_tuple != nullptr) {
  8330. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  8331. Entity *e = param_tuple->variables[i];
  8332. if (args[i].type == nullptr) {
  8333. continue;
  8334. } else if (is_type_untyped_nil(args[i].type)) {
  8335. args[i] = lb_const_nil(m, e->type);
  8336. } else if (is_type_untyped_undef(args[i].type)) {
  8337. args[i] = lb_const_undef(m, e->type);
  8338. }
  8339. }
  8340. }
  8341. auto call_args = array_slice(args, 0, final_count);
  8342. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  8343. }
  8344. bool lb_is_const(lbValue value) {
  8345. LLVMValueRef v = value.value;
  8346. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  8347. // TODO(bill): Is this correct behaviour?
  8348. return true;
  8349. }
  8350. if (LLVMIsConstant(v)) {
  8351. return true;
  8352. }
  8353. return false;
  8354. }
  8355. bool lb_is_const_or_global(lbValue value) {
  8356. if (lb_is_const(value)) {
  8357. return true;
  8358. }
  8359. if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
  8360. LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
  8361. if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
  8362. return false;
  8363. }
  8364. LLVMTypeRef elem = LLVMGetElementType(t);
  8365. return lb_is_type_kind(elem, LLVMFunctionTypeKind);
  8366. }
  8367. return false;
  8368. }
  8369. bool lb_is_const_nil(lbValue value) {
  8370. LLVMValueRef v = value.value;
  8371. if (LLVMIsConstant(v)) {
  8372. if (LLVMIsAConstantAggregateZero(v)) {
  8373. return true;
  8374. } else if (LLVMIsAConstantPointerNull(v)) {
  8375. return true;
  8376. }
  8377. }
  8378. return false;
  8379. }
  8380. String lb_get_const_string(lbModule *m, lbValue value) {
  8381. GB_ASSERT(lb_is_const(value));
  8382. GB_ASSERT(LLVMIsConstant(value.value));
  8383. Type *t = base_type(value.type);
  8384. GB_ASSERT(are_types_identical(t, t_string));
  8385. unsigned ptr_indices[1] = {0};
  8386. unsigned len_indices[1] = {1};
  8387. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  8388. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  8389. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  8390. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  8391. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  8392. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  8393. size_t length = 0;
  8394. char const *text = LLVMGetAsString(underlying_ptr, &length);
  8395. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  8396. return make_string(cast(u8 const *)text, real_length);
  8397. }
  8398. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  8399. GB_ASSERT(is_type_pointer(addr.type));
  8400. Type *type = type_deref(addr.type);
  8401. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  8402. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  8403. }
  8404. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  8405. AstPackage *pkg = m->info->runtime_package;
  8406. Entity *e = scope_lookup_current(pkg->scope, name);
  8407. lbValue *found = nullptr;
  8408. if (m != e->code_gen_module) {
  8409. gb_mutex_lock(&m->mutex);
  8410. }
  8411. GB_ASSERT(e->code_gen_module != nullptr);
  8412. found = map_get(&e->code_gen_module->values, hash_entity(e));
  8413. if (m != e->code_gen_module) {
  8414. gb_mutex_unlock(&m->mutex);
  8415. }
  8416. GB_ASSERT(found != nullptr);
  8417. return found->value;
  8418. }
  8419. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *end_type) {
  8420. GB_ASSERT(type_size_of(value.type) == type_size_of(end_type));
  8421. if (type_size_of(value.type) < 2) {
  8422. return value;
  8423. }
  8424. Type *original_type = value.type;
  8425. if (is_type_float(original_type)) {
  8426. i64 sz = type_size_of(original_type);
  8427. Type *integer_type = nullptr;
  8428. switch (sz) {
  8429. case 2: integer_type = t_u16; break;
  8430. case 4: integer_type = t_u32; break;
  8431. case 8: integer_type = t_u64; break;
  8432. }
  8433. GB_ASSERT(integer_type != nullptr);
  8434. value = lb_emit_transmute(p, value, integer_type);
  8435. }
  8436. char const *name = "llvm.bswap";
  8437. LLVMTypeRef types[1] = {lb_type(p->module, value.type)};
  8438. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8439. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8440. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8441. LLVMValueRef args[1] = {};
  8442. args[0] = value.value;
  8443. lbValue res = {};
  8444. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8445. res.type = value.type;
  8446. if (is_type_float(original_type)) {
  8447. res = lb_emit_transmute(p, res, original_type);
  8448. }
  8449. res.type = end_type;
  8450. return res;
  8451. }
  8452. lbValue lb_emit_count_ones(lbProcedure *p, lbValue x, Type *type) {
  8453. x = lb_emit_conv(p, x, type);
  8454. char const *name = "llvm.ctpop";
  8455. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8456. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8457. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8458. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8459. LLVMValueRef args[1] = {};
  8460. args[0] = x.value;
  8461. lbValue res = {};
  8462. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8463. res.type = type;
  8464. return res;
  8465. }
  8466. lbValue lb_emit_count_zeros(lbProcedure *p, lbValue x, Type *type) {
  8467. i64 sz = 8*type_size_of(type);
  8468. lbValue size = lb_const_int(p->module, type, cast(u64)sz);
  8469. lbValue count = lb_emit_count_ones(p, x, type);
  8470. return lb_emit_arith(p, Token_Sub, size, count, type);
  8471. }
  8472. lbValue lb_emit_count_trailing_zeros(lbProcedure *p, lbValue x, Type *type) {
  8473. x = lb_emit_conv(p, x, type);
  8474. char const *name = "llvm.cttz";
  8475. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8476. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8477. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8478. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8479. LLVMValueRef args[2] = {};
  8480. args[0] = x.value;
  8481. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  8482. lbValue res = {};
  8483. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8484. res.type = type;
  8485. return res;
  8486. }
  8487. lbValue lb_emit_count_leading_zeros(lbProcedure *p, lbValue x, Type *type) {
  8488. x = lb_emit_conv(p, x, type);
  8489. char const *name = "llvm.ctlz";
  8490. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8491. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8492. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8493. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8494. LLVMValueRef args[2] = {};
  8495. args[0] = x.value;
  8496. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  8497. lbValue res = {};
  8498. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8499. res.type = type;
  8500. return res;
  8501. }
  8502. lbValue lb_emit_reverse_bits(lbProcedure *p, lbValue x, Type *type) {
  8503. x = lb_emit_conv(p, x, type);
  8504. char const *name = "llvm.bitreverse";
  8505. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8506. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8507. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8508. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8509. LLVMValueRef args[1] = {};
  8510. args[0] = x.value;
  8511. lbValue res = {};
  8512. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8513. res.type = type;
  8514. return res;
  8515. }
  8516. lbValue lb_emit_bit_set_card(lbProcedure *p, lbValue x) {
  8517. GB_ASSERT(is_type_bit_set(x.type));
  8518. Type *underlying = bit_set_to_int(x.type);
  8519. lbValue card = lb_emit_count_ones(p, x, underlying);
  8520. return lb_emit_conv(p, card, t_int);
  8521. }
  8522. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  8523. lbLoopData data = {};
  8524. lbValue max = lb_const_int(p->module, t_int, count);
  8525. data.idx_addr = lb_add_local_generated(p, index_type, true);
  8526. data.body = lb_create_block(p, "loop.body");
  8527. data.done = lb_create_block(p, "loop.done");
  8528. data.loop = lb_create_block(p, "loop.loop");
  8529. lb_emit_jump(p, data.loop);
  8530. lb_start_block(p, data.loop);
  8531. data.idx = lb_addr_load(p, data.idx_addr);
  8532. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  8533. lb_emit_if(p, cond, data.body, data.done);
  8534. lb_start_block(p, data.body);
  8535. return data;
  8536. }
  8537. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  8538. if (data.idx_addr.addr.value != nullptr) {
  8539. lb_emit_increment(p, data.idx_addr.addr);
  8540. lb_emit_jump(p, data.loop);
  8541. lb_start_block(p, data.done);
  8542. }
  8543. }
  8544. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  8545. lbValue res = {};
  8546. res.type = t_llvm_bool;
  8547. Type *t = x.type;
  8548. if (is_type_pointer(t)) {
  8549. if (op_kind == Token_CmpEq) {
  8550. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8551. } else if (op_kind == Token_NotEq) {
  8552. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8553. }
  8554. return res;
  8555. } else if (is_type_cstring(t)) {
  8556. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  8557. if (op_kind == Token_CmpEq) {
  8558. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  8559. } else if (op_kind == Token_NotEq) {
  8560. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  8561. }
  8562. return res;
  8563. } else if (is_type_proc(t)) {
  8564. if (op_kind == Token_CmpEq) {
  8565. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8566. } else if (op_kind == Token_NotEq) {
  8567. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8568. }
  8569. return res;
  8570. } else if (is_type_any(t)) {
  8571. // TODO(bill): is this correct behaviour for nil comparison for any?
  8572. lbValue data = lb_emit_struct_ev(p, x, 0);
  8573. lbValue ti = lb_emit_struct_ev(p, x, 1);
  8574. if (op_kind == Token_CmpEq) {
  8575. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  8576. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  8577. res.value = LLVMBuildOr(p->builder, a, b, "");
  8578. return res;
  8579. } else if (op_kind == Token_NotEq) {
  8580. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  8581. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  8582. res.value = LLVMBuildAnd(p->builder, a, b, "");
  8583. return res;
  8584. }
  8585. } else if (is_type_slice(t)) {
  8586. lbValue len = lb_emit_struct_ev(p, x, 1);
  8587. if (op_kind == Token_CmpEq) {
  8588. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8589. return res;
  8590. } else if (op_kind == Token_NotEq) {
  8591. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8592. return res;
  8593. }
  8594. } else if (is_type_dynamic_array(t)) {
  8595. lbValue cap = lb_emit_struct_ev(p, x, 2);
  8596. if (op_kind == Token_CmpEq) {
  8597. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8598. return res;
  8599. } else if (op_kind == Token_NotEq) {
  8600. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8601. return res;
  8602. }
  8603. } else if (is_type_map(t)) {
  8604. lbValue cap = lb_map_cap(p, x);
  8605. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  8606. } else if (is_type_union(t)) {
  8607. if (type_size_of(t) == 0) {
  8608. if (op_kind == Token_CmpEq) {
  8609. return lb_const_bool(p->module, t_llvm_bool, true);
  8610. } else if (op_kind == Token_NotEq) {
  8611. return lb_const_bool(p->module, t_llvm_bool, false);
  8612. }
  8613. } else if (is_type_union_maybe_pointer(t)) {
  8614. lbValue tag = lb_emit_transmute(p, x, t_rawptr);
  8615. return lb_emit_comp_against_nil(p, op_kind, tag);
  8616. } else {
  8617. lbValue tag = lb_emit_union_tag_value(p, x);
  8618. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  8619. }
  8620. } else if (is_type_typeid(t)) {
  8621. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  8622. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  8623. } else if (is_type_soa_struct(t)) {
  8624. Type *bt = base_type(t);
  8625. if (bt->Struct.soa_kind == StructSoa_Slice) {
  8626. lbValue len = lb_soa_struct_len(p, x);
  8627. if (op_kind == Token_CmpEq) {
  8628. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8629. return res;
  8630. } else if (op_kind == Token_NotEq) {
  8631. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8632. return res;
  8633. }
  8634. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  8635. lbValue cap = lb_soa_struct_cap(p, x);
  8636. if (op_kind == Token_CmpEq) {
  8637. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8638. return res;
  8639. } else if (op_kind == Token_NotEq) {
  8640. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8641. return res;
  8642. }
  8643. }
  8644. } else if (is_type_struct(t) && type_has_nil(t)) {
  8645. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8646. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  8647. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8648. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  8649. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  8650. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  8651. return res;
  8652. }
  8653. return {};
  8654. }
  8655. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  8656. Type *original_type = type;
  8657. type = base_type(type);
  8658. GB_ASSERT(is_type_comparable(type));
  8659. Type *pt = alloc_type_pointer(type);
  8660. LLVMTypeRef ptr_type = lb_type(m, pt);
  8661. auto key = hash_type(type);
  8662. lbProcedure **found = map_get(&m->equal_procs, key);
  8663. lbProcedure *compare_proc = nullptr;
  8664. if (found) {
  8665. compare_proc = *found;
  8666. GB_ASSERT(compare_proc != nullptr);
  8667. return {compare_proc->value, compare_proc->type};
  8668. }
  8669. static u32 proc_index = 0;
  8670. char buf[16] = {};
  8671. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  8672. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8673. String proc_name = make_string_c(str);
  8674. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  8675. map_set(&m->equal_procs, key, p);
  8676. lb_begin_procedure_body(p);
  8677. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8678. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8679. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  8680. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  8681. lbValue lhs = {x, pt};
  8682. lbValue rhs = {y, pt};
  8683. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  8684. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  8685. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  8686. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  8687. lb_start_block(p, block_same_ptr);
  8688. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8689. lb_start_block(p, block_diff_ptr);
  8690. if (type->kind == Type_Struct) {
  8691. type_set_offsets(type);
  8692. lbBlock *block_false = lb_create_block(p, "bfalse");
  8693. lbValue res = lb_const_bool(m, t_bool, true);
  8694. for_array(i, type->Struct.fields) {
  8695. lbBlock *next_block = lb_create_block(p, "btrue");
  8696. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  8697. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  8698. lbValue left = lb_emit_load(p, pleft);
  8699. lbValue right = lb_emit_load(p, pright);
  8700. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8701. lb_emit_if(p, ok, next_block, block_false);
  8702. lb_emit_jump(p, next_block);
  8703. lb_start_block(p, next_block);
  8704. }
  8705. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8706. lb_start_block(p, block_false);
  8707. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  8708. } else {
  8709. lbValue left = lb_emit_load(p, lhs);
  8710. lbValue right = lb_emit_load(p, rhs);
  8711. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8712. ok = lb_emit_conv(p, ok, t_bool);
  8713. LLVMBuildRet(p->builder, ok.value);
  8714. }
  8715. lb_end_procedure_body(p);
  8716. compare_proc = p;
  8717. return {compare_proc->value, compare_proc->type};
  8718. }
  8719. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  8720. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  8721. i64 sz = type_size_of(type);
  8722. if (1 <= sz && sz <= 16) {
  8723. char name[20] = {};
  8724. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  8725. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8726. args[0] = data;
  8727. args[1] = seed;
  8728. return lb_emit_runtime_call(p, name, args);
  8729. }
  8730. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8731. args[0] = data;
  8732. args[1] = seed;
  8733. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  8734. return lb_emit_runtime_call(p, "default_hasher_n", args);
  8735. }
  8736. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  8737. Type *original_type = type;
  8738. type = core_type(type);
  8739. GB_ASSERT(is_type_valid_for_keys(type));
  8740. Type *pt = alloc_type_pointer(type);
  8741. LLVMTypeRef ptr_type = lb_type(m, pt);
  8742. auto key = hash_type(type);
  8743. lbProcedure **found = map_get(&m->hasher_procs, key);
  8744. if (found) {
  8745. GB_ASSERT(*found != nullptr);
  8746. return {(*found)->value, (*found)->type};
  8747. }
  8748. static u32 proc_index = 0;
  8749. char buf[16] = {};
  8750. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  8751. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8752. String proc_name = make_string_c(str);
  8753. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  8754. map_set(&m->hasher_procs, key, p);
  8755. lb_begin_procedure_body(p);
  8756. defer (lb_end_procedure_body(p));
  8757. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8758. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8759. lbValue data = {x, t_rawptr};
  8760. lbValue seed = {y, t_uintptr};
  8761. if (is_type_simple_compare(type)) {
  8762. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  8763. LLVMBuildRet(p->builder, res.value);
  8764. return {p->value, p->type};
  8765. }
  8766. if (type->kind == Type_Struct) {
  8767. type_set_offsets(type);
  8768. data = lb_emit_conv(p, data, t_u8_ptr);
  8769. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8770. for_array(i, type->Struct.fields) {
  8771. i64 offset = type->Struct.offsets[i];
  8772. Entity *field = type->Struct.fields[i];
  8773. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  8774. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  8775. args[0] = ptr;
  8776. args[1] = seed;
  8777. seed = lb_emit_call(p, field_hasher, args);
  8778. }
  8779. LLVMBuildRet(p->builder, seed.value);
  8780. } else if (type->kind == Type_Array) {
  8781. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  8782. lb_addr_store(p, pres, seed);
  8783. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8784. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  8785. auto loop_data = lb_loop_start(p, type->Array.count, t_i32);
  8786. data = lb_emit_conv(p, data, pt);
  8787. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8788. args[0] = ptr;
  8789. args[1] = lb_addr_load(p, pres);
  8790. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8791. lb_addr_store(p, pres, new_seed);
  8792. lb_loop_end(p, loop_data);
  8793. lbValue res = lb_addr_load(p, pres);
  8794. LLVMBuildRet(p->builder, res.value);
  8795. } else if (type->kind == Type_EnumeratedArray) {
  8796. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  8797. lb_addr_store(p, res, seed);
  8798. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8799. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  8800. auto loop_data = lb_loop_start(p, type->EnumeratedArray.count, t_i32);
  8801. data = lb_emit_conv(p, data, pt);
  8802. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8803. args[0] = ptr;
  8804. args[1] = lb_addr_load(p, res);
  8805. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8806. lb_addr_store(p, res, new_seed);
  8807. lb_loop_end(p, loop_data);
  8808. lbValue vres = lb_addr_load(p, res);
  8809. LLVMBuildRet(p->builder, vres.value);
  8810. } else if (is_type_cstring(type)) {
  8811. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8812. args[0] = data;
  8813. args[1] = seed;
  8814. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  8815. LLVMBuildRet(p->builder, res.value);
  8816. } else if (is_type_string(type)) {
  8817. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8818. args[0] = data;
  8819. args[1] = seed;
  8820. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  8821. LLVMBuildRet(p->builder, res.value);
  8822. } else {
  8823. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  8824. }
  8825. return {p->value, p->type};
  8826. }
  8827. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  8828. Type *a = core_type(left.type);
  8829. Type *b = core_type(right.type);
  8830. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  8831. lbValue nil_check = {};
  8832. if (is_type_untyped_nil(left.type)) {
  8833. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  8834. } else if (is_type_untyped_nil(right.type)) {
  8835. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  8836. }
  8837. if (nil_check.value != nullptr) {
  8838. return nil_check;
  8839. }
  8840. if (are_types_identical(a, b)) {
  8841. // NOTE(bill): No need for a conversion
  8842. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  8843. left = lb_emit_conv(p, left, right.type);
  8844. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  8845. right = lb_emit_conv(p, right, left.type);
  8846. } else {
  8847. Type *lt = left.type;
  8848. Type *rt = right.type;
  8849. // if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  8850. // Type *blt = base_type(lt);
  8851. // Type *brt = base_type(rt);
  8852. // i64 bits = gb_max(blt->BitSet.bits, brt->BitSet.bits);
  8853. // i64 bytes = bits / 8;
  8854. // switch (bytes) {
  8855. // case 1:
  8856. // left = lb_emit_conv(p, left, t_u8);
  8857. // right = lb_emit_conv(p, right, t_u8);
  8858. // break;
  8859. // case 2:
  8860. // left = lb_emit_conv(p, left, t_u16);
  8861. // right = lb_emit_conv(p, right, t_u16);
  8862. // break;
  8863. // case 4:
  8864. // left = lb_emit_conv(p, left, t_u32);
  8865. // right = lb_emit_conv(p, right, t_u32);
  8866. // break;
  8867. // case 8:
  8868. // left = lb_emit_conv(p, left, t_u64);
  8869. // right = lb_emit_conv(p, right, t_u64);
  8870. // break;
  8871. // default: GB_PANIC("Unknown integer size"); break;
  8872. // }
  8873. // }
  8874. lt = left.type;
  8875. rt = right.type;
  8876. i64 ls = type_size_of(lt);
  8877. i64 rs = type_size_of(rt);
  8878. if (ls < rs) {
  8879. left = lb_emit_conv(p, left, rt);
  8880. } else if (ls > rs) {
  8881. right = lb_emit_conv(p, right, lt);
  8882. } else {
  8883. right = lb_emit_conv(p, right, lt);
  8884. }
  8885. }
  8886. if (is_type_array(a)) {
  8887. Type *tl = base_type(a);
  8888. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  8889. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  8890. TokenKind cmp_op = Token_And;
  8891. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  8892. if (op_kind == Token_NotEq) {
  8893. res = lb_const_bool(p->module, t_llvm_bool, false);
  8894. cmp_op = Token_Or;
  8895. } else if (op_kind == Token_CmpEq) {
  8896. res = lb_const_bool(p->module, t_llvm_bool, true);
  8897. cmp_op = Token_And;
  8898. }
  8899. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  8900. i32 count = cast(i32)tl->Array.count;
  8901. if (inline_array_arith) {
  8902. // inline
  8903. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8904. lb_addr_store(p, val, res);
  8905. for (i32 i = 0; i < count; i++) {
  8906. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  8907. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  8908. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8909. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8910. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8911. }
  8912. return lb_addr_load(p, val);
  8913. } else {
  8914. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  8915. // TODO(bill): Test to see if this is actually faster!!!!
  8916. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8917. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8918. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  8919. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  8920. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  8921. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  8922. return lb_emit_conv(p, res, t_bool);
  8923. } else {
  8924. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8925. lb_addr_store(p, val, res);
  8926. auto loop_data = lb_loop_start(p, count, t_i32);
  8927. {
  8928. lbValue i = loop_data.idx;
  8929. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  8930. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  8931. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8932. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8933. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8934. }
  8935. lb_loop_end(p, loop_data);
  8936. return lb_addr_load(p, val);
  8937. }
  8938. }
  8939. }
  8940. if (is_type_struct(a) && is_type_comparable(a)) {
  8941. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  8942. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  8943. lbValue res = {};
  8944. if (is_type_simple_compare(a)) {
  8945. // TODO(bill): Test to see if this is actually faster!!!!
  8946. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8947. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8948. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8949. args[2] = lb_const_int(p->module, t_int, type_size_of(a));
  8950. res = lb_emit_runtime_call(p, "memory_equal", args);
  8951. } else {
  8952. lbValue value = lb_get_equal_proc_for_type(p->module, a);
  8953. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8954. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8955. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8956. res = lb_emit_call(p, value, args);
  8957. }
  8958. if (op_kind == Token_NotEq) {
  8959. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  8960. }
  8961. return res;
  8962. }
  8963. if (is_type_string(a)) {
  8964. if (is_type_cstring(a)) {
  8965. left = lb_emit_conv(p, left, t_string);
  8966. right = lb_emit_conv(p, right, t_string);
  8967. }
  8968. char const *runtime_procedure = nullptr;
  8969. switch (op_kind) {
  8970. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  8971. case Token_NotEq: runtime_procedure = "string_ne"; break;
  8972. case Token_Lt: runtime_procedure = "string_lt"; break;
  8973. case Token_Gt: runtime_procedure = "string_gt"; break;
  8974. case Token_LtEq: runtime_procedure = "string_le"; break;
  8975. case Token_GtEq: runtime_procedure = "string_gt"; break;
  8976. }
  8977. GB_ASSERT(runtime_procedure != nullptr);
  8978. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8979. args[0] = left;
  8980. args[1] = right;
  8981. return lb_emit_runtime_call(p, runtime_procedure, args);
  8982. }
  8983. if (is_type_complex(a)) {
  8984. char const *runtime_procedure = "";
  8985. i64 sz = 8*type_size_of(a);
  8986. switch (sz) {
  8987. case 64:
  8988. switch (op_kind) {
  8989. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  8990. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  8991. }
  8992. break;
  8993. case 128:
  8994. switch (op_kind) {
  8995. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  8996. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  8997. }
  8998. break;
  8999. }
  9000. GB_ASSERT(runtime_procedure != nullptr);
  9001. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9002. args[0] = left;
  9003. args[1] = right;
  9004. return lb_emit_runtime_call(p, runtime_procedure, args);
  9005. }
  9006. if (is_type_quaternion(a)) {
  9007. char const *runtime_procedure = "";
  9008. i64 sz = 8*type_size_of(a);
  9009. switch (sz) {
  9010. case 128:
  9011. switch (op_kind) {
  9012. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  9013. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  9014. }
  9015. break;
  9016. case 256:
  9017. switch (op_kind) {
  9018. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  9019. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  9020. }
  9021. break;
  9022. }
  9023. GB_ASSERT(runtime_procedure != nullptr);
  9024. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9025. args[0] = left;
  9026. args[1] = right;
  9027. return lb_emit_runtime_call(p, runtime_procedure, args);
  9028. }
  9029. if (is_type_bit_set(a)) {
  9030. switch (op_kind) {
  9031. case Token_Lt:
  9032. case Token_LtEq:
  9033. case Token_Gt:
  9034. case Token_GtEq:
  9035. {
  9036. Type *it = bit_set_to_int(a);
  9037. lbValue lhs = lb_emit_transmute(p, left, it);
  9038. lbValue rhs = lb_emit_transmute(p, right, it);
  9039. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  9040. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  9041. // (lhs & rhs) == lhs
  9042. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  9043. res.type = t_llvm_bool;
  9044. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  9045. // (lhs & rhs) == rhs
  9046. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  9047. res.type = t_llvm_bool;
  9048. }
  9049. // NOTE(bill): Strict subsets
  9050. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  9051. // res &~ (lhs == rhs)
  9052. lbValue eq = {};
  9053. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  9054. eq.type = t_llvm_bool;
  9055. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  9056. }
  9057. return res;
  9058. }
  9059. case Token_CmpEq:
  9060. case Token_NotEq:
  9061. {
  9062. LLVMIntPredicate pred = {};
  9063. switch (op_kind) {
  9064. case Token_CmpEq: pred = LLVMIntEQ; break;
  9065. case Token_NotEq: pred = LLVMIntNE; break;
  9066. }
  9067. lbValue res = {};
  9068. res.type = t_llvm_bool;
  9069. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  9070. return res;
  9071. }
  9072. }
  9073. }
  9074. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  9075. Type *t = left.type;
  9076. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  9077. Type *platform_type = integer_endian_type_to_platform_type(t);
  9078. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  9079. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  9080. left = x;
  9081. right = y;
  9082. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  9083. Type *platform_type = integer_endian_type_to_platform_type(t);
  9084. lbValue x = lb_emit_conv(p, left, platform_type);
  9085. lbValue y = lb_emit_conv(p, right, platform_type);
  9086. left = x;
  9087. right = y;
  9088. }
  9089. }
  9090. a = core_type(left.type);
  9091. b = core_type(right.type);
  9092. lbValue res = {};
  9093. res.type = t_llvm_bool;
  9094. if (is_type_integer(a) ||
  9095. is_type_boolean(a) ||
  9096. is_type_pointer(a) ||
  9097. is_type_proc(a) ||
  9098. is_type_enum(a)) {
  9099. LLVMIntPredicate pred = {};
  9100. if (is_type_unsigned(left.type)) {
  9101. switch (op_kind) {
  9102. case Token_Gt: pred = LLVMIntUGT; break;
  9103. case Token_GtEq: pred = LLVMIntUGE; break;
  9104. case Token_Lt: pred = LLVMIntULT; break;
  9105. case Token_LtEq: pred = LLVMIntULE; break;
  9106. }
  9107. } else {
  9108. switch (op_kind) {
  9109. case Token_Gt: pred = LLVMIntSGT; break;
  9110. case Token_GtEq: pred = LLVMIntSGE; break;
  9111. case Token_Lt: pred = LLVMIntSLT; break;
  9112. case Token_LtEq: pred = LLVMIntSLE; break;
  9113. }
  9114. }
  9115. switch (op_kind) {
  9116. case Token_CmpEq: pred = LLVMIntEQ; break;
  9117. case Token_NotEq: pred = LLVMIntNE; break;
  9118. }
  9119. LLVMValueRef lhs = left.value;
  9120. LLVMValueRef rhs = right.value;
  9121. if (LLVMTypeOf(lhs) != LLVMTypeOf(rhs)) {
  9122. if (lb_is_type_kind(LLVMTypeOf(lhs), LLVMPointerTypeKind)) {
  9123. rhs = LLVMBuildPointerCast(p->builder, rhs, LLVMTypeOf(lhs), "");
  9124. }
  9125. }
  9126. res.value = LLVMBuildICmp(p->builder, pred, lhs, rhs, "");
  9127. } else if (is_type_float(a)) {
  9128. LLVMRealPredicate pred = {};
  9129. switch (op_kind) {
  9130. case Token_CmpEq: pred = LLVMRealOEQ; break;
  9131. case Token_Gt: pred = LLVMRealOGT; break;
  9132. case Token_GtEq: pred = LLVMRealOGE; break;
  9133. case Token_Lt: pred = LLVMRealOLT; break;
  9134. case Token_LtEq: pred = LLVMRealOLE; break;
  9135. case Token_NotEq: pred = LLVMRealONE; break;
  9136. }
  9137. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  9138. } else if (is_type_typeid(a)) {
  9139. LLVMIntPredicate pred = {};
  9140. switch (op_kind) {
  9141. case Token_Gt: pred = LLVMIntUGT; break;
  9142. case Token_GtEq: pred = LLVMIntUGE; break;
  9143. case Token_Lt: pred = LLVMIntULT; break;
  9144. case Token_LtEq: pred = LLVMIntULE; break;
  9145. case Token_CmpEq: pred = LLVMIntEQ; break;
  9146. case Token_NotEq: pred = LLVMIntNE; break;
  9147. }
  9148. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  9149. } else {
  9150. 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)));
  9151. }
  9152. return res;
  9153. }
  9154. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  9155. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  9156. if (found != nullptr) {
  9157. lbValue value = {};
  9158. value.value = (*found)->value;
  9159. value.type = (*found)->type;
  9160. return value;
  9161. }
  9162. ast_node(pl, ProcLit, expr);
  9163. // NOTE(bill): Generate a new name
  9164. // parent$count
  9165. isize name_len = prefix_name.len + 1 + 8 + 1;
  9166. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  9167. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  9168. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  9169. String name = make_string((u8 *)name_text, name_len-1);
  9170. Type *type = type_of_expr(expr);
  9171. Token token = {};
  9172. token.pos = ast_token(expr).pos;
  9173. token.kind = Token_Ident;
  9174. token.string = name;
  9175. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  9176. e->file = expr->file;
  9177. e->decl_info = pl->decl;
  9178. lbProcedure *p = lb_create_procedure(m, e);
  9179. lbValue value = {};
  9180. value.value = p->value;
  9181. value.type = p->type;
  9182. array_add(&m->procedures_to_generate, p);
  9183. if (parent != nullptr) {
  9184. array_add(&parent->children, p);
  9185. } else {
  9186. string_map_set(&m->members, name, value);
  9187. }
  9188. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  9189. return value;
  9190. }
  9191. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  9192. lbModule *m = p->module;
  9193. Type *src_type = value.type;
  9194. bool is_ptr = is_type_pointer(src_type);
  9195. bool is_tuple = true;
  9196. Type *tuple = type;
  9197. if (type->kind != Type_Tuple) {
  9198. is_tuple = false;
  9199. tuple = make_optional_ok_type(type);
  9200. }
  9201. lbAddr v = lb_add_local_generated(p, tuple, true);
  9202. if (is_ptr) {
  9203. value = lb_emit_load(p, value);
  9204. }
  9205. Type *src = base_type(type_deref(src_type));
  9206. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  9207. Type *dst = tuple->Tuple.variables[0]->type;
  9208. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  9209. lbValue tag = {};
  9210. lbValue dst_tag = {};
  9211. lbValue cond = {};
  9212. lbValue data = {};
  9213. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  9214. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  9215. if (is_type_union_maybe_pointer(src)) {
  9216. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  9217. } else {
  9218. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  9219. dst_tag = lb_const_union_tag(m, src, dst);
  9220. }
  9221. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  9222. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  9223. if (data.value != nullptr) {
  9224. GB_ASSERT(is_type_union_maybe_pointer(src));
  9225. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  9226. } else {
  9227. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  9228. }
  9229. lb_emit_if(p, cond, ok_block, end_block);
  9230. lb_start_block(p, ok_block);
  9231. if (data.value == nullptr) {
  9232. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  9233. }
  9234. lb_emit_store(p, gep0, data);
  9235. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  9236. lb_emit_jump(p, end_block);
  9237. lb_start_block(p, end_block);
  9238. if (!is_tuple) {
  9239. if (do_conversion_check) {
  9240. // NOTE(bill): Panic on invalid conversion
  9241. Type *dst_type = tuple->Tuple.variables[0]->type;
  9242. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  9243. auto args = array_make<lbValue>(permanent_allocator(), 7);
  9244. args[0] = ok;
  9245. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  9246. args[2] = lb_const_int(m, t_i32, pos.line);
  9247. args[3] = lb_const_int(m, t_i32, pos.column);
  9248. args[4] = lb_typeid(m, src_type);
  9249. args[5] = lb_typeid(m, dst_type);
  9250. args[6] = lb_emit_conv(p, value_, t_rawptr);
  9251. lb_emit_runtime_call(p, "type_assertion_check2", args);
  9252. }
  9253. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  9254. }
  9255. return lb_addr_load(p, v);
  9256. }
  9257. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9258. lbModule *m = p->module;
  9259. Type *src_type = value.type;
  9260. if (is_type_pointer(src_type)) {
  9261. value = lb_emit_load(p, value);
  9262. }
  9263. bool is_tuple = true;
  9264. Type *tuple = type;
  9265. if (type->kind != Type_Tuple) {
  9266. is_tuple = false;
  9267. tuple = make_optional_ok_type(type);
  9268. }
  9269. Type *dst_type = tuple->Tuple.variables[0]->type;
  9270. lbAddr v = lb_add_local_generated(p, tuple, true);
  9271. lbValue dst_typeid = lb_typeid(m, dst_type);
  9272. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  9273. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  9274. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  9275. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  9276. lb_emit_if(p, cond, ok_block, end_block);
  9277. lb_start_block(p, ok_block);
  9278. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  9279. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  9280. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  9281. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  9282. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  9283. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  9284. lb_emit_jump(p, end_block);
  9285. lb_start_block(p, end_block);
  9286. if (!is_tuple) {
  9287. // NOTE(bill): Panic on invalid conversion
  9288. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  9289. auto args = array_make<lbValue>(permanent_allocator(), 7);
  9290. args[0] = ok;
  9291. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  9292. args[2] = lb_const_int(m, t_i32, pos.line);
  9293. args[3] = lb_const_int(m, t_i32, pos.column);
  9294. args[4] = any_typeid;
  9295. args[5] = dst_typeid;
  9296. args[6] = lb_emit_struct_ev(p, value, 0);;
  9297. lb_emit_runtime_call(p, "type_assertion_check2", args);
  9298. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  9299. }
  9300. return v;
  9301. }
  9302. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  9303. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  9304. }
  9305. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  9306. lbModule *m = p->module;
  9307. u16 prev_state_flags = p->state_flags;
  9308. defer (p->state_flags = prev_state_flags);
  9309. if (expr->state_flags != 0) {
  9310. u16 in = expr->state_flags;
  9311. u16 out = p->state_flags;
  9312. if (in & StateFlag_bounds_check) {
  9313. out |= StateFlag_bounds_check;
  9314. out &= ~StateFlag_no_bounds_check;
  9315. } else if (in & StateFlag_no_bounds_check) {
  9316. out |= StateFlag_no_bounds_check;
  9317. out &= ~StateFlag_bounds_check;
  9318. }
  9319. p->state_flags = out;
  9320. }
  9321. expr = unparen_expr(expr);
  9322. TokenPos expr_pos = ast_token(expr).pos;
  9323. TypeAndValue tv = type_and_value_of_expr(expr);
  9324. 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));
  9325. if (tv.value.kind != ExactValue_Invalid) {
  9326. // NOTE(bill): Short on constant values
  9327. return lb_const_value(p->module, tv.type, tv.value);
  9328. }
  9329. #if 0
  9330. LLVMMetadataRef prev_debug_location = nullptr;
  9331. if (p->debug_info != nullptr) {
  9332. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  9333. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, expr));
  9334. }
  9335. defer (if (prev_debug_location != nullptr) {
  9336. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  9337. });
  9338. #endif
  9339. switch (expr->kind) {
  9340. case_ast_node(bl, BasicLit, expr);
  9341. TokenPos pos = bl->token.pos;
  9342. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  9343. case_end;
  9344. case_ast_node(bd, BasicDirective, expr);
  9345. TokenPos pos = bd->token.pos;
  9346. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name));
  9347. case_end;
  9348. case_ast_node(i, Implicit, expr);
  9349. return lb_addr_load(p, lb_build_addr(p, expr));
  9350. case_end;
  9351. case_ast_node(u, Undef, expr)
  9352. lbValue res = {};
  9353. if (is_type_untyped(tv.type)) {
  9354. res.value = nullptr;
  9355. res.type = t_untyped_undef;
  9356. } else {
  9357. res.value = LLVMGetUndef(lb_type(m, tv.type));
  9358. res.type = tv.type;
  9359. }
  9360. return res;
  9361. case_end;
  9362. case_ast_node(i, Ident, expr);
  9363. Entity *e = entity_from_expr(expr);
  9364. e = strip_entity_wrapping(e);
  9365. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  9366. if (e->kind == Entity_Builtin) {
  9367. Token token = ast_token(expr);
  9368. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  9369. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  9370. token_pos_to_string(token.pos));
  9371. return {};
  9372. } else if (e->kind == Entity_Nil) {
  9373. lbValue res = {};
  9374. res.value = nullptr;
  9375. res.type = e->type;
  9376. return res;
  9377. }
  9378. GB_ASSERT(e->kind != Entity_ProcGroup);
  9379. auto *found = map_get(&p->module->values, hash_entity(e));
  9380. if (found) {
  9381. auto v = *found;
  9382. // NOTE(bill): This is because pointers are already pointers in LLVM
  9383. if (is_type_proc(v.type)) {
  9384. return v;
  9385. }
  9386. return lb_emit_load(p, v);
  9387. } else if (e != nullptr && e->kind == Entity_Variable) {
  9388. return lb_addr_load(p, lb_build_addr(p, expr));
  9389. }
  9390. gb_printf_err("Error in: %s\n", token_pos_to_string(i->token.pos));
  9391. String pkg = {};
  9392. if (e->pkg) {
  9393. pkg = e->pkg->name;
  9394. }
  9395. 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);
  9396. return {};
  9397. case_end;
  9398. case_ast_node(de, DerefExpr, expr);
  9399. return lb_addr_load(p, lb_build_addr(p, expr));
  9400. case_end;
  9401. case_ast_node(se, SelectorExpr, expr);
  9402. TypeAndValue tav = type_and_value_of_expr(expr);
  9403. GB_ASSERT(tav.mode != Addressing_Invalid);
  9404. return lb_addr_load(p, lb_build_addr(p, expr));
  9405. case_end;
  9406. case_ast_node(ise, ImplicitSelectorExpr, expr);
  9407. TypeAndValue tav = type_and_value_of_expr(expr);
  9408. GB_ASSERT(tav.mode == Addressing_Constant);
  9409. return lb_const_value(p->module, tv.type, tv.value);
  9410. case_end;
  9411. case_ast_node(se, SelectorCallExpr, expr);
  9412. GB_ASSERT(se->modified_call);
  9413. TypeAndValue tav = type_and_value_of_expr(expr);
  9414. GB_ASSERT(tav.mode != Addressing_Invalid);
  9415. return lb_build_expr(p, se->call);
  9416. case_end;
  9417. case_ast_node(te, TernaryExpr, expr);
  9418. LLVMValueRef incoming_values[2] = {};
  9419. LLVMBasicBlockRef incoming_blocks[2] = {};
  9420. GB_ASSERT(te->y != nullptr);
  9421. lbBlock *then = lb_create_block(p, "if.then");
  9422. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  9423. lbBlock *else_ = lb_create_block(p, "if.else");
  9424. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  9425. lb_start_block(p, then);
  9426. Type *type = default_type(type_of_expr(expr));
  9427. lb_open_scope(p, nullptr);
  9428. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  9429. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9430. lb_emit_jump(p, done);
  9431. lb_start_block(p, else_);
  9432. lb_open_scope(p, nullptr);
  9433. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  9434. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9435. lb_emit_jump(p, done);
  9436. lb_start_block(p, done);
  9437. lbValue res = {};
  9438. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  9439. res.type = type;
  9440. GB_ASSERT(p->curr_block->preds.count >= 2);
  9441. incoming_blocks[0] = p->curr_block->preds[0]->block;
  9442. incoming_blocks[1] = p->curr_block->preds[1]->block;
  9443. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  9444. return res;
  9445. case_end;
  9446. case_ast_node(te, TernaryIfExpr, expr);
  9447. LLVMValueRef incoming_values[2] = {};
  9448. LLVMBasicBlockRef incoming_blocks[2] = {};
  9449. GB_ASSERT(te->y != nullptr);
  9450. lbBlock *then = lb_create_block(p, "if.then");
  9451. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  9452. lbBlock *else_ = lb_create_block(p, "if.else");
  9453. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  9454. lb_start_block(p, then);
  9455. Type *type = default_type(type_of_expr(expr));
  9456. lb_open_scope(p, nullptr);
  9457. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  9458. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9459. lb_emit_jump(p, done);
  9460. lb_start_block(p, else_);
  9461. lb_open_scope(p, nullptr);
  9462. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  9463. lb_close_scope(p, lbDeferExit_Default, nullptr);
  9464. lb_emit_jump(p, done);
  9465. lb_start_block(p, done);
  9466. lbValue res = {};
  9467. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  9468. res.type = type;
  9469. GB_ASSERT(p->curr_block->preds.count >= 2);
  9470. incoming_blocks[0] = p->curr_block->preds[0]->block;
  9471. incoming_blocks[1] = p->curr_block->preds[1]->block;
  9472. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  9473. return res;
  9474. case_end;
  9475. case_ast_node(te, TernaryWhenExpr, expr);
  9476. TypeAndValue tav = type_and_value_of_expr(te->cond);
  9477. GB_ASSERT(tav.mode == Addressing_Constant);
  9478. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  9479. if (tav.value.value_bool) {
  9480. return lb_build_expr(p, te->x);
  9481. } else {
  9482. return lb_build_expr(p, te->y);
  9483. }
  9484. case_end;
  9485. case_ast_node(ta, TypeAssertion, expr);
  9486. TokenPos pos = ast_token(expr).pos;
  9487. Type *type = tv.type;
  9488. lbValue e = lb_build_expr(p, ta->expr);
  9489. Type *t = type_deref(e.type);
  9490. if (is_type_union(t)) {
  9491. return lb_emit_union_cast(p, e, type, pos);
  9492. } else if (is_type_any(t)) {
  9493. return lb_emit_any_cast(p, e, type, pos);
  9494. } else {
  9495. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  9496. }
  9497. case_end;
  9498. case_ast_node(tc, TypeCast, expr);
  9499. lbValue e = lb_build_expr(p, tc->expr);
  9500. switch (tc->token.kind) {
  9501. case Token_cast:
  9502. return lb_emit_conv(p, e, tv.type);
  9503. case Token_transmute:
  9504. return lb_emit_transmute(p, e, tv.type);
  9505. }
  9506. GB_PANIC("Invalid AST TypeCast");
  9507. case_end;
  9508. case_ast_node(ac, AutoCast, expr);
  9509. lbValue value = lb_build_expr(p, ac->expr);
  9510. return lb_emit_conv(p, value, tv.type);
  9511. case_end;
  9512. case_ast_node(ue, UnaryExpr, expr);
  9513. switch (ue->op.kind) {
  9514. case Token_And: {
  9515. Ast *ue_expr = unparen_expr(ue->expr);
  9516. if (ue_expr->kind == Ast_CompoundLit) {
  9517. lbValue v = lb_build_expr(p, ue->expr);
  9518. Type *type = v.type;
  9519. lbAddr addr = {};
  9520. if (p->is_startup) {
  9521. addr = lb_add_global_generated(p->module, type, v);
  9522. } else {
  9523. addr = lb_add_local_generated(p, type, false);
  9524. }
  9525. lb_addr_store(p, addr, v);
  9526. return addr.addr;
  9527. } else if (ue_expr->kind == Ast_TypeAssertion) {
  9528. GB_ASSERT(is_type_pointer(tv.type));
  9529. ast_node(ta, TypeAssertion, ue_expr);
  9530. TokenPos pos = ast_token(expr).pos;
  9531. Type *type = type_of_expr(ue_expr);
  9532. GB_ASSERT(!is_type_tuple(type));
  9533. lbValue e = lb_build_expr(p, ta->expr);
  9534. Type *t = type_deref(e.type);
  9535. if (is_type_union(t)) {
  9536. lbValue v = e;
  9537. if (!is_type_pointer(v.type)) {
  9538. v = lb_address_from_load_or_generate_local(p, v);
  9539. }
  9540. Type *src_type = type_deref(v.type);
  9541. Type *dst_type = type;
  9542. lbValue src_tag = {};
  9543. lbValue dst_tag = {};
  9544. if (is_type_union_maybe_pointer(src_type)) {
  9545. src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v);
  9546. dst_tag = lb_const_bool(p->module, t_bool, true);
  9547. } else {
  9548. src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  9549. dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  9550. }
  9551. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  9552. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9553. args[0] = ok;
  9554. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9555. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9556. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9557. args[4] = lb_typeid(p->module, src_type);
  9558. args[5] = lb_typeid(p->module, dst_type);
  9559. lb_emit_runtime_call(p, "type_assertion_check", args);
  9560. lbValue data_ptr = v;
  9561. return lb_emit_conv(p, data_ptr, tv.type);
  9562. } else if (is_type_any(t)) {
  9563. lbValue v = e;
  9564. if (is_type_pointer(v.type)) {
  9565. v = lb_emit_load(p, v);
  9566. }
  9567. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  9568. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  9569. lbValue id = lb_typeid(p->module, type);
  9570. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  9571. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9572. args[0] = ok;
  9573. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9574. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9575. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9576. args[4] = any_id;
  9577. args[5] = id;
  9578. lb_emit_runtime_call(p, "type_assertion_check", args);
  9579. return lb_emit_conv(p, data_ptr, tv.type);
  9580. } else {
  9581. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  9582. }
  9583. }
  9584. return lb_build_addr_ptr(p, ue->expr);
  9585. }
  9586. default:
  9587. {
  9588. lbValue v = lb_build_expr(p, ue->expr);
  9589. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  9590. }
  9591. }
  9592. case_end;
  9593. case_ast_node(be, BinaryExpr, expr);
  9594. return lb_build_binary_expr(p, expr);
  9595. case_end;
  9596. case_ast_node(pl, ProcLit, expr);
  9597. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  9598. case_end;
  9599. case_ast_node(cl, CompoundLit, expr);
  9600. return lb_addr_load(p, lb_build_addr(p, expr));
  9601. case_end;
  9602. case_ast_node(ce, CallExpr, expr);
  9603. lbValue res = lb_build_call_expr(p, expr);
  9604. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  9605. GB_ASSERT(is_type_tuple(res.type));
  9606. GB_ASSERT(res.type->Tuple.variables.count == 2);
  9607. return lb_emit_struct_ev(p, res, 0);
  9608. }
  9609. return res;
  9610. case_end;
  9611. case_ast_node(se, SliceExpr, expr);
  9612. return lb_addr_load(p, lb_build_addr(p, expr));
  9613. case_end;
  9614. case_ast_node(ie, IndexExpr, expr);
  9615. return lb_addr_load(p, lb_build_addr(p, expr));
  9616. case_end;
  9617. case_ast_node(ia, InlineAsmExpr, expr);
  9618. Type *t = type_of_expr(expr);
  9619. GB_ASSERT(is_type_asm_proc(t));
  9620. String asm_string = {};
  9621. String constraints_string = {};
  9622. TypeAndValue tav;
  9623. tav = type_and_value_of_expr(ia->asm_string);
  9624. GB_ASSERT(is_type_string(tav.type));
  9625. GB_ASSERT(tav.value.kind == ExactValue_String);
  9626. asm_string = tav.value.value_string;
  9627. tav = type_and_value_of_expr(ia->constraints_string);
  9628. GB_ASSERT(is_type_string(tav.type));
  9629. GB_ASSERT(tav.value.kind == ExactValue_String);
  9630. constraints_string = tav.value.value_string;
  9631. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  9632. switch (ia->dialect) {
  9633. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  9634. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  9635. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  9636. default: GB_PANIC("Unhandled inline asm dialect"); break;
  9637. }
  9638. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  9639. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  9640. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  9641. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  9642. ia->has_side_effects, ia->is_align_stack, dialect
  9643. );
  9644. GB_ASSERT(the_asm != nullptr);
  9645. return {the_asm, t};
  9646. case_end;
  9647. }
  9648. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  9649. return {};
  9650. }
  9651. lbAddr lb_get_soa_variable_addr(lbProcedure *p, Entity *e) {
  9652. lbAddr *found = map_get(&p->module->soa_values, hash_entity(e));
  9653. GB_ASSERT(found != nullptr);
  9654. return *found;
  9655. }
  9656. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  9657. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  9658. String name = e->token.string;
  9659. Entity *parent = e->using_parent;
  9660. Selection sel = lookup_field(parent->type, name, false);
  9661. GB_ASSERT(sel.entity != nullptr);
  9662. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  9663. lbValue v = {};
  9664. if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) {
  9665. // NOTE(bill): using SOA value (probably from for-in statement)
  9666. lbAddr parent_addr = lb_get_soa_variable_addr(p, parent);
  9667. v = lb_addr_get_ptr(p, parent_addr);
  9668. } else if (pv != nullptr) {
  9669. v = *pv;
  9670. } else {
  9671. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  9672. v = lb_build_addr_ptr(p, e->using_expr);
  9673. }
  9674. GB_ASSERT(v.value != nullptr);
  9675. GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type));
  9676. lbValue ptr = lb_emit_deep_field_gep(p, v, sel);
  9677. if (parent->scope) {
  9678. if ((parent->scope->flags & (ScopeFlag_File|ScopeFlag_Pkg)) == 0) {
  9679. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  9680. }
  9681. } else {
  9682. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  9683. }
  9684. return ptr;
  9685. }
  9686. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  9687. GB_ASSERT(e != nullptr);
  9688. if (e->kind == Entity_Constant) {
  9689. Type *t = default_type(type_of_expr(expr));
  9690. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  9691. lbAddr g = lb_add_global_generated(p->module, t, v);
  9692. return g;
  9693. }
  9694. lbValue v = {};
  9695. lbValue *found = map_get(&p->module->values, hash_entity(e));
  9696. if (found) {
  9697. v = *found;
  9698. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  9699. // NOTE(bill): Calculate the using variable every time
  9700. v = lb_get_using_variable(p, e);
  9701. } else if (e->flags & EntityFlag_SoaPtrField) {
  9702. return lb_get_soa_variable_addr(p, e);
  9703. }
  9704. if (v.value == nullptr) {
  9705. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  9706. LIT(p->name),
  9707. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  9708. GB_PANIC("Unknown value");
  9709. }
  9710. return lb_addr(v);
  9711. }
  9712. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  9713. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  9714. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  9715. map_type = base_type(map_type);
  9716. GB_ASSERT(map_type->kind == Type_Map);
  9717. Type *key_type = map_type->Map.key;
  9718. Type *val_type = map_type->Map.value;
  9719. // NOTE(bill): Removes unnecessary allocation if split gep
  9720. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  9721. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  9722. lb_emit_store(p, gep0, m);
  9723. i64 entry_size = type_size_of (map_type->Map.entry_type);
  9724. i64 entry_align = type_align_of (map_type->Map.entry_type);
  9725. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  9726. i64 key_size = type_size_of (map_type->Map.key);
  9727. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  9728. i64 value_size = type_size_of (map_type->Map.value);
  9729. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  9730. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  9731. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  9732. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  9733. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  9734. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  9735. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  9736. return lb_addr_load(p, h);
  9737. }
  9738. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  9739. if (true) {
  9740. return {};
  9741. }
  9742. lbValue hashed_key = {};
  9743. if (lb_is_const(key)) {
  9744. u64 hash = 0xcbf29ce484222325;
  9745. if (is_type_cstring(key_type)) {
  9746. size_t length = 0;
  9747. char const *text = LLVMGetAsString(key.value, &length);
  9748. hash = fnv64a(text, cast(isize)length);
  9749. } else if (is_type_string(key_type)) {
  9750. unsigned data_indices[] = {0};
  9751. unsigned len_indices[] = {1};
  9752. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  9753. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  9754. isize length = LLVMConstIntGetSExtValue(len);
  9755. char const *text = nullptr;
  9756. if (false && length != 0) {
  9757. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  9758. return {};
  9759. }
  9760. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  9761. size_t ulength = 0;
  9762. text = LLVMGetAsString(data, &ulength);
  9763. gb_printf_err("%td %td %s\n", length, ulength, text);
  9764. length = gb_min(length, cast(isize)ulength);
  9765. }
  9766. hash = fnv64a(text, cast(isize)length);
  9767. } else {
  9768. return {};
  9769. }
  9770. // TODO(bill): other const hash types
  9771. if (build_context.word_size == 4) {
  9772. hash &= 0xffffffffull;
  9773. }
  9774. hashed_key = lb_const_int(m, t_uintptr, hash);
  9775. }
  9776. return hashed_key;
  9777. }
  9778. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  9779. Type *hash_type = t_u64;
  9780. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  9781. lbValue vp = lb_addr_get_ptr(p, v);
  9782. Type *t = base_type(key.type);
  9783. key = lb_emit_conv(p, key, key_type);
  9784. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  9785. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  9786. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  9787. if (hashed_key.value == nullptr) {
  9788. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  9789. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9790. args[0] = key_ptr;
  9791. args[1] = lb_const_int(p->module, t_uintptr, 0);
  9792. hashed_key = lb_emit_call(p, hasher, args);
  9793. }
  9794. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  9795. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  9796. return lb_addr_load(p, v);
  9797. }
  9798. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  9799. lbValue map_key, lbValue map_value, Ast *node) {
  9800. map_type = base_type(map_type);
  9801. GB_ASSERT(map_type->kind == Type_Map);
  9802. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  9803. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  9804. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  9805. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  9806. lb_addr_store(p, value_addr, v);
  9807. auto args = array_make<lbValue>(permanent_allocator(), 4);
  9808. args[0] = h;
  9809. args[1] = key;
  9810. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  9811. args[3] = lb_emit_source_code_location(p, node);
  9812. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  9813. }
  9814. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  9815. expr = unparen_expr(expr);
  9816. switch (expr->kind) {
  9817. case_ast_node(i, Implicit, expr);
  9818. lbAddr v = {};
  9819. switch (i->kind) {
  9820. case Token_context:
  9821. v = lb_find_or_generate_context_ptr(p);
  9822. break;
  9823. }
  9824. GB_ASSERT(v.addr.value != nullptr);
  9825. return v;
  9826. case_end;
  9827. case_ast_node(i, Ident, expr);
  9828. if (is_blank_ident(expr)) {
  9829. lbAddr val = {};
  9830. return val;
  9831. }
  9832. String name = i->token.string;
  9833. Entity *e = entity_of_node(expr);
  9834. return lb_build_addr_from_entity(p, e, expr);
  9835. case_end;
  9836. case_ast_node(se, SelectorExpr, expr);
  9837. Ast *sel = unparen_expr(se->selector);
  9838. if (sel->kind == Ast_Ident) {
  9839. String selector = sel->Ident.token.string;
  9840. TypeAndValue tav = type_and_value_of_expr(se->expr);
  9841. if (tav.mode == Addressing_Invalid) {
  9842. // NOTE(bill): Imports
  9843. Entity *imp = entity_of_node(se->expr);
  9844. if (imp != nullptr) {
  9845. GB_ASSERT(imp->kind == Entity_ImportName);
  9846. }
  9847. return lb_build_addr(p, unparen_expr(se->selector));
  9848. }
  9849. Type *type = base_type(tav.type);
  9850. if (tav.mode == Addressing_Type) { // Addressing_Type
  9851. Selection sel = lookup_field(type, selector, true);
  9852. Entity *e = sel.entity;
  9853. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  9854. GB_ASSERT(e->flags & EntityFlag_TypeField);
  9855. String name = e->token.string;
  9856. /*if (name == "names") {
  9857. lbValue ti_ptr = lb_type_info(m, type);
  9858. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  9859. lbValue names_ptr = nullptr;
  9860. if (is_type_enum(type)) {
  9861. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  9862. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  9863. } else if (type->kind == Type_Struct) {
  9864. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  9865. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  9866. }
  9867. return ir_addr(names_ptr);
  9868. } else */{
  9869. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  9870. }
  9871. GB_PANIC("Unreachable");
  9872. }
  9873. Selection sel = lookup_field(type, selector, false);
  9874. GB_ASSERT(sel.entity != nullptr);
  9875. {
  9876. lbAddr addr = lb_build_addr(p, se->expr);
  9877. if (addr.kind == lbAddr_Map) {
  9878. lbValue v = lb_addr_load(p, addr);
  9879. lbValue a = lb_address_from_load_or_generate_local(p, v);
  9880. a = lb_emit_deep_field_gep(p, a, sel);
  9881. return lb_addr(a);
  9882. } else if (addr.kind == lbAddr_Context) {
  9883. GB_ASSERT(sel.index.count > 0);
  9884. if (addr.ctx.sel.index.count >= 0) {
  9885. sel = selection_combine(addr.ctx.sel, sel);
  9886. }
  9887. addr.ctx.sel = sel;
  9888. addr.kind = lbAddr_Context;
  9889. return addr;
  9890. } else if (addr.kind == lbAddr_SoaVariable) {
  9891. lbValue index = addr.soa.index;
  9892. i32 first_index = sel.index[0];
  9893. Selection sub_sel = sel;
  9894. sub_sel.index.data += 1;
  9895. sub_sel.index.count -= 1;
  9896. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  9897. Type *t = base_type(type_deref(addr.addr.type));
  9898. GB_ASSERT(is_type_soa_struct(t));
  9899. // TODO(bill): Bounds check
  9900. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  9901. lbValue len = lb_soa_struct_len(p, addr.addr);
  9902. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  9903. }
  9904. lbValue item = {};
  9905. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9906. item = lb_emit_array_ep(p, arr, index);
  9907. } else {
  9908. item = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  9909. }
  9910. if (sub_sel.index.count > 0) {
  9911. item = lb_emit_deep_field_gep(p, item, sub_sel);
  9912. }
  9913. return lb_addr(item);
  9914. }
  9915. lbValue a = lb_addr_get_ptr(p, addr);
  9916. a = lb_emit_deep_field_gep(p, a, sel);
  9917. return lb_addr(a);
  9918. }
  9919. } else {
  9920. GB_PANIC("Unsupported selector expression");
  9921. }
  9922. case_end;
  9923. case_ast_node(se, SelectorCallExpr, expr);
  9924. GB_ASSERT(se->modified_call);
  9925. TypeAndValue tav = type_and_value_of_expr(expr);
  9926. GB_ASSERT(tav.mode != Addressing_Invalid);
  9927. return lb_build_addr(p, se->call);
  9928. case_end;
  9929. case_ast_node(ta, TypeAssertion, expr);
  9930. TokenPos pos = ast_token(expr).pos;
  9931. lbValue e = lb_build_expr(p, ta->expr);
  9932. Type *t = type_deref(e.type);
  9933. if (is_type_union(t)) {
  9934. Type *type = type_of_expr(expr);
  9935. lbAddr v = lb_add_local_generated(p, type, false);
  9936. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  9937. return v;
  9938. } else if (is_type_any(t)) {
  9939. Type *type = type_of_expr(expr);
  9940. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  9941. } else {
  9942. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  9943. }
  9944. case_end;
  9945. case_ast_node(ue, UnaryExpr, expr);
  9946. switch (ue->op.kind) {
  9947. case Token_And: {
  9948. return lb_build_addr(p, ue->expr);
  9949. }
  9950. default:
  9951. GB_PANIC("Invalid unary expression for lb_build_addr");
  9952. }
  9953. case_end;
  9954. case_ast_node(be, BinaryExpr, expr);
  9955. lbValue v = lb_build_expr(p, expr);
  9956. Type *t = v.type;
  9957. if (is_type_pointer(t)) {
  9958. return lb_addr(v);
  9959. }
  9960. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  9961. case_end;
  9962. case_ast_node(ie, IndexExpr, expr);
  9963. Type *t = base_type(type_of_expr(ie->expr));
  9964. bool deref = is_type_pointer(t);
  9965. t = base_type(type_deref(t));
  9966. if (is_type_soa_struct(t)) {
  9967. // SOA STRUCTURES!!!!
  9968. lbValue val = lb_build_addr_ptr(p, ie->expr);
  9969. if (deref) {
  9970. val = lb_emit_load(p, val);
  9971. }
  9972. lbValue index = lb_build_expr(p, ie->index);
  9973. return lb_addr_soa_variable(val, index, ie->index);
  9974. }
  9975. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  9976. // SOA Structures for slices/dynamic arrays
  9977. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  9978. lbValue field = lb_build_expr(p, ie->expr);
  9979. lbValue index = lb_build_expr(p, ie->index);
  9980. if (!build_context.no_bounds_check) {
  9981. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  9982. // GB_ASSERT(LLVMIsALoadInst(field.value));
  9983. // lbValue a = {};
  9984. // a.value = LLVMGetOperand(field.value, 0);
  9985. // a.type = alloc_type_pointer(field.type);
  9986. // irInstr *b = &a->Instr;
  9987. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  9988. // lbValue base_struct = b->StructElementPtr.address;
  9989. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  9990. // lbValue len = ir_soa_struct_len(p, base_struct);
  9991. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9992. }
  9993. lbValue val = lb_emit_ptr_offset(p, field, index);
  9994. return lb_addr(val);
  9995. }
  9996. if (!is_type_indexable(t)) {
  9997. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9998. if (found != nullptr) {
  9999. if (found->kind == TypeAtomOp_index_get) {
  10000. return lb_build_addr(p, found->node);
  10001. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  10002. return lb_addr(lb_build_expr(p, found->node));
  10003. } else if (found->kind == TypeAtomOp_index_set) {
  10004. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  10005. if (deref) {
  10006. ptr = lb_emit_load(p, ptr);
  10007. }
  10008. lbAddr addr = {lbAddr_AtomOp_index_set};
  10009. addr.addr = ptr;
  10010. addr.index_set.index = lb_build_expr(p, ie->index);
  10011. addr.index_set.node = found->node;
  10012. return addr;
  10013. }
  10014. }
  10015. }
  10016. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  10017. if (is_type_map(t)) {
  10018. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  10019. if (deref) {
  10020. map_val = lb_emit_load(p, map_val);
  10021. }
  10022. lbValue key = lb_build_expr(p, ie->index);
  10023. key = lb_emit_conv(p, key, t->Map.key);
  10024. Type *result_type = type_of_expr(expr);
  10025. return lb_addr_map(map_val, key, t, result_type);
  10026. }
  10027. switch (t->kind) {
  10028. case Type_Array: {
  10029. lbValue array = {};
  10030. array = lb_build_addr_ptr(p, ie->expr);
  10031. if (deref) {
  10032. array = lb_emit_load(p, array);
  10033. }
  10034. lbValue index = lb_build_expr(p, ie->index);
  10035. index = lb_emit_conv(p, index, t_int);
  10036. lbValue elem = lb_emit_array_ep(p, array, index);
  10037. auto index_tv = type_and_value_of_expr(ie->index);
  10038. if (index_tv.mode != Addressing_Constant) {
  10039. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  10040. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10041. }
  10042. return lb_addr(elem);
  10043. }
  10044. case Type_EnumeratedArray: {
  10045. lbValue array = {};
  10046. array = lb_build_addr_ptr(p, ie->expr);
  10047. if (deref) {
  10048. array = lb_emit_load(p, array);
  10049. }
  10050. Type *index_type = t->EnumeratedArray.index;
  10051. auto index_tv = type_and_value_of_expr(ie->index);
  10052. lbValue index = {};
  10053. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  10054. if (index_tv.mode == Addressing_Constant) {
  10055. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  10056. index = lb_const_value(p->module, index_type, idx);
  10057. } else {
  10058. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10059. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  10060. }
  10061. } else {
  10062. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10063. }
  10064. lbValue elem = lb_emit_array_ep(p, array, index);
  10065. if (index_tv.mode != Addressing_Constant) {
  10066. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  10067. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10068. }
  10069. return lb_addr(elem);
  10070. }
  10071. case Type_Slice: {
  10072. lbValue slice = {};
  10073. slice = lb_build_expr(p, ie->expr);
  10074. if (deref) {
  10075. slice = lb_emit_load(p, slice);
  10076. }
  10077. lbValue elem = lb_slice_elem(p, slice);
  10078. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10079. lbValue len = lb_slice_len(p, slice);
  10080. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10081. lbValue v = lb_emit_ptr_offset(p, elem, index);
  10082. return lb_addr(v);
  10083. }
  10084. case Type_RelativeSlice: {
  10085. lbAddr slice_addr = {};
  10086. if (deref) {
  10087. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  10088. } else {
  10089. slice_addr = lb_build_addr(p, ie->expr);
  10090. }
  10091. lbValue slice = lb_addr_load(p, slice_addr);
  10092. lbValue elem = lb_slice_elem(p, slice);
  10093. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10094. lbValue len = lb_slice_len(p, slice);
  10095. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10096. lbValue v = lb_emit_ptr_offset(p, elem, index);
  10097. return lb_addr(v);
  10098. }
  10099. case Type_DynamicArray: {
  10100. lbValue dynamic_array = {};
  10101. dynamic_array = lb_build_expr(p, ie->expr);
  10102. if (deref) {
  10103. dynamic_array = lb_emit_load(p, dynamic_array);
  10104. }
  10105. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  10106. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  10107. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10108. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10109. lbValue v = lb_emit_ptr_offset(p, elem, index);
  10110. return lb_addr(v);
  10111. }
  10112. case Type_Basic: { // Basic_string
  10113. lbValue str;
  10114. lbValue elem;
  10115. lbValue len;
  10116. lbValue index;
  10117. str = lb_build_expr(p, ie->expr);
  10118. if (deref) {
  10119. str = lb_emit_load(p, str);
  10120. }
  10121. elem = lb_string_elem(p, str);
  10122. len = lb_string_len(p, str);
  10123. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  10124. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  10125. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  10126. }
  10127. }
  10128. case_end;
  10129. case_ast_node(se, SliceExpr, expr);
  10130. lbValue low = lb_const_int(p->module, t_int, 0);
  10131. lbValue high = {};
  10132. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  10133. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  10134. bool no_indices = se->low == nullptr && se->high == nullptr;
  10135. {
  10136. Type *type = base_type(type_of_expr(se->expr));
  10137. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  10138. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  10139. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  10140. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  10141. if (found) {
  10142. lbValue base = lb_build_expr(p, found->node);
  10143. Type *slice_type = base.type;
  10144. lbValue len = lb_slice_len(p, base);
  10145. if (high.value == nullptr) high = len;
  10146. if (!no_indices) {
  10147. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10148. }
  10149. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  10150. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10151. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10152. lb_fill_slice(p, slice, elem, new_len);
  10153. return slice;
  10154. }
  10155. }
  10156. }
  10157. }
  10158. lbAddr addr = lb_build_addr(p, se->expr);
  10159. lbValue base = lb_addr_load(p, addr);
  10160. Type *type = base_type(base.type);
  10161. if (is_type_pointer(type)) {
  10162. type = base_type(type_deref(type));
  10163. addr = lb_addr(base);
  10164. base = lb_addr_load(p, addr);
  10165. }
  10166. switch (type->kind) {
  10167. case Type_Slice: {
  10168. Type *slice_type = type;
  10169. lbValue len = lb_slice_len(p, base);
  10170. if (high.value == nullptr) high = len;
  10171. if (!no_indices) {
  10172. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10173. }
  10174. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  10175. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10176. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10177. lb_fill_slice(p, slice, elem, new_len);
  10178. return slice;
  10179. }
  10180. case Type_RelativeSlice:
  10181. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  10182. break;
  10183. case Type_DynamicArray: {
  10184. Type *elem_type = type->DynamicArray.elem;
  10185. Type *slice_type = alloc_type_slice(elem_type);
  10186. lbValue len = lb_dynamic_array_len(p, base);
  10187. if (high.value == nullptr) high = len;
  10188. if (!no_indices) {
  10189. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10190. }
  10191. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  10192. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10193. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10194. lb_fill_slice(p, slice, elem, new_len);
  10195. return slice;
  10196. }
  10197. case Type_Array: {
  10198. Type *slice_type = alloc_type_slice(type->Array.elem);
  10199. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  10200. if (high.value == nullptr) high = len;
  10201. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  10202. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  10203. if (!low_const || !high_const) {
  10204. if (!no_indices) {
  10205. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10206. }
  10207. }
  10208. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  10209. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10210. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  10211. lb_fill_slice(p, slice, elem, new_len);
  10212. return slice;
  10213. }
  10214. case Type_Basic: {
  10215. GB_ASSERT(type == t_string);
  10216. lbValue len = lb_string_len(p, base);
  10217. if (high.value == nullptr) high = len;
  10218. if (!no_indices) {
  10219. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10220. }
  10221. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  10222. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10223. lbAddr str = lb_add_local_generated(p, t_string, false);
  10224. lb_fill_string(p, str, elem, new_len);
  10225. return str;
  10226. }
  10227. case Type_Struct:
  10228. if (is_type_soa_struct(type)) {
  10229. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  10230. if (high.value == nullptr) high = len;
  10231. if (!no_indices) {
  10232. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  10233. }
  10234. #if 1
  10235. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  10236. if (type->Struct.soa_kind == StructSoa_Fixed) {
  10237. i32 field_count = cast(i32)type->Struct.fields.count;
  10238. for (i32 i = 0; i < field_count; i++) {
  10239. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  10240. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  10241. field_src = lb_emit_array_ep(p, field_src, low);
  10242. lb_emit_store(p, field_dst, field_src);
  10243. }
  10244. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  10245. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10246. lb_emit_store(p, len_dst, new_len);
  10247. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  10248. if (no_indices) {
  10249. lb_addr_store(p, dst, base);
  10250. } else {
  10251. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  10252. for (i32 i = 0; i < field_count; i++) {
  10253. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  10254. lbValue field_src = lb_emit_struct_ev(p, base, i);
  10255. field_src = lb_emit_ptr_offset(p, field_src, low);
  10256. lb_emit_store(p, field_dst, field_src);
  10257. }
  10258. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  10259. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10260. lb_emit_store(p, len_dst, new_len);
  10261. }
  10262. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  10263. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  10264. for (i32 i = 0; i < field_count; i++) {
  10265. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  10266. lbValue field_src = lb_emit_struct_ev(p, base, i);
  10267. field_src = lb_emit_ptr_offset(p, field_src, low);
  10268. lb_emit_store(p, field_dst, field_src);
  10269. }
  10270. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  10271. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  10272. lb_emit_store(p, len_dst, new_len);
  10273. }
  10274. return dst;
  10275. #endif
  10276. }
  10277. break;
  10278. }
  10279. GB_PANIC("Unknown slicable type");
  10280. case_end;
  10281. case_ast_node(de, DerefExpr, expr);
  10282. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  10283. lbAddr addr = lb_build_addr(p, de->expr);
  10284. addr.relative.deref = true;
  10285. return addr;
  10286. }
  10287. lbValue addr = lb_build_expr(p, de->expr);
  10288. return lb_addr(addr);
  10289. case_end;
  10290. case_ast_node(ce, CallExpr, expr);
  10291. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  10292. lbValue e = lb_build_expr(p, expr);
  10293. lbAddr v = lb_add_local_generated(p, e.type, false);
  10294. lb_addr_store(p, v, e);
  10295. return v;
  10296. case_end;
  10297. case_ast_node(cl, CompoundLit, expr);
  10298. Type *type = type_of_expr(expr);
  10299. Type *bt = base_type(type);
  10300. lbAddr v = lb_add_local_generated(p, type, true);
  10301. Type *et = nullptr;
  10302. switch (bt->kind) {
  10303. case Type_Array: et = bt->Array.elem; break;
  10304. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  10305. case Type_Slice: et = bt->Slice.elem; break;
  10306. case Type_BitSet: et = bt->BitSet.elem; break;
  10307. case Type_SimdVector: et = bt->SimdVector.elem; break;
  10308. }
  10309. String proc_name = {};
  10310. if (p->entity) {
  10311. proc_name = p->entity->token.string;
  10312. }
  10313. TokenPos pos = ast_token(expr).pos;
  10314. switch (bt->kind) {
  10315. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  10316. case Type_Struct: {
  10317. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  10318. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  10319. bool is_raw_union = is_type_raw_union(bt);
  10320. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  10321. TypeStruct *st = &bt->Struct;
  10322. if (cl->elems.count > 0) {
  10323. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10324. for_array(field_index, cl->elems) {
  10325. Ast *elem = cl->elems[field_index];
  10326. lbValue field_expr = {};
  10327. Entity *field = nullptr;
  10328. isize index = field_index;
  10329. if (elem->kind == Ast_FieldValue) {
  10330. ast_node(fv, FieldValue, elem);
  10331. String name = fv->field->Ident.token.string;
  10332. Selection sel = lookup_field(bt, name, false);
  10333. index = sel.index[0];
  10334. elem = fv->value;
  10335. TypeAndValue tav = type_and_value_of_expr(elem);
  10336. } else {
  10337. TypeAndValue tav = type_and_value_of_expr(elem);
  10338. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  10339. index = sel.index[0];
  10340. }
  10341. field = st->fields[index];
  10342. Type *ft = field->type;
  10343. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  10344. continue;
  10345. }
  10346. field_expr = lb_build_expr(p, elem);
  10347. Type *fet = field_expr.type;
  10348. GB_ASSERT(fet->kind != Type_Tuple);
  10349. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  10350. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  10351. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  10352. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10353. lb_emit_store_union_variant(p, gep, field_expr, fet);
  10354. } else {
  10355. lbValue fv = lb_emit_conv(p, field_expr, ft);
  10356. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10357. lb_emit_store(p, gep, fv);
  10358. }
  10359. }
  10360. }
  10361. break;
  10362. }
  10363. case Type_Map: {
  10364. if (cl->elems.count == 0) {
  10365. break;
  10366. }
  10367. {
  10368. auto args = array_make<lbValue>(permanent_allocator(), 3);
  10369. args[0] = lb_gen_map_header(p, v.addr, type);
  10370. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  10371. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  10372. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  10373. }
  10374. for_array(field_index, cl->elems) {
  10375. Ast *elem = cl->elems[field_index];
  10376. ast_node(fv, FieldValue, elem);
  10377. lbValue key = lb_build_expr(p, fv->field);
  10378. lbValue value = lb_build_expr(p, fv->value);
  10379. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  10380. }
  10381. break;
  10382. }
  10383. case Type_Array: {
  10384. if (cl->elems.count > 0) {
  10385. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10386. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10387. // NOTE(bill): Separate value, gep, store into their own chunks
  10388. for_array(i, cl->elems) {
  10389. Ast *elem = cl->elems[i];
  10390. if (elem->kind == Ast_FieldValue) {
  10391. ast_node(fv, FieldValue, elem);
  10392. if (lb_is_elem_const(fv->value, et)) {
  10393. continue;
  10394. }
  10395. if (is_ast_range(fv->field)) {
  10396. ast_node(ie, BinaryExpr, fv->field);
  10397. TypeAndValue lo_tav = ie->left->tav;
  10398. TypeAndValue hi_tav = ie->right->tav;
  10399. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10400. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10401. TokenKind op = ie->op.kind;
  10402. i64 lo = exact_value_to_i64(lo_tav.value);
  10403. i64 hi = exact_value_to_i64(hi_tav.value);
  10404. if (op == Token_Ellipsis) {
  10405. hi += 1;
  10406. }
  10407. lbValue value = lb_build_expr(p, fv->value);
  10408. for (i64 k = lo; k < hi; k++) {
  10409. lbCompoundLitElemTempData data = {};
  10410. data.value = value;
  10411. data.elem_index = cast(i32)k;
  10412. array_add(&temp_data, data);
  10413. }
  10414. } else {
  10415. auto tav = fv->field->tav;
  10416. GB_ASSERT(tav.mode == Addressing_Constant);
  10417. i64 index = exact_value_to_i64(tav.value);
  10418. lbValue value = lb_build_expr(p, fv->value);
  10419. lbCompoundLitElemTempData data = {};
  10420. data.value = lb_emit_conv(p, value, et);
  10421. data.expr = fv->value;
  10422. data.elem_index = cast(i32)index;
  10423. array_add(&temp_data, data);
  10424. }
  10425. } else {
  10426. if (lb_is_elem_const(elem, et)) {
  10427. continue;
  10428. }
  10429. lbCompoundLitElemTempData data = {};
  10430. data.expr = elem;
  10431. data.elem_index = cast(i32)i;
  10432. array_add(&temp_data, data);
  10433. }
  10434. }
  10435. for_array(i, temp_data) {
  10436. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  10437. }
  10438. for_array(i, temp_data) {
  10439. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  10440. auto return_ptr_hint_value = p->return_ptr_hint_value;
  10441. auto return_ptr_hint_used = p->return_ptr_hint_used;
  10442. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  10443. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  10444. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  10445. lbValue field_expr = temp_data[i].value;
  10446. Ast *expr = temp_data[i].expr;
  10447. p->return_ptr_hint_value = temp_data[i].gep;
  10448. p->return_ptr_hint_ast = unparen_expr(expr);
  10449. if (field_expr.value == nullptr) {
  10450. field_expr = lb_build_expr(p, expr);
  10451. }
  10452. Type *t = field_expr.type;
  10453. GB_ASSERT(t->kind != Type_Tuple);
  10454. lbValue ev = lb_emit_conv(p, field_expr, et);
  10455. if (!p->return_ptr_hint_used) {
  10456. temp_data[i].value = ev;
  10457. }
  10458. }
  10459. for_array(i, temp_data) {
  10460. if (temp_data[i].value.value != nullptr) {
  10461. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10462. }
  10463. }
  10464. }
  10465. break;
  10466. }
  10467. case Type_EnumeratedArray: {
  10468. if (cl->elems.count > 0) {
  10469. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10470. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10471. // NOTE(bill): Separate value, gep, store into their own chunks
  10472. for_array(i, cl->elems) {
  10473. Ast *elem = cl->elems[i];
  10474. if (elem->kind == Ast_FieldValue) {
  10475. ast_node(fv, FieldValue, elem);
  10476. if (lb_is_elem_const(fv->value, et)) {
  10477. continue;
  10478. }
  10479. if (is_ast_range(fv->field)) {
  10480. ast_node(ie, BinaryExpr, fv->field);
  10481. TypeAndValue lo_tav = ie->left->tav;
  10482. TypeAndValue hi_tav = ie->right->tav;
  10483. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10484. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10485. TokenKind op = ie->op.kind;
  10486. i64 lo = exact_value_to_i64(lo_tav.value);
  10487. i64 hi = exact_value_to_i64(hi_tav.value);
  10488. if (op == Token_Ellipsis) {
  10489. hi += 1;
  10490. }
  10491. lbValue value = lb_build_expr(p, fv->value);
  10492. for (i64 k = lo; k < hi; k++) {
  10493. lbCompoundLitElemTempData data = {};
  10494. data.value = value;
  10495. data.elem_index = cast(i32)k;
  10496. array_add(&temp_data, data);
  10497. }
  10498. } else {
  10499. auto tav = fv->field->tav;
  10500. GB_ASSERT(tav.mode == Addressing_Constant);
  10501. i64 index = exact_value_to_i64(tav.value);
  10502. lbValue value = lb_build_expr(p, fv->value);
  10503. lbCompoundLitElemTempData data = {};
  10504. data.value = lb_emit_conv(p, value, et);
  10505. data.expr = fv->value;
  10506. data.elem_index = cast(i32)index;
  10507. array_add(&temp_data, data);
  10508. }
  10509. } else {
  10510. if (lb_is_elem_const(elem, et)) {
  10511. continue;
  10512. }
  10513. lbCompoundLitElemTempData data = {};
  10514. data.expr = elem;
  10515. data.elem_index = cast(i32)i;
  10516. array_add(&temp_data, data);
  10517. }
  10518. }
  10519. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  10520. for_array(i, temp_data) {
  10521. i32 index = temp_data[i].elem_index - index_offset;
  10522. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  10523. }
  10524. for_array(i, temp_data) {
  10525. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  10526. auto return_ptr_hint_value = p->return_ptr_hint_value;
  10527. auto return_ptr_hint_used = p->return_ptr_hint_used;
  10528. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  10529. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  10530. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  10531. lbValue field_expr = temp_data[i].value;
  10532. Ast *expr = temp_data[i].expr;
  10533. p->return_ptr_hint_value = temp_data[i].gep;
  10534. p->return_ptr_hint_ast = unparen_expr(expr);
  10535. if (field_expr.value == nullptr) {
  10536. field_expr = lb_build_expr(p, expr);
  10537. }
  10538. Type *t = field_expr.type;
  10539. GB_ASSERT(t->kind != Type_Tuple);
  10540. lbValue ev = lb_emit_conv(p, field_expr, et);
  10541. if (!p->return_ptr_hint_used) {
  10542. temp_data[i].value = ev;
  10543. }
  10544. }
  10545. for_array(i, temp_data) {
  10546. if (temp_data[i].value.value != nullptr) {
  10547. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10548. }
  10549. }
  10550. }
  10551. break;
  10552. }
  10553. case Type_Slice: {
  10554. if (cl->elems.count > 0) {
  10555. Type *elem_type = bt->Slice.elem;
  10556. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  10557. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  10558. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  10559. lbValue data = lb_slice_elem(p, slice);
  10560. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10561. for_array(i, cl->elems) {
  10562. Ast *elem = cl->elems[i];
  10563. if (elem->kind == Ast_FieldValue) {
  10564. ast_node(fv, FieldValue, elem);
  10565. if (lb_is_elem_const(fv->value, et)) {
  10566. continue;
  10567. }
  10568. if (is_ast_range(fv->field)) {
  10569. ast_node(ie, BinaryExpr, fv->field);
  10570. TypeAndValue lo_tav = ie->left->tav;
  10571. TypeAndValue hi_tav = ie->right->tav;
  10572. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10573. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10574. TokenKind op = ie->op.kind;
  10575. i64 lo = exact_value_to_i64(lo_tav.value);
  10576. i64 hi = exact_value_to_i64(hi_tav.value);
  10577. if (op == Token_Ellipsis) {
  10578. hi += 1;
  10579. }
  10580. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10581. for (i64 k = lo; k < hi; k++) {
  10582. lbCompoundLitElemTempData data = {};
  10583. data.value = value;
  10584. data.elem_index = cast(i32)k;
  10585. array_add(&temp_data, data);
  10586. }
  10587. } else {
  10588. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10589. i64 index = exact_value_to_i64(fv->field->tav.value);
  10590. lbValue field_expr = lb_build_expr(p, fv->value);
  10591. GB_ASSERT(!is_type_tuple(field_expr.type));
  10592. lbValue ev = lb_emit_conv(p, field_expr, et);
  10593. lbCompoundLitElemTempData data = {};
  10594. data.value = ev;
  10595. data.elem_index = cast(i32)index;
  10596. array_add(&temp_data, data);
  10597. }
  10598. } else {
  10599. if (lb_is_elem_const(elem, et)) {
  10600. continue;
  10601. }
  10602. lbValue field_expr = lb_build_expr(p, elem);
  10603. GB_ASSERT(!is_type_tuple(field_expr.type));
  10604. lbValue ev = lb_emit_conv(p, field_expr, et);
  10605. lbCompoundLitElemTempData data = {};
  10606. data.value = ev;
  10607. data.elem_index = cast(i32)i;
  10608. array_add(&temp_data, data);
  10609. }
  10610. }
  10611. for_array(i, temp_data) {
  10612. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  10613. }
  10614. for_array(i, temp_data) {
  10615. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10616. }
  10617. {
  10618. lbValue count = {};
  10619. count.type = t_int;
  10620. if (lb_is_const(slice)) {
  10621. unsigned indices[1] = {1};
  10622. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  10623. } else {
  10624. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  10625. }
  10626. lb_fill_slice(p, v, data, count);
  10627. }
  10628. }
  10629. break;
  10630. }
  10631. case Type_DynamicArray: {
  10632. if (cl->elems.count == 0) {
  10633. break;
  10634. }
  10635. Type *et = bt->DynamicArray.elem;
  10636. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  10637. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  10638. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  10639. {
  10640. auto args = array_make<lbValue>(permanent_allocator(), 5);
  10641. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  10642. args[1] = size;
  10643. args[2] = align;
  10644. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  10645. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  10646. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  10647. }
  10648. lbValue items = lb_generate_local_array(p, et, item_count);
  10649. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  10650. for_array(i, cl->elems) {
  10651. Ast *elem = cl->elems[i];
  10652. if (elem->kind == Ast_FieldValue) {
  10653. ast_node(fv, FieldValue, elem);
  10654. if (is_ast_range(fv->field)) {
  10655. ast_node(ie, BinaryExpr, fv->field);
  10656. TypeAndValue lo_tav = ie->left->tav;
  10657. TypeAndValue hi_tav = ie->right->tav;
  10658. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10659. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10660. TokenKind op = ie->op.kind;
  10661. i64 lo = exact_value_to_i64(lo_tav.value);
  10662. i64 hi = exact_value_to_i64(hi_tav.value);
  10663. if (op == Token_Ellipsis) {
  10664. hi += 1;
  10665. }
  10666. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10667. for (i64 k = lo; k < hi; k++) {
  10668. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  10669. lb_emit_store(p, ep, value);
  10670. }
  10671. } else {
  10672. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10673. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  10674. lbValue ev = lb_build_expr(p, fv->value);
  10675. lbValue value = lb_emit_conv(p, ev, et);
  10676. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  10677. lb_emit_store(p, ep, value);
  10678. }
  10679. } else {
  10680. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  10681. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  10682. lb_emit_store(p, ep, value);
  10683. }
  10684. }
  10685. {
  10686. auto args = array_make<lbValue>(permanent_allocator(), 6);
  10687. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  10688. args[1] = size;
  10689. args[2] = align;
  10690. args[3] = lb_emit_conv(p, items, t_rawptr);
  10691. args[4] = lb_const_int(p->module, t_int, item_count);
  10692. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  10693. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  10694. }
  10695. break;
  10696. }
  10697. case Type_Basic: {
  10698. GB_ASSERT(is_type_any(bt));
  10699. if (cl->elems.count > 0) {
  10700. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10701. String field_names[2] = {
  10702. str_lit("data"),
  10703. str_lit("id"),
  10704. };
  10705. Type *field_types[2] = {
  10706. t_rawptr,
  10707. t_typeid,
  10708. };
  10709. for_array(field_index, cl->elems) {
  10710. Ast *elem = cl->elems[field_index];
  10711. lbValue field_expr = {};
  10712. isize index = field_index;
  10713. if (elem->kind == Ast_FieldValue) {
  10714. ast_node(fv, FieldValue, elem);
  10715. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  10716. index = sel.index[0];
  10717. elem = fv->value;
  10718. } else {
  10719. TypeAndValue tav = type_and_value_of_expr(elem);
  10720. Selection sel = lookup_field(bt, field_names[field_index], false);
  10721. index = sel.index[0];
  10722. }
  10723. field_expr = lb_build_expr(p, elem);
  10724. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  10725. Type *ft = field_types[index];
  10726. lbValue fv = lb_emit_conv(p, field_expr, ft);
  10727. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10728. lb_emit_store(p, gep, fv);
  10729. }
  10730. }
  10731. break;
  10732. }
  10733. case Type_BitSet: {
  10734. i64 sz = type_size_of(type);
  10735. if (cl->elems.count > 0 && sz > 0) {
  10736. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10737. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  10738. for_array(i, cl->elems) {
  10739. Ast *elem = cl->elems[i];
  10740. GB_ASSERT(elem->kind != Ast_FieldValue);
  10741. if (lb_is_elem_const(elem, et)) {
  10742. continue;
  10743. }
  10744. lbValue expr = lb_build_expr(p, elem);
  10745. GB_ASSERT(expr.type->kind != Type_Tuple);
  10746. Type *it = bit_set_to_int(bt);
  10747. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  10748. lbValue e = lb_emit_conv(p, expr, it);
  10749. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  10750. e = lb_emit_arith(p, Token_Shl, one, e, it);
  10751. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  10752. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  10753. new_value = lb_emit_transmute(p, new_value, type);
  10754. lb_addr_store(p, v, new_value);
  10755. }
  10756. }
  10757. break;
  10758. }
  10759. }
  10760. return v;
  10761. case_end;
  10762. case_ast_node(tc, TypeCast, expr);
  10763. Type *type = type_of_expr(expr);
  10764. lbValue x = lb_build_expr(p, tc->expr);
  10765. lbValue e = {};
  10766. switch (tc->token.kind) {
  10767. case Token_cast:
  10768. e = lb_emit_conv(p, x, type);
  10769. break;
  10770. case Token_transmute:
  10771. e = lb_emit_transmute(p, x, type);
  10772. break;
  10773. default:
  10774. GB_PANIC("Invalid AST TypeCast");
  10775. }
  10776. lbAddr v = lb_add_local_generated(p, type, false);
  10777. lb_addr_store(p, v, e);
  10778. return v;
  10779. case_end;
  10780. case_ast_node(ac, AutoCast, expr);
  10781. return lb_build_addr(p, ac->expr);
  10782. case_end;
  10783. }
  10784. TokenPos token_pos = ast_token(expr).pos;
  10785. GB_PANIC("Unexpected address expression\n"
  10786. "\tAst: %.*s @ "
  10787. "%s\n",
  10788. LIT(ast_strings[expr->kind]),
  10789. token_pos_to_string(token_pos));
  10790. return {};
  10791. }
  10792. void lb_init_module(lbModule *m, Checker *c) {
  10793. m->info = &c->info;
  10794. m->ctx = LLVMGetGlobalContext();
  10795. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  10796. // m->debug_builder = nullptr;
  10797. if (build_context.ODIN_DEBUG) {
  10798. enum {DEBUG_METADATA_VERSION = 3};
  10799. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  10800. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  10801. switch (build_context.metrics.os) {
  10802. case TargetOs_windows:
  10803. LLVMAddModuleFlag(m->mod,
  10804. LLVMModuleFlagBehaviorWarning,
  10805. "CodeView", 8,
  10806. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true)));
  10807. break;
  10808. case TargetOs_darwin:
  10809. // NOTE(bill): Darwin only supports DWARF2 (that I know of)
  10810. LLVMAddModuleFlag(m->mod,
  10811. LLVMModuleFlagBehaviorWarning,
  10812. "Dwarf Version", 13,
  10813. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 2, true)));
  10814. break;
  10815. }
  10816. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  10817. }
  10818. gb_mutex_init(&m->mutex);
  10819. gbAllocator a = heap_allocator();
  10820. map_init(&m->types, a);
  10821. map_init(&m->llvm_types, a);
  10822. map_init(&m->values, a);
  10823. map_init(&m->soa_values, a);
  10824. string_map_init(&m->members, a);
  10825. map_init(&m->procedure_values, a);
  10826. string_map_init(&m->procedures, a);
  10827. string_map_init(&m->const_strings, a);
  10828. map_init(&m->anonymous_proc_lits, a);
  10829. map_init(&m->function_type_map, a);
  10830. map_init(&m->equal_procs, a);
  10831. map_init(&m->hasher_procs, a);
  10832. array_init(&m->procedures_to_generate, a, 0, 1024);
  10833. array_init(&m->foreign_library_paths, a, 0, 1024);
  10834. map_init(&m->debug_values, a);
  10835. array_init(&m->debug_incomplete_types, a, 0, 1024);
  10836. }
  10837. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  10838. if (global_error_collector.count != 0) {
  10839. return false;
  10840. }
  10841. isize tc = c->parser->total_token_count;
  10842. if (tc < 2) {
  10843. return false;
  10844. }
  10845. String init_fullpath = c->parser->init_fullpath;
  10846. if (build_context.out_filepath.len == 0) {
  10847. gen->output_name = remove_directory_from_path(init_fullpath);
  10848. gen->output_name = remove_extension_from_path(gen->output_name);
  10849. gen->output_name = string_trim_whitespace(gen->output_name);
  10850. if (gen->output_name.len == 0) {
  10851. gen->output_name = c->info.init_scope->pkg->name;
  10852. }
  10853. gen->output_base = gen->output_name;
  10854. } else {
  10855. gen->output_name = build_context.out_filepath;
  10856. gen->output_name = string_trim_whitespace(gen->output_name);
  10857. if (gen->output_name.len == 0) {
  10858. gen->output_name = c->info.init_scope->pkg->name;
  10859. }
  10860. isize pos = string_extension_position(gen->output_name);
  10861. if (pos < 0) {
  10862. gen->output_base = gen->output_name;
  10863. } else {
  10864. gen->output_base = substring(gen->output_name, 0, pos);
  10865. }
  10866. }
  10867. gbAllocator ha = heap_allocator();
  10868. array_init(&gen->output_object_paths, ha);
  10869. gen->output_base = path_to_full_path(ha, gen->output_base);
  10870. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  10871. output_file_path = gb_string_appendc(output_file_path, ".obj");
  10872. defer (gb_string_free(output_file_path));
  10873. gen->info = &c->info;
  10874. lb_init_module(&gen->module, c);
  10875. return true;
  10876. }
  10877. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  10878. GB_ASSERT(type != nullptr);
  10879. type = default_type(type);
  10880. isize max_len = 7+8+1;
  10881. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  10882. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  10883. m->global_generated_index++;
  10884. String name = make_string(str, len-1);
  10885. Scope *scope = nullptr;
  10886. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  10887. lbValue g = {};
  10888. g.type = alloc_type_pointer(type);
  10889. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  10890. if (value.value != nullptr) {
  10891. GB_ASSERT(LLVMIsConstant(value.value));
  10892. LLVMSetInitializer(g.value, value.value);
  10893. } else {
  10894. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  10895. }
  10896. lb_add_entity(m, e, g);
  10897. lb_add_member(m, name, g);
  10898. return lb_addr(g);
  10899. }
  10900. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  10901. AstPackage *p = m->info->runtime_package;
  10902. Entity *e = scope_lookup_current(p->scope, name);
  10903. lbValue *found = map_get(&m->values, hash_entity(e));
  10904. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  10905. lbValue value = *found;
  10906. return value;
  10907. }
  10908. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  10909. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  10910. lbValue *found = map_get(&m->values, hash_entity(e));
  10911. GB_ASSERT_MSG(found != nullptr, "Unable to find value '%.*s.%.*s'", LIT(pkg), LIT(name));
  10912. lbValue value = *found;
  10913. return value;
  10914. }
  10915. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  10916. i32 index = cast(i32)lb_type_info_index(m->info, type);
  10917. GB_ASSERT(index >= 0);
  10918. // gb_printf_err("%d %s\n", index, type_to_string(type));
  10919. LLVMValueRef indices[2] = {
  10920. LLVMConstInt(lb_type(m, t_int), 0, false),
  10921. LLVMConstInt(lb_type(m, t_int), index, false),
  10922. };
  10923. lbValue res = {};
  10924. res.type = t_type_info_ptr;
  10925. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  10926. return res;
  10927. }
  10928. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  10929. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  10930. lb_global_type_info_member_types_index += cast(i32)count;
  10931. return offset;
  10932. }
  10933. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  10934. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  10935. lb_global_type_info_member_names_index += cast(i32)count;
  10936. return offset;
  10937. }
  10938. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  10939. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  10940. lb_global_type_info_member_offsets_index += cast(i32)count;
  10941. return offset;
  10942. }
  10943. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  10944. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  10945. lb_global_type_info_member_usings_index += cast(i32)count;
  10946. return offset;
  10947. }
  10948. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  10949. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  10950. lb_global_type_info_member_tags_index += cast(i32)count;
  10951. return offset;
  10952. }
  10953. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  10954. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  10955. return lb_addr_get_ptr(p, addr);
  10956. }
  10957. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  10958. Token token = {Token_Ident};
  10959. isize name_len = prefix.len + 1 + 20;
  10960. auto suffix_id = cast(unsigned long long)id;
  10961. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  10962. gb_snprintf(text, name_len,
  10963. "%.*s-%llu", LIT(prefix), suffix_id);
  10964. text[name_len] = 0;
  10965. String s = make_string_c(text);
  10966. Type *t = alloc_type_array(elem_type, count);
  10967. lbValue g = {};
  10968. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  10969. g.type = alloc_type_pointer(t);
  10970. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  10971. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  10972. string_map_set(&m->members, s, g);
  10973. return g;
  10974. }
  10975. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  10976. lbModule *m = p->module;
  10977. LLVMContextRef ctx = m->ctx;
  10978. CheckerInfo *info = m->info;
  10979. {
  10980. // NOTE(bill): Set the type_table slice with the global backing array
  10981. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  10982. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  10983. GB_ASSERT(is_type_array(type));
  10984. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  10985. LLVMValueRef values[2] = {
  10986. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  10987. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  10988. };
  10989. LLVMValueRef slice = llvm_const_named_struct(llvm_addr_type(global_type_table), values, gb_count_of(values));
  10990. LLVMSetInitializer(global_type_table.value, slice);
  10991. }
  10992. // Useful types
  10993. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  10994. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  10995. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  10996. Type *t_type_info_flags = type_info_flags_entity->type;
  10997. i32 type_info_member_types_index = 0;
  10998. i32 type_info_member_names_index = 0;
  10999. i32 type_info_member_offsets_index = 0;
  11000. for_array(type_info_type_index, info->type_info_types) {
  11001. Type *t = info->type_info_types[type_info_type_index];
  11002. if (t == nullptr || t == t_invalid) {
  11003. continue;
  11004. }
  11005. isize entry_index = lb_type_info_index(info, t, false);
  11006. if (entry_index <= 0) {
  11007. continue;
  11008. }
  11009. lbValue tag = {};
  11010. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  11011. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  11012. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  11013. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  11014. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  11015. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  11016. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  11017. switch (t->kind) {
  11018. case Type_Named: {
  11019. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  11020. LLVMValueRef pkg_name = nullptr;
  11021. if (t->Named.type_name->pkg) {
  11022. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  11023. } else {
  11024. pkg_name = LLVMConstNull(lb_type(m, t_string));
  11025. }
  11026. String proc_name = {};
  11027. if (t->Named.type_name->parent_proc_decl) {
  11028. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  11029. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  11030. proc_name = decl->entity->token.string;
  11031. }
  11032. }
  11033. TokenPos pos = t->Named.type_name->token.pos;
  11034. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  11035. LLVMValueRef vals[4] = {
  11036. lb_const_string(p->module, t->Named.type_name->token.string).value,
  11037. lb_get_type_info_ptr(m, t->Named.base).value,
  11038. pkg_name,
  11039. loc.value
  11040. };
  11041. lbValue res = {};
  11042. res.type = type_deref(tag.type);
  11043. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11044. lb_emit_store(p, tag, res);
  11045. break;
  11046. }
  11047. case Type_Basic:
  11048. switch (t->Basic.kind) {
  11049. case Basic_bool:
  11050. case Basic_b8:
  11051. case Basic_b16:
  11052. case Basic_b32:
  11053. case Basic_b64:
  11054. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  11055. break;
  11056. case Basic_i8:
  11057. case Basic_u8:
  11058. case Basic_i16:
  11059. case Basic_u16:
  11060. case Basic_i32:
  11061. case Basic_u32:
  11062. case Basic_i64:
  11063. case Basic_u64:
  11064. case Basic_i128:
  11065. case Basic_u128:
  11066. case Basic_i16le:
  11067. case Basic_u16le:
  11068. case Basic_i32le:
  11069. case Basic_u32le:
  11070. case Basic_i64le:
  11071. case Basic_u64le:
  11072. case Basic_i128le:
  11073. case Basic_u128le:
  11074. case Basic_i16be:
  11075. case Basic_u16be:
  11076. case Basic_i32be:
  11077. case Basic_u32be:
  11078. case Basic_i64be:
  11079. case Basic_u64be:
  11080. case Basic_i128be:
  11081. case Basic_u128be:
  11082. case Basic_int:
  11083. case Basic_uint:
  11084. case Basic_uintptr: {
  11085. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  11086. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  11087. // NOTE(bill): This is matches the runtime layout
  11088. u8 endianness_value = 0;
  11089. if (t->Basic.flags & BasicFlag_EndianLittle) {
  11090. endianness_value = 1;
  11091. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  11092. endianness_value = 2;
  11093. }
  11094. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  11095. LLVMValueRef vals[2] = {
  11096. is_signed.value,
  11097. endianness.value,
  11098. };
  11099. lbValue res = {};
  11100. res.type = type_deref(tag.type);
  11101. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11102. lb_emit_store(p, tag, res);
  11103. break;
  11104. }
  11105. case Basic_rune:
  11106. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  11107. break;
  11108. case Basic_f16:
  11109. case Basic_f32:
  11110. case Basic_f64:
  11111. case Basic_f16le:
  11112. case Basic_f32le:
  11113. case Basic_f64le:
  11114. case Basic_f16be:
  11115. case Basic_f32be:
  11116. case Basic_f64be:
  11117. {
  11118. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  11119. // NOTE(bill): This is matches the runtime layout
  11120. u8 endianness_value = 0;
  11121. if (t->Basic.flags & BasicFlag_EndianLittle) {
  11122. endianness_value = 1;
  11123. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  11124. endianness_value = 2;
  11125. }
  11126. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  11127. LLVMValueRef vals[1] = {
  11128. endianness.value,
  11129. };
  11130. lbValue res = {};
  11131. res.type = type_deref(tag.type);
  11132. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11133. lb_emit_store(p, tag, res);
  11134. }
  11135. break;
  11136. case Basic_complex32:
  11137. case Basic_complex64:
  11138. case Basic_complex128:
  11139. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  11140. break;
  11141. case Basic_quaternion64:
  11142. case Basic_quaternion128:
  11143. case Basic_quaternion256:
  11144. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  11145. break;
  11146. case Basic_rawptr:
  11147. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  11148. break;
  11149. case Basic_string:
  11150. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  11151. break;
  11152. case Basic_cstring:
  11153. {
  11154. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  11155. LLVMValueRef vals[1] = {
  11156. lb_const_bool(m, t_bool, true).value,
  11157. };
  11158. lbValue res = {};
  11159. res.type = type_deref(tag.type);
  11160. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11161. lb_emit_store(p, tag, res);
  11162. }
  11163. break;
  11164. case Basic_any:
  11165. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  11166. break;
  11167. case Basic_typeid:
  11168. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  11169. break;
  11170. }
  11171. break;
  11172. case Type_Pointer: {
  11173. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  11174. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  11175. LLVMValueRef vals[1] = {
  11176. gep.value,
  11177. };
  11178. lbValue res = {};
  11179. res.type = type_deref(tag.type);
  11180. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11181. lb_emit_store(p, tag, res);
  11182. break;
  11183. }
  11184. case Type_Array: {
  11185. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  11186. i64 ez = type_size_of(t->Array.elem);
  11187. LLVMValueRef vals[3] = {
  11188. lb_get_type_info_ptr(m, t->Array.elem).value,
  11189. lb_const_int(m, t_int, ez).value,
  11190. lb_const_int(m, t_int, t->Array.count).value,
  11191. };
  11192. lbValue res = {};
  11193. res.type = type_deref(tag.type);
  11194. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11195. lb_emit_store(p, tag, res);
  11196. break;
  11197. }
  11198. case Type_EnumeratedArray: {
  11199. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  11200. LLVMValueRef vals[6] = {
  11201. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  11202. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  11203. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  11204. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  11205. // Unions
  11206. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  11207. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  11208. };
  11209. lbValue res = {};
  11210. res.type = type_deref(tag.type);
  11211. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11212. lb_emit_store(p, tag, res);
  11213. // NOTE(bill): Union assignment
  11214. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  11215. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  11216. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  11217. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  11218. lb_emit_store(p, min_value, min_v);
  11219. lb_emit_store(p, max_value, max_v);
  11220. break;
  11221. }
  11222. case Type_DynamicArray: {
  11223. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  11224. LLVMValueRef vals[2] = {
  11225. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  11226. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  11227. };
  11228. lbValue res = {};
  11229. res.type = type_deref(tag.type);
  11230. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11231. lb_emit_store(p, tag, res);
  11232. break;
  11233. }
  11234. case Type_Slice: {
  11235. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  11236. LLVMValueRef vals[2] = {
  11237. lb_get_type_info_ptr(m, t->Slice.elem).value,
  11238. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  11239. };
  11240. lbValue res = {};
  11241. res.type = type_deref(tag.type);
  11242. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11243. lb_emit_store(p, tag, res);
  11244. break;
  11245. }
  11246. case Type_Proc: {
  11247. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  11248. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11249. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11250. if (t->Proc.params != nullptr) {
  11251. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  11252. }
  11253. if (t->Proc.results != nullptr) {
  11254. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  11255. }
  11256. LLVMValueRef vals[4] = {
  11257. params,
  11258. results,
  11259. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  11260. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  11261. };
  11262. lbValue res = {};
  11263. res.type = type_deref(tag.type);
  11264. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11265. lb_emit_store(p, tag, res);
  11266. break;
  11267. }
  11268. case Type_Tuple: {
  11269. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  11270. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  11271. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  11272. for_array(i, t->Tuple.variables) {
  11273. // NOTE(bill): offset is not used for tuples
  11274. Entity *f = t->Tuple.variables[i];
  11275. lbValue index = lb_const_int(m, t_int, i);
  11276. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11277. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  11278. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  11279. if (f->token.string.len > 0) {
  11280. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  11281. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  11282. }
  11283. }
  11284. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  11285. LLVMValueRef types_slice = llvm_const_slice(m, memory_types, count);
  11286. LLVMValueRef names_slice = llvm_const_slice(m, memory_names, count);
  11287. LLVMValueRef vals[2] = {
  11288. types_slice,
  11289. names_slice,
  11290. };
  11291. lbValue res = {};
  11292. res.type = type_deref(tag.type);
  11293. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11294. lb_emit_store(p, tag, res);
  11295. break;
  11296. }
  11297. case Type_Enum:
  11298. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  11299. {
  11300. GB_ASSERT(t->Enum.base_type != nullptr);
  11301. // 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));
  11302. LLVMValueRef vals[3] = {};
  11303. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  11304. if (t->Enum.fields.count > 0) {
  11305. auto fields = t->Enum.fields;
  11306. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  11307. str_lit("$enum_names"), cast(i64)entry_index);
  11308. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  11309. str_lit("$enum_values"), cast(i64)entry_index);
  11310. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  11311. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  11312. GB_ASSERT(is_type_integer(t->Enum.base_type));
  11313. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  11314. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  11315. for_array(i, fields) {
  11316. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  11317. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  11318. }
  11319. LLVMValueRef name_init = llvm_const_array(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  11320. LLVMValueRef value_init = llvm_const_array(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  11321. LLVMSetInitializer(name_array.value, name_init);
  11322. LLVMSetInitializer(value_array.value, value_init);
  11323. lbValue v_count = lb_const_int(m, t_int, fields.count);
  11324. vals[1] = llvm_const_slice(m, lb_array_elem(p, name_array), v_count);
  11325. vals[2] = llvm_const_slice(m, lb_array_elem(p, value_array), v_count);
  11326. } else {
  11327. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  11328. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  11329. }
  11330. lbValue res = {};
  11331. res.type = type_deref(tag.type);
  11332. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11333. lb_emit_store(p, tag, res);
  11334. }
  11335. break;
  11336. case Type_Union: {
  11337. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  11338. {
  11339. LLVMValueRef vals[6] = {};
  11340. isize variant_count = gb_max(0, t->Union.variants.count);
  11341. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  11342. // NOTE(bill): Zeroth is nil so ignore it
  11343. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  11344. Type *vt = t->Union.variants[variant_index];
  11345. lbValue tip = lb_get_type_info_ptr(m, vt);
  11346. lbValue index = lb_const_int(m, t_int, variant_index);
  11347. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11348. lb_emit_store(p, type_info, lb_type_info(m, vt));
  11349. }
  11350. lbValue count = lb_const_int(m, t_int, variant_count);
  11351. vals[0] = llvm_const_slice(m, memory_types, count);
  11352. i64 tag_size = union_tag_size(t);
  11353. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  11354. if (tag_size > 0) {
  11355. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  11356. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  11357. } else {
  11358. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  11359. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  11360. }
  11361. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  11362. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  11363. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  11364. lbValue res = {};
  11365. res.type = type_deref(tag.type);
  11366. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11367. lb_emit_store(p, tag, res);
  11368. }
  11369. break;
  11370. }
  11371. case Type_Struct: {
  11372. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  11373. LLVMValueRef vals[12] = {};
  11374. {
  11375. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  11376. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  11377. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  11378. vals[5] = is_packed.value;
  11379. vals[6] = is_raw_union.value;
  11380. vals[7] = is_custom_align.value;
  11381. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  11382. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  11383. }
  11384. if (t->Struct.soa_kind != StructSoa_None) {
  11385. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  11386. Type *kind_type = type_deref(kind.type);
  11387. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  11388. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  11389. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  11390. vals[9] = soa_kind.value;
  11391. vals[10] = soa_type.value;
  11392. vals[11] = soa_len.value;
  11393. }
  11394. }
  11395. isize count = t->Struct.fields.count;
  11396. if (count > 0) {
  11397. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  11398. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  11399. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  11400. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  11401. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  11402. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  11403. for (isize source_index = 0; source_index < count; source_index++) {
  11404. // TODO(bill): Order fields in source order not layout order
  11405. Entity *f = t->Struct.fields[source_index];
  11406. lbValue tip = lb_get_type_info_ptr(m, f->type);
  11407. i64 foffset = 0;
  11408. if (!t->Struct.is_raw_union) {
  11409. foffset = t->Struct.offsets[f->Variable.field_index];
  11410. }
  11411. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  11412. lbValue index = lb_const_int(m, t_int, source_index);
  11413. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  11414. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  11415. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  11416. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  11417. if (f->token.string.len > 0) {
  11418. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  11419. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  11420. }
  11421. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  11422. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  11423. if (t->Struct.tags.count > 0) {
  11424. String tag_string = t->Struct.tags[source_index];
  11425. if (tag_string.len > 0) {
  11426. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  11427. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  11428. }
  11429. }
  11430. }
  11431. lbValue cv = lb_const_int(m, t_int, count);
  11432. vals[0] = llvm_const_slice(m, memory_types, cv);
  11433. vals[1] = llvm_const_slice(m, memory_names, cv);
  11434. vals[2] = llvm_const_slice(m, memory_offsets, cv);
  11435. vals[3] = llvm_const_slice(m, memory_usings, cv);
  11436. vals[4] = llvm_const_slice(m, memory_tags, cv);
  11437. }
  11438. for (isize i = 0; i < gb_count_of(vals); i++) {
  11439. if (vals[i] == nullptr) {
  11440. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  11441. }
  11442. }
  11443. lbValue res = {};
  11444. res.type = type_deref(tag.type);
  11445. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11446. lb_emit_store(p, tag, res);
  11447. break;
  11448. }
  11449. case Type_Map: {
  11450. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  11451. init_map_internal_types(t);
  11452. LLVMValueRef vals[5] = {
  11453. lb_get_type_info_ptr(m, t->Map.key).value,
  11454. lb_get_type_info_ptr(m, t->Map.value).value,
  11455. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  11456. lb_get_equal_proc_for_type(m, t->Map.key).value,
  11457. lb_get_hasher_proc_for_type(m, t->Map.key).value
  11458. };
  11459. lbValue res = {};
  11460. res.type = type_deref(tag.type);
  11461. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11462. lb_emit_store(p, tag, res);
  11463. break;
  11464. }
  11465. case Type_BitSet:
  11466. {
  11467. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  11468. GB_ASSERT(is_type_typed(t->BitSet.elem));
  11469. LLVMValueRef vals[4] = {
  11470. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  11471. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  11472. lb_const_int(m, t_i64, t->BitSet.lower).value,
  11473. lb_const_int(m, t_i64, t->BitSet.upper).value,
  11474. };
  11475. if (t->BitSet.underlying != nullptr) {
  11476. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  11477. }
  11478. lbValue res = {};
  11479. res.type = type_deref(tag.type);
  11480. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11481. lb_emit_store(p, tag, res);
  11482. }
  11483. break;
  11484. case Type_SimdVector:
  11485. {
  11486. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  11487. LLVMValueRef vals[3] = {};
  11488. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  11489. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  11490. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  11491. lbValue res = {};
  11492. res.type = type_deref(tag.type);
  11493. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11494. lb_emit_store(p, tag, res);
  11495. }
  11496. break;
  11497. case Type_RelativePointer:
  11498. {
  11499. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  11500. LLVMValueRef vals[2] = {
  11501. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  11502. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  11503. };
  11504. lbValue res = {};
  11505. res.type = type_deref(tag.type);
  11506. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11507. lb_emit_store(p, tag, res);
  11508. }
  11509. break;
  11510. case Type_RelativeSlice:
  11511. {
  11512. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  11513. LLVMValueRef vals[2] = {
  11514. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  11515. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  11516. };
  11517. lbValue res = {};
  11518. res.type = type_deref(tag.type);
  11519. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11520. lb_emit_store(p, tag, res);
  11521. }
  11522. break;
  11523. }
  11524. if (tag.value != nullptr) {
  11525. Type *tag_type = type_deref(tag.type);
  11526. GB_ASSERT(is_type_named(tag_type));
  11527. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  11528. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  11529. } else {
  11530. if (t != t_llvm_bool) {
  11531. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  11532. }
  11533. }
  11534. }
  11535. }
  11536. void lb_generate_code(lbGenerator *gen) {
  11537. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  11538. TIME_SECTION("LLVM Initializtion");
  11539. lbModule *m = &gen->module;
  11540. LLVMModuleRef mod = gen->module.mod;
  11541. CheckerInfo *info = gen->info;
  11542. auto *min_dep_set = &info->minimum_dependency_set;
  11543. LLVMInitializeAllTargetInfos();
  11544. LLVMInitializeAllTargets();
  11545. LLVMInitializeAllTargetMCs();
  11546. LLVMInitializeAllAsmPrinters();
  11547. LLVMInitializeAllAsmParsers();
  11548. LLVMInitializeAllDisassemblers();
  11549. LLVMInitializeNativeTarget();
  11550. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  11551. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  11552. LLVMSetTarget(mod, target_triple);
  11553. LLVMTargetRef target = {};
  11554. char *llvm_error = nullptr;
  11555. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  11556. GB_ASSERT(target != nullptr);
  11557. TIME_SECTION("LLVM Create Target Machine");
  11558. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  11559. if (build_context.metrics.arch == TargetArch_wasm32) {
  11560. code_mode = LLVMCodeModelJITDefault;
  11561. }
  11562. char const *host_cpu_name = LLVMGetHostCPUName();
  11563. char const *llvm_cpu = "generic";
  11564. char const *llvm_features = "";
  11565. if (build_context.microarch.len != 0) {
  11566. if (build_context.microarch == "native") {
  11567. llvm_cpu = host_cpu_name;
  11568. } else {
  11569. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  11570. }
  11571. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  11572. llvm_features = LLVMGetHostCPUFeatures();
  11573. }
  11574. }
  11575. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  11576. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  11577. switch (build_context.optimization_level) {
  11578. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  11579. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  11580. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  11581. case 3: code_gen_level = LLVMCodeGenLevelDefault; break; // NOTE(bill): force -opt:3 to be the same as -opt:2
  11582. // case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  11583. }
  11584. // NOTE(bill): Target Machine Creation
  11585. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(
  11586. target, target_triple, llvm_cpu,
  11587. llvm_features,
  11588. code_gen_level,
  11589. LLVMRelocDefault,
  11590. code_mode);
  11591. defer (LLVMDisposeTargetMachine(target_machine));
  11592. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  11593. if (m->debug_builder) { // Debug Info
  11594. for_array(i, info->files.entries) {
  11595. AstFile *f = info->files.entries[i].value;
  11596. String fullpath = f->fullpath;
  11597. String filename = remove_directory_from_path(fullpath);
  11598. String directory = directory_from_path(fullpath);
  11599. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  11600. cast(char const *)filename.text, filename.len,
  11601. cast(char const *)directory.text, directory.len);
  11602. lb_set_llvm_metadata(m, f, res);
  11603. }
  11604. gbString producer = gb_string_make(heap_allocator(), "odin");
  11605. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  11606. // #ifdef NIGHTLY
  11607. // producer = gb_string_appendc(producer, "-nightly");
  11608. // #endif
  11609. // #ifdef GIT_SHA
  11610. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  11611. // #endif
  11612. gbString split_name = gb_string_make(heap_allocator(), "");
  11613. LLVMBool is_optimized = build_context.optimization_level > 0;
  11614. AstFile *init_file = m->info->init_package->files[0];
  11615. if (m->info->entry_point && m->info->entry_point->identifier && m->info->entry_point->identifier->file) {
  11616. init_file = m->info->entry_point->identifier->file;
  11617. }
  11618. LLVMBool split_debug_inlining = false;
  11619. LLVMBool debug_info_for_profiling = false;
  11620. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  11621. lb_get_llvm_metadata(m, init_file),
  11622. producer, gb_string_length(producer),
  11623. is_optimized, "", 0,
  11624. 1, split_name, gb_string_length(split_name),
  11625. LLVMDWARFEmissionFull,
  11626. 0, split_debug_inlining,
  11627. debug_info_for_profiling,
  11628. "", 0, // sys_root
  11629. "", 0 // SDK
  11630. );
  11631. GB_ASSERT(m->debug_compile_unit != nullptr);
  11632. }
  11633. TIME_SECTION("LLVM Global Variables");
  11634. {
  11635. { // Add type info data
  11636. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  11637. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  11638. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  11639. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  11640. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11641. LLVMSetLinkage(g, LLVMInternalLinkage);
  11642. lbValue value = {};
  11643. value.value = g;
  11644. value.type = alloc_type_pointer(t);
  11645. lb_global_type_info_data = lb_addr(value);
  11646. }
  11647. { // Type info member buffer
  11648. // NOTE(bill): Removes need for heap allocation by making it global memory
  11649. isize count = 0;
  11650. for_array(entry_index, m->info->type_info_types) {
  11651. Type *t = m->info->type_info_types[entry_index];
  11652. isize index = lb_type_info_index(m->info, t, false);
  11653. if (index < 0) {
  11654. continue;
  11655. }
  11656. switch (t->kind) {
  11657. case Type_Union:
  11658. count += t->Union.variants.count;
  11659. break;
  11660. case Type_Struct:
  11661. count += t->Struct.fields.count;
  11662. break;
  11663. case Type_Tuple:
  11664. count += t->Tuple.variables.count;
  11665. break;
  11666. }
  11667. }
  11668. if (count > 0) {
  11669. {
  11670. char const *name = LB_TYPE_INFO_TYPES_NAME;
  11671. Type *t = alloc_type_array(t_type_info_ptr, count);
  11672. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11673. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11674. LLVMSetLinkage(g, LLVMInternalLinkage);
  11675. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  11676. }
  11677. {
  11678. char const *name = LB_TYPE_INFO_NAMES_NAME;
  11679. Type *t = alloc_type_array(t_string, count);
  11680. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11681. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11682. LLVMSetLinkage(g, LLVMInternalLinkage);
  11683. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  11684. }
  11685. {
  11686. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  11687. Type *t = alloc_type_array(t_uintptr, count);
  11688. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11689. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11690. LLVMSetLinkage(g, LLVMInternalLinkage);
  11691. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  11692. }
  11693. {
  11694. char const *name = LB_TYPE_INFO_USINGS_NAME;
  11695. Type *t = alloc_type_array(t_bool, count);
  11696. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11697. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11698. LLVMSetLinkage(g, LLVMInternalLinkage);
  11699. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  11700. }
  11701. {
  11702. char const *name = LB_TYPE_INFO_TAGS_NAME;
  11703. Type *t = alloc_type_array(t_string, count);
  11704. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11705. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11706. LLVMSetLinkage(g, LLVMInternalLinkage);
  11707. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  11708. }
  11709. }
  11710. }
  11711. }
  11712. isize global_variable_max_count = 0;
  11713. Entity *entry_point = info->entry_point;
  11714. bool has_dll_main = false;
  11715. bool has_win_main = false;
  11716. for_array(i, info->entities) {
  11717. Entity *e = info->entities[i];
  11718. String name = e->token.string;
  11719. bool is_global = e->pkg != nullptr;
  11720. if (e->kind == Entity_Variable) {
  11721. global_variable_max_count++;
  11722. } else if (e->kind == Entity_Procedure && !is_global) {
  11723. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  11724. GB_ASSERT(e == entry_point);
  11725. // entry_point = e;
  11726. }
  11727. if (e->Procedure.is_export ||
  11728. (e->Procedure.link_name.len > 0) ||
  11729. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  11730. if (!has_dll_main && name == "DllMain") {
  11731. has_dll_main = true;
  11732. } else if (!has_win_main && name == "WinMain") {
  11733. has_win_main = true;
  11734. }
  11735. }
  11736. }
  11737. }
  11738. struct GlobalVariable {
  11739. lbValue var;
  11740. lbValue init;
  11741. DeclInfo *decl;
  11742. bool is_initialized;
  11743. };
  11744. auto global_variables = array_make<GlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  11745. for_array(i, info->variable_init_order) {
  11746. DeclInfo *d = info->variable_init_order[i];
  11747. Entity *e = d->entity;
  11748. if ((e->scope->flags & ScopeFlag_File) == 0) {
  11749. continue;
  11750. }
  11751. if (!ptr_set_exists(min_dep_set, e)) {
  11752. continue;
  11753. }
  11754. DeclInfo *decl = decl_info_of_entity(e);
  11755. if (decl == nullptr) {
  11756. continue;
  11757. }
  11758. GB_ASSERT(e->kind == Entity_Variable);
  11759. bool is_foreign = e->Variable.is_foreign;
  11760. bool is_export = e->Variable.is_export;
  11761. String name = lb_get_entity_name(m, e);
  11762. lbValue g = {};
  11763. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  11764. g.type = alloc_type_pointer(e->type);
  11765. if (e->Variable.thread_local_model != "") {
  11766. LLVMSetThreadLocal(g.value, true);
  11767. String m = e->Variable.thread_local_model;
  11768. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  11769. if (m == "default") {
  11770. mode = LLVMGeneralDynamicTLSModel;
  11771. } else if (m == "localdynamic") {
  11772. mode = LLVMLocalDynamicTLSModel;
  11773. } else if (m == "initialexec") {
  11774. mode = LLVMInitialExecTLSModel;
  11775. } else if (m == "localexec") {
  11776. mode = LLVMLocalExecTLSModel;
  11777. } else {
  11778. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  11779. }
  11780. LLVMSetThreadLocalMode(g.value, mode);
  11781. }
  11782. if (is_foreign) {
  11783. LLVMSetExternallyInitialized(g.value, true);
  11784. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  11785. } else {
  11786. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  11787. }
  11788. if (is_export) {
  11789. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  11790. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  11791. }
  11792. if (e->flags & EntityFlag_Static) {
  11793. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  11794. }
  11795. GlobalVariable var = {};
  11796. var.var = g;
  11797. var.decl = decl;
  11798. if (decl->init_expr != nullptr) {
  11799. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  11800. if (!is_type_any(e->type)) {
  11801. if (tav.mode != Addressing_Invalid) {
  11802. if (tav.value.kind != ExactValue_Invalid) {
  11803. ExactValue v = tav.value;
  11804. lbValue init = lb_const_value(m, tav.type, v);
  11805. LLVMSetInitializer(g.value, init.value);
  11806. var.is_initialized = true;
  11807. }
  11808. }
  11809. }
  11810. if (!var.is_initialized &&
  11811. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  11812. var.is_initialized = true;
  11813. }
  11814. }
  11815. array_add(&global_variables, var);
  11816. lb_add_entity(m, e, g);
  11817. lb_add_member(m, name, g);
  11818. if (m->debug_builder) {
  11819. String global_name = e->token.string;
  11820. if (global_name.len != 0 && global_name != "_") {
  11821. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  11822. LLVMMetadataRef llvm_scope = llvm_file;
  11823. LLVMBool local_to_unit = e->flags & EntityFlag_Static;
  11824. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  11825. LLVMMetadataRef llvm_decl = nullptr;
  11826. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  11827. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  11828. m->debug_builder, llvm_scope,
  11829. cast(char const *)global_name.text, global_name.len,
  11830. "", 0, // linkage
  11831. llvm_file, e->token.pos.line,
  11832. lb_debug_type(m, e->type),
  11833. local_to_unit,
  11834. llvm_expr,
  11835. llvm_decl,
  11836. align_in_bits
  11837. );
  11838. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  11839. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  11840. }
  11841. }
  11842. }
  11843. TIME_SECTION("LLVM Global Procedures and Types");
  11844. for_array(i, info->entities) {
  11845. Entity *e = info->entities[i];
  11846. String name = e->token.string;
  11847. DeclInfo *decl = e->decl_info;
  11848. Scope * scope = e->scope;
  11849. if ((scope->flags & ScopeFlag_File) == 0) {
  11850. continue;
  11851. }
  11852. Scope *package_scope = scope->parent;
  11853. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  11854. switch (e->kind) {
  11855. case Entity_Variable:
  11856. // NOTE(bill): Handled above as it requires a specific load order
  11857. continue;
  11858. case Entity_ProcGroup:
  11859. continue;
  11860. case Entity_TypeName:
  11861. case Entity_Procedure:
  11862. break;
  11863. }
  11864. bool polymorphic_struct = false;
  11865. if (e->type != nullptr && e->kind == Entity_TypeName) {
  11866. Type *bt = base_type(e->type);
  11867. if (bt->kind == Type_Struct) {
  11868. polymorphic_struct = is_type_polymorphic(bt);
  11869. }
  11870. }
  11871. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  11872. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  11873. continue;
  11874. }
  11875. String mangled_name = lb_get_entity_name(m, e);
  11876. switch (e->kind) {
  11877. case Entity_TypeName:
  11878. lb_type(m, e->type);
  11879. break;
  11880. case Entity_Procedure:
  11881. {
  11882. lbProcedure *p = lb_create_procedure(m, e);
  11883. array_add(&m->procedures_to_generate, p);
  11884. }
  11885. break;
  11886. }
  11887. }
  11888. TIME_SECTION("LLVM Registry Initializtion");
  11889. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  11890. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  11891. LLVMPassManagerRef function_pass_manager_minimal = LLVMCreateFunctionPassManagerForModule(mod);
  11892. LLVMPassManagerRef function_pass_manager_size = LLVMCreateFunctionPassManagerForModule(mod);
  11893. LLVMPassManagerRef function_pass_manager_speed = LLVMCreateFunctionPassManagerForModule(mod);
  11894. defer (LLVMDisposePassManager(default_function_pass_manager));
  11895. defer (LLVMDisposePassManager(function_pass_manager_minimal));
  11896. defer (LLVMDisposePassManager(function_pass_manager_size));
  11897. defer (LLVMDisposePassManager(function_pass_manager_speed));
  11898. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  11899. LLVMInitializeFunctionPassManager(function_pass_manager_minimal);
  11900. LLVMInitializeFunctionPassManager(function_pass_manager_size);
  11901. LLVMInitializeFunctionPassManager(function_pass_manager_speed);
  11902. lb_populate_function_pass_manager(default_function_pass_manager, false, build_context.optimization_level);
  11903. lb_populate_function_pass_manager_specific(function_pass_manager_minimal, 0);
  11904. lb_populate_function_pass_manager_specific(function_pass_manager_size, 1);
  11905. lb_populate_function_pass_manager_specific(function_pass_manager_speed, 2);
  11906. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  11907. LLVMFinalizeFunctionPassManager(function_pass_manager_minimal);
  11908. LLVMFinalizeFunctionPassManager(function_pass_manager_size);
  11909. LLVMFinalizeFunctionPassManager(function_pass_manager_speed);
  11910. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  11911. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  11912. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  11913. lb_populate_function_pass_manager(default_function_pass_manager_without_memcpy, true, build_context.optimization_level);
  11914. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  11915. TIME_SECTION("LLVM Runtime Type Information Creation");
  11916. lbProcedure *startup_type_info = nullptr;
  11917. lbProcedure *startup_runtime = nullptr;
  11918. { // Startup Type Info
  11919. Type *params = alloc_type_tuple();
  11920. Type *results = alloc_type_tuple();
  11921. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11922. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  11923. p->is_startup = true;
  11924. startup_type_info = p;
  11925. lb_begin_procedure_body(p);
  11926. lb_setup_type_info_data(p);
  11927. lb_end_procedure_body(p);
  11928. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11929. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11930. LLVMDumpValue(p->value);
  11931. gb_printf_err("\n\n\n\n");
  11932. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11933. }
  11934. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11935. }
  11936. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  11937. { // Startup Runtime
  11938. Type *params = alloc_type_tuple();
  11939. Type *results = alloc_type_tuple();
  11940. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11941. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  11942. p->is_startup = true;
  11943. startup_runtime = p;
  11944. lb_begin_procedure_body(p);
  11945. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  11946. for_array(i, global_variables) {
  11947. auto *var = &global_variables[i];
  11948. if (var->is_initialized) {
  11949. continue;
  11950. }
  11951. Entity *e = var->decl->entity;
  11952. GB_ASSERT(e->kind == Entity_Variable);
  11953. if (var->decl->init_expr != nullptr) {
  11954. // gb_printf_err("%s\n", expr_to_string(var->decl->init_expr));
  11955. lbValue init = lb_build_expr(p, var->decl->init_expr);
  11956. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  11957. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  11958. if (lb_is_const_or_global(init)) {
  11959. if (!var->is_initialized) {
  11960. LLVMSetInitializer(var->var.value, init.value);
  11961. var->is_initialized = true;
  11962. continue;
  11963. }
  11964. } else {
  11965. var->init = init;
  11966. }
  11967. }
  11968. if (var->init.value != nullptr) {
  11969. GB_ASSERT(!var->is_initialized);
  11970. Type *t = type_deref(var->var.type);
  11971. if (is_type_any(t)) {
  11972. // NOTE(bill): Edge case for 'any' type
  11973. Type *var_type = default_type(var->init.type);
  11974. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  11975. lb_addr_store(p, g, var->init);
  11976. lbValue gp = lb_addr_get_ptr(p, g);
  11977. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  11978. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  11979. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  11980. lb_emit_store(p, ti, lb_type_info(m, var_type));
  11981. } else {
  11982. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  11983. LLVMTypeRef vt = LLVMGetElementType(pvt);
  11984. lbValue src0 = lb_emit_conv(p, var->init, t);
  11985. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  11986. LLVMValueRef dst = var->var.value;
  11987. LLVMBuildStore(p->builder, src, dst);
  11988. }
  11989. var->is_initialized = true;
  11990. }
  11991. }
  11992. lb_end_procedure_body(p);
  11993. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11994. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11995. LLVMDumpValue(p->value);
  11996. gb_printf_err("\n\n\n\n");
  11997. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11998. }
  11999. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  12000. /*{
  12001. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  12002. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  12003. instr != last_instr;
  12004. instr = LLVMGetNextInstruction(instr)) {
  12005. if (LLVMIsAAllocaInst(instr)) {
  12006. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  12007. LLVMValueRef sz_val = LLVMSizeOf(type);
  12008. GB_ASSERT(LLVMIsConstant(sz_val));
  12009. gb_printf_err(">> 0x%p\n", sz_val);
  12010. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  12011. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  12012. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  12013. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  12014. gb_printf_err(">> %ll\n", sz);
  12015. }
  12016. }
  12017. }*/
  12018. }
  12019. String filepath_ll = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".ll"));
  12020. TIME_SECTION("LLVM Procedure Generation");
  12021. for_array(i, m->procedures_to_generate) {
  12022. lbProcedure *p = m->procedures_to_generate[i];
  12023. if (p->is_done) {
  12024. continue;
  12025. }
  12026. if (p->body != nullptr) { // Build Procedure
  12027. m->curr_procedure = p;
  12028. lb_begin_procedure_body(p);
  12029. lb_build_stmt(p, p->body);
  12030. lb_end_procedure_body(p);
  12031. p->is_done = true;
  12032. m->curr_procedure = nullptr;
  12033. }
  12034. lb_end_procedure(p);
  12035. // Add Flags
  12036. if (p->body != nullptr) {
  12037. if (p->name == "memcpy" || p->name == "memmove" ||
  12038. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  12039. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  12040. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  12041. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  12042. }
  12043. }
  12044. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12045. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  12046. LLVMDumpValue(p->value);
  12047. gb_printf_err("\n\n\n\n");
  12048. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12049. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12050. }
  12051. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  12052. gb_exit(1);
  12053. }
  12054. }
  12055. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  12056. TIME_SECTION("LLVM DLL main");
  12057. Type *params = alloc_type_tuple();
  12058. Type *results = alloc_type_tuple();
  12059. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  12060. String name = str_lit("main");
  12061. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  12062. name = str_lit("mainCRTStartup");
  12063. } else {
  12064. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  12065. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  12066. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  12067. }
  12068. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  12069. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  12070. Type *proc_type = alloc_type_proc(nullptr,
  12071. params, params->Tuple.variables.count,
  12072. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  12073. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  12074. p->is_startup = true;
  12075. lb_begin_procedure_body(p);
  12076. { // initialize `runtime.args__`
  12077. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  12078. argc = lb_emit_conv(p, argc, t_int);
  12079. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  12080. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  12081. lb_fill_slice(p, args, argv, argc);
  12082. }
  12083. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  12084. if (build_context.command_kind == Command_test) {
  12085. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  12086. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  12087. Type *slice_type = alloc_type_slice(t_Internal_Test);
  12088. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  12089. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  12090. LLVMTypeRef lbt_Internal_Test = lb_type(m, t_Internal_Test);
  12091. LLVMValueRef indices[2] = {};
  12092. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  12093. for_array(i, m->info->testing_procedures) {
  12094. Entity *testing_proc = m->info->testing_procedures[i];
  12095. String name = testing_proc->token.string;
  12096. lbValue *found = map_get(&m->values, hash_entity(testing_proc));
  12097. GB_ASSERT(found != nullptr);
  12098. String pkg_name = {};
  12099. if (testing_proc->pkg != nullptr) {
  12100. pkg_name = testing_proc->pkg->name;
  12101. }
  12102. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  12103. lbValue v_name = lb_find_or_add_entity_string(m, name);
  12104. lbValue v_proc = *found;
  12105. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  12106. LLVMValueRef vals[3] = {};
  12107. vals[0] = v_pkg.value;
  12108. vals[1] = v_name.value;
  12109. vals[2] = v_proc.value;
  12110. GB_ASSERT(LLVMIsConstant(vals[0]));
  12111. GB_ASSERT(LLVMIsConstant(vals[1]));
  12112. GB_ASSERT(LLVMIsConstant(vals[2]));
  12113. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  12114. LLVMValueRef src = llvm_const_named_struct(lbt_Internal_Test, vals, gb_count_of(vals));
  12115. LLVMBuildStore(p->builder, src, dst);
  12116. }
  12117. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  12118. lb_fill_slice(p, all_tests_slice,
  12119. lb_array_elem(p, all_tests_array),
  12120. lb_const_int(m, t_int, m->info->testing_procedures.count));
  12121. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  12122. auto args = array_make<lbValue>(heap_allocator(), 1);
  12123. args[0] = lb_addr_load(p, all_tests_slice);
  12124. lb_emit_call(p, runner, args);
  12125. } else {
  12126. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  12127. GB_ASSERT(found != nullptr);
  12128. lb_emit_call(p, *found, {});
  12129. }
  12130. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  12131. lb_end_procedure_body(p);
  12132. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12133. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  12134. LLVMDumpValue(p->value);
  12135. gb_printf_err("\n\n\n\n");
  12136. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  12137. }
  12138. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  12139. }
  12140. if (m->debug_builder != nullptr) {
  12141. TIME_SECTION("LLVM Debug Info Complete Types");
  12142. lb_debug_complete_types(m);
  12143. TIME_SECTION("LLVM Print Module to File");
  12144. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12145. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12146. gb_exit(1);
  12147. return;
  12148. }
  12149. TIME_SECTION("LLVM Debug Info Builder Finalize");
  12150. LLVMDIBuilderFinalize(m->debug_builder);
  12151. }
  12152. TIME_SECTION("LLVM Function Pass");
  12153. {
  12154. for_array(i, m->procedures_to_generate) {
  12155. lbProcedure *p = m->procedures_to_generate[i];
  12156. if (p->body != nullptr) { // Build Procedure
  12157. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  12158. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  12159. } else {
  12160. if (p->entity && p->entity->kind == Entity_Procedure) {
  12161. switch (p->entity->Procedure.optimization_mode) {
  12162. case ProcedureOptimizationMode_None:
  12163. case ProcedureOptimizationMode_Minimal:
  12164. LLVMRunFunctionPassManager(function_pass_manager_minimal, p->value);
  12165. break;
  12166. case ProcedureOptimizationMode_Size:
  12167. LLVMRunFunctionPassManager(function_pass_manager_size, p->value);
  12168. break;
  12169. case ProcedureOptimizationMode_Speed:
  12170. LLVMRunFunctionPassManager(function_pass_manager_speed, p->value);
  12171. break;
  12172. default:
  12173. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  12174. break;
  12175. }
  12176. } else {
  12177. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  12178. }
  12179. }
  12180. }
  12181. }
  12182. for_array(i, m->equal_procs.entries) {
  12183. lbProcedure *p = m->equal_procs.entries[i].value;
  12184. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  12185. }
  12186. for_array(i, m->hasher_procs.entries) {
  12187. lbProcedure *p = m->hasher_procs.entries[i].value;
  12188. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  12189. }
  12190. }
  12191. TIME_SECTION("LLVM Module Pass");
  12192. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  12193. defer (LLVMDisposePassManager(module_pass_manager));
  12194. lb_populate_module_pass_manager(target_machine, module_pass_manager, build_context.optimization_level);
  12195. LLVMRunPassManager(module_pass_manager, mod);
  12196. llvm_error = nullptr;
  12197. defer (LLVMDisposeMessage(llvm_error));
  12198. String filepath_obj = {};
  12199. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  12200. if (build_context.build_mode == BuildMode_Assembly) {
  12201. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".S"));
  12202. code_gen_file_type = LLVMAssemblyFile;
  12203. } else {
  12204. switch (build_context.metrics.os) {
  12205. case TargetOs_windows:
  12206. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".obj"));
  12207. break;
  12208. case TargetOs_darwin:
  12209. case TargetOs_linux:
  12210. case TargetOs_essence:
  12211. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".o"));
  12212. break;
  12213. case TargetOs_js:
  12214. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  12215. break;
  12216. }
  12217. }
  12218. if (LLVMVerifyModule(mod, LLVMReturnStatusAction, &llvm_error)) {
  12219. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  12220. if (build_context.keep_temp_files) {
  12221. TIME_SECTION("LLVM Print Module to File");
  12222. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12223. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12224. gb_exit(1);
  12225. return;
  12226. }
  12227. }
  12228. gb_exit(1);
  12229. return;
  12230. }
  12231. llvm_error = nullptr;
  12232. if (build_context.keep_temp_files ||
  12233. build_context.build_mode == BuildMode_LLVM_IR) {
  12234. TIME_SECTION("LLVM Print Module to File");
  12235. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  12236. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12237. gb_exit(1);
  12238. return;
  12239. }
  12240. if (build_context.build_mode == BuildMode_LLVM_IR) {
  12241. gb_exit(0);
  12242. return;
  12243. }
  12244. }
  12245. TIME_SECTION("LLVM Object Generation");
  12246. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  12247. gb_printf_err("LLVM Error: %s\n", llvm_error);
  12248. gb_exit(1);
  12249. return;
  12250. }
  12251. array_add(&gen->output_object_paths, filepath_obj);
  12252. for_array(i, m->info->required_foreign_imports_through_force) {
  12253. Entity *e = m->info->required_foreign_imports_through_force[i];
  12254. lb_add_foreign_library_path(m, e);
  12255. }
  12256. #undef TIME_SECTION
  12257. }