llvm_backend.cpp 337 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024
  1. #include "llvm_backend.hpp"
  2. gb_global lbAddr lb_global_type_info_data = {};
  3. gb_global lbAddr lb_global_type_info_member_types = {};
  4. gb_global lbAddr lb_global_type_info_member_names = {};
  5. gb_global lbAddr lb_global_type_info_member_offsets = {};
  6. gb_global lbAddr lb_global_type_info_member_usings = {};
  7. gb_global lbAddr lb_global_type_info_member_tags = {};
  8. gb_global isize lb_global_type_info_data_index = 0;
  9. gb_global isize lb_global_type_info_member_types_index = 0;
  10. gb_global isize lb_global_type_info_member_names_index = 0;
  11. gb_global isize lb_global_type_info_member_offsets_index = 0;
  12. gb_global isize lb_global_type_info_member_usings_index = 0;
  13. gb_global isize lb_global_type_info_member_tags_index = 0;
  14. struct lbLoopData {
  15. lbAddr idx_addr;
  16. lbValue idx;
  17. lbBlock *body;
  18. lbBlock *done;
  19. lbBlock *loop;
  20. };
  21. struct lbCompoundLitElemTempData {
  22. Ast * expr;
  23. lbValue value;
  24. i32 elem_index;
  25. lbValue gep;
  26. };
  27. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  28. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  29. LLVMValueRef llvm_zero32(lbModule *m) {
  30. return LLVMConstInt(lb_type(m, t_i32), 0, false);
  31. }
  32. LLVMValueRef llvm_one32(lbModule *m) {
  33. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  34. }
  35. lbValue lb_zero(lbModule *m, Type *t) {
  36. lbValue v = {};
  37. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  38. v.type = t;
  39. return v;
  40. }
  41. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  42. lbValue v = lb_find_or_add_entity_string(m, str);
  43. unsigned indices[1] = {0};
  44. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  45. }
  46. lbAddr lb_addr(lbValue addr) {
  47. lbAddr v = {lbAddr_Default, addr};
  48. return v;
  49. }
  50. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  51. lbAddr v = {lbAddr_Map, addr};
  52. v.map.key = map_key;
  53. v.map.type = map_type;
  54. v.map.result = map_result;
  55. return v;
  56. }
  57. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  58. lbAddr v = {lbAddr_SoaVariable, addr};
  59. v.soa.index = index;
  60. v.soa.index_expr = index_expr;
  61. return v;
  62. }
  63. lbAddr lb_addr_bit_field(lbValue value, i32 index) {
  64. lbAddr addr = {};
  65. addr.kind = lbAddr_BitField;
  66. addr.addr = value;
  67. addr.bit_field.value_index = index;
  68. return addr;
  69. }
  70. Type *lb_addr_type(lbAddr const &addr) {
  71. if (addr.addr.value == nullptr) {
  72. return nullptr;
  73. }
  74. if (addr.kind == lbAddr_Map) {
  75. Type *t = base_type(addr.map.type);
  76. GB_ASSERT(is_type_map(t));
  77. return t->Map.value;
  78. }
  79. return type_deref(addr.addr.type);
  80. }
  81. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  82. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  83. }
  84. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  85. if (addr.addr.value == nullptr) {
  86. GB_PANIC("Illegal addr -> nullptr");
  87. return {};
  88. }
  89. switch (addr.kind) {
  90. case lbAddr_Map: {
  91. Type *map_type = base_type(addr.map.type);
  92. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  93. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  94. auto args = array_make<lbValue>(heap_allocator(), 2);
  95. args[0] = h;
  96. args[1] = key;
  97. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  98. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  99. }
  100. case lbAddr_BitField: {
  101. lbValue v = lb_addr_load(p, addr);
  102. return lb_address_from_load_or_generate_local(p, v);
  103. }
  104. case lbAddr_Context:
  105. GB_PANIC("lbAddr_Context should be handled elsewhere");
  106. }
  107. return addr.addr;
  108. }
  109. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  110. lbAddr addr = lb_build_addr(p, expr);
  111. return lb_addr_get_ptr(p, addr);
  112. }
  113. void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value) {
  114. if (addr.addr.value == nullptr) {
  115. return;
  116. }
  117. GB_ASSERT(value.type != nullptr);
  118. if (is_type_untyped_undef(value.type)) {
  119. Type *t = lb_addr_type(addr);
  120. value.type = t;
  121. value.value = LLVMGetUndef(lb_type(p->module, t));
  122. } else if (is_type_untyped_nil(value.type)) {
  123. Type *t = lb_addr_type(addr);
  124. value.type = t;
  125. value.value = LLVMConstNull(lb_type(p->module, t));
  126. }
  127. if (addr.kind == lbAddr_Map) {
  128. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value);
  129. return;
  130. } else if (addr.kind == lbAddr_BitField) {
  131. Type *bft = base_type(type_deref(addr.addr.type));
  132. GB_ASSERT(is_type_bit_field(bft));
  133. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  134. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  135. if (size_in_bits == 0) {
  136. return;
  137. }
  138. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  139. LLVMTypeRef dst_type = LLVMIntTypeInContext(p->module->ctx, size_in_bits);
  140. LLVMValueRef src = LLVMBuildIntCast2(p->builder, value.value, dst_type, false, "");
  141. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  142. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  143. LLVMBuildStore(p->builder, src, field_ptr);
  144. return;
  145. } else if (addr.kind == lbAddr_Context) {
  146. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  147. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  148. lb_addr_store(p, next_addr, old);
  149. lb_push_context_onto_stack(p, next_addr);
  150. lbValue next = lb_addr_get_ptr(p, next_addr);
  151. if (addr.ctx.sel.index.count > 0) {
  152. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  153. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  154. lb_emit_store(p, lhs, rhs);
  155. } else {
  156. lbValue lhs = next;
  157. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  158. lb_emit_store(p, lhs, rhs);
  159. }
  160. return;
  161. } else if (addr.kind == lbAddr_SoaVariable) {
  162. Type *t = type_deref(addr.addr.type);
  163. t = base_type(t);
  164. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  165. value = lb_emit_conv(p, value, t->Struct.soa_elem);
  166. lbValue index = addr.soa.index;
  167. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  168. Type *t = base_type(type_deref(addr.addr.type));
  169. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  170. i64 count = t->Struct.soa_count;
  171. lbValue len = lb_const_int(p->module, t_int, count);
  172. // lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  173. }
  174. for_array(i, t->Struct.fields) {
  175. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  176. dst = lb_emit_array_ep(p, dst, index);
  177. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  178. lb_emit_store(p, dst, src);
  179. }
  180. return;
  181. }
  182. GB_ASSERT(value.value != nullptr);
  183. value = lb_emit_conv(p, value, lb_addr_type(addr));
  184. LLVMBuildStore(p->builder, value.value, addr.addr.value);
  185. }
  186. void lb_const_store(lbValue ptr, lbValue value) {
  187. GB_ASSERT(lb_is_const(ptr));
  188. GB_ASSERT(lb_is_const(value));
  189. GB_ASSERT(is_type_pointer(ptr.type));
  190. LLVMSetInitializer(ptr.value, value.value);
  191. }
  192. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  193. GB_ASSERT(value.value != nullptr);
  194. Type *a = type_deref(ptr.type);
  195. if (is_type_boolean(a)) {
  196. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  197. value = lb_emit_conv(p, value, a);
  198. }
  199. Type *ca = core_type(a);
  200. if (ca->kind == Type_Basic) {
  201. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  202. } else {
  203. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  204. }
  205. LLVMBuildStore(p->builder, value.value, ptr.value);
  206. }
  207. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  208. lbModule *m = p->module;
  209. GB_ASSERT(value.value != nullptr);
  210. Type *t = type_deref(value.type);
  211. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(m, t), value.value, "");
  212. return lbValue{v, t};
  213. }
  214. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  215. GB_ASSERT(addr.addr.value != nullptr);
  216. if (addr.kind == lbAddr_Map) {
  217. Type *map_type = base_type(addr.map.type);
  218. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  219. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  220. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  221. auto args = array_make<lbValue>(heap_allocator(), 2);
  222. args[0] = h;
  223. args[1] = key;
  224. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  225. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  226. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  227. lbBlock *then = lb_create_block(p, "map.get.then");
  228. lbBlock *done = lb_create_block(p, "map.get.done");
  229. lb_emit_if(p, ok, then, done);
  230. lb_start_block(p, then);
  231. {
  232. // TODO(bill): mem copy it instead?
  233. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  234. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  235. lb_emit_store(p, gep0, lb_emit_load(p, value));
  236. }
  237. lb_emit_jump(p, done);
  238. lb_start_block(p, done);
  239. if (is_type_tuple(addr.map.result)) {
  240. return lb_addr_load(p, v);
  241. } else {
  242. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  243. return lb_emit_load(p, single);
  244. }
  245. } else if (addr.kind == lbAddr_BitField) {
  246. Type *bft = base_type(type_deref(addr.addr.type));
  247. GB_ASSERT(is_type_bit_field(bft));
  248. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  249. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  250. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  251. if (size_in_bytes == 0) {
  252. GB_ASSERT(size_in_bits == 0);
  253. lbValue res = {};
  254. res.type = t_i32;
  255. res.value = LLVMConstInt(lb_type(p->module, res.type), 0, false);
  256. return res;
  257. }
  258. Type *int_type = nullptr;
  259. switch (size_in_bytes) {
  260. case 1: int_type = t_u8; break;
  261. case 2: int_type = t_u16; break;
  262. case 4: int_type = t_u32; break;
  263. case 8: int_type = t_u64; break;
  264. case 16: int_type = t_u128; break;
  265. }
  266. GB_ASSERT(int_type != nullptr);
  267. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  268. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  269. LLVMValueRef field = LLVMBuildLoad(p->builder, field_ptr, "");
  270. lbValue res = {};
  271. res.type = int_type;
  272. res.value = LLVMBuildZExtOrBitCast(p->builder, field, lb_type(p->module, int_type), "");
  273. return res;
  274. } else if (addr.kind == lbAddr_Context) {
  275. if (addr.ctx.sel.index.count > 0) {
  276. lbValue a = addr.addr;
  277. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  278. return lb_emit_load(p, b);
  279. } else {
  280. return lb_emit_load(p, addr.addr);
  281. }
  282. } else if (addr.kind == lbAddr_SoaVariable) {
  283. Type *t = type_deref(addr.addr.type);
  284. t = base_type(t);
  285. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  286. Type *elem = t->Struct.soa_elem;
  287. lbValue len = {};
  288. if (t->Struct.soa_kind == StructSoa_Fixed) {
  289. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  290. } else {
  291. lbValue v = lb_emit_load(p, addr.addr);
  292. len = lb_soa_struct_len(p, v);
  293. }
  294. lbAddr res = lb_add_local_generated(p, elem, true);
  295. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  296. // lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  297. }
  298. if (t->Struct.soa_kind == StructSoa_Fixed) {
  299. for_array(i, t->Struct.fields) {
  300. Entity *field = t->Struct.fields[i];
  301. Type *base_type = field->type;
  302. GB_ASSERT(base_type->kind == Type_Array);
  303. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  304. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  305. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  306. lbValue src = lb_emit_load(p, src_ptr);
  307. lb_emit_store(p, dst, src);
  308. }
  309. } else {
  310. isize field_count = t->Struct.fields.count;
  311. if (t->Struct.soa_kind == StructSoa_Slice) {
  312. field_count -= 1;
  313. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  314. field_count -= 3;
  315. }
  316. for (isize i = 0; i < field_count; i++) {
  317. Entity *field = t->Struct.fields[i];
  318. Type *base_type = field->type;
  319. GB_ASSERT(base_type->kind == Type_Pointer);
  320. Type *elem = base_type->Pointer.elem;
  321. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  322. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  323. src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index);
  324. lbValue src = lb_emit_load(p, src_ptr);
  325. src = lb_emit_load(p, src);
  326. lb_emit_store(p, dst, src);
  327. }
  328. }
  329. return lb_addr_load(p, res);
  330. }
  331. if (is_type_proc(addr.addr.type)) {
  332. return addr.addr;
  333. }
  334. return lb_emit_load(p, addr.addr);
  335. }
  336. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  337. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  338. }
  339. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  340. Type *t = u.type;
  341. GB_ASSERT_MSG(is_type_pointer(t) &&
  342. is_type_union(type_deref(t)), "%s", type_to_string(t));
  343. Type *ut = type_deref(t);
  344. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  345. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  346. GB_ASSERT(type_size_of(ut) > 0);
  347. Type *tag_type = union_tag_type(ut);
  348. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  349. unsigned element_count = LLVMCountStructElementTypes(uvt);
  350. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  351. lbValue tag_ptr = {};
  352. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  353. tag_ptr.type = alloc_type_pointer(tag_type);
  354. return tag_ptr;
  355. }
  356. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  357. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  358. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  359. return lb_emit_load(p, tag_ptr);
  360. }
  361. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  362. Type *t = type_deref(parent.type);
  363. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  364. // No tag needed!
  365. } else {
  366. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  367. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  368. }
  369. }
  370. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  371. gbAllocator a = heap_allocator();
  372. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  373. lb_emit_store(p, underlying, variant);
  374. lb_emit_store_union_variant_tag(p, parent, variant_type);
  375. }
  376. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  377. unsigned field_count = LLVMCountStructElementTypes(src);
  378. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  379. LLVMGetStructElementTypes(src, fields);
  380. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  381. gb_free(heap_allocator(), fields);
  382. }
  383. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  384. switch (alignment) {
  385. case 1:
  386. return LLVMArrayType(lb_type(m, t_u8), 0);
  387. case 2:
  388. return LLVMArrayType(lb_type(m, t_u16), 0);
  389. case 4:
  390. return LLVMArrayType(lb_type(m, t_u32), 0);
  391. case 8:
  392. return LLVMArrayType(lb_type(m, t_u64), 0);
  393. case 16:
  394. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  395. default:
  396. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  397. break;
  398. }
  399. return nullptr;
  400. }
  401. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  402. if (!elem_type_can_be_constant(elem_type)) {
  403. return false;
  404. }
  405. if (elem->kind == Ast_FieldValue) {
  406. elem = elem->FieldValue.value;
  407. }
  408. TypeAndValue tav = type_and_value_of_expr(elem);
  409. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  410. return tav.value.kind != ExactValue_Invalid;
  411. }
  412. String lb_mangle_name(lbModule *m, Entity *e) {
  413. gbAllocator a = heap_allocator();
  414. String name = e->token.string;
  415. AstPackage *pkg = e->pkg;
  416. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  417. String pkgn = pkg->name;
  418. GB_ASSERT(!rune_is_digit(pkgn[0]));
  419. isize max_len = pkgn.len + 1 + name.len + 1;
  420. bool require_suffix_id = is_type_polymorphic(e->type, true);
  421. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  422. require_suffix_id = true;
  423. } else if (is_blank_ident(e->token)) {
  424. require_suffix_id = true;
  425. }
  426. if (require_suffix_id) {
  427. max_len += 21;
  428. }
  429. char *new_name = gb_alloc_array(a, char, max_len);
  430. isize new_name_len = gb_snprintf(
  431. new_name, max_len,
  432. "%.*s.%.*s", LIT(pkgn), LIT(name)
  433. );
  434. if (require_suffix_id) {
  435. char *str = new_name + new_name_len-1;
  436. isize len = max_len-new_name_len;
  437. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  438. new_name_len += extra-1;
  439. }
  440. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  441. return mangled_name;
  442. }
  443. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  444. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  445. // and as a result, the declaration does not have time to determine what it should be
  446. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  447. if (e->TypeName.ir_mangled_name.len != 0) {
  448. return e->TypeName.ir_mangled_name;
  449. }
  450. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  451. if (p == nullptr) {
  452. Entity *proc = nullptr;
  453. if (e->parent_proc_decl != nullptr) {
  454. proc = e->parent_proc_decl->entity;
  455. } else {
  456. Scope *scope = e->scope;
  457. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  458. scope = scope->parent;
  459. }
  460. GB_ASSERT(scope != nullptr);
  461. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  462. proc = scope->procedure_entity;
  463. }
  464. GB_ASSERT(proc->kind == Entity_Procedure);
  465. GB_ASSERT(proc->code_gen_procedure != nullptr);
  466. p = proc->code_gen_procedure;
  467. }
  468. // NOTE(bill): Generate a new name
  469. // parent_proc.name-guid
  470. String ts_name = e->token.string;
  471. lbModule *m = p->module;
  472. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  473. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  474. u32 guid = ++p->module->nested_type_name_guid;
  475. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  476. String name = make_string(cast(u8 *)name_text, name_len-1);
  477. e->TypeName.ir_mangled_name = name;
  478. return name;
  479. }
  480. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  481. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  482. return e->TypeName.ir_mangled_name;
  483. }
  484. GB_ASSERT(e != nullptr);
  485. if (e->pkg == nullptr) {
  486. return e->token.string;
  487. }
  488. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  489. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  490. }
  491. String name = {};
  492. bool no_name_mangle = false;
  493. if (e->kind == Entity_Variable) {
  494. bool is_foreign = e->Variable.is_foreign;
  495. bool is_export = e->Variable.is_export;
  496. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  497. if (e->Variable.link_name.len > 0) {
  498. return e->Variable.link_name;
  499. }
  500. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  501. return e->Procedure.link_name;
  502. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  503. no_name_mangle = true;
  504. }
  505. if (!no_name_mangle) {
  506. name = lb_mangle_name(m, e);
  507. }
  508. if (name.len == 0) {
  509. name = e->token.string;
  510. }
  511. if (e->kind == Entity_TypeName) {
  512. if ((e->scope->flags & ScopeFlag_File) == 0) {
  513. gb_printf_err("<<< %.*s %.*s %p\n", LIT(e->token.string), LIT(name), e);
  514. }
  515. e->TypeName.ir_mangled_name = name;
  516. } else if (e->kind == Entity_Procedure) {
  517. e->Procedure.link_name = name;
  518. }
  519. return name;
  520. }
  521. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  522. Type *original_type = type;
  523. LLVMContextRef ctx = m->ctx;
  524. i64 size = type_size_of(type); // Check size
  525. GB_ASSERT(type != t_invalid);
  526. switch (type->kind) {
  527. case Type_Basic:
  528. switch (type->Basic.kind) {
  529. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  530. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  531. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  532. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  533. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  534. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  535. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  536. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  537. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  538. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  539. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  540. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  541. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  542. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  543. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  544. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  545. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  546. // Basic_f16,
  547. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  548. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  549. // Basic_complex32,
  550. case Basic_complex64:
  551. {
  552. char const *name = "..complex64";
  553. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  554. if (type != nullptr) {
  555. return type;
  556. }
  557. type = LLVMStructCreateNamed(ctx, name);
  558. LLVMTypeRef fields[2] = {
  559. lb_type(m, t_f32),
  560. lb_type(m, t_f32),
  561. };
  562. LLVMStructSetBody(type, fields, 2, false);
  563. return type;
  564. }
  565. case Basic_complex128:
  566. {
  567. char const *name = "..complex128";
  568. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  569. if (type != nullptr) {
  570. return type;
  571. }
  572. type = LLVMStructCreateNamed(ctx, name);
  573. LLVMTypeRef fields[2] = {
  574. lb_type(m, t_f64),
  575. lb_type(m, t_f64),
  576. };
  577. LLVMStructSetBody(type, fields, 2, false);
  578. return type;
  579. }
  580. case Basic_quaternion128:
  581. {
  582. char const *name = "..quaternion128";
  583. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  584. if (type != nullptr) {
  585. return type;
  586. }
  587. type = LLVMStructCreateNamed(ctx, name);
  588. LLVMTypeRef fields[4] = {
  589. lb_type(m, t_f32),
  590. lb_type(m, t_f32),
  591. lb_type(m, t_f32),
  592. lb_type(m, t_f32),
  593. };
  594. LLVMStructSetBody(type, fields, 4, false);
  595. return type;
  596. }
  597. case Basic_quaternion256:
  598. {
  599. char const *name = "..quaternion256";
  600. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  601. if (type != nullptr) {
  602. return type;
  603. }
  604. type = LLVMStructCreateNamed(ctx, name);
  605. LLVMTypeRef fields[4] = {
  606. lb_type(m, t_f64),
  607. lb_type(m, t_f64),
  608. lb_type(m, t_f64),
  609. lb_type(m, t_f64),
  610. };
  611. LLVMStructSetBody(type, fields, 4, false);
  612. return type;
  613. }
  614. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  615. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  616. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  617. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  618. case Basic_string:
  619. {
  620. char const *name = "..string";
  621. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  622. if (type != nullptr) {
  623. return type;
  624. }
  625. type = LLVMStructCreateNamed(ctx, name);
  626. LLVMTypeRef fields[2] = {
  627. LLVMPointerType(lb_type(m, t_u8), 0),
  628. lb_type(m, t_int),
  629. };
  630. LLVMStructSetBody(type, fields, 2, false);
  631. return type;
  632. }
  633. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  634. case Basic_any:
  635. {
  636. char const *name = "..any";
  637. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  638. if (type != nullptr) {
  639. return type;
  640. }
  641. type = LLVMStructCreateNamed(ctx, name);
  642. LLVMTypeRef fields[2] = {
  643. lb_type(m, t_rawptr),
  644. lb_type(m, t_typeid),
  645. };
  646. LLVMStructSetBody(type, fields, 2, false);
  647. return type;
  648. }
  649. case Basic_typeid: return LLVMIntType(8*cast(unsigned)build_context.word_size);
  650. // Endian Specific Types
  651. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  652. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  653. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  654. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  655. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  656. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  657. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  658. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  659. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  660. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  661. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  662. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  663. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  664. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  665. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  666. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  667. // Untyped types
  668. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  669. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  670. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  671. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  672. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  673. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  674. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  675. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  676. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  677. }
  678. break;
  679. case Type_Named:
  680. {
  681. Type *base = base_type(type->Named.base);
  682. switch (base->kind) {
  683. case Type_Basic:
  684. return lb_type(m, base);
  685. case Type_Named:
  686. case Type_Generic:
  687. case Type_BitFieldValue:
  688. GB_PANIC("INVALID TYPE");
  689. break;
  690. case Type_Opaque:
  691. return lb_type(m, base->Opaque.elem);
  692. case Type_Pointer:
  693. case Type_Array:
  694. case Type_EnumeratedArray:
  695. case Type_Slice:
  696. case Type_DynamicArray:
  697. case Type_Map:
  698. case Type_Enum:
  699. case Type_BitSet:
  700. case Type_SimdVector:
  701. return lb_type(m, base);
  702. // TODO(bill): Deal with this correctly. Can this be named?
  703. case Type_Proc:
  704. return lb_type(m, base);
  705. case Type_Tuple:
  706. return lb_type(m, base);
  707. }
  708. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  709. if (found) {
  710. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  711. if (kind == LLVMStructTypeKind) {
  712. char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  713. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  714. if (llvm_type != nullptr) {
  715. return llvm_type;
  716. }
  717. llvm_type = LLVMStructCreateNamed(ctx, name);
  718. map_set(&m->types, hash_type(type), llvm_type);
  719. lb_clone_struct_type(llvm_type, *found);
  720. return llvm_type;
  721. }
  722. }
  723. switch (base->kind) {
  724. case Type_Struct:
  725. case Type_Union:
  726. case Type_BitField:
  727. {
  728. char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  729. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  730. if (llvm_type != nullptr) {
  731. return llvm_type;
  732. }
  733. llvm_type = LLVMStructCreateNamed(ctx, name);
  734. map_set(&m->types, hash_type(type), llvm_type);
  735. lb_clone_struct_type(llvm_type, lb_type(m, base));
  736. return llvm_type;
  737. }
  738. }
  739. return lb_type(m, base);
  740. }
  741. case Type_Pointer:
  742. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  743. case Type_Opaque:
  744. return lb_type(m, base_type(type));
  745. case Type_Array:
  746. return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  747. case Type_EnumeratedArray:
  748. return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  749. case Type_Slice:
  750. {
  751. LLVMTypeRef fields[2] = {
  752. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  753. lb_type(m, t_int), // len
  754. };
  755. return LLVMStructTypeInContext(ctx, fields, 2, false);
  756. }
  757. break;
  758. case Type_DynamicArray:
  759. {
  760. LLVMTypeRef fields[4] = {
  761. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  762. lb_type(m, t_int), // len
  763. lb_type(m, t_int), // cap
  764. lb_type(m, t_allocator), // allocator
  765. };
  766. return LLVMStructTypeInContext(ctx, fields, 4, false);
  767. }
  768. break;
  769. case Type_Map:
  770. return lb_type(m, type->Map.internal_type);
  771. case Type_Struct:
  772. {
  773. if (type->Struct.is_raw_union) {
  774. unsigned field_count = 2;
  775. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  776. i64 alignment = type_align_of(type);
  777. unsigned size_of_union = cast(unsigned)type_size_of(type);
  778. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  779. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  780. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  781. }
  782. isize offset = 0;
  783. if (type->Struct.custom_align > 0) {
  784. offset = 1;
  785. }
  786. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  787. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  788. GB_ASSERT(fields != nullptr);
  789. defer (gb_free(heap_allocator(), fields));
  790. for_array(i, type->Struct.fields) {
  791. Entity *field = type->Struct.fields[i];
  792. fields[i+offset] = lb_type(m, field->type);
  793. }
  794. if (type->Struct.custom_align > 0) {
  795. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  796. }
  797. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  798. }
  799. break;
  800. case Type_Union:
  801. if (type->Union.variants.count == 0) {
  802. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  803. } else {
  804. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  805. // LLVM takes the first element's alignment as the entire alignment (like C)
  806. i64 align = type_align_of(type);
  807. i64 size = type_size_of(type);
  808. if (is_type_union_maybe_pointer_original_alignment(type)) {
  809. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  810. return LLVMStructTypeInContext(ctx, fields, 1, false);
  811. }
  812. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  813. LLVMTypeRef fields[3] = {};
  814. unsigned field_count = 1;
  815. fields[0] = lb_alignment_prefix_type_hack(m, align);
  816. if (is_type_union_maybe_pointer(type)) {
  817. field_count += 1;
  818. fields[1] = lb_type(m, type->Union.variants[0]);
  819. } else {
  820. field_count += 2;
  821. if (block_size == align) {
  822. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  823. } else {
  824. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  825. }
  826. fields[2] = lb_type(m, union_tag_type(type));
  827. }
  828. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  829. }
  830. break;
  831. case Type_Enum:
  832. return lb_type(m, base_enum_type(type));
  833. case Type_Tuple:
  834. if (type->Tuple.variables.count == 1) {
  835. return lb_type(m, type->Tuple.variables[0]->type);
  836. } else {
  837. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  838. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  839. defer (gb_free(heap_allocator(), fields));
  840. for_array(i, type->Tuple.variables) {
  841. Entity *field = type->Tuple.variables[i];
  842. fields[i] = lb_type(m, field->type);
  843. }
  844. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  845. }
  846. case Type_Proc:
  847. {
  848. set_procedure_abi_types(heap_allocator(), type);
  849. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  850. isize offset = 0;
  851. if (type->Proc.return_by_pointer) {
  852. offset = 1;
  853. } else if (type->Proc.abi_compat_result_type != nullptr) {
  854. return_type = lb_type(m, type->Proc.abi_compat_result_type);
  855. }
  856. isize extra_param_count = offset;
  857. if (type->Proc.calling_convention == ProcCC_Odin) {
  858. extra_param_count += 1;
  859. }
  860. isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  861. LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  862. defer (gb_free(heap_allocator(), param_types));
  863. isize param_index = offset;
  864. for_array(i, type->Proc.abi_compat_params) {
  865. Type *param = type->Proc.abi_compat_params[i];
  866. if (param == nullptr) {
  867. continue;
  868. }
  869. param_types[param_index++] = lb_type(m, param);
  870. }
  871. if (type->Proc.return_by_pointer) {
  872. param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0);
  873. }
  874. if (type->Proc.calling_convention == ProcCC_Odin) {
  875. param_types[param_index++] = lb_type(m, t_context_ptr);
  876. }
  877. LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg);
  878. return LLVMPointerType(t, 0);
  879. }
  880. break;
  881. case Type_BitFieldValue:
  882. return LLVMIntType(type->BitFieldValue.bits);
  883. case Type_BitField:
  884. {
  885. LLVMTypeRef internal_type = nullptr;
  886. {
  887. GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  888. unsigned field_count = cast(unsigned)type->BitField.fields.count;
  889. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  890. defer (gb_free(heap_allocator(), fields));
  891. for_array(i, type->BitField.sizes) {
  892. u32 size = type->BitField.sizes[i];
  893. fields[i] = LLVMIntType(size);
  894. }
  895. internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  896. }
  897. unsigned field_count = 2;
  898. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  899. i64 alignment = 1;
  900. if (type->BitField.custom_align > 0) {
  901. alignment = type->BitField.custom_align;
  902. }
  903. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  904. fields[1] = internal_type;
  905. return LLVMStructTypeInContext(ctx, fields, field_count, true);
  906. }
  907. break;
  908. case Type_BitSet:
  909. return LLVMIntType(8*cast(unsigned)type_size_of(type));
  910. case Type_SimdVector:
  911. if (type->SimdVector.is_x86_mmx) {
  912. return LLVMX86MMXTypeInContext(ctx);
  913. }
  914. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  915. }
  916. GB_PANIC("Invalid type %s", type_to_string(type));
  917. return LLVMInt32TypeInContext(ctx);
  918. }
  919. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  920. type = default_type(type);
  921. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  922. if (found) {
  923. return *found;
  924. }
  925. LLVMTypeRef llvm_type = lb_type_internal(m, type);
  926. map_set(&m->types, hash_type(type), llvm_type);
  927. return llvm_type;
  928. }
  929. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  930. if (e != nullptr) {
  931. map_set(&m->values, hash_entity(e), val);
  932. }
  933. }
  934. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  935. if (name.len > 0) {
  936. map_set(&m->members, hash_string(name), val);
  937. }
  938. }
  939. void lb_add_member(lbModule *m, HashKey const &key, lbValue val) {
  940. map_set(&m->members, key, val);
  941. }
  942. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  943. if (p->entity != nullptr) {
  944. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  945. }
  946. map_set(&m->procedures, hash_string(p->name), p);
  947. }
  948. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  949. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  950. LLVMValueRef values[2] = {
  951. str_elem.value,
  952. str_len.value,
  953. };
  954. lbValue res = {};
  955. res.type = t_string;
  956. res.value = LLVMConstNamedStruct(lb_type(p->module, t_string), values, gb_count_of(values));
  957. return res;
  958. } else {
  959. lbAddr res = lb_add_local_generated(p, t_string, false);
  960. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  961. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  962. return lb_addr_load(p, res);
  963. }
  964. }
  965. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  966. unsigned kind = LLVMGetEnumAttributeKindForName(name, gb_strlen(name));
  967. GB_ASSERT(kind != 0);
  968. return LLVMCreateEnumAttribute(ctx, kind, value);
  969. }
  970. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  971. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  972. GB_ASSERT(attr != nullptr);
  973. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  974. }
  975. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  976. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  977. }
  978. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  979. GB_ASSERT(entity != nullptr);
  980. String link_name = lb_get_entity_name(m, entity);
  981. {
  982. HashKey key = hash_string(link_name);
  983. lbValue *found = map_get(&m->members, key);
  984. if (found) {
  985. lb_add_entity(m, entity, *found);
  986. lbProcedure **p_found = map_get(&m->procedures, key);
  987. GB_ASSERT(p_found != nullptr);
  988. return *p_found;
  989. }
  990. }
  991. lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure);
  992. p->module = m;
  993. entity->code_gen_module = m;
  994. entity->code_gen_procedure = p;
  995. p->entity = entity;
  996. p->name = link_name;
  997. DeclInfo *decl = entity->decl_info;
  998. ast_node(pl, ProcLit, decl->proc_lit);
  999. Type *pt = base_type(entity->type);
  1000. GB_ASSERT(pt->kind == Type_Proc);
  1001. set_procedure_abi_types(heap_allocator(), entity->type);
  1002. p->type = entity->type;
  1003. p->type_expr = decl->type_expr;
  1004. p->body = pl->body;
  1005. p->tags = pt->Proc.tags;
  1006. p->inlining = ProcInlining_none;
  1007. p->is_foreign = entity->Procedure.is_foreign;
  1008. p->is_export = entity->Procedure.is_export;
  1009. p->is_entry_point = false;
  1010. gbAllocator a = heap_allocator();
  1011. p->children.allocator = a;
  1012. p->params.allocator = a;
  1013. p->defer_stmts.allocator = a;
  1014. p->blocks.allocator = a;
  1015. p->branch_blocks.allocator = a;
  1016. p->context_stack.allocator = a;
  1017. char *c_link_name = alloc_cstring(heap_allocator(), p->name);
  1018. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1019. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1020. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1021. LLVMSetFunctionCallConv(p->value, lb_calling_convention_map[pt->Proc.calling_convention]);
  1022. lbValue proc_value = {p->value, p->type};
  1023. lb_add_entity(m, entity, proc_value);
  1024. lb_add_member(m, p->name, proc_value);
  1025. lb_add_procedure_value(m, p);
  1026. // NOTE(bill): offset==0 is the return value
  1027. isize offset = 1;
  1028. if (pt->Proc.return_by_pointer) {
  1029. lb_add_proc_attribute_at_index(p, 1, "sret");
  1030. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1031. offset = 2;
  1032. }
  1033. isize parameter_index = 0;
  1034. if (pt->Proc.param_count) {
  1035. TypeTuple *params = &pt->Proc.params->Tuple;
  1036. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1037. Entity *e = params->variables[i];
  1038. Type *original_type = e->type;
  1039. Type *abi_type = pt->Proc.abi_compat_params[i];
  1040. if (e->kind != Entity_Variable) continue;
  1041. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1042. continue;
  1043. }
  1044. if (is_type_tuple(abi_type)) {
  1045. for_array(j, abi_type->Tuple.variables) {
  1046. Type *tft = abi_type->Tuple.variables[j]->type;
  1047. if (e->flags&EntityFlag_NoAlias) {
  1048. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1049. }
  1050. }
  1051. parameter_index += abi_type->Tuple.variables.count;
  1052. } else {
  1053. if (e->flags&EntityFlag_NoAlias) {
  1054. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1055. }
  1056. parameter_index += 1;
  1057. }
  1058. }
  1059. }
  1060. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1061. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1062. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1063. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1064. }
  1065. if (entity->Procedure.is_foreign) {
  1066. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  1067. }
  1068. { // Debug Information
  1069. unsigned line = cast(unsigned)entity->token.pos.line;
  1070. LLVMMetadataRef file = nullptr;
  1071. if (entity->file != nullptr) {
  1072. cast(LLVMMetadataRef)entity->file->llvm_metadata;
  1073. }
  1074. LLVMMetadataRef scope = nullptr;
  1075. LLVMMetadataRef type = nullptr;
  1076. // type = LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, nullptr, 0, LLVMDIFlagZero);
  1077. LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  1078. cast(char const *)entity->token.string.text, entity->token.string.len,
  1079. cast(char const *)p->name.text, p->name.len,
  1080. file, line, type,
  1081. true, p->body == nullptr,
  1082. line, LLVMDIFlagZero, false
  1083. );
  1084. GB_ASSERT(res != nullptr);
  1085. map_set(&m->debug_values, hash_pointer(p), res);
  1086. }
  1087. return p;
  1088. }
  1089. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  1090. {
  1091. HashKey key = hash_string(link_name);
  1092. lbValue *found = map_get(&m->members, key);
  1093. GB_ASSERT(found == nullptr);
  1094. }
  1095. lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure);
  1096. p->module = m;
  1097. p->name = link_name;
  1098. p->type = type;
  1099. p->type_expr = nullptr;
  1100. p->body = nullptr;
  1101. p->tags = 0;
  1102. p->inlining = ProcInlining_none;
  1103. p->is_foreign = false;
  1104. p->is_export = false;
  1105. p->is_entry_point = false;
  1106. gbAllocator a = heap_allocator();
  1107. p->children.allocator = a;
  1108. p->params.allocator = a;
  1109. p->defer_stmts.allocator = a;
  1110. p->blocks.allocator = a;
  1111. p->branch_blocks.allocator = a;
  1112. p->context_stack.allocator = a;
  1113. char *c_link_name = alloc_cstring(heap_allocator(), p->name);
  1114. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1115. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1116. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1117. Type *pt = p->type;
  1118. LLVMSetFunctionCallConv(p->value, lb_calling_convention_map[pt->Proc.calling_convention]);
  1119. lbValue proc_value = {p->value, p->type};
  1120. lb_add_member(m, p->name, proc_value);
  1121. lb_add_procedure_value(m, p);
  1122. // NOTE(bill): offset==0 is the return value
  1123. isize offset = 1;
  1124. if (pt->Proc.return_by_pointer) {
  1125. lb_add_proc_attribute_at_index(p, 1, "sret");
  1126. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1127. offset = 2;
  1128. }
  1129. isize parameter_index = 0;
  1130. if (pt->Proc.param_count) {
  1131. TypeTuple *params = &pt->Proc.params->Tuple;
  1132. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1133. Entity *e = params->variables[i];
  1134. Type *original_type = e->type;
  1135. Type *abi_type = pt->Proc.abi_compat_params[i];
  1136. if (e->kind != Entity_Variable) continue;
  1137. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1138. continue;
  1139. }
  1140. if (is_type_tuple(abi_type)) {
  1141. for_array(j, abi_type->Tuple.variables) {
  1142. Type *tft = abi_type->Tuple.variables[j]->type;
  1143. if (e->flags&EntityFlag_NoAlias) {
  1144. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1145. }
  1146. }
  1147. parameter_index += abi_type->Tuple.variables.count;
  1148. } else {
  1149. if (e->flags&EntityFlag_NoAlias) {
  1150. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1151. }
  1152. parameter_index += 1;
  1153. }
  1154. }
  1155. }
  1156. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1157. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1158. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1159. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1160. }
  1161. return p;
  1162. }
  1163. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  1164. lbParamPasskind kind = lbParamPass_Value;
  1165. if (e != nullptr && abi_type != e->type) {
  1166. if (is_type_pointer(abi_type)) {
  1167. GB_ASSERT(e->kind == Entity_Variable);
  1168. kind = lbParamPass_Pointer;
  1169. if (e->flags&EntityFlag_Value) {
  1170. kind = lbParamPass_ConstRef;
  1171. }
  1172. } else if (is_type_integer(abi_type)) {
  1173. kind = lbParamPass_Integer;
  1174. } else if (abi_type == t_llvm_bool) {
  1175. kind = lbParamPass_Value;
  1176. } else if (is_type_simd_vector(abi_type)) {
  1177. kind = lbParamPass_BitCast;
  1178. } else if (is_type_float(abi_type)) {
  1179. kind = lbParamPass_BitCast;
  1180. } else if (is_type_tuple(abi_type)) {
  1181. kind = lbParamPass_Tuple;
  1182. } else {
  1183. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  1184. }
  1185. }
  1186. if (kind_) *kind_ = kind;
  1187. lbValue res = {};
  1188. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  1189. res.type = abi_type;
  1190. return res;
  1191. }
  1192. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  1193. lbParamPasskind kind = lbParamPass_Value;
  1194. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  1195. array_add(&p->params, v);
  1196. lbValue res = {};
  1197. switch (kind) {
  1198. case lbParamPass_Value: {
  1199. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1200. lbValue x = v;
  1201. if (abi_type == t_llvm_bool) {
  1202. x = lb_emit_conv(p, x, t_bool);
  1203. }
  1204. lb_addr_store(p, l, x);
  1205. return x;
  1206. }
  1207. case lbParamPass_Pointer:
  1208. lb_add_entity(p->module, e, v);
  1209. return lb_emit_load(p, v);
  1210. case lbParamPass_Integer: {
  1211. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1212. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  1213. lb_emit_store(p, iptr, v);
  1214. return lb_addr_load(p, l);
  1215. }
  1216. case lbParamPass_ConstRef:
  1217. lb_add_entity(p->module, e, v);
  1218. return lb_emit_load(p, v);
  1219. case lbParamPass_BitCast: {
  1220. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1221. lbValue x = lb_emit_transmute(p, v, e->type);
  1222. lb_addr_store(p, l, x);
  1223. return x;
  1224. }
  1225. case lbParamPass_Tuple: {
  1226. lbAddr l = lb_add_local(p, e->type, e, true, index);
  1227. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  1228. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  1229. if (abi_type->Tuple.variables.count > 0) {
  1230. array_pop(&p->params);
  1231. }
  1232. for_array(i, abi_type->Tuple.variables) {
  1233. Type *t = abi_type->Tuple.variables[i]->type;
  1234. lbParamPasskind elem_kind = lbParamPass_Value;
  1235. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  1236. array_add(&p->params, elem);
  1237. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  1238. lb_emit_store(p, dst, elem);
  1239. }
  1240. return lb_addr_load(p, l);
  1241. }
  1242. }
  1243. GB_PANIC("Unreachable");
  1244. return {};
  1245. }
  1246. void lb_start_block(lbProcedure *p, lbBlock *b) {
  1247. GB_ASSERT(b != nullptr);
  1248. if (!b->appended) {
  1249. b->appended = true;
  1250. LLVMAppendExistingBasicBlock(p->value, b->block);
  1251. }
  1252. LLVMPositionBuilderAtEnd(p->builder, b->block);
  1253. p->curr_block = b;
  1254. }
  1255. void lb_begin_procedure_body(lbProcedure *p) {
  1256. DeclInfo *decl = decl_info_of_entity(p->entity);
  1257. if (decl != nullptr) {
  1258. for_array(i, decl->labels) {
  1259. BlockLabel bl = decl->labels[i];
  1260. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  1261. array_add(&p->branch_blocks, bb);
  1262. }
  1263. }
  1264. p->builder = LLVMCreateBuilder();
  1265. p->decl_block = lb_create_block(p, "decls", true);
  1266. p->entry_block = lb_create_block(p, "entry", true);
  1267. lb_start_block(p, p->entry_block);
  1268. GB_ASSERT(p->type != nullptr);
  1269. i32 parameter_index = 0;
  1270. if (p->type->Proc.return_by_pointer) {
  1271. // NOTE(bill): this must be parameter 0
  1272. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  1273. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  1274. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  1275. lbValue return_ptr_value = {};
  1276. return_ptr_value.value = LLVMGetParam(p->value, 0);
  1277. return_ptr_value.type = alloc_type_pointer(p->type->Proc.abi_compat_result_type);
  1278. p->return_ptr = lb_addr(return_ptr_value);
  1279. lb_add_entity(p->module, e, return_ptr_value);
  1280. parameter_index += 1;
  1281. }
  1282. if (p->type->Proc.params != nullptr) {
  1283. TypeTuple *params = &p->type->Proc.params->Tuple;
  1284. if (p->type_expr != nullptr) {
  1285. ast_node(pt, ProcType, p->type_expr);
  1286. isize param_index = 0;
  1287. isize q_index = 0;
  1288. for_array(i, params->variables) {
  1289. ast_node(fl, FieldList, pt->params);
  1290. GB_ASSERT(fl->list.count > 0);
  1291. GB_ASSERT(fl->list[0]->kind == Ast_Field);
  1292. if (q_index == fl->list[param_index]->Field.names.count) {
  1293. q_index = 0;
  1294. param_index++;
  1295. }
  1296. ast_node(field, Field, fl->list[param_index]);
  1297. Ast *name = field->names[q_index++];
  1298. Entity *e = params->variables[i];
  1299. if (e->kind != Entity_Variable) {
  1300. continue;
  1301. }
  1302. Type *abi_type = p->type->Proc.abi_compat_params[i];
  1303. if (e->token.string != "") {
  1304. lb_add_param(p, e, name, abi_type, parameter_index);
  1305. }
  1306. if (is_type_tuple(abi_type)) {
  1307. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  1308. } else {
  1309. parameter_index += 1;
  1310. }
  1311. }
  1312. } else {
  1313. auto abi_types = p->type->Proc.abi_compat_params;
  1314. for_array(i, params->variables) {
  1315. Entity *e = params->variables[i];
  1316. if (e->kind != Entity_Variable) {
  1317. continue;
  1318. }
  1319. Type *abi_type = e->type;
  1320. if (abi_types.count > 0) {
  1321. abi_type = abi_types[i];
  1322. }
  1323. if (e->token.string != "") {
  1324. lb_add_param(p, e, nullptr, abi_type, parameter_index);
  1325. }
  1326. if (is_type_tuple(abi_type)) {
  1327. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  1328. } else {
  1329. parameter_index += 1;
  1330. }
  1331. }
  1332. }
  1333. }
  1334. if (p->type->Proc.has_named_results) {
  1335. GB_ASSERT(p->type->Proc.result_count > 0);
  1336. TypeTuple *results = &p->type->Proc.results->Tuple;
  1337. LLVMValueRef return_ptr = LLVMGetParam(p->value, 0);
  1338. isize result_index = 0;
  1339. for_array(i, results->variables) {
  1340. Entity *e = results->variables[i];
  1341. if (e->kind != Entity_Variable) {
  1342. continue;
  1343. }
  1344. if (e->token.string != "") {
  1345. GB_ASSERT(!is_blank_ident(e->token));
  1346. lbAddr res = lb_add_local(p, e->type, e);
  1347. lbValue c = {};
  1348. switch (e->Variable.param_value.kind) {
  1349. case ParameterValue_Constant:
  1350. c = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  1351. break;
  1352. case ParameterValue_Nil:
  1353. c = lb_const_nil(p->module, e->type);
  1354. break;
  1355. case ParameterValue_Location:
  1356. GB_PANIC("ParameterValue_Location");
  1357. break;
  1358. }
  1359. if (c.value != nullptr) {
  1360. lb_addr_store(p, res, c);
  1361. }
  1362. }
  1363. result_index += 1;
  1364. }
  1365. }
  1366. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  1367. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  1368. e->flags |= EntityFlag_NoAlias;
  1369. lbValue param = {};
  1370. param.value = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  1371. param.type = e->type;
  1372. lb_add_entity(p->module, e, param);
  1373. lbAddr ctx_addr = {};
  1374. ctx_addr.kind = lbAddr_Context;
  1375. ctx_addr.addr = param;
  1376. lbContextData ctx = {ctx_addr, p->scope_index};
  1377. array_add(&p->context_stack, ctx);
  1378. }
  1379. lb_start_block(p, p->entry_block);
  1380. }
  1381. void lb_end_procedure_body(lbProcedure *p) {
  1382. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  1383. LLVMBuildBr(p->builder, p->entry_block->block);
  1384. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  1385. if (p->type->Proc.result_count == 0) {
  1386. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  1387. if (!LLVMIsAReturnInst(instr)) {
  1388. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1389. LLVMBuildRetVoid(p->builder);
  1390. }
  1391. } else {
  1392. if (p->curr_block->preds.count == 0) {
  1393. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  1394. if (instr == nullptr) {
  1395. // NOTE(bill): Remove dead trailing block
  1396. LLVMDeleteBasicBlock(p->curr_block->block);
  1397. }
  1398. }
  1399. }
  1400. p->curr_block = nullptr;
  1401. }
  1402. void lb_end_procedure(lbProcedure *p) {
  1403. LLVMDisposeBuilder(p->builder);
  1404. }
  1405. void lb_add_edge(lbBlock *from, lbBlock *to) {
  1406. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  1407. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  1408. array_add(&from->succs, to);
  1409. array_add(&to->preds, from);
  1410. }
  1411. }
  1412. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  1413. lbBlock *b = gb_alloc_item(heap_allocator(), lbBlock);
  1414. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  1415. b->appended = false;
  1416. if (append) {
  1417. b->appended = true;
  1418. LLVMAppendExistingBasicBlock(p->value, b->block);
  1419. }
  1420. b->scope = p->curr_scope;
  1421. b->scope_index = p->scope_index;
  1422. b->preds.allocator = heap_allocator();
  1423. b->succs.allocator = heap_allocator();
  1424. array_add(&p->blocks, b);
  1425. return b;
  1426. }
  1427. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  1428. if (p->curr_block == nullptr) {
  1429. return;
  1430. }
  1431. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1432. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  1433. return;
  1434. }
  1435. lb_add_edge(p->curr_block, target_block);
  1436. LLVMBuildBr(p->builder, target_block->block);
  1437. p->curr_block = nullptr;
  1438. }
  1439. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  1440. lbBlock *b = p->curr_block;
  1441. if (b == nullptr) {
  1442. return;
  1443. }
  1444. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1445. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  1446. return;
  1447. }
  1448. lb_add_edge(b, true_block);
  1449. lb_add_edge(b, false_block);
  1450. LLVMValueRef cv = cond.value;
  1451. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  1452. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  1453. }
  1454. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  1455. GB_ASSERT(cond != nullptr);
  1456. GB_ASSERT(true_block != nullptr);
  1457. GB_ASSERT(false_block != nullptr);
  1458. switch (cond->kind) {
  1459. case_ast_node(pe, ParenExpr, cond);
  1460. return lb_build_cond(p, pe->expr, true_block, false_block);
  1461. case_end;
  1462. case_ast_node(ue, UnaryExpr, cond);
  1463. if (ue->op.kind == Token_Not) {
  1464. return lb_build_cond(p, ue->expr, false_block, true_block);
  1465. }
  1466. case_end;
  1467. case_ast_node(be, BinaryExpr, cond);
  1468. if (be->op.kind == Token_CmpAnd) {
  1469. lbBlock *block = lb_create_block(p, "cmp.and");
  1470. lb_build_cond(p, be->left, block, false_block);
  1471. lb_start_block(p, block);
  1472. return lb_build_cond(p, be->right, true_block, false_block);
  1473. } else if (be->op.kind == Token_CmpOr) {
  1474. lbBlock *block = lb_create_block(p, "cmp.or");
  1475. lb_build_cond(p, be->left, true_block, block);
  1476. lb_start_block(p, block);
  1477. return lb_build_cond(p, be->right, true_block, false_block);
  1478. }
  1479. case_end;
  1480. }
  1481. lbValue v = lb_build_expr(p, cond);
  1482. // v = lb_emit_conv(p, v, t_bool);
  1483. v = lb_emit_conv(p, v, t_llvm_bool);
  1484. lb_emit_if(p, v, true_block, false_block);
  1485. return v;
  1486. }
  1487. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  1488. GB_ASSERT(p->decl_block != p->curr_block);
  1489. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  1490. char const *name = "";
  1491. if (e != nullptr) {
  1492. // name = alloc_cstring(heap_allocator(), e->token.string);
  1493. }
  1494. LLVMTypeRef llvm_type = lb_type(p->module, type);
  1495. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  1496. LLVMSetAlignment(ptr, 16); // TODO(bill): Make this configurable
  1497. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  1498. if (zero_init) {
  1499. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  1500. }
  1501. lbValue val = {};
  1502. val.value = ptr;
  1503. val.type = alloc_type_pointer(type);
  1504. if (e != nullptr) {
  1505. lb_add_entity(p->module, e, val);
  1506. }
  1507. return lb_addr(val);
  1508. }
  1509. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  1510. return lb_add_local(p, type, nullptr, zero_init);
  1511. }
  1512. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  1513. GB_ASSERT(pd->body != nullptr);
  1514. lbModule *m = p->module;
  1515. auto *min_dep_set = &m->info->minimum_dependency_set;
  1516. if (ptr_set_exists(min_dep_set, e) == false) {
  1517. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1518. return;
  1519. }
  1520. // NOTE(bill): Generate a new name
  1521. // parent.name-guid
  1522. String original_name = e->token.string;
  1523. String pd_name = original_name;
  1524. if (e->Procedure.link_name.len > 0) {
  1525. pd_name = e->Procedure.link_name;
  1526. }
  1527. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  1528. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  1529. i32 guid = cast(i32)p->children.count;
  1530. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  1531. String name = make_string(cast(u8 *)name_text, name_len-1);
  1532. set_procedure_abi_types(heap_allocator(), e->type);
  1533. e->Procedure.link_name = name;
  1534. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  1535. lbValue value = {};
  1536. value.value = nested_proc->value;
  1537. value.type = nested_proc->type;
  1538. lb_add_entity(m, e, value);
  1539. array_add(&p->children, nested_proc);
  1540. array_add(&m->procedures_to_generate, nested_proc);
  1541. }
  1542. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  1543. if (e == nullptr) {
  1544. return;
  1545. }
  1546. GB_ASSERT(e->kind == Entity_LibraryName);
  1547. GB_ASSERT(e->flags & EntityFlag_Used);
  1548. for_array(i, e->LibraryName.paths) {
  1549. String library_path = e->LibraryName.paths[i];
  1550. if (library_path.len == 0) {
  1551. continue;
  1552. }
  1553. bool ok = true;
  1554. for_array(path_index, m->foreign_library_paths) {
  1555. String path = m->foreign_library_paths[path_index];
  1556. #if defined(GB_SYSTEM_WINDOWS)
  1557. if (str_eq_ignore_case(path, library_path)) {
  1558. #else
  1559. if (str_eq(path, library_path)) {
  1560. #endif
  1561. ok = false;
  1562. break;
  1563. }
  1564. }
  1565. if (ok) {
  1566. array_add(&m->foreign_library_paths, library_path);
  1567. }
  1568. }
  1569. }
  1570. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  1571. if (vd == nullptr || vd->is_mutable) {
  1572. return;
  1573. }
  1574. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  1575. static i32 global_guid = 0;
  1576. for_array(i, vd->names) {
  1577. Ast *ident = vd->names[i];
  1578. GB_ASSERT(ident->kind == Ast_Ident);
  1579. Entity *e = entity_of_ident(ident);
  1580. GB_ASSERT(e != nullptr);
  1581. if (e->kind != Entity_TypeName) {
  1582. continue;
  1583. }
  1584. bool polymorphic_struct = false;
  1585. if (e->type != nullptr && e->kind == Entity_TypeName) {
  1586. Type *bt = base_type(e->type);
  1587. if (bt->kind == Type_Struct) {
  1588. polymorphic_struct = bt->Struct.is_polymorphic;
  1589. }
  1590. }
  1591. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  1592. continue;
  1593. }
  1594. if (e->TypeName.ir_mangled_name.len != 0) {
  1595. // NOTE(bill): Already set
  1596. continue;
  1597. }
  1598. lb_set_nested_type_name_ir_mangled_name(e, p);
  1599. }
  1600. for_array(i, vd->names) {
  1601. Ast *ident = vd->names[i];
  1602. GB_ASSERT(ident->kind == Ast_Ident);
  1603. Entity *e = entity_of_ident(ident);
  1604. GB_ASSERT(e != nullptr);
  1605. if (e->kind != Entity_Procedure) {
  1606. continue;
  1607. }
  1608. CheckerInfo *info = p->module->info;
  1609. DeclInfo *decl = decl_info_of_entity(e);
  1610. ast_node(pl, ProcLit, decl->proc_lit);
  1611. if (pl->body != nullptr) {
  1612. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  1613. if (found) {
  1614. auto procs = *found;
  1615. for_array(i, procs) {
  1616. Entity *e = procs[i];
  1617. if (!ptr_set_exists(min_dep_set, e)) {
  1618. continue;
  1619. }
  1620. DeclInfo *d = decl_info_of_entity(e);
  1621. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  1622. }
  1623. } else {
  1624. lb_build_nested_proc(p, pl, e);
  1625. }
  1626. } else {
  1627. // FFI - Foreign function interace
  1628. String original_name = e->token.string;
  1629. String name = original_name;
  1630. if (e->Procedure.is_foreign) {
  1631. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  1632. }
  1633. if (e->Procedure.link_name.len > 0) {
  1634. name = e->Procedure.link_name;
  1635. }
  1636. HashKey key = hash_string(name);
  1637. lbValue *prev_value = map_get(&p->module->members, key);
  1638. if (prev_value != nullptr) {
  1639. // NOTE(bill): Don't do mutliple declarations in the IR
  1640. return;
  1641. }
  1642. set_procedure_abi_types(heap_allocator(), e->type);
  1643. e->Procedure.link_name = name;
  1644. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  1645. lbValue value = {};
  1646. value.value = nested_proc->value;
  1647. value.type = nested_proc->type;
  1648. array_add(&p->module->procedures_to_generate, nested_proc);
  1649. if (p != nullptr) {
  1650. array_add(&p->children, nested_proc);
  1651. } else {
  1652. map_set(&p->module->members, hash_string(name), value);
  1653. }
  1654. }
  1655. }
  1656. }
  1657. void lb_build_stmt_list(lbProcedure *p, Array<Ast *> const &stmts) {
  1658. for_array(i, stmts) {
  1659. Ast *stmt = stmts[i];
  1660. switch (stmt->kind) {
  1661. case_ast_node(vd, ValueDecl, stmt);
  1662. lb_build_constant_value_decl(p, vd);
  1663. case_end;
  1664. case_ast_node(fb, ForeignBlockDecl, stmt);
  1665. ast_node(block, BlockStmt, fb->body);
  1666. lb_build_stmt_list(p, block->stmts);
  1667. case_end;
  1668. }
  1669. }
  1670. for_array(i, stmts) {
  1671. lb_build_stmt(p, stmts[i]);
  1672. }
  1673. }
  1674. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  1675. GB_ASSERT(ident->kind == Ast_Ident);
  1676. Entity *e = entity_of_ident(ident);
  1677. GB_ASSERT(e->kind == Entity_Label);
  1678. for_array(i, p->branch_blocks) {
  1679. lbBranchBlocks *b = &p->branch_blocks[i];
  1680. if (b->label == e->Label.node) {
  1681. return *b;
  1682. }
  1683. }
  1684. GB_PANIC("Unreachable");
  1685. lbBranchBlocks empty = {};
  1686. return empty;
  1687. }
  1688. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  1689. lbTargetList *tl = gb_alloc_item(heap_allocator(), lbTargetList);
  1690. tl->prev = p->target_list;
  1691. tl->break_ = break_;
  1692. tl->continue_ = continue_;
  1693. tl->fallthrough_ = fallthrough_;
  1694. p->target_list = tl;
  1695. if (label != nullptr) { // Set label blocks
  1696. GB_ASSERT(label->kind == Ast_Label);
  1697. for_array(i, p->branch_blocks) {
  1698. lbBranchBlocks *b = &p->branch_blocks[i];
  1699. GB_ASSERT(b->label != nullptr && label != nullptr);
  1700. GB_ASSERT(b->label->kind == Ast_Label);
  1701. if (b->label == label) {
  1702. b->break_ = break_;
  1703. b->continue_ = continue_;
  1704. return tl;
  1705. }
  1706. }
  1707. GB_PANIC("Unreachable");
  1708. }
  1709. return tl;
  1710. }
  1711. void lb_pop_target_list(lbProcedure *p) {
  1712. p->target_list = p->target_list->prev;
  1713. }
  1714. void lb_open_scope(lbProcedure *p) {
  1715. p->scope_index += 1;
  1716. }
  1717. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  1718. lb_emit_defer_stmts(p, kind, block);
  1719. GB_ASSERT(p->scope_index > 0);
  1720. // NOTE(bill): Remove `context`s made in that scope
  1721. while (p->context_stack.count > 0) {
  1722. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  1723. if (ctx->scope_index >= p->scope_index) {
  1724. array_pop(&p->context_stack);
  1725. } else {
  1726. break;
  1727. }
  1728. }
  1729. p->scope_index -= 1;
  1730. }
  1731. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  1732. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  1733. GB_ASSERT(is_type_boolean(tv.type));
  1734. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  1735. if (tv.value.value_bool) {
  1736. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  1737. } else if (ws->else_stmt) {
  1738. switch (ws->else_stmt->kind) {
  1739. case Ast_BlockStmt:
  1740. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  1741. break;
  1742. case Ast_WhenStmt:
  1743. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  1744. break;
  1745. default:
  1746. GB_PANIC("Invalid 'else' statement in 'when' statement");
  1747. break;
  1748. }
  1749. }
  1750. }
  1751. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  1752. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  1753. lbModule *m = p->module;
  1754. lbValue count = {};
  1755. Type *expr_type = base_type(type_deref(expr.type));
  1756. switch (expr_type->kind) {
  1757. case Type_Array:
  1758. count = lb_const_int(m, t_int, expr_type->Array.count);
  1759. break;
  1760. }
  1761. lbValue val = {};
  1762. lbValue idx = {};
  1763. lbBlock *loop = nullptr;
  1764. lbBlock *done = nullptr;
  1765. lbBlock *body = nullptr;
  1766. lbAddr index = lb_add_local_generated(p, t_int, false);
  1767. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  1768. loop = lb_create_block(p, "for.index.loop");
  1769. lb_emit_jump(p, loop);
  1770. lb_start_block(p, loop);
  1771. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  1772. lb_addr_store(p, index, incr);
  1773. body = lb_create_block(p, "for.index.body");
  1774. done = lb_create_block(p, "for.index.done");
  1775. if (count.value == nullptr) {
  1776. GB_ASSERT(count_ptr.value != nullptr);
  1777. count = lb_emit_load(p, count_ptr);
  1778. }
  1779. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  1780. lb_emit_if(p, cond, body, done);
  1781. lb_start_block(p, body);
  1782. idx = lb_addr_load(p, index);
  1783. switch (expr_type->kind) {
  1784. case Type_Array: {
  1785. if (val_type != nullptr) {
  1786. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  1787. }
  1788. break;
  1789. }
  1790. case Type_EnumeratedArray: {
  1791. if (val_type != nullptr) {
  1792. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  1793. // NOTE(bill): Override the idx value for the enumeration
  1794. Type *index_type = expr_type->EnumeratedArray.index;
  1795. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  1796. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  1797. }
  1798. }
  1799. break;
  1800. }
  1801. case Type_Slice: {
  1802. if (val_type != nullptr) {
  1803. lbValue elem = lb_slice_elem(p, expr);
  1804. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  1805. }
  1806. break;
  1807. }
  1808. case Type_DynamicArray: {
  1809. if (val_type != nullptr) {
  1810. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  1811. elem = lb_emit_load(p, elem);
  1812. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  1813. }
  1814. break;
  1815. }
  1816. case Type_Map: {
  1817. lbAddr key = lb_add_local_generated(p, expr_type->Map.key, true);
  1818. lbValue entries = lb_map_entries_ptr(p, expr);
  1819. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  1820. elem = lb_emit_load(p, elem);
  1821. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  1822. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  1823. lbValue hash = lb_emit_struct_ep(p, entry, 0);
  1824. if (is_type_string(expr_type->Map.key)) {
  1825. lbValue str = lb_emit_struct_ep(p, hash, 1);
  1826. lb_addr_store(p, key, lb_emit_load(p, str));
  1827. } else {
  1828. lbValue hash_ptr = lb_emit_struct_ep(p, hash, 0);
  1829. hash_ptr = lb_emit_conv(p, hash_ptr, key.addr.type);
  1830. lb_addr_store(p, key, lb_emit_load(p, hash_ptr));
  1831. }
  1832. idx = lb_addr_load(p, key);
  1833. break;
  1834. }
  1835. default:
  1836. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  1837. break;
  1838. }
  1839. if (val_) *val_ = val;
  1840. if (idx_) *idx_ = idx;
  1841. if (loop_) *loop_ = loop;
  1842. if (done_) *done_ = done;
  1843. }
  1844. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  1845. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  1846. lbModule *m = p->module;
  1847. lbValue count = lb_const_int(m, t_int, 0);
  1848. Type *expr_type = base_type(expr.type);
  1849. switch (expr_type->kind) {
  1850. case Type_Basic:
  1851. count = lb_string_len(p, expr);
  1852. break;
  1853. default:
  1854. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  1855. break;
  1856. }
  1857. lbValue val = {};
  1858. lbValue idx = {};
  1859. lbBlock *loop = nullptr;
  1860. lbBlock *done = nullptr;
  1861. lbBlock *body = nullptr;
  1862. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  1863. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  1864. loop = lb_create_block(p, "for.string.loop");
  1865. lb_emit_jump(p, loop);
  1866. lb_start_block(p, loop);
  1867. body = lb_create_block(p, "for.string.body");
  1868. done = lb_create_block(p, "for.string.done");
  1869. lbValue offset = lb_addr_load(p, offset_);
  1870. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  1871. lb_emit_if(p, cond, body, done);
  1872. lb_start_block(p, body);
  1873. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  1874. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  1875. auto args = array_make<lbValue>(heap_allocator(), 1);
  1876. args[0] = lb_emit_string(p, str_elem, str_len);
  1877. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  1878. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  1879. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  1880. idx = offset;
  1881. if (val_type != nullptr) {
  1882. val = lb_emit_struct_ev(p, rune_and_len, 0);
  1883. }
  1884. if (val_) *val_ = val;
  1885. if (idx_) *idx_ = idx;
  1886. if (loop_) *loop_ = loop;
  1887. if (done_) *done_ = done;
  1888. }
  1889. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  1890. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  1891. lbModule *m = p->module;
  1892. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  1893. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  1894. lbValue lower = lb_build_expr(p, node->left);
  1895. lbValue upper = {};
  1896. lbValue val = {};
  1897. lbValue idx = {};
  1898. lbBlock *loop = nullptr;
  1899. lbBlock *done = nullptr;
  1900. lbBlock *body = nullptr;
  1901. if (val_type == nullptr) {
  1902. val_type = lower.type;
  1903. }
  1904. lbAddr value = lb_add_local_generated(p, val_type, false);
  1905. lb_addr_store(p, value, lower);
  1906. lbAddr index = lb_add_local_generated(p, t_int, false);
  1907. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  1908. loop = lb_create_block(p, "for.interval.loop");
  1909. lb_emit_jump(p, loop);
  1910. lb_start_block(p, loop);
  1911. body = lb_create_block(p, "for.interval.body");
  1912. done = lb_create_block(p, "for.interval.done");
  1913. TokenKind op = Token_Lt;
  1914. switch (node->op.kind) {
  1915. case Token_Ellipsis: op = Token_LtEq; break;
  1916. case Token_RangeHalf: op = Token_Lt; break;
  1917. default: GB_PANIC("Invalid interval operator"); break;
  1918. }
  1919. upper = lb_build_expr(p, node->right);
  1920. lbValue curr_value = lb_addr_load(p, value);
  1921. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  1922. lb_emit_if(p, cond, body, done);
  1923. lb_start_block(p, body);
  1924. val = lb_addr_load(p, value);
  1925. idx = lb_addr_load(p, index);
  1926. lb_emit_increment(p, value.addr);
  1927. lb_emit_increment(p, index.addr);
  1928. if (val_) *val_ = val;
  1929. if (idx_) *idx_ = idx;
  1930. if (loop_) *loop_ = loop;
  1931. if (done_) *done_ = done;
  1932. }
  1933. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  1934. lbModule *m = p->module;
  1935. Type *t = enum_type;
  1936. GB_ASSERT(is_type_enum(t));
  1937. Type *enum_ptr = alloc_type_pointer(t);
  1938. t = base_type(t);
  1939. Type *core_elem = core_type(t);
  1940. GB_ASSERT(t->kind == Type_Enum);
  1941. i64 enum_count = t->Enum.fields.count;
  1942. lbValue max_count = lb_const_int(m, t_int, enum_count);
  1943. lbValue ti = lb_type_info(m, t);
  1944. lbValue variant = lb_emit_struct_ep(p, ti, 3);
  1945. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  1946. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  1947. lbValue values_data = lb_slice_elem(p, values);
  1948. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  1949. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  1950. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  1951. lb_emit_jump(p, loop);
  1952. lb_start_block(p, loop);
  1953. lbBlock *body = lb_create_block(p, "for.enum.body");
  1954. lbBlock *done = lb_create_block(p, "for.enum.done");
  1955. lbValue offset = lb_addr_load(p, offset_);
  1956. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  1957. lb_emit_if(p, cond, body, done);
  1958. lb_start_block(p, body);
  1959. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  1960. lb_emit_increment(p, offset_.addr);
  1961. lbValue val = {};
  1962. if (val_type != nullptr) {
  1963. GB_ASSERT(are_types_identical(enum_type, val_type));
  1964. if (is_type_integer(core_elem)) {
  1965. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  1966. val = lb_emit_conv(p, i, t);
  1967. } else {
  1968. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  1969. }
  1970. }
  1971. if (val_) *val_ = val;
  1972. if (idx_) *idx_ = offset;
  1973. if (loop_) *loop_ = loop;
  1974. if (done_) *done_ = done;
  1975. }
  1976. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  1977. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  1978. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  1979. lb_emit_jump(p, loop);
  1980. lb_start_block(p, loop);
  1981. lbBlock *body = lb_create_block(p, "for.tuple.body");
  1982. lbBlock *done = lb_create_block(p, "for.tuple.done");
  1983. lbValue tuple_value = lb_build_expr(p, expr);
  1984. Type *tuple = tuple_value.type;
  1985. GB_ASSERT(tuple->kind == Type_Tuple);
  1986. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  1987. i32 cond_index = tuple_count-1;
  1988. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  1989. lb_emit_if(p, cond, body, done);
  1990. lb_start_block(p, body);
  1991. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  1992. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  1993. if (loop_) *loop_ = loop;
  1994. if (done_) *done_ = done;
  1995. }
  1996. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) {
  1997. lb_open_scope(p);
  1998. Type *val0_type = nullptr;
  1999. Type *val1_type = nullptr;
  2000. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2001. val0_type = type_of_expr(rs->val0);
  2002. }
  2003. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2004. val1_type = type_of_expr(rs->val1);
  2005. }
  2006. if (val0_type != nullptr) {
  2007. Entity *e = entity_of_ident(rs->val0);
  2008. lb_add_local(p, e->type, e, true);
  2009. }
  2010. if (val1_type != nullptr) {
  2011. Entity *e = entity_of_ident(rs->val1);
  2012. lb_add_local(p, e->type, e, true);
  2013. }
  2014. lbValue val = {};
  2015. lbValue key = {};
  2016. lbBlock *loop = nullptr;
  2017. lbBlock *done = nullptr;
  2018. Ast *expr = unparen_expr(rs->expr);
  2019. bool is_map = false;
  2020. TypeAndValue tav = type_and_value_of_expr(expr);
  2021. if (is_ast_range(expr)) {
  2022. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  2023. } else if (tav.mode == Addressing_Type) {
  2024. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  2025. } else {
  2026. Type *expr_type = type_of_expr(expr);
  2027. Type *et = base_type(type_deref(expr_type));
  2028. switch (et->kind) {
  2029. case Type_Map: {
  2030. is_map = true;
  2031. gbAllocator a = heap_allocator();
  2032. lbAddr addr = lb_build_addr(p, expr);
  2033. lbValue map = lb_addr_get_ptr(p, addr);
  2034. if (is_type_pointer(type_deref(lb_addr_type(addr)))) {
  2035. map = lb_addr_load(p, addr);
  2036. }
  2037. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  2038. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  2039. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  2040. break;
  2041. }
  2042. case Type_Array: {
  2043. lbValue array = lb_build_addr_ptr(p, expr);
  2044. if (is_type_pointer(type_deref(array.type))) {
  2045. array = lb_emit_load(p, array);
  2046. }
  2047. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2048. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  2049. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2050. break;
  2051. }
  2052. case Type_EnumeratedArray: {
  2053. lbValue array = lb_build_addr_ptr(p, expr);
  2054. if (is_type_pointer(type_deref(array.type))) {
  2055. array = lb_emit_load(p, array);
  2056. }
  2057. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2058. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  2059. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2060. break;
  2061. }
  2062. case Type_DynamicArray: {
  2063. lbValue count_ptr = {};
  2064. lbValue array = lb_build_addr_ptr(p, expr);
  2065. if (is_type_pointer(type_deref(array.type))) {
  2066. array = lb_emit_load(p, array);
  2067. }
  2068. count_ptr = lb_emit_struct_ep(p, array, 1);
  2069. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  2070. break;
  2071. }
  2072. case Type_Slice: {
  2073. lbValue count_ptr = {};
  2074. lbValue slice = lb_build_expr(p, expr);
  2075. if (is_type_pointer(slice.type)) {
  2076. count_ptr = lb_emit_struct_ep(p, slice, 1);
  2077. slice = lb_emit_load(p, slice);
  2078. } else {
  2079. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  2080. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  2081. }
  2082. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  2083. break;
  2084. }
  2085. case Type_Basic: {
  2086. lbValue string = lb_build_expr(p, expr);
  2087. if (is_type_pointer(string.type)) {
  2088. string = lb_emit_load(p, string);
  2089. }
  2090. if (is_type_untyped(expr_type)) {
  2091. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  2092. lb_addr_store(p, s, string);
  2093. string = lb_addr_load(p, s);
  2094. }
  2095. Type *t = base_type(string.type);
  2096. GB_ASSERT(!is_type_cstring(t));
  2097. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  2098. break;
  2099. }
  2100. case Type_Tuple:
  2101. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  2102. break;
  2103. default:
  2104. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  2105. break;
  2106. }
  2107. }
  2108. if (is_map) {
  2109. if (val0_type) lb_store_range_stmt_val(p, rs->val0, key);
  2110. if (val1_type) lb_store_range_stmt_val(p, rs->val1, val);
  2111. } else {
  2112. if (val0_type) lb_store_range_stmt_val(p, rs->val0, val);
  2113. if (val1_type) lb_store_range_stmt_val(p, rs->val1, key);
  2114. }
  2115. lb_push_target_list(p, rs->label, done, loop, nullptr);
  2116. lb_build_stmt(p, rs->body);
  2117. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2118. lb_pop_target_list(p);
  2119. lb_emit_jump(p, loop);
  2120. lb_start_block(p, done);
  2121. }
  2122. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) {
  2123. lbModule *m = p->module;
  2124. lb_open_scope(p); // Open scope here
  2125. Type *val0_type = nullptr;
  2126. Type *val1_type = nullptr;
  2127. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2128. val0_type = type_of_expr(rs->val0);
  2129. }
  2130. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2131. val1_type = type_of_expr(rs->val1);
  2132. }
  2133. if (val0_type != nullptr) {
  2134. Entity *e = entity_of_ident(rs->val0);
  2135. lb_add_local(p, e->type, e, true);
  2136. }
  2137. if (val1_type != nullptr) {
  2138. Entity *e = entity_of_ident(rs->val1);
  2139. lb_add_local(p, e->type, e, true);
  2140. }
  2141. lbValue val = {};
  2142. lbValue key = {};
  2143. lbBlock *loop = nullptr;
  2144. lbBlock *done = nullptr;
  2145. Ast *expr = unparen_expr(rs->expr);
  2146. TypeAndValue tav = type_and_value_of_expr(expr);
  2147. if (is_ast_range(expr)) {
  2148. lbAddr val0_addr = {};
  2149. lbAddr val1_addr = {};
  2150. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2151. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2152. TokenKind op = expr->BinaryExpr.op.kind;
  2153. Ast *start_expr = expr->BinaryExpr.left;
  2154. Ast *end_expr = expr->BinaryExpr.right;
  2155. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  2156. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  2157. ExactValue start = start_expr->tav.value;
  2158. ExactValue end = end_expr->tav.value;
  2159. if (op == Token_Ellipsis) { // .. [start, end]
  2160. ExactValue index = exact_value_i64(0);
  2161. for (ExactValue val = start;
  2162. compare_exact_values(Token_LtEq, val, end);
  2163. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2164. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2165. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2166. lb_build_stmt(p, rs->body);
  2167. }
  2168. } else if (op == Token_RangeHalf) { // ..< [start, end)
  2169. ExactValue index = exact_value_i64(0);
  2170. for (ExactValue val = start;
  2171. compare_exact_values(Token_Lt, val, end);
  2172. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2173. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2174. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2175. lb_build_stmt(p, rs->body);
  2176. }
  2177. }
  2178. } else if (tav.mode == Addressing_Type) {
  2179. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  2180. Type *et = type_deref(tav.type);
  2181. Type *bet = base_type(et);
  2182. lbAddr val0_addr = {};
  2183. lbAddr val1_addr = {};
  2184. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2185. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2186. for_array(i, bet->Enum.fields) {
  2187. Entity *field = bet->Enum.fields[i];
  2188. GB_ASSERT(field->kind == Entity_Constant);
  2189. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  2190. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2191. lb_build_stmt(p, rs->body);
  2192. }
  2193. } else {
  2194. lbAddr val0_addr = {};
  2195. lbAddr val1_addr = {};
  2196. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2197. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2198. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  2199. Type *t = base_type(expr->tav.type);
  2200. switch (t->kind) {
  2201. case Type_Basic:
  2202. GB_ASSERT(is_type_string(t));
  2203. {
  2204. ExactValue value = expr->tav.value;
  2205. GB_ASSERT(value.kind == ExactValue_String);
  2206. String str = value.value_string;
  2207. Rune codepoint = 0;
  2208. isize offset = 0;
  2209. do {
  2210. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  2211. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  2212. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  2213. lb_build_stmt(p, rs->body);
  2214. offset += width;
  2215. } while (offset < str.len);
  2216. }
  2217. break;
  2218. case Type_Array:
  2219. if (t->Array.count > 0) {
  2220. lbValue val = lb_build_expr(p, expr);
  2221. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2222. for (i64 i = 0; i < t->Array.count; i++) {
  2223. if (val0_type) {
  2224. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2225. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2226. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2227. }
  2228. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2229. lb_build_stmt(p, rs->body);
  2230. }
  2231. }
  2232. break;
  2233. case Type_EnumeratedArray:
  2234. if (t->EnumeratedArray.count > 0) {
  2235. lbValue val = lb_build_expr(p, expr);
  2236. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2237. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  2238. if (val0_type) {
  2239. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2240. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2241. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2242. }
  2243. if (val1_type) {
  2244. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  2245. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  2246. }
  2247. lb_build_stmt(p, rs->body);
  2248. }
  2249. }
  2250. break;
  2251. default:
  2252. GB_PANIC("Invalid inline for type");
  2253. break;
  2254. }
  2255. }
  2256. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2257. }
  2258. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) {
  2259. if (ss->init != nullptr) {
  2260. lb_build_stmt(p, ss->init);
  2261. }
  2262. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  2263. if (ss->tag != nullptr) {
  2264. tag = lb_build_expr(p, ss->tag);
  2265. }
  2266. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  2267. ast_node(body, BlockStmt, ss->body);
  2268. Array<Ast *> default_stmts = {};
  2269. lbBlock *default_fall = nullptr;
  2270. lbBlock *default_block = nullptr;
  2271. lbBlock *fall = nullptr;
  2272. isize case_count = body->stmts.count;
  2273. for_array(i, body->stmts) {
  2274. Ast *clause = body->stmts[i];
  2275. ast_node(cc, CaseClause, clause);
  2276. lbBlock *body = fall;
  2277. if (body == nullptr) {
  2278. body = lb_create_block(p, "switch.case.body");
  2279. }
  2280. fall = done;
  2281. if (i+1 < case_count) {
  2282. fall = lb_create_block(p, "switch.fall.body");
  2283. }
  2284. if (cc->list.count == 0) {
  2285. // default case
  2286. default_stmts = cc->stmts;
  2287. default_fall = fall;
  2288. default_block = body;
  2289. continue;
  2290. }
  2291. lbBlock *next_cond = nullptr;
  2292. for_array(j, cc->list) {
  2293. Ast *expr = unparen_expr(cc->list[j]);
  2294. next_cond = lb_create_block(p, "switch.case.next");
  2295. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  2296. if (is_ast_range(expr)) {
  2297. ast_node(ie, BinaryExpr, expr);
  2298. TokenKind op = Token_Invalid;
  2299. switch (ie->op.kind) {
  2300. case Token_Ellipsis: op = Token_LtEq; break;
  2301. case Token_RangeHalf: op = Token_Lt; break;
  2302. default: GB_PANIC("Invalid interval operator"); break;
  2303. }
  2304. lbValue lhs = lb_build_expr(p, ie->left);
  2305. lbValue rhs = lb_build_expr(p, ie->right);
  2306. // TODO(bill): do short circuit here
  2307. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  2308. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  2309. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  2310. } else {
  2311. if (expr->tav.mode == Addressing_Type) {
  2312. GB_ASSERT(is_type_typeid(tag.type));
  2313. lbValue e = lb_typeid(p->module, expr->tav.type);
  2314. e = lb_emit_conv(p, e, tag.type);
  2315. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  2316. } else {
  2317. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  2318. }
  2319. }
  2320. lb_emit_if(p, cond, body, next_cond);
  2321. lb_start_block(p, next_cond);
  2322. }
  2323. lb_start_block(p, body);
  2324. lb_push_target_list(p, ss->label, done, nullptr, fall);
  2325. lb_open_scope(p);
  2326. lb_build_stmt_list(p, cc->stmts);
  2327. lb_close_scope(p, lbDeferExit_Default, body);
  2328. lb_pop_target_list(p);
  2329. lb_emit_jump(p, done);
  2330. lb_start_block(p, next_cond);
  2331. }
  2332. if (default_block != nullptr) {
  2333. lb_emit_jump(p, default_block);
  2334. lb_start_block(p, default_block);
  2335. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  2336. lb_open_scope(p);
  2337. lb_build_stmt_list(p, default_stmts);
  2338. lb_close_scope(p, lbDeferExit_Default, default_block);
  2339. lb_pop_target_list(p);
  2340. }
  2341. lb_emit_jump(p, done);
  2342. lb_start_block(p, done);
  2343. }
  2344. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  2345. Entity *e = implicit_entity_of_node(clause);
  2346. GB_ASSERT(e != nullptr);
  2347. if (e->flags & EntityFlag_Value) {
  2348. // by value
  2349. GB_ASSERT(are_types_identical(e->type, value.type));
  2350. lbAddr x = lb_add_local(p, e->type, e, false);
  2351. lb_addr_store(p, x, value);
  2352. } else {
  2353. // by reference
  2354. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  2355. lb_add_entity(p->module, e, value);
  2356. }
  2357. }
  2358. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  2359. Entity *e = entity_of_node(stmt_val);
  2360. if (e == nullptr) {
  2361. return {};
  2362. }
  2363. if ((e->flags & EntityFlag_Value) == 0) {
  2364. if (LLVMIsALoadInst(value.value)) {
  2365. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  2366. lb_add_entity(p->module, e, ptr);
  2367. return lb_addr(ptr);
  2368. }
  2369. }
  2370. // by value
  2371. lbAddr addr = lb_add_local(p, e->type, e, false);
  2372. lb_addr_store(p, addr, value);
  2373. return addr;
  2374. }
  2375. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  2376. ast_node(cc, CaseClause, clause);
  2377. lb_push_target_list(p, label, done, nullptr, nullptr);
  2378. lb_open_scope(p);
  2379. lb_build_stmt_list(p, cc->stmts);
  2380. lb_close_scope(p, lbDeferExit_Default, body);
  2381. lb_pop_target_list(p);
  2382. lb_emit_jump(p, done);
  2383. }
  2384. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  2385. lbModule *m = p->module;
  2386. ast_node(as, AssignStmt, ss->tag);
  2387. GB_ASSERT(as->lhs.count == 1);
  2388. GB_ASSERT(as->rhs.count == 1);
  2389. lbValue parent = lb_build_expr(p, as->rhs[0]);
  2390. bool is_parent_ptr = is_type_pointer(parent.type);
  2391. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  2392. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  2393. lbValue parent_value = parent;
  2394. lbValue parent_ptr = parent;
  2395. if (!is_parent_ptr) {
  2396. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  2397. }
  2398. lbValue tag_index = {};
  2399. lbValue union_data = {};
  2400. if (switch_kind == TypeSwitch_Union) {
  2401. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  2402. tag_index = lb_emit_load(p, tag_ptr);
  2403. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  2404. }
  2405. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  2406. lb_emit_jump(p, start_block);
  2407. lb_start_block(p, start_block);
  2408. // NOTE(bill): Append this later
  2409. lbBlock *done = lb_create_block(p, "typeswitch.done");
  2410. Ast *default_ = nullptr;
  2411. ast_node(body, BlockStmt, ss->body);
  2412. gb_local_persist i32 weird_count = 0;
  2413. for_array(i, body->stmts) {
  2414. Ast *clause = body->stmts[i];
  2415. ast_node(cc, CaseClause, clause);
  2416. if (cc->list.count == 0) {
  2417. default_ = clause;
  2418. continue;
  2419. }
  2420. lbBlock *body = lb_create_block(p, "typeswitch.body");
  2421. lbBlock *next = nullptr;
  2422. Type *case_type = nullptr;
  2423. for_array(type_index, cc->list) {
  2424. next = lb_create_block(p, "typeswitch.next");
  2425. case_type = type_of_expr(cc->list[type_index]);
  2426. lbValue cond = {};
  2427. if (switch_kind == TypeSwitch_Union) {
  2428. Type *ut = base_type(type_deref(parent.type));
  2429. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  2430. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  2431. } else if (switch_kind == TypeSwitch_Any) {
  2432. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  2433. lbValue case_typeid = lb_typeid(m, case_type);
  2434. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  2435. }
  2436. GB_ASSERT(cond.value != nullptr);
  2437. lb_emit_if(p, cond, body, next);
  2438. lb_start_block(p, next);
  2439. }
  2440. Entity *case_entity = implicit_entity_of_node(clause);
  2441. lbValue value = parent_value;
  2442. lb_start_block(p, body);
  2443. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  2444. if (cc->list.count == 1) {
  2445. lbValue data = {};
  2446. if (switch_kind == TypeSwitch_Union) {
  2447. data = union_data;
  2448. } else if (switch_kind == TypeSwitch_Any) {
  2449. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  2450. data = any_data;
  2451. }
  2452. Type *ct = case_entity->type;
  2453. Type *ct_ptr = alloc_type_pointer(ct);
  2454. value = lb_emit_conv(p, data, ct_ptr);
  2455. if (!by_reference) {
  2456. value = lb_emit_load(p, value);
  2457. }
  2458. }
  2459. lb_store_type_case_implicit(p, clause, value);
  2460. lb_type_case_body(p, ss->label, clause, body, done);
  2461. lb_start_block(p, next);
  2462. }
  2463. if (default_ != nullptr) {
  2464. lb_store_type_case_implicit(p, default_, parent_value);
  2465. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  2466. } else {
  2467. lb_emit_jump(p, done);
  2468. }
  2469. lb_start_block(p, done);
  2470. }
  2471. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  2472. lbModule *m = p->module;
  2473. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  2474. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  2475. type = default_type(type);
  2476. lbValue short_circuit = {};
  2477. if (op == Token_CmpAnd) {
  2478. lb_build_cond(p, left, rhs, done);
  2479. short_circuit = lb_const_bool(m, type, false);
  2480. } else if (op == Token_CmpOr) {
  2481. lb_build_cond(p, left, done, rhs);
  2482. short_circuit = lb_const_bool(m, type, true);
  2483. }
  2484. if (rhs->preds.count == 0) {
  2485. lb_start_block(p, done);
  2486. return short_circuit;
  2487. }
  2488. if (done->preds.count == 0) {
  2489. lb_start_block(p, rhs);
  2490. return lb_build_expr(p, right);
  2491. }
  2492. Array<LLVMValueRef> incoming_values = {};
  2493. Array<LLVMBasicBlockRef> incoming_blocks = {};
  2494. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  2495. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  2496. for_array(i, done->preds) {
  2497. incoming_values[i] = short_circuit.value;
  2498. incoming_blocks[i] = done->preds[i]->block;
  2499. }
  2500. lb_start_block(p, rhs);
  2501. lbValue edge = lb_build_expr(p, right);
  2502. incoming_values[done->preds.count] = edge.value;
  2503. incoming_blocks[done->preds.count] = p->curr_block->block;
  2504. lb_emit_jump(p, done);
  2505. lb_start_block(p, done);
  2506. lbValue res = {};
  2507. res.type = type;
  2508. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  2509. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  2510. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  2511. return res;
  2512. }
  2513. void lb_build_stmt(lbProcedure *p, Ast *node) {
  2514. switch (node->kind) {
  2515. case_ast_node(bs, EmptyStmt, node);
  2516. case_end;
  2517. case_ast_node(us, UsingStmt, node);
  2518. case_end;
  2519. case_ast_node(ws, WhenStmt, node);
  2520. lb_build_when_stmt(p, ws);
  2521. case_end;
  2522. case_ast_node(bs, BlockStmt, node);
  2523. if (bs->label != nullptr) {
  2524. lbBlock *done = lb_create_block(p, "block.done");
  2525. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  2526. tl->is_block = true;
  2527. lb_open_scope(p);
  2528. lb_build_stmt_list(p, bs->stmts);
  2529. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2530. lb_emit_jump(p, done);
  2531. lb_start_block(p, done);
  2532. } else {
  2533. lb_open_scope(p);
  2534. lb_build_stmt_list(p, bs->stmts);
  2535. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2536. }
  2537. case_end;
  2538. case_ast_node(vd, ValueDecl, node);
  2539. if (!vd->is_mutable) {
  2540. return;
  2541. }
  2542. bool is_static = false;
  2543. if (vd->names.count > 0) {
  2544. Entity *e = entity_of_ident(vd->names[0]);
  2545. if (e->flags & EntityFlag_Static) {
  2546. // NOTE(bill): If one of the entities is static, they all are
  2547. is_static = true;
  2548. }
  2549. }
  2550. if (is_static) {
  2551. for_array(i, vd->names) {
  2552. lbValue value = {};
  2553. if (vd->values.count > 0) {
  2554. GB_ASSERT(vd->names.count == vd->values.count);
  2555. Ast *ast_value = vd->values[i];
  2556. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  2557. ast_value->tav.mode == Addressing_Invalid);
  2558. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value);
  2559. }
  2560. Ast *ident = vd->names[i];
  2561. GB_ASSERT(!is_blank_ident(ident));
  2562. Entity *e = entity_of_ident(ident);
  2563. GB_ASSERT(e->flags & EntityFlag_Static);
  2564. String name = e->token.string;
  2565. String mangled_name = {};
  2566. {
  2567. gbString str = gb_string_make_length(heap_allocator(), p->name.text, p->name.len);
  2568. str = gb_string_appendc(str, "-");
  2569. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  2570. mangled_name.text = cast(u8 *)str;
  2571. mangled_name.len = gb_string_length(str);
  2572. }
  2573. char *c_name = alloc_cstring(heap_allocator(), mangled_name);
  2574. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  2575. if (value.value != nullptr) {
  2576. LLVMSetInitializer(global, value.value);
  2577. } else {
  2578. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  2579. }
  2580. if (e->Variable.thread_local_model != "") {
  2581. LLVMSetThreadLocal(global, true);
  2582. String m = e->Variable.thread_local_model;
  2583. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  2584. if (m == "default") {
  2585. mode = LLVMGeneralDynamicTLSModel;
  2586. } else if (m == "localdynamic") {
  2587. mode = LLVMLocalDynamicTLSModel;
  2588. } else if (m == "initialexec") {
  2589. mode = LLVMInitialExecTLSModel;
  2590. } else if (m == "localexec") {
  2591. mode = LLVMLocalExecTLSModel;
  2592. } else {
  2593. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  2594. }
  2595. LLVMSetThreadLocalMode(global, mode);
  2596. } else {
  2597. LLVMSetLinkage(global, LLVMInternalLinkage);
  2598. }
  2599. lbValue global_val = {global, alloc_type_pointer(e->type)};
  2600. lb_add_entity(p->module, e, global_val);
  2601. lb_add_member(p->module, mangled_name, global_val);
  2602. }
  2603. return;
  2604. }
  2605. if (vd->values.count == 0) { // declared and zero-initialized
  2606. for_array(i, vd->names) {
  2607. Ast *name = vd->names[i];
  2608. if (!is_blank_ident(name)) {
  2609. Entity *e = entity_of_ident(name);
  2610. lb_add_local(p, e->type, e, true);
  2611. }
  2612. }
  2613. } else { // Tuple(s)
  2614. auto lvals = array_make<lbAddr>(heap_allocator(), 0, vd->names.count);
  2615. auto inits = array_make<lbValue>(heap_allocator(), 0, vd->names.count);
  2616. for_array(i, vd->names) {
  2617. Ast *name = vd->names[i];
  2618. lbAddr lval = {};
  2619. if (!is_blank_ident(name)) {
  2620. Entity *e = entity_of_ident(name);
  2621. lval = lb_add_local(p, e->type, e, false);
  2622. }
  2623. array_add(&lvals, lval);
  2624. }
  2625. for_array(i, vd->values) {
  2626. lbValue init = lb_build_expr(p, vd->values[i]);
  2627. Type *t = init.type;
  2628. if (t->kind == Type_Tuple) {
  2629. for_array(i, t->Tuple.variables) {
  2630. Entity *e = t->Tuple.variables[i];
  2631. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  2632. array_add(&inits, v);
  2633. }
  2634. } else {
  2635. array_add(&inits, init);
  2636. }
  2637. }
  2638. for_array(i, inits) {
  2639. lbAddr lval = lvals[i];
  2640. lbValue init = inits[i];
  2641. lb_addr_store(p, lval, init);
  2642. }
  2643. }
  2644. case_end;
  2645. case_ast_node(as, AssignStmt, node);
  2646. if (as->op.kind == Token_Eq) {
  2647. auto lvals = array_make<lbAddr>(heap_allocator(), 0, as->lhs.count);
  2648. for_array(i, as->lhs) {
  2649. Ast *lhs = as->lhs[i];
  2650. lbAddr lval = {};
  2651. if (!is_blank_ident(lhs)) {
  2652. lval = lb_build_addr(p, lhs);
  2653. }
  2654. array_add(&lvals, lval);
  2655. }
  2656. if (as->lhs.count == as->rhs.count) {
  2657. if (as->lhs.count == 1) {
  2658. lbAddr lval = lvals[0];
  2659. Ast *rhs = as->rhs[0];
  2660. lbValue init = lb_build_expr(p, rhs);
  2661. lb_addr_store(p, lvals[0], init);
  2662. } else {
  2663. auto inits = array_make<lbValue>(heap_allocator(), 0, lvals.count);
  2664. for_array(i, as->rhs) {
  2665. lbValue init = lb_build_expr(p, as->rhs[i]);
  2666. array_add(&inits, init);
  2667. }
  2668. for_array(i, inits) {
  2669. lbAddr lval = lvals[i];
  2670. lbValue init = inits[i];
  2671. lb_addr_store(p, lval, init);
  2672. }
  2673. }
  2674. } else {
  2675. auto inits = array_make<lbValue>(heap_allocator(), 0, lvals.count);
  2676. for_array(i, as->rhs) {
  2677. lbValue init = lb_build_expr(p, as->rhs[i]);
  2678. Type *t = init.type;
  2679. // TODO(bill): refactor for code reuse as this is repeated a bit
  2680. if (t->kind == Type_Tuple) {
  2681. for_array(i, t->Tuple.variables) {
  2682. Entity *e = t->Tuple.variables[i];
  2683. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  2684. array_add(&inits, v);
  2685. }
  2686. } else {
  2687. array_add(&inits, init);
  2688. }
  2689. }
  2690. for_array(i, inits) {
  2691. lbAddr lval = lvals[i];
  2692. lbValue init = inits[i];
  2693. lb_addr_store(p, lval, init);
  2694. }
  2695. }
  2696. } else {
  2697. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  2698. // +=, -=, etc
  2699. i32 op = cast(i32)as->op.kind;
  2700. op += Token_Add - Token_AddEq; // Convert += to +
  2701. if (op == Token_CmpAnd || op == Token_CmpOr) {
  2702. Type *type = as->lhs[0]->tav.type;
  2703. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  2704. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  2705. lb_addr_store(p, lhs, new_value);
  2706. } else {
  2707. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  2708. lbValue value = lb_build_expr(p, as->rhs[0]);
  2709. lbValue old_value = lb_addr_load(p, lhs);
  2710. Type *type = old_value.type;
  2711. lbValue change = lb_emit_conv(p, value, type);
  2712. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  2713. lb_addr_store(p, lhs, new_value);
  2714. }
  2715. return;
  2716. }
  2717. case_end;
  2718. case_ast_node(es, ExprStmt, node);
  2719. lb_build_expr(p, es->expr);
  2720. case_end;
  2721. case_ast_node(ds, DeferStmt, node);
  2722. isize scope_index = p->scope_index;
  2723. lb_add_defer_node(p, scope_index, ds->stmt);
  2724. case_end;
  2725. case_ast_node(rs, ReturnStmt, node);
  2726. lbValue res = {};
  2727. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  2728. isize return_count = p->type->Proc.result_count;
  2729. isize res_count = rs->results.count;
  2730. if (return_count == 0) {
  2731. // No return values
  2732. LLVMBuildRetVoid(p->builder);
  2733. return;
  2734. } else if (return_count == 1) {
  2735. Entity *e = tuple->variables[0];
  2736. if (res_count == 0) {
  2737. lbValue *found = map_get(&p->module->values, hash_entity(e));
  2738. GB_ASSERT(found);
  2739. res = lb_emit_load(p, *found);
  2740. } else {
  2741. res = lb_build_expr(p, rs->results[0]);
  2742. res = lb_emit_conv(p, res, e->type);
  2743. }
  2744. } else {
  2745. auto results = array_make<lbValue>(heap_allocator(), 0, return_count);
  2746. if (res_count != 0) {
  2747. for (isize res_index = 0; res_index < res_count; res_index++) {
  2748. lbValue res = lb_build_expr(p, rs->results[res_index]);
  2749. Type *t = res.type;
  2750. if (t->kind == Type_Tuple) {
  2751. for_array(i, t->Tuple.variables) {
  2752. Entity *e = t->Tuple.variables[i];
  2753. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  2754. array_add(&results, v);
  2755. }
  2756. } else {
  2757. array_add(&results, res);
  2758. }
  2759. }
  2760. } else {
  2761. for (isize res_index = 0; res_index < return_count; res_index++) {
  2762. Entity *e = tuple->variables[res_index];
  2763. lbValue *found = map_get(&p->module->values, hash_entity(e));
  2764. GB_ASSERT(found);
  2765. lbValue res = lb_emit_load(p, *found);
  2766. array_add(&results, res);
  2767. }
  2768. }
  2769. GB_ASSERT(results.count == return_count);
  2770. Type *ret_type = p->type->Proc.results;
  2771. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  2772. res = lb_add_local_generated(p, ret_type, false).addr;
  2773. for_array(i, results) {
  2774. Entity *e = tuple->variables[i];
  2775. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  2776. lbValue val = lb_emit_conv(p, results[i], e->type);
  2777. lb_emit_store(p, field, val);
  2778. }
  2779. res = lb_emit_load(p, res);
  2780. }
  2781. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2782. if (p->type->Proc.return_by_pointer) {
  2783. if (res.value != nullptr) {
  2784. lb_addr_store(p, p->return_ptr, res);
  2785. } else {
  2786. lb_addr_store(p, p->return_ptr, lb_const_nil(p->module, p->type->Proc.abi_compat_result_type));
  2787. }
  2788. LLVMBuildRetVoid(p->builder);
  2789. } else {
  2790. GB_ASSERT_MSG(res.value != nullptr, "%.*s", LIT(p->name));
  2791. Type *abi_rt = p->type->Proc.abi_compat_result_type;
  2792. if (!are_types_identical(res.type, abi_rt)) {
  2793. res = lb_emit_transmute(p, res, abi_rt);
  2794. }
  2795. LLVMBuildRet(p->builder, res.value);
  2796. }
  2797. case_end;
  2798. case_ast_node(is, IfStmt, node);
  2799. lb_open_scope(p); // Scope #1
  2800. if (is->init != nullptr) {
  2801. // TODO(bill): Should this have a separate block to begin with?
  2802. #if 1
  2803. lbBlock *init = lb_create_block(p, "if.init");
  2804. lb_emit_jump(p, init);
  2805. lb_start_block(p, init);
  2806. #endif
  2807. lb_build_stmt(p, is->init);
  2808. }
  2809. lbBlock *then = lb_create_block(p, "if.then");
  2810. lbBlock *done = lb_create_block(p, "if.done");
  2811. lbBlock *else_ = done;
  2812. if (is->else_stmt != nullptr) {
  2813. else_ = lb_create_block(p, "if.else");
  2814. }
  2815. lb_build_cond(p, is->cond, then, else_);
  2816. lb_start_block(p, then);
  2817. if (is->label != nullptr) {
  2818. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  2819. tl->is_block = true;
  2820. }
  2821. lb_build_stmt(p, is->body);
  2822. lb_emit_jump(p, done);
  2823. if (is->else_stmt != nullptr) {
  2824. lb_start_block(p, else_);
  2825. lb_open_scope(p);
  2826. lb_build_stmt(p, is->else_stmt);
  2827. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2828. lb_emit_jump(p, done);
  2829. }
  2830. lb_start_block(p, done);
  2831. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2832. case_end;
  2833. case_ast_node(fs, ForStmt, node);
  2834. lb_open_scope(p); // Open Scope here
  2835. if (fs->init != nullptr) {
  2836. #if 1
  2837. lbBlock *init = lb_create_block(p, "for.init");
  2838. lb_emit_jump(p, init);
  2839. lb_start_block(p, init);
  2840. #endif
  2841. lb_build_stmt(p, fs->init);
  2842. }
  2843. lbBlock *body = lb_create_block(p, "for.body");
  2844. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  2845. lbBlock *loop = body;
  2846. if (fs->cond != nullptr) {
  2847. loop = lb_create_block(p, "for.loop");
  2848. }
  2849. lbBlock *post = loop;
  2850. if (fs->post != nullptr) {
  2851. post = lb_create_block(p, "for.post");
  2852. }
  2853. lb_emit_jump(p, loop);
  2854. lb_start_block(p, loop);
  2855. if (loop != body) {
  2856. lb_build_cond(p, fs->cond, body, done);
  2857. lb_start_block(p, body);
  2858. }
  2859. lb_push_target_list(p, fs->label, done, post, nullptr);
  2860. lb_build_stmt(p, fs->body);
  2861. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2862. lb_pop_target_list(p);
  2863. lb_emit_jump(p, post);
  2864. if (fs->post != nullptr) {
  2865. lb_start_block(p, post);
  2866. lb_build_stmt(p, fs->post);
  2867. lb_emit_jump(p, loop);
  2868. }
  2869. lb_start_block(p, done);
  2870. case_end;
  2871. case_ast_node(rs, RangeStmt, node);
  2872. lb_build_range_stmt(p, rs);
  2873. case_end;
  2874. case_ast_node(rs, InlineRangeStmt, node);
  2875. lb_build_inline_range_stmt(p, rs);
  2876. case_end;
  2877. case_ast_node(ss, SwitchStmt, node);
  2878. lb_build_switch_stmt(p, ss);
  2879. case_end;
  2880. case_ast_node(ss, TypeSwitchStmt, node);
  2881. lb_build_type_switch_stmt(p, ss);
  2882. case_end;
  2883. case_ast_node(bs, BranchStmt, node);
  2884. lbBlock *block = nullptr;
  2885. if (bs->label != nullptr) {
  2886. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  2887. switch (bs->token.kind) {
  2888. case Token_break: block = bb.break_; break;
  2889. case Token_continue: block = bb.continue_; break;
  2890. case Token_fallthrough:
  2891. GB_PANIC("fallthrough cannot have a label");
  2892. break;
  2893. }
  2894. } else {
  2895. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  2896. if (t->is_block) {
  2897. continue;
  2898. }
  2899. switch (bs->token.kind) {
  2900. case Token_break: block = t->break_; break;
  2901. case Token_continue: block = t->continue_; break;
  2902. case Token_fallthrough: block = t->fallthrough_; break;
  2903. }
  2904. }
  2905. }
  2906. if (block != nullptr) {
  2907. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  2908. }
  2909. lb_emit_jump(p, block);
  2910. case_end;
  2911. }
  2912. }
  2913. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  2914. cond = lb_emit_conv(p, cond, t_llvm_bool);
  2915. lbValue res = {};
  2916. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  2917. res.type = x.type;
  2918. return res;
  2919. }
  2920. lbValue lb_const_nil(lbModule *m, Type *type) {
  2921. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  2922. return lbValue{v, type};
  2923. }
  2924. lbValue lb_const_undef(lbModule *m, Type *type) {
  2925. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  2926. return lbValue{v, type};
  2927. }
  2928. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  2929. lbValue res = {};
  2930. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  2931. res.type = type;
  2932. return res;
  2933. }
  2934. lbValue lb_const_string(lbModule *m, String const &value) {
  2935. return lb_const_value(m, t_string, exact_value_string(value));
  2936. }
  2937. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  2938. lbValue res = {};
  2939. res.value = LLVMConstInt(lb_type(m, type), value, false);
  2940. res.type = type;
  2941. return res;
  2942. }
  2943. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  2944. u32 u = bit_cast<u32>(f);
  2945. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  2946. return LLVMConstBitCast(i, lb_type(m, type));
  2947. }
  2948. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  2949. x = lb_emit_conv(p, x, t);
  2950. y = lb_emit_conv(p, y, t);
  2951. if (is_type_float(t)) {
  2952. gbAllocator a = heap_allocator();
  2953. i64 sz = 8*type_size_of(t);
  2954. auto args = array_make<lbValue>(heap_allocator(), 2);
  2955. args[0] = x;
  2956. args[1] = y;
  2957. switch (sz) {
  2958. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  2959. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  2960. }
  2961. GB_PANIC("Unknown float type");
  2962. }
  2963. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  2964. }
  2965. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  2966. x = lb_emit_conv(p, x, t);
  2967. y = lb_emit_conv(p, y, t);
  2968. if (is_type_float(t)) {
  2969. gbAllocator a = heap_allocator();
  2970. i64 sz = 8*type_size_of(t);
  2971. auto args = array_make<lbValue>(heap_allocator(), 2);
  2972. args[0] = x;
  2973. args[1] = y;
  2974. switch (sz) {
  2975. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  2976. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  2977. }
  2978. GB_PANIC("Unknown float type");
  2979. }
  2980. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  2981. }
  2982. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  2983. lbValue z = {};
  2984. z = lb_emit_max(p, t, x, min);
  2985. z = lb_emit_min(p, t, z, max);
  2986. return z;
  2987. }
  2988. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  2989. HashKey key = hash_string(str);
  2990. LLVMValueRef *found = map_get(&m->const_strings, key);
  2991. if (found != nullptr) {
  2992. return *found;
  2993. } else {
  2994. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  2995. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  2996. cast(char const *)str.text,
  2997. cast(unsigned)str.len,
  2998. false);
  2999. isize max_len = 7+8+1;
  3000. char *name = gb_alloc_array(heap_allocator(), char, max_len);
  3001. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  3002. len -= 1;
  3003. m->global_array_index++;
  3004. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  3005. LLVMSetInitializer(global_data, data);
  3006. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3007. map_set(&m->const_strings, key, ptr);
  3008. return ptr;
  3009. }
  3010. }
  3011. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  3012. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, str);
  3013. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  3014. LLVMValueRef values[2] = {ptr, str_len};
  3015. lbValue res = {};
  3016. res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2);
  3017. res.type = t_string;
  3018. return res;
  3019. }
  3020. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  3021. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  3022. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  3023. cast(char const *)str.text,
  3024. cast(unsigned)str.len,
  3025. false);
  3026. char *name = nullptr;
  3027. {
  3028. isize max_len = 7+8+1;
  3029. name = gb_alloc_array(heap_allocator(), char, max_len);
  3030. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  3031. len -= 1;
  3032. m->global_array_index++;
  3033. }
  3034. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  3035. LLVMSetInitializer(global_data, data);
  3036. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3037. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  3038. LLVMValueRef values[2] = {ptr, len};
  3039. lbValue res = {};
  3040. res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2);
  3041. res.type = t_u8_slice;
  3042. return res;
  3043. }
  3044. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  3045. isize index = type_info_index(info, type, false);
  3046. if (index >= 0) {
  3047. auto *set = &info->minimum_dependency_type_info_set;
  3048. for_array(i, set->entries) {
  3049. if (set->entries[i].ptr == index) {
  3050. return i+1;
  3051. }
  3052. }
  3053. }
  3054. if (err_on_not_found) {
  3055. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  3056. }
  3057. return -1;
  3058. }
  3059. lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type) {
  3060. type = default_type(type);
  3061. u64 id = cast(u64)lb_type_info_index(m->info, type);
  3062. GB_ASSERT(id >= 0);
  3063. u64 kind = Typeid_Invalid;
  3064. u64 named = is_type_named(type) && type->kind != Type_Basic;
  3065. u64 special = 0;
  3066. u64 reserved = 0;
  3067. Type *bt = base_type(type);
  3068. TypeKind tk = bt->kind;
  3069. switch (tk) {
  3070. case Type_Basic: {
  3071. u32 flags = bt->Basic.flags;
  3072. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  3073. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  3074. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  3075. if (flags & BasicFlag_Float) kind = Typeid_Float;
  3076. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  3077. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  3078. if (flags & BasicFlag_String) kind = Typeid_String;
  3079. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  3080. } break;
  3081. case Type_Pointer: kind = Typeid_Pointer; break;
  3082. case Type_Array: kind = Typeid_Array; break;
  3083. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  3084. case Type_Slice: kind = Typeid_Slice; break;
  3085. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  3086. case Type_Map: kind = Typeid_Map; break;
  3087. case Type_Struct: kind = Typeid_Struct; break;
  3088. case Type_Enum: kind = Typeid_Enum; break;
  3089. case Type_Union: kind = Typeid_Union; break;
  3090. case Type_Tuple: kind = Typeid_Tuple; break;
  3091. case Type_Proc: kind = Typeid_Procedure; break;
  3092. case Type_BitField: kind = Typeid_Bit_Field; break;
  3093. case Type_BitSet: kind = Typeid_Bit_Set; break;
  3094. }
  3095. if (is_type_cstring(type)) {
  3096. special = 1;
  3097. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  3098. special = 1;
  3099. }
  3100. u64 data = 0;
  3101. if (build_context.word_size == 4) {
  3102. data |= (id &~ (1u<<24)) << 0u; // index
  3103. data |= (kind &~ (1u<<5)) << 24u; // kind
  3104. data |= (named &~ (1u<<1)) << 29u; // kind
  3105. data |= (special &~ (1u<<1)) << 30u; // kind
  3106. data |= (reserved &~ (1u<<1)) << 31u; // kind
  3107. } else {
  3108. GB_ASSERT(build_context.word_size == 8);
  3109. data |= (id &~ (1ull<<56)) << 0ul; // index
  3110. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  3111. data |= (named &~ (1ull<<1)) << 61ull; // kind
  3112. data |= (special &~ (1ull<<1)) << 62ull; // kind
  3113. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  3114. }
  3115. lbValue res = {};
  3116. res.value = LLVMConstInt(lb_type(m, typeid_type), data, false);
  3117. res.type = typeid_type;
  3118. return res;
  3119. }
  3120. lbValue lb_type_info(lbModule *m, Type *type) {
  3121. type = default_type(type);
  3122. isize index = lb_type_info_index(m->info, type);
  3123. GB_ASSERT(index >= 0);
  3124. LLVMTypeRef it = lb_type(m, t_int);
  3125. LLVMValueRef indices[2] = {
  3126. LLVMConstInt(it, 0, false),
  3127. LLVMConstInt(it, index, true),
  3128. };
  3129. lbValue value = {};
  3130. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  3131. value.type = t_type_info_ptr;
  3132. return value;
  3133. }
  3134. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) {
  3135. LLVMContextRef ctx = m->ctx;
  3136. type = default_type(type);
  3137. Type *original_type = type;
  3138. lbValue res = {};
  3139. res.type = original_type;
  3140. type = core_type(type);
  3141. value = convert_exact_value_for_type(value, type);
  3142. if (value.kind == ExactValue_Typeid) {
  3143. return lb_typeid(m, value.value_typeid, original_type);
  3144. }
  3145. if (value.kind == ExactValue_Invalid) {
  3146. return lb_const_nil(m, type);
  3147. }
  3148. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  3149. if (is_type_slice(type)) {
  3150. if (value.kind == ExactValue_String) {
  3151. GB_ASSERT(is_type_u8_slice(type));
  3152. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  3153. return res;
  3154. } else {
  3155. ast_node(cl, CompoundLit, value.value_compound);
  3156. isize count = cl->elems.count;
  3157. if (count == 0) {
  3158. return lb_const_nil(m, type);
  3159. }
  3160. count = gb_max(cl->max_count, count);
  3161. Type *elem = base_type(type)->Slice.elem;
  3162. Type *t = alloc_type_array(elem, count);
  3163. lbValue backing_array = lb_const_value(m, t, value);
  3164. isize max_len = 7+8+1;
  3165. char *str = gb_alloc_array(heap_allocator(), char, max_len);
  3166. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  3167. m->global_array_index++;
  3168. String name = make_string(cast(u8 *)str, len-1);
  3169. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  3170. LLVMValueRef global_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  3171. LLVMSetInitializer(global_data, backing_array.value);
  3172. lbValue g = {};
  3173. g.value = global_data;
  3174. g.type = t;
  3175. lb_add_entity(m, e, g);
  3176. lb_add_member(m, name, g);
  3177. {
  3178. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  3179. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3180. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  3181. LLVMValueRef values[2] = {ptr, len};
  3182. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3183. return res;
  3184. }
  3185. }
  3186. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  3187. LLVMValueRef data = LLVMConstStringInContext(ctx,
  3188. cast(char const *)value.value_string.text,
  3189. cast(unsigned)value.value_string.len,
  3190. false);
  3191. res.value = data;
  3192. return res;
  3193. } else if (is_type_array(type) &&
  3194. value.kind != ExactValue_Invalid &&
  3195. value.kind != ExactValue_String &&
  3196. value.kind != ExactValue_Compound) {
  3197. i64 count = type->Array.count;
  3198. Type *elem = type->Array.elem;
  3199. lbValue single_elem = lb_const_value(m, elem, value);
  3200. LLVMValueRef *elems = gb_alloc_array(heap_allocator(), LLVMValueRef, count);
  3201. for (i64 i = 0; i < count; i++) {
  3202. elems[i] = single_elem.value;
  3203. }
  3204. res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)count);
  3205. return res;
  3206. }
  3207. switch (value.kind) {
  3208. case ExactValue_Invalid:
  3209. res.value = LLVMConstNull(lb_type(m, original_type));
  3210. return res;
  3211. case ExactValue_Bool:
  3212. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  3213. return res;
  3214. case ExactValue_String:
  3215. {
  3216. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  3217. lbValue res = {};
  3218. res.type = default_type(original_type);
  3219. if (is_type_cstring(res.type)) {
  3220. res.value = ptr;
  3221. } else {
  3222. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  3223. LLVMValueRef values[2] = {ptr, str_len};
  3224. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3225. }
  3226. return res;
  3227. }
  3228. case ExactValue_Integer:
  3229. if (is_type_pointer(type)) {
  3230. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  3231. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  3232. } else {
  3233. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  3234. if (value.value_integer.neg) {
  3235. res.value = LLVMConstNeg(res.value);
  3236. }
  3237. }
  3238. return res;
  3239. case ExactValue_Float:
  3240. if (type_size_of(type) == 4) {
  3241. f32 f = cast(f32)value.value_float;
  3242. res.value = lb_const_f32(m, f, type);
  3243. return res;
  3244. }
  3245. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  3246. return res;
  3247. case ExactValue_Complex:
  3248. {
  3249. LLVMValueRef values[2] = {};
  3250. switch (8*type_size_of(type)) {
  3251. case 64:
  3252. values[0] = lb_const_f32(m, cast(f32)value.value_complex.real);
  3253. values[1] = lb_const_f32(m, cast(f32)value.value_complex.imag);
  3254. break;
  3255. case 128:
  3256. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.real);
  3257. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.imag);
  3258. break;
  3259. }
  3260. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3261. return res;
  3262. }
  3263. break;
  3264. case ExactValue_Quaternion:
  3265. {
  3266. LLVMValueRef values[4] = {};
  3267. switch (8*type_size_of(type)) {
  3268. case 128:
  3269. // @QuaternionLayout
  3270. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion.real);
  3271. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion.imag);
  3272. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion.jmag);
  3273. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion.kmag);
  3274. break;
  3275. case 256:
  3276. // @QuaternionLayout
  3277. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.real);
  3278. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.imag);
  3279. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.jmag);
  3280. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.kmag);
  3281. break;
  3282. }
  3283. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 4);
  3284. return res;
  3285. }
  3286. break;
  3287. case ExactValue_Pointer:
  3288. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  3289. return res;
  3290. case ExactValue_Compound:
  3291. if (is_type_slice(type)) {
  3292. return lb_const_value(m, type, value);
  3293. } else if (is_type_array(type)) {
  3294. ast_node(cl, CompoundLit, value.value_compound);
  3295. Type *elem_type = type->Array.elem;
  3296. isize elem_count = cl->elems.count;
  3297. if (elem_count == 0) {
  3298. return lb_const_nil(m, original_type);
  3299. }
  3300. if (cl->elems[0]->kind == Ast_FieldValue) {
  3301. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  3302. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count);
  3303. defer (gb_free(heap_allocator(), values));
  3304. isize value_index = 0;
  3305. for (i64 i = 0; i < type->Array.count; i++) {
  3306. bool found = false;
  3307. for (isize j = 0; j < elem_count; j++) {
  3308. Ast *elem = cl->elems[j];
  3309. ast_node(fv, FieldValue, elem);
  3310. if (is_ast_range(fv->field)) {
  3311. ast_node(ie, BinaryExpr, fv->field);
  3312. TypeAndValue lo_tav = ie->left->tav;
  3313. TypeAndValue hi_tav = ie->right->tav;
  3314. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3315. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3316. TokenKind op = ie->op.kind;
  3317. i64 lo = exact_value_to_i64(lo_tav.value);
  3318. i64 hi = exact_value_to_i64(hi_tav.value);
  3319. if (op == Token_Ellipsis) {
  3320. hi += 1;
  3321. }
  3322. if (lo == i) {
  3323. TypeAndValue tav = fv->value->tav;
  3324. if (tav.mode != Addressing_Constant) {
  3325. break;
  3326. }
  3327. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3328. for (i64 k = lo; k < hi; k++) {
  3329. values[value_index++] = val;
  3330. }
  3331. found = true;
  3332. i += (hi-lo-1);
  3333. break;
  3334. }
  3335. } else {
  3336. TypeAndValue index_tav = fv->field->tav;
  3337. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3338. i64 index = exact_value_to_i64(index_tav.value);
  3339. if (index == i) {
  3340. TypeAndValue tav = fv->value->tav;
  3341. if (tav.mode != Addressing_Constant) {
  3342. break;
  3343. }
  3344. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3345. values[value_index++] = val;
  3346. found = true;
  3347. break;
  3348. }
  3349. }
  3350. }
  3351. if (!found) {
  3352. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  3353. }
  3354. }
  3355. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  3356. return res;
  3357. } else {
  3358. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  3359. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count);
  3360. defer (gb_free(heap_allocator(), values));
  3361. for (isize i = 0; i < elem_count; i++) {
  3362. TypeAndValue tav = cl->elems[i]->tav;
  3363. GB_ASSERT(tav.mode != Addressing_Invalid);
  3364. values[i] = lb_const_value(m, elem_type, tav.value).value;
  3365. }
  3366. for (isize i = elem_count; i < type->Array.count; i++) {
  3367. values[i] = LLVMConstNull(lb_type(m, elem_type));
  3368. }
  3369. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  3370. return res;
  3371. }
  3372. } else if (is_type_enumerated_array(type)) {
  3373. ast_node(cl, CompoundLit, value.value_compound);
  3374. Type *elem_type = type->EnumeratedArray.elem;
  3375. isize elem_count = cl->elems.count;
  3376. if (elem_count == 0) {
  3377. return lb_const_nil(m, original_type);
  3378. }
  3379. if (cl->elems[0]->kind == Ast_FieldValue) {
  3380. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  3381. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  3382. defer (gb_free(heap_allocator(), values));
  3383. isize value_index = 0;
  3384. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  3385. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  3386. for (i64 i = total_lo; i <= total_hi; i++) {
  3387. bool found = false;
  3388. for (isize j = 0; j < elem_count; j++) {
  3389. Ast *elem = cl->elems[j];
  3390. ast_node(fv, FieldValue, elem);
  3391. if (is_ast_range(fv->field)) {
  3392. ast_node(ie, BinaryExpr, fv->field);
  3393. TypeAndValue lo_tav = ie->left->tav;
  3394. TypeAndValue hi_tav = ie->right->tav;
  3395. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3396. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3397. TokenKind op = ie->op.kind;
  3398. i64 lo = exact_value_to_i64(lo_tav.value);
  3399. i64 hi = exact_value_to_i64(hi_tav.value);
  3400. if (op == Token_Ellipsis) {
  3401. hi += 1;
  3402. }
  3403. if (lo == i) {
  3404. TypeAndValue tav = fv->value->tav;
  3405. if (tav.mode != Addressing_Constant) {
  3406. break;
  3407. }
  3408. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3409. for (i64 k = lo; k < hi; k++) {
  3410. values[value_index++] = val;
  3411. }
  3412. found = true;
  3413. i += (hi-lo-1);
  3414. break;
  3415. }
  3416. } else {
  3417. TypeAndValue index_tav = fv->field->tav;
  3418. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3419. i64 index = exact_value_to_i64(index_tav.value);
  3420. if (index == i) {
  3421. TypeAndValue tav = fv->value->tav;
  3422. if (tav.mode != Addressing_Constant) {
  3423. break;
  3424. }
  3425. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3426. values[value_index++] = val;
  3427. found = true;
  3428. break;
  3429. }
  3430. }
  3431. }
  3432. if (!found) {
  3433. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  3434. }
  3435. }
  3436. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  3437. return res;
  3438. } else {
  3439. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  3440. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  3441. defer (gb_free(heap_allocator(), values));
  3442. for (isize i = 0; i < elem_count; i++) {
  3443. TypeAndValue tav = cl->elems[i]->tav;
  3444. GB_ASSERT(tav.mode != Addressing_Invalid);
  3445. values[i] = lb_const_value(m, elem_type, tav.value).value;
  3446. }
  3447. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  3448. values[i] = LLVMConstNull(lb_type(m, elem_type));
  3449. }
  3450. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  3451. return res;
  3452. }
  3453. } else if (is_type_simd_vector(type)) {
  3454. ast_node(cl, CompoundLit, value.value_compound);
  3455. Type *elem_type = type->SimdVector.elem;
  3456. isize elem_count = cl->elems.count;
  3457. if (elem_count == 0) {
  3458. return lb_const_nil(m, original_type);
  3459. }
  3460. isize total_elem_count = type->SimdVector.count;
  3461. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, total_elem_count);
  3462. defer (gb_free(heap_allocator(), values));
  3463. for (isize i = 0; i < elem_count; i++) {
  3464. TypeAndValue tav = cl->elems[i]->tav;
  3465. GB_ASSERT(tav.mode != Addressing_Invalid);
  3466. values[i] = lb_const_value(m, elem_type, tav.value).value;
  3467. }
  3468. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  3469. values[i] = LLVMConstNull(lb_type(m, elem_type));
  3470. }
  3471. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  3472. return res;
  3473. } else if (is_type_struct(type)) {
  3474. ast_node(cl, CompoundLit, value.value_compound);
  3475. if (cl->elems.count == 0) {
  3476. return lb_const_nil(m, original_type);
  3477. }
  3478. isize offset = 0;
  3479. if (type->Struct.custom_align > 0) {
  3480. offset = 1;
  3481. }
  3482. isize value_count = type->Struct.fields.count + offset;
  3483. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, value_count);
  3484. bool *visited = gb_alloc_array(heap_allocator(), bool, value_count);
  3485. defer (gb_free(heap_allocator(), values));
  3486. defer (gb_free(heap_allocator(), visited));
  3487. if (cl->elems.count > 0) {
  3488. if (cl->elems[0]->kind == Ast_FieldValue) {
  3489. isize elem_count = cl->elems.count;
  3490. for (isize i = 0; i < elem_count; i++) {
  3491. ast_node(fv, FieldValue, cl->elems[i]);
  3492. String name = fv->field->Ident.token.string;
  3493. TypeAndValue tav = fv->value->tav;
  3494. GB_ASSERT(tav.mode != Addressing_Invalid);
  3495. Selection sel = lookup_field(type, name, false);
  3496. Entity *f = type->Struct.fields[sel.index[0]];
  3497. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value).value;
  3498. visited[offset+f->Variable.field_index] = true;
  3499. }
  3500. } else {
  3501. for_array(i, cl->elems) {
  3502. Entity *f = type->Struct.fields[i];
  3503. TypeAndValue tav = cl->elems[i]->tav;
  3504. ExactValue val = {};
  3505. if (tav.mode != Addressing_Invalid) {
  3506. val = tav.value;
  3507. }
  3508. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val).value;
  3509. visited[offset+f->Variable.field_index] = true;
  3510. }
  3511. }
  3512. }
  3513. for (isize i = 0; i < type->Struct.fields.count; i++) {
  3514. if (!visited[offset+i]) {
  3515. GB_ASSERT(values[offset+i] == nullptr);
  3516. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  3517. }
  3518. }
  3519. if (type->Struct.custom_align > 0) {
  3520. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  3521. }
  3522. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, cast(unsigned)value_count);
  3523. return res;
  3524. } else if (is_type_bit_set(type)) {
  3525. ast_node(cl, CompoundLit, value.value_compound);
  3526. if (cl->elems.count == 0) {
  3527. return lb_const_nil(m, original_type);
  3528. }
  3529. i64 sz = type_size_of(type);
  3530. if (sz == 0) {
  3531. return lb_const_nil(m, original_type);
  3532. }
  3533. u64 bits = 0;
  3534. for_array(i, cl->elems) {
  3535. Ast *e = cl->elems[i];
  3536. GB_ASSERT(e->kind != Ast_FieldValue);
  3537. TypeAndValue tav = e->tav;
  3538. if (tav.mode != Addressing_Constant) {
  3539. continue;
  3540. }
  3541. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  3542. i64 v = big_int_to_i64(&tav.value.value_integer);
  3543. i64 lower = type->BitSet.lower;
  3544. bits |= 1ull<<cast(u64)(v-lower);
  3545. }
  3546. if (is_type_different_to_arch_endianness(type)) {
  3547. i64 size = type_size_of(type);
  3548. switch (size) {
  3549. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  3550. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  3551. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  3552. }
  3553. }
  3554. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  3555. return res;
  3556. } else {
  3557. return lb_const_nil(m, original_type);
  3558. }
  3559. break;
  3560. case ExactValue_Procedure:
  3561. {
  3562. Ast *expr = value.value_procedure;
  3563. GB_ASSERT(expr != nullptr);
  3564. if (expr->kind == Ast_ProcLit) {
  3565. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  3566. }
  3567. }
  3568. break;
  3569. case ExactValue_Typeid:
  3570. return lb_typeid(m, value.value_typeid, original_type);
  3571. }
  3572. return lb_const_nil(m, original_type);
  3573. }
  3574. u64 lb_generate_source_code_location_hash(TokenPos const &pos) {
  3575. u64 h = 0xcbf29ce484222325;
  3576. for (isize i = 0; i < pos.file.len; i++) {
  3577. h = (h ^ u64(pos.file[i])) * 0x100000001b3;
  3578. }
  3579. h = h ^ (u64(pos.line) * 0x100000001b3);
  3580. h = h ^ (u64(pos.column) * 0x100000001b3);
  3581. return h;
  3582. }
  3583. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  3584. lbModule *m = p->module;
  3585. LLVMValueRef fields[5] = {};
  3586. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value;
  3587. fields[1]/*line*/ = lb_const_int(m, t_int, pos.line).value;
  3588. fields[2]/*column*/ = lb_const_int(m, t_int, pos.column).value;
  3589. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  3590. fields[4]/*hash*/ = lb_const_int(m, t_u64, lb_generate_source_code_location_hash(pos)).value;
  3591. lbValue res = {};
  3592. res.value = LLVMConstNamedStruct(lb_type(m, t_source_code_location), fields, 5);
  3593. res.type = t_source_code_location;
  3594. return res;
  3595. }
  3596. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  3597. String proc_name = {};
  3598. if (p->entity) {
  3599. proc_name = p->entity->token.string;
  3600. }
  3601. TokenPos pos = {};
  3602. if (node) {
  3603. pos = ast_token(node).pos;
  3604. }
  3605. return lb_emit_source_code_location(p, proc_name, pos);
  3606. }
  3607. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  3608. switch (op) {
  3609. case Token_Add:
  3610. return x;
  3611. case Token_Not: // Boolean not
  3612. case Token_Xor: // Bitwise not
  3613. case Token_Sub: // Number negation
  3614. break;
  3615. case Token_Pointer:
  3616. GB_PANIC("This should be handled elsewhere");
  3617. break;
  3618. }
  3619. if (is_type_array(x.type)) {
  3620. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  3621. Type *tl = base_type(x.type);
  3622. lbValue val = lb_address_from_load_or_generate_local(p, x);
  3623. GB_ASSERT(is_type_array(type));
  3624. Type *elem_type = base_array_type(type);
  3625. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3626. lbAddr res_addr = lb_add_local_generated(p, type, false);
  3627. lbValue res = lb_addr_get_ptr(p, res_addr);
  3628. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3629. i32 count = cast(i32)tl->Array.count;
  3630. if (inline_array_arith) {
  3631. // inline
  3632. for (i32 i = 0; i < count; i++) {
  3633. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  3634. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  3635. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  3636. }
  3637. } else {
  3638. auto loop_data = lb_loop_start(p, count, t_i32);
  3639. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  3640. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  3641. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  3642. lb_loop_end(p, loop_data);
  3643. }
  3644. return lb_emit_load(p, res);
  3645. }
  3646. if (op == Token_Xor) {
  3647. lbValue cmp = {};
  3648. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  3649. cmp.type = x.type;
  3650. return lb_emit_conv(p, cmp, type);
  3651. }
  3652. if (op == Token_Not) {
  3653. lbValue cmp = {};
  3654. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  3655. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  3656. cmp.type = t_llvm_bool;
  3657. return lb_emit_conv(p, cmp, type);
  3658. }
  3659. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3660. Type *platform_type = integer_endian_type_to_platform_type(type);
  3661. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  3662. lbValue res = {};
  3663. res.value = LLVMBuildNeg(p->builder, v.value, "");
  3664. res.type = platform_type;
  3665. return lb_emit_byte_swap(p, res, type);
  3666. }
  3667. lbValue res = {};
  3668. switch (op) {
  3669. case Token_Not: // Boolean not
  3670. case Token_Xor: // Bitwise not
  3671. res.value = LLVMBuildNot(p->builder, x.value, "");
  3672. res.type = x.type;
  3673. return res;
  3674. case Token_Sub: // Number negation
  3675. if (is_type_integer(x.type)) {
  3676. res.value = LLVMBuildNeg(p->builder, x.value, "");
  3677. } else if (is_type_float(x.type)) {
  3678. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  3679. } else {
  3680. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  3681. }
  3682. res.type = x.type;
  3683. return res;
  3684. }
  3685. return res;
  3686. }
  3687. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  3688. lbModule *m = p->module;
  3689. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  3690. lhs = lb_emit_conv(p, lhs, type);
  3691. rhs = lb_emit_conv(p, rhs, type);
  3692. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  3693. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  3694. GB_ASSERT(is_type_array(type));
  3695. Type *elem_type = base_array_type(type);
  3696. lbAddr res = lb_add_local_generated(p, type, false);
  3697. i64 count = base_type(type)->Array.count;
  3698. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3699. if (inline_array_arith) {
  3700. for (i64 i = 0; i < count; i++) {
  3701. lbValue a = lb_emit_load(p, lb_emit_array_epi(p, x, i));
  3702. lbValue b = lb_emit_load(p, lb_emit_array_epi(p, y, i));
  3703. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  3704. lb_emit_store(p, lb_emit_array_epi(p, res.addr, i), c);
  3705. }
  3706. } else {
  3707. auto loop_data = lb_loop_start(p, count);
  3708. lbValue a = lb_emit_load(p, lb_emit_array_ep(p, x, loop_data.idx));
  3709. lbValue b = lb_emit_load(p, lb_emit_array_ep(p, y, loop_data.idx));
  3710. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  3711. lb_emit_store(p, lb_emit_array_ep(p, res.addr, loop_data.idx), c);
  3712. lb_loop_end(p, loop_data);
  3713. }
  3714. return lb_addr_load(p, res);
  3715. } else if (is_type_complex(type)) {
  3716. lhs = lb_emit_conv(p, lhs, type);
  3717. rhs = lb_emit_conv(p, rhs, type);
  3718. Type *ft = base_complex_elem_type(type);
  3719. if (op == Token_Quo) {
  3720. auto args = array_make<lbValue>(heap_allocator(), 2);
  3721. args[0] = lhs;
  3722. args[1] = rhs;
  3723. switch (type_size_of(ft)) {
  3724. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  3725. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  3726. default: GB_PANIC("Unknown float type"); break;
  3727. }
  3728. }
  3729. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  3730. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  3731. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  3732. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  3733. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  3734. lbValue real = {};
  3735. lbValue imag = {};
  3736. switch (op) {
  3737. case Token_Add:
  3738. real = lb_emit_arith(p, Token_Add, a, c, ft);
  3739. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  3740. break;
  3741. case Token_Sub:
  3742. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  3743. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  3744. break;
  3745. case Token_Mul: {
  3746. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  3747. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  3748. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  3749. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  3750. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  3751. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  3752. break;
  3753. }
  3754. }
  3755. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  3756. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  3757. return lb_addr_load(p, res);
  3758. } else if (is_type_quaternion(type)) {
  3759. lhs = lb_emit_conv(p, lhs, type);
  3760. rhs = lb_emit_conv(p, rhs, type);
  3761. Type *ft = base_complex_elem_type(type);
  3762. if (op == Token_Add || op == Token_Sub) {
  3763. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  3764. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  3765. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  3766. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  3767. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  3768. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  3769. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  3770. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  3771. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  3772. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  3773. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  3774. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  3775. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  3776. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  3777. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  3778. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  3779. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  3780. return lb_addr_load(p, res);
  3781. } else if (op == Token_Mul) {
  3782. auto args = array_make<lbValue>(heap_allocator(), 2);
  3783. args[0] = lhs;
  3784. args[1] = rhs;
  3785. switch (8*type_size_of(ft)) {
  3786. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  3787. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  3788. default: GB_PANIC("Unknown float type"); break;
  3789. }
  3790. } else if (op == Token_Quo) {
  3791. auto args = array_make<lbValue>(heap_allocator(), 2);
  3792. args[0] = lhs;
  3793. args[1] = rhs;
  3794. switch (8*type_size_of(ft)) {
  3795. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  3796. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  3797. default: GB_PANIC("Unknown float type"); break;
  3798. }
  3799. }
  3800. }
  3801. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3802. switch (op) {
  3803. case Token_AndNot:
  3804. case Token_And:
  3805. case Token_Or:
  3806. case Token_Xor:
  3807. goto handle_op;
  3808. }
  3809. Type *platform_type = integer_endian_type_to_platform_type(type);
  3810. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  3811. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  3812. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  3813. return lb_emit_byte_swap(p, res, type);
  3814. }
  3815. handle_op:
  3816. lhs = lb_emit_conv(p, lhs, type);
  3817. rhs = lb_emit_conv(p, rhs, type);
  3818. lbValue res = {};
  3819. res.type = type;
  3820. switch (op) {
  3821. case Token_Add:
  3822. if (is_type_float(type)) {
  3823. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  3824. return res;
  3825. }
  3826. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  3827. return res;
  3828. case Token_Sub:
  3829. if (is_type_float(type)) {
  3830. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  3831. return res;
  3832. }
  3833. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  3834. return res;
  3835. case Token_Mul:
  3836. if (is_type_float(type)) {
  3837. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  3838. return res;
  3839. }
  3840. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  3841. return res;
  3842. case Token_Quo:
  3843. if (is_type_float(type)) {
  3844. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  3845. return res;
  3846. } else if (is_type_unsigned(type)) {
  3847. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  3848. return res;
  3849. }
  3850. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  3851. return res;
  3852. case Token_Mod:
  3853. if (is_type_float(type)) {
  3854. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  3855. return res;
  3856. } else if (is_type_unsigned(type)) {
  3857. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  3858. return res;
  3859. }
  3860. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  3861. return res;
  3862. case Token_ModMod:
  3863. if (is_type_unsigned(type)) {
  3864. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  3865. return res;
  3866. } else {
  3867. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  3868. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  3869. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  3870. res.value = c;
  3871. return res;
  3872. }
  3873. case Token_And:
  3874. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  3875. return res;
  3876. case Token_Or:
  3877. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  3878. return res;
  3879. case Token_Xor:
  3880. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  3881. return res;
  3882. case Token_Shl:
  3883. rhs = lb_emit_conv(p, rhs, lhs.type);
  3884. res.value = LLVMBuildShl(p->builder, lhs.value, rhs.value, "");
  3885. return res;
  3886. case Token_Shr:
  3887. if (is_type_unsigned(type)) {
  3888. res.value = LLVMBuildLShr(p->builder, lhs.value, rhs.value, "");
  3889. return res;
  3890. }
  3891. rhs = lb_emit_conv(p, rhs, lhs.type);
  3892. res.value = LLVMBuildAShr(p->builder, lhs.value, rhs.value, "");
  3893. return res;
  3894. case Token_AndNot:
  3895. {
  3896. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  3897. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  3898. return res;
  3899. }
  3900. break;
  3901. }
  3902. GB_PANIC("unhandled operator of lb_emit_arith");
  3903. return {};
  3904. }
  3905. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  3906. ast_node(be, BinaryExpr, expr);
  3907. TypeAndValue tv = type_and_value_of_expr(expr);
  3908. switch (be->op.kind) {
  3909. case Token_Add:
  3910. case Token_Sub:
  3911. case Token_Mul:
  3912. case Token_Quo:
  3913. case Token_Mod:
  3914. case Token_ModMod:
  3915. case Token_And:
  3916. case Token_Or:
  3917. case Token_Xor:
  3918. case Token_AndNot:
  3919. case Token_Shl:
  3920. case Token_Shr: {
  3921. Type *type = default_type(tv.type);
  3922. lbValue left = lb_build_expr(p, be->left);
  3923. lbValue right = lb_build_expr(p, be->right);
  3924. return lb_emit_arith(p, be->op.kind, left, right, type);
  3925. }
  3926. case Token_CmpEq:
  3927. case Token_NotEq:
  3928. case Token_Lt:
  3929. case Token_LtEq:
  3930. case Token_Gt:
  3931. case Token_GtEq:
  3932. {
  3933. lbValue left = lb_build_expr(p, be->left);
  3934. Type *type = default_type(tv.type);
  3935. lbValue right = lb_build_expr(p, be->right);
  3936. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  3937. return lb_emit_conv(p, cmp, type);
  3938. }
  3939. case Token_CmpAnd:
  3940. case Token_CmpOr:
  3941. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  3942. case Token_in:
  3943. case Token_not_in:
  3944. {
  3945. lbValue left = lb_build_expr(p, be->left);
  3946. Type *type = default_type(tv.type);
  3947. lbValue right = lb_build_expr(p, be->right);
  3948. Type *rt = base_type(right.type);
  3949. switch (rt->kind) {
  3950. case Type_Map:
  3951. {
  3952. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  3953. lbValue h = lb_gen_map_header(p, addr, rt);
  3954. lbValue key = lb_gen_map_key(p, left, rt->Map.key);
  3955. auto args = array_make<lbValue>(heap_allocator(), 2);
  3956. args[0] = h;
  3957. args[1] = key;
  3958. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  3959. if (be->op.kind == Token_in) {
  3960. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  3961. } else {
  3962. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  3963. }
  3964. }
  3965. break;
  3966. case Type_BitSet:
  3967. {
  3968. Type *key_type = rt->BitSet.elem;
  3969. GB_ASSERT(are_types_identical(left.type, key_type));
  3970. Type *it = bit_set_to_int(rt);
  3971. left = lb_emit_conv(p, left, it);
  3972. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  3973. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  3974. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  3975. bit = lb_emit_conv(p, bit, it);
  3976. lbValue old_value = lb_emit_transmute(p, right, it);
  3977. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  3978. if (be->op.kind == Token_in) {
  3979. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  3980. } else {
  3981. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  3982. }
  3983. }
  3984. break;
  3985. default:
  3986. GB_PANIC("Invalid 'in' type");
  3987. }
  3988. break;
  3989. }
  3990. break;
  3991. default:
  3992. GB_PANIC("Invalid binary expression");
  3993. break;
  3994. }
  3995. return {};
  3996. }
  3997. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  3998. Type *prev_src = src;
  3999. // Type *prev_dst = dst;
  4000. src = base_type(type_deref(src));
  4001. // dst = base_type(type_deref(dst));
  4002. bool src_is_ptr = src != prev_src;
  4003. // bool dst_is_ptr = dst != prev_dst;
  4004. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  4005. for_array(i, src->Struct.fields) {
  4006. Entity *f = src->Struct.fields[i];
  4007. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  4008. if (are_types_identical(dst, f->type)) {
  4009. return f->token.string;
  4010. }
  4011. if (src_is_ptr && is_type_pointer(dst)) {
  4012. if (are_types_identical(type_deref(dst), f->type)) {
  4013. return f->token.string;
  4014. }
  4015. }
  4016. if (is_type_struct(f->type)) {
  4017. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  4018. if (name.len > 0) {
  4019. return name;
  4020. }
  4021. }
  4022. }
  4023. }
  4024. return str_lit("");
  4025. }
  4026. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  4027. GB_ASSERT(is_type_pointer(value.type));
  4028. GB_ASSERT(is_type_pointer(t));
  4029. GB_ASSERT(lb_is_const(value));
  4030. lbValue res = {};
  4031. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  4032. res.type = t;
  4033. return res;
  4034. }
  4035. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  4036. lbModule *m = p->module;
  4037. t = reduce_tuple_to_single_type(t);
  4038. Type *src_type = value.type;
  4039. if (are_types_identical(t, src_type)) {
  4040. return value;
  4041. }
  4042. Type *src = core_type(src_type);
  4043. Type *dst = core_type(t);
  4044. if (is_type_untyped_nil(src)) {
  4045. return lb_const_nil(m, t);
  4046. }
  4047. if (is_type_untyped_undef(src)) {
  4048. return lb_const_undef(m, t);
  4049. }
  4050. if (LLVMIsConstant(value.value)) {
  4051. if (is_type_any(dst)) {
  4052. Type *st = default_type(src_type);
  4053. lbAddr default_value = lb_add_local_generated(p, st, false);
  4054. lb_addr_store(p, default_value, value);
  4055. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  4056. lbValue id = lb_typeid(m, st);
  4057. lbAddr res = lb_add_local_generated(p, t, false);
  4058. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  4059. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  4060. lb_emit_store(p, a0, data);
  4061. lb_emit_store(p, a1, id);
  4062. return lb_addr_load(p, res);
  4063. } else if (dst->kind == Type_Basic) {
  4064. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  4065. String str = lb_get_const_string(m, value);
  4066. lbValue res = {};
  4067. res.type = t;
  4068. res.value = llvm_cstring(m, str);
  4069. return res;
  4070. }
  4071. // if (is_type_float(dst)) {
  4072. // return value;
  4073. // } else if (is_type_integer(dst)) {
  4074. // return value;
  4075. // }
  4076. // ExactValue ev = value->Constant.value;
  4077. // if (is_type_float(dst)) {
  4078. // ev = exact_value_to_float(ev);
  4079. // } else if (is_type_complex(dst)) {
  4080. // ev = exact_value_to_complex(ev);
  4081. // } else if (is_type_quaternion(dst)) {
  4082. // ev = exact_value_to_quaternion(ev);
  4083. // } else if (is_type_string(dst)) {
  4084. // // Handled elsewhere
  4085. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  4086. // } else if (is_type_integer(dst)) {
  4087. // ev = exact_value_to_integer(ev);
  4088. // } else if (is_type_pointer(dst)) {
  4089. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  4090. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  4091. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  4092. // }
  4093. // return lb_const_value(p->module, t, ev);
  4094. }
  4095. }
  4096. if (are_types_identical(src, dst)) {
  4097. if (!are_types_identical(src_type, t)) {
  4098. return lb_emit_transmute(p, value, t);
  4099. }
  4100. return value;
  4101. }
  4102. // bool <-> llvm bool
  4103. if (is_type_boolean(src) && dst == t_llvm_bool) {
  4104. lbValue res = {};
  4105. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  4106. res.type = dst;
  4107. return res;
  4108. }
  4109. if (src == t_llvm_bool && is_type_boolean(dst)) {
  4110. lbValue res = {};
  4111. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  4112. res.type = dst;
  4113. return res;
  4114. }
  4115. // integer -> integer
  4116. if (is_type_integer(src) && is_type_integer(dst)) {
  4117. GB_ASSERT(src->kind == Type_Basic &&
  4118. dst->kind == Type_Basic);
  4119. i64 sz = type_size_of(default_type(src));
  4120. i64 dz = type_size_of(default_type(dst));
  4121. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  4122. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  4123. value = lb_emit_byte_swap(p, value, platform_src_type);
  4124. }
  4125. LLVMOpcode op = LLVMTrunc;
  4126. if (dz < sz) {
  4127. op = LLVMTrunc;
  4128. } else if (dz == sz) {
  4129. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  4130. // NOTE(bill): Copy the value just for type correctness
  4131. op = LLVMBitCast;
  4132. } else if (dz > sz) {
  4133. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  4134. }
  4135. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  4136. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  4137. lbValue res = {};
  4138. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  4139. res.type = t;
  4140. return lb_emit_byte_swap(p, res, t);
  4141. } else {
  4142. lbValue res = {};
  4143. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  4144. res.type = t;
  4145. return res;
  4146. }
  4147. }
  4148. // boolean -> boolean/integer
  4149. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  4150. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  4151. lbValue res = {};
  4152. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  4153. res.type = t;
  4154. return res;
  4155. }
  4156. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  4157. return lb_emit_transmute(p, value, dst);
  4158. }
  4159. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  4160. return lb_emit_transmute(p, value, dst);
  4161. }
  4162. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  4163. return lb_emit_transmute(p, value, dst);
  4164. }
  4165. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  4166. return lb_emit_transmute(p, value, dst);
  4167. }
  4168. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  4169. lbValue c = lb_emit_conv(p, value, t_cstring);
  4170. auto args = array_make<lbValue>(heap_allocator(), 1);
  4171. args[0] = c;
  4172. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  4173. return lb_emit_conv(p, s, dst);
  4174. }
  4175. // integer -> boolean
  4176. if (is_type_integer(src) && is_type_boolean(dst)) {
  4177. lbValue res = {};
  4178. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  4179. res.type = t_llvm_bool;
  4180. return lb_emit_conv(p, res, t);
  4181. }
  4182. // float -> float
  4183. if (is_type_float(src) && is_type_float(dst)) {
  4184. gbAllocator a = heap_allocator();
  4185. i64 sz = type_size_of(src);
  4186. i64 dz = type_size_of(dst);
  4187. lbValue res = {};
  4188. res.type = t;
  4189. if (dz >= sz) {
  4190. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  4191. } else {
  4192. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  4193. }
  4194. return res;
  4195. }
  4196. if (is_type_complex(src) && is_type_complex(dst)) {
  4197. Type *ft = base_complex_elem_type(dst);
  4198. lbAddr gen = lb_add_local_generated(p, dst, false);
  4199. lbValue gp = lb_addr_get_ptr(p, gen);
  4200. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  4201. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  4202. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  4203. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  4204. return lb_addr_load(p, gen);
  4205. }
  4206. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  4207. // @QuaternionLayout
  4208. Type *ft = base_complex_elem_type(dst);
  4209. lbAddr gen = lb_add_local_generated(p, dst, false);
  4210. lbValue gp = lb_addr_get_ptr(p, gen);
  4211. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  4212. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  4213. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  4214. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  4215. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  4216. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  4217. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  4218. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  4219. return lb_addr_load(p, gen);
  4220. }
  4221. if (is_type_float(src) && is_type_complex(dst)) {
  4222. Type *ft = base_complex_elem_type(dst);
  4223. lbAddr gen = lb_add_local_generated(p, dst, true);
  4224. lbValue gp = lb_addr_get_ptr(p, gen);
  4225. lbValue real = lb_emit_conv(p, value, ft);
  4226. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  4227. return lb_addr_load(p, gen);
  4228. }
  4229. if (is_type_float(src) && is_type_quaternion(dst)) {
  4230. Type *ft = base_complex_elem_type(dst);
  4231. lbAddr gen = lb_add_local_generated(p, dst, true);
  4232. lbValue gp = lb_addr_get_ptr(p, gen);
  4233. lbValue real = lb_emit_conv(p, value, ft);
  4234. // @QuaternionLayout
  4235. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  4236. return lb_addr_load(p, gen);
  4237. }
  4238. if (is_type_complex(src) && is_type_quaternion(dst)) {
  4239. Type *ft = base_complex_elem_type(dst);
  4240. lbAddr gen = lb_add_local_generated(p, dst, true);
  4241. lbValue gp = lb_addr_get_ptr(p, gen);
  4242. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  4243. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  4244. // @QuaternionLayout
  4245. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  4246. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  4247. return lb_addr_load(p, gen);
  4248. }
  4249. // float <-> integer
  4250. if (is_type_float(src) && is_type_integer(dst)) {
  4251. lbValue res = {};
  4252. res.type = t;
  4253. if (is_type_unsigned(dst)) {
  4254. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  4255. } else {
  4256. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  4257. }
  4258. return res;
  4259. }
  4260. if (is_type_integer(src) && is_type_float(dst)) {
  4261. lbValue res = {};
  4262. res.type = t;
  4263. if (is_type_unsigned(src)) {
  4264. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  4265. } else {
  4266. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  4267. }
  4268. return res;
  4269. }
  4270. // Pointer <-> uintptr
  4271. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  4272. lbValue res = {};
  4273. res.type = t;
  4274. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4275. return res;
  4276. }
  4277. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  4278. lbValue res = {};
  4279. res.type = t;
  4280. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4281. return res;
  4282. }
  4283. #if 1
  4284. if (is_type_union(dst)) {
  4285. for_array(i, dst->Union.variants) {
  4286. Type *vt = dst->Union.variants[i];
  4287. if (are_types_identical(vt, src_type)) {
  4288. lbAddr parent = lb_add_local_generated(p, t, true);
  4289. lb_emit_store_union_variant(p, parent.addr, value, vt);
  4290. return lb_addr_load(p, parent);
  4291. }
  4292. }
  4293. }
  4294. #endif
  4295. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  4296. // subtype polymorphism casting
  4297. if (check_is_assignable_to_using_subtype(src_type, t)) {
  4298. Type *st = type_deref(src_type);
  4299. Type *pst = st;
  4300. st = type_deref(st);
  4301. bool st_is_ptr = is_type_pointer(src_type);
  4302. st = base_type(st);
  4303. Type *dt = t;
  4304. bool dt_is_ptr = type_deref(dt) != dt;
  4305. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  4306. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  4307. if (field_name.len > 0) {
  4308. // NOTE(bill): It can be casted
  4309. Selection sel = lookup_field(st, field_name, false, true);
  4310. if (sel.entity != nullptr) {
  4311. if (st_is_ptr) {
  4312. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  4313. Type *rt = res.type;
  4314. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4315. res = lb_emit_load(p, res);
  4316. }
  4317. return res;
  4318. } else {
  4319. if (is_type_pointer(value.type)) {
  4320. Type *rt = value.type;
  4321. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4322. value = lb_emit_load(p, value);
  4323. } else {
  4324. value = lb_emit_deep_field_gep(p, value, sel);
  4325. return lb_emit_load(p, value);
  4326. }
  4327. }
  4328. return lb_emit_deep_field_ev(p, value, sel);
  4329. }
  4330. } else {
  4331. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  4332. }
  4333. }
  4334. }
  4335. // Pointer <-> Pointer
  4336. if (is_type_pointer(src) && is_type_pointer(dst)) {
  4337. lbValue res = {};
  4338. res.type = t;
  4339. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4340. return res;
  4341. }
  4342. // proc <-> proc
  4343. if (is_type_proc(src) && is_type_proc(dst)) {
  4344. lbValue res = {};
  4345. res.type = t;
  4346. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4347. return res;
  4348. }
  4349. // pointer -> proc
  4350. if (is_type_pointer(src) && is_type_proc(dst)) {
  4351. lbValue res = {};
  4352. res.type = t;
  4353. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4354. return res;
  4355. }
  4356. // proc -> pointer
  4357. if (is_type_proc(src) && is_type_pointer(dst)) {
  4358. lbValue res = {};
  4359. res.type = t;
  4360. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4361. return res;
  4362. }
  4363. // []byte/[]u8 <-> string
  4364. if (is_type_u8_slice(src) && is_type_string(dst)) {
  4365. return lb_emit_transmute(p, value, t);
  4366. }
  4367. if (is_type_string(src) && is_type_u8_slice(dst)) {
  4368. return lb_emit_transmute(p, value, t);
  4369. }
  4370. if (is_type_array(dst)) {
  4371. Type *elem = dst->Array.elem;
  4372. lbValue e = lb_emit_conv(p, value, elem);
  4373. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4374. lbAddr v = lb_add_local_generated(p, t, false);
  4375. isize index_count = cast(isize)dst->Array.count;
  4376. for (isize i = 0; i < index_count; i++) {
  4377. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  4378. lb_emit_store(p, elem, e);
  4379. }
  4380. return lb_addr_load(p, v);
  4381. }
  4382. if (is_type_any(dst)) {
  4383. if (is_type_untyped_nil(src)) {
  4384. return lb_const_nil(p->module, t);
  4385. }
  4386. if (is_type_untyped_undef(src)) {
  4387. return lb_const_undef(p->module, t);
  4388. }
  4389. lbAddr result = lb_add_local_generated(p, t, true);
  4390. Type *st = default_type(src_type);
  4391. lbValue data = lb_address_from_load_or_generate_local(p, value);
  4392. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  4393. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  4394. data = lb_emit_conv(p, data, t_rawptr);
  4395. lbValue id = lb_typeid(p->module, st);
  4396. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  4397. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  4398. lb_emit_store(p, any_data, data);
  4399. lb_emit_store(p, any_id, id);
  4400. return lb_addr_load(p, result);
  4401. }
  4402. if (is_type_untyped(src)) {
  4403. if (is_type_string(src) && is_type_string(dst)) {
  4404. lbAddr result = lb_add_local_generated(p, t, false);
  4405. lb_addr_store(p, result, value);
  4406. return lb_addr_load(p, result);
  4407. }
  4408. }
  4409. gb_printf_err("%.*s\n", LIT(p->name));
  4410. gb_printf_err("lb_emit_conv: src -> dst\n");
  4411. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  4412. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  4413. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  4414. gb_printf_err("Not Identical %p != %p\n", src, dst);
  4415. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  4416. type_to_string(src_type), type_to_string(t),
  4417. LIT(p->name));
  4418. return {};
  4419. }
  4420. bool lb_is_type_aggregate(Type *t) {
  4421. t = base_type(t);
  4422. switch (t->kind) {
  4423. case Type_Basic:
  4424. switch (t->Basic.kind) {
  4425. case Basic_string:
  4426. case Basic_any:
  4427. return true;
  4428. // case Basic_complex32:
  4429. case Basic_complex64:
  4430. case Basic_complex128:
  4431. case Basic_quaternion128:
  4432. case Basic_quaternion256:
  4433. return true;
  4434. }
  4435. break;
  4436. case Type_Pointer:
  4437. return false;
  4438. case Type_Array:
  4439. case Type_Slice:
  4440. case Type_Struct:
  4441. case Type_Union:
  4442. case Type_Tuple:
  4443. case Type_DynamicArray:
  4444. case Type_Map:
  4445. case Type_BitField:
  4446. case Type_SimdVector:
  4447. return true;
  4448. case Type_Named:
  4449. return lb_is_type_aggregate(t->Named.base);
  4450. }
  4451. return false;
  4452. }
  4453. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  4454. Type *src_type = value.type;
  4455. if (are_types_identical(t, src_type)) {
  4456. return value;
  4457. }
  4458. lbValue res = {};
  4459. res.type = t;
  4460. Type *src = base_type(src_type);
  4461. Type *dst = base_type(t);
  4462. lbModule *m = p->module;
  4463. i64 sz = type_size_of(src);
  4464. i64 dz = type_size_of(dst);
  4465. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  4466. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  4467. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  4468. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4469. return res;
  4470. }
  4471. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  4472. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4473. return res;
  4474. }
  4475. if (is_type_uintptr(src) && is_type_proc(dst)) {
  4476. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4477. return res;
  4478. }
  4479. if (is_type_proc(src) && is_type_uintptr(dst)) {
  4480. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4481. return res;
  4482. }
  4483. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  4484. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4485. return res;
  4486. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  4487. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4488. return res;
  4489. }
  4490. if (is_type_pointer(src) && is_type_pointer(dst)) {
  4491. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  4492. return res;
  4493. }
  4494. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  4495. lbValue s = lb_address_from_load_or_generate_local(p, value);
  4496. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  4497. return lb_emit_load(p, d);
  4498. }
  4499. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  4500. // GB_PANIC("lb_emit_transmute");
  4501. return res;
  4502. }
  4503. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  4504. GB_ASSERT(addr.kind == lbAddr_Context);
  4505. GB_ASSERT(addr.ctx.sel.index.count == 0);
  4506. lbModule *m = p->module;
  4507. gbAllocator a = heap_allocator();
  4508. auto args = array_make<lbValue>(a, 1);
  4509. args[0] = addr.addr;
  4510. lb_emit_runtime_call(p, "__init_context", args);
  4511. }
  4512. void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  4513. ctx.kind = lbAddr_Context;
  4514. lbContextData cd = {ctx, p->scope_index};
  4515. array_add(&p->context_stack, cd);
  4516. }
  4517. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  4518. if (p->context_stack.count > 0) {
  4519. return p->context_stack[p->context_stack.count-1].ctx;
  4520. }
  4521. Type *pt = base_type(p->type);
  4522. GB_ASSERT(pt->kind == Type_Proc);
  4523. if (pt->Proc.calling_convention != ProcCC_Odin) {
  4524. return p->module->global_default_context;
  4525. } else {
  4526. lbAddr c = lb_add_local_generated(p, t_context, false);
  4527. c.kind = lbAddr_Context;
  4528. lb_push_context_onto_stack(p, c);
  4529. lb_addr_store(p, c, lb_addr_load(p, p->module->global_default_context));
  4530. lb_emit_init_context(p, c);
  4531. return c;
  4532. }
  4533. }
  4534. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  4535. if (LLVMIsALoadInst(value.value)) {
  4536. lbValue res = {};
  4537. res.value = LLVMGetOperand(value.value, 0);
  4538. res.type = alloc_type_pointer(value.type);
  4539. return res;
  4540. }
  4541. GB_ASSERT(is_type_typed(value.type));
  4542. lbAddr res = lb_add_local_generated(p, value.type, false);
  4543. lb_addr_store(p, res, value);
  4544. return res.addr;
  4545. }
  4546. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  4547. i64 type_alignment = type_align_of(new_type);
  4548. if (alignment < type_alignment) {
  4549. alignment = type_alignment;
  4550. }
  4551. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  4552. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  4553. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  4554. lb_addr_store(p, ptr, val);
  4555. ptr.kind = lbAddr_Context;
  4556. return ptr.addr;
  4557. }
  4558. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  4559. gbAllocator a = heap_allocator();
  4560. GB_ASSERT(is_type_pointer(s.type));
  4561. Type *t = base_type(type_deref(s.type));
  4562. Type *result_type = nullptr;
  4563. if (t->kind == Type_Opaque) {
  4564. t = t->Opaque.elem;
  4565. }
  4566. if (is_type_struct(t)) {
  4567. result_type = get_struct_field_type(t, index);
  4568. } else if (is_type_union(t)) {
  4569. GB_ASSERT(index == -1);
  4570. return lb_emit_union_tag_ptr(p, s);
  4571. } else if (is_type_tuple(t)) {
  4572. GB_ASSERT(t->Tuple.variables.count > 0);
  4573. result_type = t->Tuple.variables[index]->type;
  4574. } else if (is_type_complex(t)) {
  4575. Type *ft = base_complex_elem_type(t);
  4576. switch (index) {
  4577. case 0: result_type = ft; break;
  4578. case 1: result_type = ft; break;
  4579. }
  4580. } else if (is_type_quaternion(t)) {
  4581. Type *ft = base_complex_elem_type(t);
  4582. switch (index) {
  4583. case 0: result_type = ft; break;
  4584. case 1: result_type = ft; break;
  4585. case 2: result_type = ft; break;
  4586. case 3: result_type = ft; break;
  4587. }
  4588. } else if (is_type_slice(t)) {
  4589. switch (index) {
  4590. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  4591. case 1: result_type = t_int; break;
  4592. }
  4593. } else if (is_type_string(t)) {
  4594. switch (index) {
  4595. case 0: result_type = t_u8_ptr; break;
  4596. case 1: result_type = t_int; break;
  4597. }
  4598. } else if (is_type_any(t)) {
  4599. switch (index) {
  4600. case 0: result_type = t_rawptr; break;
  4601. case 1: result_type = t_typeid; break;
  4602. }
  4603. } else if (is_type_dynamic_array(t)) {
  4604. switch (index) {
  4605. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  4606. case 1: result_type = t_int; break;
  4607. case 2: result_type = t_int; break;
  4608. case 3: result_type = t_allocator; break;
  4609. }
  4610. } else if (is_type_map(t)) {
  4611. init_map_internal_types(t);
  4612. Type *itp = alloc_type_pointer(t->Map.internal_type);
  4613. s = lb_emit_transmute(p, s, itp);
  4614. Type *gst = t->Map.internal_type;
  4615. GB_ASSERT(gst->kind == Type_Struct);
  4616. switch (index) {
  4617. case 0: result_type = get_struct_field_type(gst, 0); break;
  4618. case 1: result_type = get_struct_field_type(gst, 1); break;
  4619. }
  4620. } else if (is_type_array(t)) {
  4621. return lb_emit_array_epi(p, s, index);
  4622. } else {
  4623. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  4624. }
  4625. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  4626. if (lb_is_const(s)) {
  4627. lbModule *m = p->module;
  4628. lbValue res = {};
  4629. LLVMValueRef indices[2] = {llvm_zero32(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  4630. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  4631. res.type = alloc_type_pointer(result_type);
  4632. return res;
  4633. } else {
  4634. lbValue res = {};
  4635. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  4636. res.type = alloc_type_pointer(result_type);
  4637. return res;
  4638. }
  4639. }
  4640. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  4641. if (LLVMIsALoadInst(s.value)) {
  4642. lbValue res = {};
  4643. res.value = LLVMGetOperand(s.value, 0);
  4644. res.type = alloc_type_pointer(s.type);
  4645. lbValue ptr = lb_emit_struct_ep(p, res, index);
  4646. return lb_emit_load(p, ptr);
  4647. }
  4648. gbAllocator a = heap_allocator();
  4649. Type *t = base_type(s.type);
  4650. Type *result_type = nullptr;
  4651. switch (t->kind) {
  4652. case Type_Basic:
  4653. switch (t->Basic.kind) {
  4654. case Basic_string:
  4655. switch (index) {
  4656. case 0: result_type = t_u8_ptr; break;
  4657. case 1: result_type = t_int; break;
  4658. }
  4659. break;
  4660. case Basic_any:
  4661. switch (index) {
  4662. case 0: result_type = t_rawptr; break;
  4663. case 1: result_type = t_typeid; break;
  4664. }
  4665. break;
  4666. case Basic_complex64: case Basic_complex128:
  4667. {
  4668. Type *ft = base_complex_elem_type(t);
  4669. switch (index) {
  4670. case 0: result_type = ft; break;
  4671. case 1: result_type = ft; break;
  4672. }
  4673. break;
  4674. }
  4675. case Basic_quaternion128: case Basic_quaternion256:
  4676. {
  4677. Type *ft = base_complex_elem_type(t);
  4678. switch (index) {
  4679. case 0: result_type = ft; break;
  4680. case 1: result_type = ft; break;
  4681. case 2: result_type = ft; break;
  4682. case 3: result_type = ft; break;
  4683. }
  4684. break;
  4685. }
  4686. }
  4687. break;
  4688. case Type_Struct:
  4689. result_type = get_struct_field_type(t, index);
  4690. break;
  4691. case Type_Union:
  4692. GB_ASSERT(index == -1);
  4693. // return lb_emit_union_tag_value(p, s);
  4694. GB_PANIC("lb_emit_union_tag_value");
  4695. case Type_Tuple:
  4696. GB_ASSERT(t->Tuple.variables.count > 0);
  4697. result_type = t->Tuple.variables[index]->type;
  4698. if (t->Tuple.variables.count == 1) {
  4699. return s;
  4700. }
  4701. break;
  4702. case Type_Slice:
  4703. switch (index) {
  4704. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  4705. case 1: result_type = t_int; break;
  4706. }
  4707. break;
  4708. case Type_DynamicArray:
  4709. switch (index) {
  4710. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  4711. case 1: result_type = t_int; break;
  4712. case 2: result_type = t_int; break;
  4713. case 3: result_type = t_allocator; break;
  4714. }
  4715. break;
  4716. case Type_Map:
  4717. {
  4718. init_map_internal_types(t);
  4719. Type *gst = t->Map.generated_struct_type;
  4720. switch (index) {
  4721. case 0: result_type = get_struct_field_type(gst, 0); break;
  4722. case 1: result_type = get_struct_field_type(gst, 1); break;
  4723. }
  4724. }
  4725. break;
  4726. case Type_Array:
  4727. result_type = t->Array.elem;
  4728. break;
  4729. default:
  4730. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  4731. break;
  4732. }
  4733. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  4734. lbValue res = {};
  4735. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  4736. res.type = result_type;
  4737. return res;
  4738. }
  4739. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  4740. GB_ASSERT(sel.index.count > 0);
  4741. Type *type = type_deref(e.type);
  4742. gbAllocator a = heap_allocator();
  4743. for_array(i, sel.index) {
  4744. i32 index = cast(i32)sel.index[i];
  4745. if (is_type_pointer(type)) {
  4746. type = type_deref(type);
  4747. e = lb_emit_load(p, e);
  4748. }
  4749. type = core_type(type);
  4750. if (type->kind == Type_Opaque) {
  4751. type = type->Opaque.elem;
  4752. }
  4753. if (is_type_quaternion(type)) {
  4754. e = lb_emit_struct_ep(p, e, index);
  4755. } else if (is_type_raw_union(type)) {
  4756. type = get_struct_field_type(type, index);
  4757. GB_ASSERT(is_type_pointer(e.type));
  4758. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  4759. } else if (is_type_struct(type)) {
  4760. type = get_struct_field_type(type, index);
  4761. e = lb_emit_struct_ep(p, e, index);
  4762. } else if (type->kind == Type_Union) {
  4763. GB_ASSERT(index == -1);
  4764. type = t_type_info_ptr;
  4765. e = lb_emit_struct_ep(p, e, index);
  4766. } else if (type->kind == Type_Tuple) {
  4767. type = type->Tuple.variables[index]->type;
  4768. e = lb_emit_struct_ep(p, e, index);
  4769. } else if (type->kind == Type_Basic) {
  4770. switch (type->Basic.kind) {
  4771. case Basic_any: {
  4772. if (index == 0) {
  4773. type = t_rawptr;
  4774. } else if (index == 1) {
  4775. type = t_type_info_ptr;
  4776. }
  4777. e = lb_emit_struct_ep(p, e, index);
  4778. break;
  4779. }
  4780. case Basic_string:
  4781. e = lb_emit_struct_ep(p, e, index);
  4782. break;
  4783. default:
  4784. GB_PANIC("un-gep-able type");
  4785. break;
  4786. }
  4787. } else if (type->kind == Type_Slice) {
  4788. e = lb_emit_struct_ep(p, e, index);
  4789. } else if (type->kind == Type_DynamicArray) {
  4790. e = lb_emit_struct_ep(p, e, index);
  4791. } else if (type->kind == Type_Array) {
  4792. e = lb_emit_array_epi(p, e, index);
  4793. } else if (type->kind == Type_Map) {
  4794. e = lb_emit_struct_ep(p, e, index);
  4795. } else {
  4796. GB_PANIC("un-gep-able type %s", type_to_string(type));
  4797. }
  4798. }
  4799. return e;
  4800. }
  4801. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  4802. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  4803. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  4804. return lb_emit_load(p, res);
  4805. }
  4806. void lb_build_defer_stmt(lbProcedure *p, lbDefer d) {
  4807. // NOTE(bill): The prev block may defer injection before it's terminator
  4808. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  4809. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  4810. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  4811. return;
  4812. }
  4813. lbBlock *b = lb_create_block(p, "defer");
  4814. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  4815. lb_emit_jump(p, b);
  4816. }
  4817. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  4818. lb_emit_jump(p, b);
  4819. }
  4820. lb_start_block(p, b);
  4821. if (d.kind == lbDefer_Node) {
  4822. lb_build_stmt(p, d.stmt);
  4823. } else if (d.kind == lbDefer_Instr) {
  4824. // NOTE(bill): Need to make a new copy
  4825. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  4826. LLVMInsertIntoBuilder(p->builder, instr);
  4827. } else if (d.kind == lbDefer_Proc) {
  4828. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  4829. }
  4830. }
  4831. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  4832. isize count = p->defer_stmts.count;
  4833. isize i = count;
  4834. while (i --> 0) {
  4835. lbDefer d = p->defer_stmts[i];
  4836. if (kind == lbDeferExit_Default) {
  4837. if (p->scope_index == d.scope_index &&
  4838. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  4839. lb_build_defer_stmt(p, d);
  4840. array_pop(&p->defer_stmts);
  4841. continue;
  4842. } else {
  4843. break;
  4844. }
  4845. } else if (kind == lbDeferExit_Return) {
  4846. lb_build_defer_stmt(p, d);
  4847. } else if (kind == lbDeferExit_Branch) {
  4848. GB_ASSERT(block != nullptr);
  4849. isize lower_limit = block->scope_index;
  4850. if (lower_limit < d.scope_index) {
  4851. lb_build_defer_stmt(p, d);
  4852. }
  4853. }
  4854. }
  4855. }
  4856. lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  4857. lbDefer d = {lbDefer_Node};
  4858. d.scope_index = scope_index;
  4859. d.context_stack_count = p->context_stack.count;
  4860. d.block = p->curr_block;
  4861. d.stmt = stmt;
  4862. array_add(&p->defer_stmts, d);
  4863. return d;
  4864. }
  4865. lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  4866. lbDefer d = {lbDefer_Proc};
  4867. d.scope_index = p->scope_index;
  4868. d.block = p->curr_block;
  4869. d.proc.deferred = deferred;
  4870. d.proc.result_as_args = result_as_args;
  4871. array_add(&p->defer_stmts, d);
  4872. return d;
  4873. }
  4874. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  4875. Array<lbValue> array = {};
  4876. Type *t = base_type(value.type);
  4877. if (t == nullptr) {
  4878. // Do nothing
  4879. } else if (is_type_tuple(t)) {
  4880. GB_ASSERT(t->kind == Type_Tuple);
  4881. auto *rt = &t->Tuple;
  4882. if (rt->variables.count > 0) {
  4883. array = array_make<lbValue>(heap_allocator(), rt->variables.count);
  4884. for_array(i, rt->variables) {
  4885. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  4886. array[i] = elem;
  4887. }
  4888. }
  4889. } else {
  4890. array = array_make<lbValue>(heap_allocator(), 1);
  4891. array[0] = value;
  4892. }
  4893. return array;
  4894. }
  4895. 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) {
  4896. unsigned arg_count = cast(unsigned)processed_args.count;
  4897. if (return_ptr.value != nullptr) {
  4898. arg_count += 1;
  4899. }
  4900. if (context_ptr.addr.value != nullptr) {
  4901. arg_count += 1;
  4902. }
  4903. LLVMValueRef *args = gb_alloc_array(heap_allocator(), LLVMValueRef, arg_count);
  4904. isize arg_index = 0;
  4905. if (return_ptr.value != nullptr) {
  4906. args[arg_index++] = return_ptr.value;
  4907. }
  4908. for_array(i, processed_args) {
  4909. lbValue arg = processed_args[i];
  4910. args[arg_index++] = arg.value;
  4911. }
  4912. if (context_ptr.addr.value != nullptr) {
  4913. args[arg_index++] = context_ptr.addr.value;
  4914. }
  4915. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  4916. GB_ASSERT(curr_block != p->decl_block->block);
  4917. LLVMValueRef ret = LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(p->module, value.type)), value.value, args, arg_count, "");;
  4918. lbValue res = {};
  4919. res.value = ret;
  4920. res.type = abi_rt;
  4921. return res;
  4922. }
  4923. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  4924. String name = make_string_c(c_name);
  4925. AstPackage *pkg = p->module->info->runtime_package;
  4926. Entity *e = scope_lookup_current(pkg->scope, name);
  4927. lbValue *found = nullptr;
  4928. if (p->module != e->code_gen_module) {
  4929. gb_mutex_lock(&p->module->mutex);
  4930. }
  4931. found = map_get(&e->code_gen_module->values, hash_entity(e));
  4932. if (p->module != e->code_gen_module) {
  4933. gb_mutex_unlock(&p->module->mutex);
  4934. }
  4935. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  4936. return lb_emit_call(p, *found, args);
  4937. }
  4938. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  4939. lbModule *m = p->module;
  4940. Type *pt = base_type(value.type);
  4941. GB_ASSERT(pt->kind == Type_Proc);
  4942. Type *results = pt->Proc.results;
  4943. if (p->entity != nullptr) {
  4944. if (p->entity->flags & EntityFlag_Disabled) {
  4945. return {};
  4946. }
  4947. }
  4948. lbAddr context_ptr = {};
  4949. if (pt->Proc.calling_convention == ProcCC_Odin) {
  4950. context_ptr = lb_find_or_generate_context_ptr(p);
  4951. }
  4952. set_procedure_abi_types(heap_allocator(), pt);
  4953. bool is_c_vararg = pt->Proc.c_vararg;
  4954. isize param_count = pt->Proc.param_count;
  4955. if (is_c_vararg) {
  4956. GB_ASSERT(param_count-1 <= args.count);
  4957. param_count -= 1;
  4958. } else {
  4959. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  4960. }
  4961. auto processed_args = array_make<lbValue>(heap_allocator(), 0, args.count);
  4962. for (isize i = 0; i < param_count; i++) {
  4963. Entity *e = pt->Proc.params->Tuple.variables[i];
  4964. if (e->kind != Entity_Variable) {
  4965. // array_add(&processed_args, args[i]);
  4966. continue;
  4967. }
  4968. GB_ASSERT(e->flags & EntityFlag_Param);
  4969. Type *original_type = e->type;
  4970. Type *new_type = pt->Proc.abi_compat_params[i];
  4971. Type *arg_type = args[i].type;
  4972. if (are_types_identical(arg_type, new_type)) {
  4973. // NOTE(bill): Done
  4974. array_add(&processed_args, args[i]);
  4975. } else if (!are_types_identical(original_type, new_type)) {
  4976. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  4977. if (e->flags&EntityFlag_ImplicitReference) {
  4978. array_add(&processed_args, lb_address_from_load_or_generate_local(p, args[i]));
  4979. } else if (!is_type_pointer(arg_type)) {
  4980. array_add(&processed_args, lb_copy_value_to_ptr(p, args[i], original_type, 16));
  4981. }
  4982. } else if (is_type_integer(new_type) || is_type_float(new_type)) {
  4983. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  4984. } else if (new_type == t_llvm_bool) {
  4985. array_add(&processed_args, lb_emit_conv(p, args[i], new_type));
  4986. } else if (is_type_simd_vector(new_type)) {
  4987. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  4988. } else if (is_type_tuple(new_type)) {
  4989. Type *abi_type = pt->Proc.abi_compat_params[i];
  4990. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  4991. lbValue x = lb_emit_transmute(p, args[i], st);
  4992. for (isize j = 0; j < new_type->Tuple.variables.count; j++) {
  4993. lbValue xx = lb_emit_struct_ev(p, x, cast(i32)j);
  4994. array_add(&processed_args, xx);
  4995. }
  4996. }
  4997. } else {
  4998. lbValue x = lb_emit_conv(p, args[i], new_type);
  4999. array_add(&processed_args, x);
  5000. }
  5001. }
  5002. if (inlining == ProcInlining_none) {
  5003. inlining = p->inlining;
  5004. }
  5005. lbValue result = {};
  5006. Type *abi_rt = reduce_tuple_to_single_type(pt->Proc.abi_compat_result_type);
  5007. Type *rt = reduce_tuple_to_single_type(results);
  5008. if (pt->Proc.return_by_pointer) {
  5009. lbValue return_ptr = {};
  5010. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  5011. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  5012. return_ptr = p->return_ptr_hint_value;
  5013. p->return_ptr_hint_used = true;
  5014. }
  5015. }
  5016. if (return_ptr.value == nullptr) {
  5017. lbAddr r = lb_add_local_generated(p, rt, true);
  5018. return_ptr = r.addr;
  5019. }
  5020. GB_ASSERT(is_type_pointer(return_ptr.type));
  5021. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  5022. result = lb_emit_load(p, return_ptr);
  5023. } else {
  5024. result = lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining);
  5025. if (abi_rt != rt) {
  5026. result = lb_emit_transmute(p, result, rt);
  5027. }
  5028. }
  5029. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  5030. if (found != nullptr) {
  5031. Entity *e = *found;
  5032. if (e != nullptr && entity_has_deferred_procedure(e)) {
  5033. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  5034. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  5035. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  5036. GB_ASSERT(deferred_found != nullptr);
  5037. lbValue deferred = *deferred_found;
  5038. auto in_args = args;
  5039. Array<lbValue> result_as_args = {};
  5040. switch (kind) {
  5041. case DeferredProcedure_none:
  5042. break;
  5043. case DeferredProcedure_in:
  5044. result_as_args = in_args;
  5045. break;
  5046. case DeferredProcedure_out:
  5047. result_as_args = lb_value_to_array(p, result);
  5048. break;
  5049. }
  5050. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  5051. }
  5052. }
  5053. return result;
  5054. }
  5055. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  5056. Type *t = s.type;
  5057. GB_ASSERT(is_type_pointer(t));
  5058. Type *st = base_type(type_deref(t));
  5059. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  5060. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  5061. LLVMValueRef indices[2] = {};
  5062. indices[0] = llvm_zero32(p->module);
  5063. indices[1] = lb_emit_conv(p, index, t_int).value;
  5064. Type *ptr = base_array_type(st);
  5065. lbValue res = {};
  5066. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  5067. res.type = alloc_type_pointer(ptr);
  5068. return res;
  5069. }
  5070. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  5071. Type *t = s.type;
  5072. GB_ASSERT(is_type_pointer(t));
  5073. Type *st = base_type(type_deref(t));
  5074. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  5075. GB_ASSERT(0 <= index);
  5076. Type *ptr = base_array_type(st);
  5077. LLVMValueRef indices[2] = {
  5078. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  5079. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  5080. };
  5081. lbValue res = {};
  5082. if (lb_is_const(s)) {
  5083. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  5084. } else {
  5085. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  5086. }
  5087. res.type = alloc_type_pointer(ptr);
  5088. return res;
  5089. }
  5090. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  5091. LLVMValueRef indices[1] = {index.value};
  5092. lbValue res = {};
  5093. res.type = ptr.type;
  5094. if (lb_is_const(ptr) && lb_is_const(index)) {
  5095. res.value = LLVMConstGEP(ptr.value, indices, 1);
  5096. } else {
  5097. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  5098. }
  5099. return res;
  5100. }
  5101. LLVMValueRef llvm_const_slice(lbValue data, lbValue len) {
  5102. GB_ASSERT(is_type_pointer(data.type));
  5103. GB_ASSERT(are_types_identical(len.type, t_int));
  5104. LLVMValueRef vals[2] = {
  5105. data.value,
  5106. len.value,
  5107. };
  5108. return LLVMConstStruct(vals, gb_count_of(vals), false);
  5109. }
  5110. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  5111. Type *t = lb_addr_type(slice);
  5112. GB_ASSERT(is_type_slice(t));
  5113. lbValue ptr = lb_addr_get_ptr(p, slice);
  5114. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  5115. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  5116. }
  5117. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  5118. Type *t = lb_addr_type(string);
  5119. GB_ASSERT(is_type_string(t));
  5120. lbValue ptr = lb_addr_get_ptr(p, string);
  5121. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  5122. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  5123. }
  5124. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  5125. Type *t = base_type(string.type);
  5126. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  5127. return lb_emit_struct_ev(p, string, 0);
  5128. }
  5129. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  5130. Type *t = base_type(string.type);
  5131. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  5132. return lb_emit_struct_ev(p, string, 1);
  5133. }
  5134. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  5135. GB_ASSERT(is_type_cstring(value.type));
  5136. auto args = array_make<lbValue>(heap_allocator(), 1);
  5137. args[0] = lb_emit_conv(p, value, t_cstring);
  5138. return lb_emit_runtime_call(p, "cstring_len", args);
  5139. }
  5140. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  5141. Type *t = type_deref(array_ptr.type);
  5142. GB_ASSERT(is_type_array(t));
  5143. return lb_emit_struct_ep(p, array_ptr, 0);
  5144. }
  5145. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  5146. GB_ASSERT(is_type_slice(slice.type));
  5147. return lb_emit_struct_ev(p, slice, 0);
  5148. }
  5149. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  5150. GB_ASSERT(is_type_slice(slice.type));
  5151. return lb_emit_struct_ev(p, slice, 1);
  5152. }
  5153. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  5154. GB_ASSERT(is_type_dynamic_array(da.type));
  5155. return lb_emit_struct_ev(p, da, 0);
  5156. }
  5157. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  5158. GB_ASSERT(is_type_dynamic_array(da.type));
  5159. return lb_emit_struct_ev(p, da, 1);
  5160. }
  5161. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  5162. GB_ASSERT(is_type_dynamic_array(da.type));
  5163. return lb_emit_struct_ev(p, da, 2);
  5164. }
  5165. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  5166. GB_ASSERT(is_type_dynamic_array(da.type));
  5167. return lb_emit_struct_ev(p, da, 3);
  5168. }
  5169. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  5170. gbAllocator a = heap_allocator();
  5171. Type *t = base_type(value.type);
  5172. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  5173. init_map_internal_types(t);
  5174. Type *gst = t->Map.generated_struct_type;
  5175. i32 index = 1;
  5176. lbValue entries = lb_emit_struct_ev(p, value, index);
  5177. return entries;
  5178. }
  5179. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  5180. gbAllocator a = heap_allocator();
  5181. Type *t = base_type(type_deref(value.type));
  5182. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  5183. init_map_internal_types(t);
  5184. Type *gst = t->Map.generated_struct_type;
  5185. i32 index = 1;
  5186. lbValue entries = lb_emit_struct_ep(p, value, index);
  5187. return entries;
  5188. }
  5189. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  5190. lbValue entries = lb_map_entries(p, value);
  5191. return lb_dynamic_array_len(p, entries);
  5192. }
  5193. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  5194. lbValue entries = lb_map_entries(p, value);
  5195. return lb_dynamic_array_cap(p, entries);
  5196. }
  5197. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  5198. Type *t = base_type(value.type);
  5199. bool is_ptr = false;
  5200. if (is_type_pointer(t)) {
  5201. is_ptr = true;
  5202. t = base_type(type_deref(t));
  5203. }
  5204. if (t->Struct.soa_kind == StructSoa_Fixed) {
  5205. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  5206. }
  5207. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  5208. t->Struct.soa_kind == StructSoa_Dynamic);
  5209. isize n = 0;
  5210. Type *elem = base_type(t->Struct.soa_elem);
  5211. if (elem->kind == Type_Struct) {
  5212. n = elem->Struct.fields.count;
  5213. } else if (elem->kind == Type_Array) {
  5214. n = elem->Array.count;
  5215. } else {
  5216. GB_PANIC("Unreachable");
  5217. }
  5218. if (is_ptr) {
  5219. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  5220. return lb_emit_load(p, v);
  5221. }
  5222. return lb_emit_struct_ev(p, value, cast(i32)n);
  5223. }
  5224. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  5225. Type *t = base_type(value.type);
  5226. bool is_ptr = false;
  5227. if (is_type_pointer(t)) {
  5228. is_ptr = true;
  5229. t = base_type(type_deref(t));
  5230. }
  5231. if (t->Struct.soa_kind == StructSoa_Fixed) {
  5232. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  5233. }
  5234. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  5235. isize n = 0;
  5236. Type *elem = base_type(t->Struct.soa_elem);
  5237. if (elem->kind == Type_Struct) {
  5238. n = elem->Struct.fields.count+1;
  5239. } else if (elem->kind == Type_Array) {
  5240. n = elem->Array.count+1;
  5241. } else {
  5242. GB_PANIC("Unreachable");
  5243. }
  5244. if (is_ptr) {
  5245. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  5246. return lb_emit_load(p, v);
  5247. }
  5248. return lb_emit_struct_ev(p, value, cast(i32)n);
  5249. }
  5250. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  5251. ast_node(ce, CallExpr, expr);
  5252. switch (id) {
  5253. case BuiltinProc_DIRECTIVE: {
  5254. ast_node(bd, BasicDirective, ce->proc);
  5255. String name = bd->name;
  5256. GB_ASSERT(name == "location");
  5257. String procedure = p->entity->token.string;
  5258. TokenPos pos = ast_token(ce->proc).pos;
  5259. if (ce->args.count > 0) {
  5260. Ast *ident = unselector_expr(ce->args[0]);
  5261. GB_ASSERT(ident->kind == Ast_Ident);
  5262. Entity *e = entity_of_ident(ident);
  5263. GB_ASSERT(e != nullptr);
  5264. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  5265. procedure = e->parent_proc_decl->entity->token.string;
  5266. } else {
  5267. procedure = str_lit("");
  5268. }
  5269. pos = e->token.pos;
  5270. }
  5271. return lb_emit_source_code_location(p, procedure, pos);
  5272. }
  5273. case BuiltinProc_type_info_of: {
  5274. Ast *arg = ce->args[0];
  5275. TypeAndValue tav = type_and_value_of_expr(arg);
  5276. if (tav.mode == Addressing_Type) {
  5277. Type *t = default_type(type_of_expr(arg));
  5278. return lb_type_info(p->module, t);
  5279. }
  5280. GB_ASSERT(is_type_typeid(tav.type));
  5281. auto args = array_make<lbValue>(heap_allocator(), 1);
  5282. args[0] = lb_build_expr(p, arg);
  5283. return lb_emit_runtime_call(p, "__type_info_of", args);
  5284. }
  5285. case BuiltinProc_typeid_of: {
  5286. Ast *arg = ce->args[0];
  5287. TypeAndValue tav = type_and_value_of_expr(arg);
  5288. if (tav.mode == Addressing_Type) {
  5289. Type *t = default_type(type_of_expr(arg));
  5290. return lb_typeid(p->module, t);
  5291. }
  5292. Type *t = base_type(tav.type);
  5293. GB_ASSERT(are_types_identical(t, t_type_info_ptr));
  5294. auto args = array_make<lbValue>(heap_allocator(), 1);
  5295. args[0] = lb_emit_conv(p, lb_build_expr(p, arg), t_type_info_ptr);
  5296. return lb_emit_runtime_call(p, "__typeid_of", args);
  5297. }
  5298. case BuiltinProc_len: {
  5299. lbValue v = lb_build_expr(p, ce->args[0]);
  5300. Type *t = base_type(v.type);
  5301. if (is_type_pointer(t)) {
  5302. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5303. v = lb_emit_load(p, v);
  5304. t = type_deref(t);
  5305. }
  5306. if (is_type_cstring(t)) {
  5307. return lb_cstring_len(p, v);
  5308. } else if (is_type_string(t)) {
  5309. return lb_string_len(p, v);
  5310. } else if (is_type_array(t)) {
  5311. GB_PANIC("Array lengths are constant");
  5312. } else if (is_type_slice(t)) {
  5313. return lb_slice_len(p, v);
  5314. } else if (is_type_dynamic_array(t)) {
  5315. return lb_dynamic_array_len(p, v);
  5316. } else if (is_type_map(t)) {
  5317. return lb_map_len(p, v);
  5318. } else if (is_type_soa_struct(t)) {
  5319. return lb_soa_struct_len(p, v);
  5320. }
  5321. GB_PANIC("Unreachable");
  5322. break;
  5323. }
  5324. case BuiltinProc_cap: {
  5325. lbValue v = lb_build_expr(p, ce->args[0]);
  5326. Type *t = base_type(v.type);
  5327. if (is_type_pointer(t)) {
  5328. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5329. v = lb_emit_load(p, v);
  5330. t = type_deref(t);
  5331. }
  5332. if (is_type_string(t)) {
  5333. GB_PANIC("Unreachable");
  5334. } else if (is_type_array(t)) {
  5335. GB_PANIC("Array lengths are constant");
  5336. } else if (is_type_slice(t)) {
  5337. return lb_slice_len(p, v);
  5338. } else if (is_type_dynamic_array(t)) {
  5339. return lb_dynamic_array_cap(p, v);
  5340. } else if (is_type_map(t)) {
  5341. return lb_map_cap(p, v);
  5342. } else if (is_type_soa_struct(t)) {
  5343. return lb_soa_struct_cap(p, v);
  5344. }
  5345. GB_PANIC("Unreachable");
  5346. break;
  5347. }
  5348. case BuiltinProc_swizzle: {
  5349. lbAddr addr = lb_build_addr(p, ce->args[0]);
  5350. isize index_count = ce->args.count-1;
  5351. if (index_count == 0) {
  5352. return lb_addr_load(p, addr);
  5353. }
  5354. lbValue src = lb_addr_get_ptr(p, addr);
  5355. // TODO(bill): Should this be zeroed or not?
  5356. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  5357. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  5358. for (i32 i = 1; i < ce->args.count; i++) {
  5359. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  5360. GB_ASSERT(is_type_integer(tv.type));
  5361. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  5362. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  5363. i32 dst_index = i-1;
  5364. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  5365. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  5366. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  5367. }
  5368. return lb_addr_load(p, dst);
  5369. }
  5370. case BuiltinProc_complex: {
  5371. lbValue real = lb_build_expr(p, ce->args[0]);
  5372. lbValue imag = lb_build_expr(p, ce->args[1]);
  5373. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  5374. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  5375. Type *ft = base_complex_elem_type(tv.type);
  5376. real = lb_emit_conv(p, real, ft);
  5377. imag = lb_emit_conv(p, imag, ft);
  5378. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  5379. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  5380. return lb_emit_load(p, dst);
  5381. }
  5382. case BuiltinProc_quaternion: {
  5383. lbValue real = lb_build_expr(p, ce->args[0]);
  5384. lbValue imag = lb_build_expr(p, ce->args[1]);
  5385. lbValue jmag = lb_build_expr(p, ce->args[2]);
  5386. lbValue kmag = lb_build_expr(p, ce->args[3]);
  5387. // @QuaternionLayout
  5388. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  5389. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  5390. Type *ft = base_complex_elem_type(tv.type);
  5391. real = lb_emit_conv(p, real, ft);
  5392. imag = lb_emit_conv(p, imag, ft);
  5393. jmag = lb_emit_conv(p, jmag, ft);
  5394. kmag = lb_emit_conv(p, kmag, ft);
  5395. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  5396. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  5397. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  5398. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  5399. return lb_emit_load(p, dst);
  5400. }
  5401. case BuiltinProc_real: {
  5402. lbValue val = lb_build_expr(p, ce->args[0]);
  5403. if (is_type_complex(val.type)) {
  5404. lbValue real = lb_emit_struct_ev(p, val, 0);
  5405. return lb_emit_conv(p, real, tv.type);
  5406. } else if (is_type_quaternion(val.type)) {
  5407. // @QuaternionLayout
  5408. lbValue real = lb_emit_struct_ev(p, val, 3);
  5409. return lb_emit_conv(p, real, tv.type);
  5410. }
  5411. GB_PANIC("invalid type for real");
  5412. return {};
  5413. }
  5414. case BuiltinProc_imag: {
  5415. lbValue val = lb_build_expr(p, ce->args[0]);
  5416. if (is_type_complex(val.type)) {
  5417. lbValue imag = lb_emit_struct_ev(p, val, 1);
  5418. return lb_emit_conv(p, imag, tv.type);
  5419. } else if (is_type_quaternion(val.type)) {
  5420. // @QuaternionLayout
  5421. lbValue imag = lb_emit_struct_ev(p, val, 0);
  5422. return lb_emit_conv(p, imag, tv.type);
  5423. }
  5424. GB_PANIC("invalid type for imag");
  5425. return {};
  5426. }
  5427. case BuiltinProc_jmag: {
  5428. lbValue val = lb_build_expr(p, ce->args[0]);
  5429. if (is_type_quaternion(val.type)) {
  5430. // @QuaternionLayout
  5431. lbValue imag = lb_emit_struct_ev(p, val, 1);
  5432. return lb_emit_conv(p, imag, tv.type);
  5433. }
  5434. GB_PANIC("invalid type for jmag");
  5435. return {};
  5436. }
  5437. case BuiltinProc_kmag: {
  5438. lbValue val = lb_build_expr(p, ce->args[0]);
  5439. if (is_type_quaternion(val.type)) {
  5440. // @QuaternionLayout
  5441. lbValue imag = lb_emit_struct_ev(p, val, 2);
  5442. return lb_emit_conv(p, imag, tv.type);
  5443. }
  5444. GB_PANIC("invalid type for kmag");
  5445. return {};
  5446. }
  5447. case BuiltinProc_conj: {
  5448. lbValue val = lb_build_expr(p, ce->args[0]);
  5449. lbValue res = {};
  5450. Type *t = val.type;
  5451. if (is_type_complex(t)) {
  5452. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  5453. lbValue real = lb_emit_struct_ev(p, val, 0);
  5454. lbValue imag = lb_emit_struct_ev(p, val, 1);
  5455. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  5456. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  5457. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  5458. } else if (is_type_quaternion(t)) {
  5459. // @QuaternionLayout
  5460. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  5461. lbValue real = lb_emit_struct_ev(p, val, 3);
  5462. lbValue imag = lb_emit_struct_ev(p, val, 0);
  5463. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  5464. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  5465. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  5466. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  5467. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  5468. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  5469. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  5470. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  5471. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  5472. }
  5473. return lb_emit_load(p, res);
  5474. }
  5475. case BuiltinProc_expand_to_tuple: {
  5476. lbValue val = lb_build_expr(p, ce->args[0]);
  5477. Type *t = base_type(val.type);
  5478. if (!is_type_tuple(tv.type)) {
  5479. if (t->kind == Type_Struct) {
  5480. GB_ASSERT(t->Struct.fields.count == 1);
  5481. return lb_emit_struct_ev(p, val, 0);
  5482. } else if (t->kind == Type_Array) {
  5483. GB_ASSERT(t->Array.count == 1);
  5484. return lb_emit_array_epi(p, val, 0);
  5485. } else {
  5486. GB_PANIC("Unknown type of expand_to_tuple");
  5487. }
  5488. }
  5489. GB_ASSERT(is_type_tuple(tv.type));
  5490. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5491. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  5492. if (t->kind == Type_Struct) {
  5493. for_array(src_index, t->Struct.fields) {
  5494. Entity *field = t->Struct.fields[src_index];
  5495. i32 field_index = field->Variable.field_index;
  5496. lbValue f = lb_emit_struct_ev(p, val, field_index);
  5497. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  5498. lb_emit_store(p, ep, f);
  5499. }
  5500. } else if (t->kind == Type_Array) {
  5501. // TODO(bill): Clean-up this code
  5502. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  5503. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  5504. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  5505. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  5506. lb_emit_store(p, ep, f);
  5507. }
  5508. } else {
  5509. GB_PANIC("Unknown type of expand_to_tuple");
  5510. }
  5511. return lb_emit_load(p, tuple);
  5512. }
  5513. case BuiltinProc_min: {
  5514. Type *t = type_of_expr(expr);
  5515. if (ce->args.count == 2) {
  5516. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  5517. } else {
  5518. lbValue x = lb_build_expr(p, ce->args[0]);
  5519. for (isize i = 1; i < ce->args.count; i++) {
  5520. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  5521. }
  5522. return x;
  5523. }
  5524. }
  5525. case BuiltinProc_max: {
  5526. Type *t = type_of_expr(expr);
  5527. if (ce->args.count == 2) {
  5528. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  5529. } else {
  5530. lbValue x = lb_build_expr(p, ce->args[0]);
  5531. for (isize i = 1; i < ce->args.count; i++) {
  5532. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  5533. }
  5534. return x;
  5535. }
  5536. }
  5537. case BuiltinProc_abs: {
  5538. gbAllocator a = heap_allocator();
  5539. lbValue x = lb_build_expr(p, ce->args[0]);
  5540. Type *t = x.type;
  5541. if (is_type_unsigned(t)) {
  5542. return x;
  5543. }
  5544. if (is_type_quaternion(t)) {
  5545. i64 sz = 8*type_size_of(t);
  5546. auto args = array_make<lbValue>(heap_allocator(), 1);
  5547. args[0] = x;
  5548. switch (sz) {
  5549. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  5550. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  5551. }
  5552. GB_PANIC("Unknown complex type");
  5553. } else if (is_type_complex(t)) {
  5554. i64 sz = 8*type_size_of(t);
  5555. auto args = array_make<lbValue>(heap_allocator(), 1);
  5556. args[0] = x;
  5557. switch (sz) {
  5558. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  5559. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  5560. }
  5561. GB_PANIC("Unknown complex type");
  5562. } else if (is_type_float(t)) {
  5563. i64 sz = 8*type_size_of(t);
  5564. auto args = array_make<lbValue>(heap_allocator(), 1);
  5565. args[0] = x;
  5566. switch (sz) {
  5567. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  5568. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  5569. }
  5570. GB_PANIC("Unknown float type");
  5571. }
  5572. lbValue zero = lb_const_nil(p->module, t);
  5573. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  5574. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  5575. return lb_emit_select(p, cond, neg, x);
  5576. }
  5577. case BuiltinProc_clamp:
  5578. return lb_emit_clamp(p, type_of_expr(expr),
  5579. lb_build_expr(p, ce->args[0]),
  5580. lb_build_expr(p, ce->args[1]),
  5581. lb_build_expr(p, ce->args[2]));
  5582. // "Intrinsics"
  5583. case BuiltinProc_cpu_relax:
  5584. // TODO(bill): BuiltinProc_cpu_relax
  5585. // ir_write_str_lit(f, "call void asm sideeffect \"pause\", \"\"()");
  5586. return {};
  5587. case BuiltinProc_atomic_fence:
  5588. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  5589. return {};
  5590. case BuiltinProc_atomic_fence_acq:
  5591. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  5592. return {};
  5593. case BuiltinProc_atomic_fence_rel:
  5594. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  5595. return {};
  5596. case BuiltinProc_atomic_fence_acqrel:
  5597. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  5598. return {};
  5599. case BuiltinProc_atomic_store:
  5600. case BuiltinProc_atomic_store_rel:
  5601. case BuiltinProc_atomic_store_relaxed:
  5602. case BuiltinProc_atomic_store_unordered: {
  5603. lbValue dst = lb_build_expr(p, ce->args[0]);
  5604. lbValue val = lb_build_expr(p, ce->args[1]);
  5605. val = lb_emit_conv(p, val, type_deref(dst.type));
  5606. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  5607. switch (id) {
  5608. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  5609. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  5610. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  5611. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  5612. }
  5613. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  5614. return {};
  5615. }
  5616. case BuiltinProc_atomic_load:
  5617. case BuiltinProc_atomic_load_acq:
  5618. case BuiltinProc_atomic_load_relaxed:
  5619. case BuiltinProc_atomic_load_unordered: {
  5620. lbValue dst = lb_build_expr(p, ce->args[0]);
  5621. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  5622. switch (id) {
  5623. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  5624. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  5625. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  5626. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  5627. }
  5628. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  5629. lbValue res = {};
  5630. res.value = instr;
  5631. res.type = type_deref(dst.type);
  5632. return res;
  5633. }
  5634. case BuiltinProc_atomic_add:
  5635. case BuiltinProc_atomic_add_acq:
  5636. case BuiltinProc_atomic_add_rel:
  5637. case BuiltinProc_atomic_add_acqrel:
  5638. case BuiltinProc_atomic_add_relaxed:
  5639. case BuiltinProc_atomic_sub:
  5640. case BuiltinProc_atomic_sub_acq:
  5641. case BuiltinProc_atomic_sub_rel:
  5642. case BuiltinProc_atomic_sub_acqrel:
  5643. case BuiltinProc_atomic_sub_relaxed:
  5644. case BuiltinProc_atomic_and:
  5645. case BuiltinProc_atomic_and_acq:
  5646. case BuiltinProc_atomic_and_rel:
  5647. case BuiltinProc_atomic_and_acqrel:
  5648. case BuiltinProc_atomic_and_relaxed:
  5649. case BuiltinProc_atomic_nand:
  5650. case BuiltinProc_atomic_nand_acq:
  5651. case BuiltinProc_atomic_nand_rel:
  5652. case BuiltinProc_atomic_nand_acqrel:
  5653. case BuiltinProc_atomic_nand_relaxed:
  5654. case BuiltinProc_atomic_or:
  5655. case BuiltinProc_atomic_or_acq:
  5656. case BuiltinProc_atomic_or_rel:
  5657. case BuiltinProc_atomic_or_acqrel:
  5658. case BuiltinProc_atomic_or_relaxed:
  5659. case BuiltinProc_atomic_xor:
  5660. case BuiltinProc_atomic_xor_acq:
  5661. case BuiltinProc_atomic_xor_rel:
  5662. case BuiltinProc_atomic_xor_acqrel:
  5663. case BuiltinProc_atomic_xor_relaxed:
  5664. case BuiltinProc_atomic_xchg:
  5665. case BuiltinProc_atomic_xchg_acq:
  5666. case BuiltinProc_atomic_xchg_rel:
  5667. case BuiltinProc_atomic_xchg_acqrel:
  5668. case BuiltinProc_atomic_xchg_relaxed: {
  5669. lbValue dst = lb_build_expr(p, ce->args[0]);
  5670. lbValue val = lb_build_expr(p, ce->args[1]);
  5671. val = lb_emit_conv(p, val, type_deref(dst.type));
  5672. LLVMAtomicRMWBinOp op = {};
  5673. LLVMAtomicOrdering ordering = {};
  5674. switch (id) {
  5675. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5676. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  5677. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  5678. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5679. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  5680. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5681. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  5682. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  5683. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5684. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  5685. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5686. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  5687. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  5688. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5689. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  5690. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5691. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  5692. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  5693. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5694. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  5695. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5696. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  5697. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  5698. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5699. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  5700. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5701. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  5702. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  5703. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5704. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  5705. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5706. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  5707. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  5708. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5709. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  5710. }
  5711. LLVMValueRef instr = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  5712. return {};
  5713. }
  5714. case BuiltinProc_atomic_cxchg:
  5715. case BuiltinProc_atomic_cxchg_acq:
  5716. case BuiltinProc_atomic_cxchg_rel:
  5717. case BuiltinProc_atomic_cxchg_acqrel:
  5718. case BuiltinProc_atomic_cxchg_relaxed:
  5719. case BuiltinProc_atomic_cxchg_failrelaxed:
  5720. case BuiltinProc_atomic_cxchg_failacq:
  5721. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  5722. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  5723. case BuiltinProc_atomic_cxchgweak:
  5724. case BuiltinProc_atomic_cxchgweak_acq:
  5725. case BuiltinProc_atomic_cxchgweak_rel:
  5726. case BuiltinProc_atomic_cxchgweak_acqrel:
  5727. case BuiltinProc_atomic_cxchgweak_relaxed:
  5728. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  5729. case BuiltinProc_atomic_cxchgweak_failacq:
  5730. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  5731. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  5732. Type *type = expr->tav.type;
  5733. lbValue address = lb_build_expr(p, ce->args[0]);
  5734. Type *elem = type_deref(address.type);
  5735. lbValue old_value = lb_build_expr(p, ce->args[1]);
  5736. lbValue new_value = lb_build_expr(p, ce->args[2]);
  5737. old_value = lb_emit_conv(p, old_value, elem);
  5738. new_value = lb_emit_conv(p, new_value, elem);
  5739. LLVMAtomicOrdering success_ordering = {};
  5740. LLVMAtomicOrdering failure_ordering = {};
  5741. LLVMBool weak = false;
  5742. switch (id) {
  5743. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5744. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5745. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5746. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5747. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  5748. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  5749. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  5750. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  5751. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  5752. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5753. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  5754. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  5755. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  5756. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  5757. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  5758. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  5759. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  5760. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  5761. }
  5762. // TODO(bill): Figure out how to make it weak
  5763. LLVMBool single_threaded = !weak;
  5764. LLVMValueRef instr = LLVMBuildAtomicCmpXchg(p->builder, address.value,
  5765. old_value.value, new_value.value,
  5766. success_ordering,
  5767. failure_ordering,
  5768. single_threaded);
  5769. return {};
  5770. }
  5771. }
  5772. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  5773. return {};
  5774. }
  5775. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  5776. lbModule *m = p->module;
  5777. TypeAndValue tv = type_and_value_of_expr(expr);
  5778. ast_node(ce, CallExpr, expr);
  5779. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  5780. AddressingMode proc_mode = proc_tv.mode;
  5781. if (proc_mode == Addressing_Type) {
  5782. GB_ASSERT(ce->args.count == 1);
  5783. lbValue x = lb_build_expr(p, ce->args[0]);
  5784. lbValue y = lb_emit_conv(p, x, tv.type);
  5785. return y;
  5786. }
  5787. Ast *pexpr = unparen_expr(ce->proc);
  5788. if (proc_mode == Addressing_Builtin) {
  5789. Entity *e = entity_of_node(pexpr);
  5790. BuiltinProcId id = BuiltinProc_Invalid;
  5791. if (e != nullptr) {
  5792. id = cast(BuiltinProcId)e->Builtin.id;
  5793. } else {
  5794. id = BuiltinProc_DIRECTIVE;
  5795. }
  5796. return lb_build_builtin_proc(p, expr, tv, id);
  5797. }
  5798. // NOTE(bill): Regular call
  5799. lbValue value = {};
  5800. Ast *proc_expr = unparen_expr(ce->proc);
  5801. if (proc_expr->tav.mode == Addressing_Constant) {
  5802. ExactValue v = proc_expr->tav.value;
  5803. switch (v.kind) {
  5804. case ExactValue_Integer:
  5805. {
  5806. u64 u = big_int_to_u64(&v.value_integer);
  5807. lbValue x = {};
  5808. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  5809. x.type = t_uintptr;
  5810. x = lb_emit_conv(p, x, t_rawptr);
  5811. value = lb_emit_conv(p, x, proc_expr->tav.type);
  5812. break;
  5813. }
  5814. case ExactValue_Pointer:
  5815. {
  5816. u64 u = cast(u64)v.value_pointer;
  5817. lbValue x = {};
  5818. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  5819. x.type = t_uintptr;
  5820. x = lb_emit_conv(p, x, t_rawptr);
  5821. value = lb_emit_conv(p, x, proc_expr->tav.type);
  5822. break;
  5823. }
  5824. }
  5825. }
  5826. if (value.value == nullptr) {
  5827. value = lb_build_expr(p, proc_expr);
  5828. }
  5829. GB_ASSERT(value.value != nullptr);
  5830. Type *proc_type_ = base_type(value.type);
  5831. GB_ASSERT(proc_type_->kind == Type_Proc);
  5832. TypeProc *pt = &proc_type_->Proc;
  5833. set_procedure_abi_types(heap_allocator(), proc_type_);
  5834. if (is_call_expr_field_value(ce)) {
  5835. auto args = array_make<lbValue>(heap_allocator(), pt->param_count);
  5836. for_array(arg_index, ce->args) {
  5837. Ast *arg = ce->args[arg_index];
  5838. ast_node(fv, FieldValue, arg);
  5839. GB_ASSERT(fv->field->kind == Ast_Ident);
  5840. String name = fv->field->Ident.token.string;
  5841. isize index = lookup_procedure_parameter(pt, name);
  5842. GB_ASSERT(index >= 0);
  5843. TypeAndValue tav = type_and_value_of_expr(fv->value);
  5844. if (tav.mode == Addressing_Type) {
  5845. args[index] = lb_const_nil(m, tav.type);
  5846. } else {
  5847. args[index] = lb_build_expr(p, fv->value);
  5848. }
  5849. }
  5850. TypeTuple *params = &pt->params->Tuple;
  5851. for (isize i = 0; i < args.count; i++) {
  5852. Entity *e = params->variables[i];
  5853. if (e->kind == Entity_TypeName) {
  5854. args[i] = lb_const_nil(m, e->type);
  5855. } else if (e->kind == Entity_Constant) {
  5856. continue;
  5857. } else {
  5858. GB_ASSERT(e->kind == Entity_Variable);
  5859. if (args[i].value == nullptr) {
  5860. switch (e->Variable.param_value.kind) {
  5861. case ParameterValue_Constant:
  5862. args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  5863. break;
  5864. case ParameterValue_Nil:
  5865. args[i] = lb_const_nil(m, e->type);
  5866. break;
  5867. case ParameterValue_Location:
  5868. args[i] = lb_emit_source_code_location(p, p->entity->token.string, ast_token(expr).pos);
  5869. break;
  5870. case ParameterValue_Value:
  5871. args[i] = lb_build_expr(p, e->Variable.param_value.ast_value);
  5872. break;
  5873. }
  5874. } else {
  5875. args[i] = lb_emit_conv(p, args[i], e->type);
  5876. }
  5877. }
  5878. }
  5879. for (isize i = 0; i < args.count; i++) {
  5880. Entity *e = params->variables[i];
  5881. if (args[i].type == nullptr) {
  5882. continue;
  5883. } else if (is_type_untyped_nil(args[i].type)) {
  5884. args[i] = lb_const_nil(m, e->type);
  5885. } else if (is_type_untyped_undef(args[i].type)) {
  5886. args[i] = lb_const_undef(m, e->type);
  5887. }
  5888. }
  5889. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  5890. }
  5891. isize arg_index = 0;
  5892. isize arg_count = 0;
  5893. for_array(i, ce->args) {
  5894. Ast *arg = ce->args[i];
  5895. TypeAndValue tav = type_and_value_of_expr(arg);
  5896. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  5897. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  5898. Type *at = tav.type;
  5899. if (at->kind == Type_Tuple) {
  5900. arg_count += at->Tuple.variables.count;
  5901. } else {
  5902. arg_count++;
  5903. }
  5904. }
  5905. isize param_count = 0;
  5906. if (pt->params) {
  5907. GB_ASSERT(pt->params->kind == Type_Tuple);
  5908. param_count = pt->params->Tuple.variables.count;
  5909. }
  5910. auto args = array_make<lbValue>(heap_allocator(), cast(isize)gb_max(param_count, arg_count));
  5911. isize variadic_index = pt->variadic_index;
  5912. bool variadic = pt->variadic && variadic_index >= 0;
  5913. bool vari_expand = ce->ellipsis.pos.line != 0;
  5914. bool is_c_vararg = pt->c_vararg;
  5915. String proc_name = {};
  5916. if (p->entity != nullptr) {
  5917. proc_name = p->entity->token.string;
  5918. }
  5919. TokenPos pos = ast_token(ce->proc).pos;
  5920. TypeTuple *param_tuple = nullptr;
  5921. if (pt->params) {
  5922. GB_ASSERT(pt->params->kind == Type_Tuple);
  5923. param_tuple = &pt->params->Tuple;
  5924. }
  5925. for_array(i, ce->args) {
  5926. Ast *arg = ce->args[i];
  5927. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  5928. if (arg_tv.mode == Addressing_Type) {
  5929. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  5930. } else {
  5931. lbValue a = lb_build_expr(p, arg);
  5932. Type *at = a.type;
  5933. if (at->kind == Type_Tuple) {
  5934. for_array(i, at->Tuple.variables) {
  5935. Entity *e = at->Tuple.variables[i];
  5936. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  5937. args[arg_index++] = v;
  5938. }
  5939. } else {
  5940. args[arg_index++] = a;
  5941. }
  5942. }
  5943. }
  5944. if (param_count > 0) {
  5945. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  5946. GB_ASSERT(param_count < 1000000);
  5947. if (arg_count < param_count) {
  5948. isize end = cast(isize)param_count;
  5949. if (variadic) {
  5950. end = variadic_index;
  5951. }
  5952. while (arg_index < end) {
  5953. Entity *e = param_tuple->variables[arg_index];
  5954. GB_ASSERT(e->kind == Entity_Variable);
  5955. switch (e->Variable.param_value.kind) {
  5956. case ParameterValue_Constant:
  5957. args[arg_index++] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  5958. break;
  5959. case ParameterValue_Nil:
  5960. args[arg_index++] = lb_const_nil(m, e->type);
  5961. break;
  5962. case ParameterValue_Location:
  5963. args[arg_index++] = lb_emit_source_code_location(p, proc_name, pos);
  5964. break;
  5965. case ParameterValue_Value:
  5966. args[arg_index++] = lb_build_expr(p, e->Variable.param_value.ast_value);
  5967. break;
  5968. }
  5969. }
  5970. }
  5971. if (is_c_vararg) {
  5972. GB_ASSERT(variadic);
  5973. GB_ASSERT(!vari_expand);
  5974. isize i = 0;
  5975. for (; i < variadic_index; i++) {
  5976. Entity *e = param_tuple->variables[i];
  5977. if (e->kind == Entity_Variable) {
  5978. args[i] = lb_emit_conv(p, args[i], e->type);
  5979. }
  5980. }
  5981. Type *variadic_type = param_tuple->variables[i]->type;
  5982. GB_ASSERT(is_type_slice(variadic_type));
  5983. variadic_type = base_type(variadic_type)->Slice.elem;
  5984. if (!is_type_any(variadic_type)) {
  5985. for (; i < arg_count; i++) {
  5986. args[i] = lb_emit_conv(p, args[i], variadic_type);
  5987. }
  5988. } else {
  5989. for (; i < arg_count; i++) {
  5990. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  5991. }
  5992. }
  5993. } else if (variadic) {
  5994. isize i = 0;
  5995. for (; i < variadic_index; i++) {
  5996. Entity *e = param_tuple->variables[i];
  5997. if (e->kind == Entity_Variable) {
  5998. args[i] = lb_emit_conv(p, args[i], e->type);
  5999. }
  6000. }
  6001. if (!vari_expand) {
  6002. Type *variadic_type = param_tuple->variables[i]->type;
  6003. GB_ASSERT(is_type_slice(variadic_type));
  6004. variadic_type = base_type(variadic_type)->Slice.elem;
  6005. for (; i < arg_count; i++) {
  6006. args[i] = lb_emit_conv(p, args[i], variadic_type);
  6007. }
  6008. }
  6009. } else {
  6010. for (isize i = 0; i < param_count; i++) {
  6011. Entity *e = param_tuple->variables[i];
  6012. if (e->kind == Entity_Variable) {
  6013. if (args[i].value == nullptr) {
  6014. continue;
  6015. }
  6016. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  6017. args[i] = lb_emit_conv(p, args[i], e->type);
  6018. }
  6019. }
  6020. }
  6021. if (variadic && !vari_expand && !is_c_vararg) {
  6022. // variadic call argument generation
  6023. gbAllocator allocator = heap_allocator();
  6024. Type *slice_type = param_tuple->variables[variadic_index]->type;
  6025. Type *elem_type = base_type(slice_type)->Slice.elem;
  6026. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  6027. isize slice_len = arg_count+1 - (variadic_index+1);
  6028. if (slice_len > 0) {
  6029. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  6030. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  6031. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  6032. lb_emit_store(p, addr, args[i]);
  6033. }
  6034. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  6035. lbValue len = lb_const_int(m, t_int, slice_len);
  6036. lb_fill_slice(p, slice, base_elem, len);
  6037. }
  6038. arg_count = param_count;
  6039. args[variadic_index] = lb_addr_load(p, slice);
  6040. }
  6041. }
  6042. if (variadic && variadic_index+1 < param_count) {
  6043. for (isize i = variadic_index+1; i < param_count; i++) {
  6044. Entity *e = param_tuple->variables[i];
  6045. switch (e->Variable.param_value.kind) {
  6046. case ParameterValue_Constant:
  6047. args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  6048. break;
  6049. case ParameterValue_Nil:
  6050. args[i] = lb_const_nil(m, e->type);
  6051. break;
  6052. case ParameterValue_Location:
  6053. args[i] = lb_emit_source_code_location(p, proc_name, pos);
  6054. break;
  6055. case ParameterValue_Value:
  6056. args[i] = lb_build_expr(p, e->Variable.param_value.ast_value);
  6057. break;
  6058. }
  6059. }
  6060. }
  6061. isize final_count = param_count;
  6062. if (is_c_vararg) {
  6063. final_count = arg_count;
  6064. }
  6065. if (param_tuple != nullptr) {
  6066. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  6067. Entity *e = param_tuple->variables[i];
  6068. if (args[i].type == nullptr) {
  6069. continue;
  6070. } else if (is_type_untyped_nil(args[i].type)) {
  6071. args[i] = lb_const_nil(m, e->type);
  6072. } else if (is_type_untyped_undef(args[i].type)) {
  6073. args[i] = lb_const_undef(m, e->type);
  6074. }
  6075. }
  6076. }
  6077. auto call_args = array_slice(args, 0, final_count);
  6078. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  6079. }
  6080. bool lb_is_const(lbValue value) {
  6081. LLVMValueRef v = value.value;
  6082. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  6083. // TODO(bill): Is this correct behaviour?
  6084. return true;
  6085. }
  6086. if (LLVMIsConstant(v)) {
  6087. return true;
  6088. }
  6089. return false;
  6090. }
  6091. bool lb_is_const_nil(lbValue value) {
  6092. LLVMValueRef v = value.value;
  6093. if (LLVMIsConstant(v)) {
  6094. if (LLVMIsAConstantAggregateZero(v)) {
  6095. return true;
  6096. } else if (LLVMIsAConstantPointerNull(v)) {
  6097. return true;
  6098. }
  6099. }
  6100. return false;
  6101. }
  6102. String lb_get_const_string(lbModule *m, lbValue value) {
  6103. GB_ASSERT(lb_is_const(value));
  6104. Type *t = base_type(value.type);
  6105. GB_ASSERT(are_types_identical(t, t_string));
  6106. unsigned ptr_indices[1] = {0};
  6107. unsigned len_indices[1] = {1};
  6108. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  6109. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  6110. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  6111. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  6112. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  6113. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  6114. size_t length = 0;
  6115. char const *text = LLVMGetAsString(underlying_ptr, &length);
  6116. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  6117. return make_string(cast(u8 const *)text, real_length);
  6118. }
  6119. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  6120. GB_ASSERT(is_type_pointer(addr.type));
  6121. Type *type = type_deref(addr.type);
  6122. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  6123. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  6124. }
  6125. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  6126. Type *vt = core_type(value.type);
  6127. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  6128. GB_ASSERT(is_type_integer(vt));
  6129. // TODO(bill): lb_emit_byte_swap
  6130. lbValue res = {};
  6131. res.type = platform_type;
  6132. res.value = value.value;
  6133. // int sz = cast(int)type_size_of(vt);
  6134. // if (sz > 1) {
  6135. // char buf[32] = {};
  6136. // gb_snprintf(buf, gb_count_of(buf), "llvm.bswap.i%d", sz*8);
  6137. // unsigned id = LLVMLookupIntrinsicID(buf, gb_strlen(buf));
  6138. // gb_printf(">>> %s %u\n", buf, id);
  6139. // LLVMTypeRef types[2] = {};
  6140. // types[0] = lb_type(p->module, value.type);
  6141. // types[1] = lb_type(p->module, value.type);
  6142. // LLVMValueRef fn = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  6143. // res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  6144. // }
  6145. return res;
  6146. }
  6147. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  6148. lbLoopData data = {};
  6149. lbValue max = lb_const_int(p->module, t_int, count);
  6150. data.idx_addr = lb_add_local_generated(p, index_type, true);
  6151. data.body = lb_create_block(p, "loop.body");
  6152. data.done = lb_create_block(p, "loop.done");
  6153. data.loop = lb_create_block(p, "loop.loop");
  6154. lb_emit_jump(p, data.loop);
  6155. lb_start_block(p, data.loop);
  6156. data.idx = lb_addr_load(p, data.idx_addr);
  6157. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  6158. lb_emit_if(p, cond, data.body, data.done);
  6159. lb_start_block(p, data.body);
  6160. return data;
  6161. }
  6162. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  6163. if (data.idx_addr.addr.value != nullptr) {
  6164. lb_emit_increment(p, data.idx_addr.addr);
  6165. lb_emit_jump(p, data.loop);
  6166. lb_start_block(p, data.done);
  6167. }
  6168. }
  6169. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  6170. lbValue res = {};
  6171. res.type = t_llvm_bool;
  6172. Type *t = x.type;
  6173. if (is_type_pointer(t)) {
  6174. if (op_kind == Token_CmpEq) {
  6175. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  6176. } else if (op_kind == Token_NotEq) {
  6177. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  6178. }
  6179. return res;
  6180. } else if (is_type_cstring(t)) {
  6181. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  6182. if (op_kind == Token_CmpEq) {
  6183. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  6184. } else if (op_kind == Token_NotEq) {
  6185. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  6186. }
  6187. return res;
  6188. } else if (is_type_any(t)) {
  6189. lbValue data = lb_emit_struct_ev(p, x, 0);
  6190. lbValue ti = lb_emit_struct_ev(p, x, 1);
  6191. if (op_kind == Token_CmpEq) {
  6192. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  6193. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  6194. res.value = LLVMBuildOr(p->builder, a, b, "");
  6195. return res;
  6196. } else if (op_kind == Token_NotEq) {
  6197. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  6198. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  6199. res.value = LLVMBuildAnd(p->builder, a, b, "");
  6200. return res;
  6201. }
  6202. } else if (is_type_slice(t)) {
  6203. lbValue data = lb_emit_struct_ev(p, x, 0);
  6204. lbValue cap = lb_emit_struct_ev(p, x, 1);
  6205. if (op_kind == Token_CmpEq) {
  6206. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  6207. LLVMValueRef b = LLVMBuildIsNull(p->builder, cap.value, "");
  6208. res.value = LLVMBuildOr(p->builder, a, b, "");
  6209. return res;
  6210. } else if (op_kind == Token_NotEq) {
  6211. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  6212. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, cap.value, "");
  6213. res.value = LLVMBuildAnd(p->builder, a, b, "");
  6214. return res;
  6215. }
  6216. } else if (is_type_dynamic_array(t)) {
  6217. lbValue data = lb_emit_struct_ev(p, x, 0);
  6218. lbValue cap = lb_emit_struct_ev(p, x, 2);
  6219. if (op_kind == Token_CmpEq) {
  6220. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  6221. LLVMValueRef b = LLVMBuildIsNull(p->builder, cap.value, "");
  6222. res.value = LLVMBuildOr(p->builder, a, b, "");
  6223. return res;
  6224. } else if (op_kind == Token_NotEq) {
  6225. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  6226. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, cap.value, "");
  6227. res.value = LLVMBuildAnd(p->builder, a, b, "");
  6228. return res;
  6229. }
  6230. } else if (is_type_map(t)) {
  6231. lbValue cap = lb_map_cap(p, x);
  6232. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  6233. } else if (is_type_union(t)) {
  6234. if (type_size_of(t) == 0) {
  6235. if (op_kind == Token_CmpEq) {
  6236. return lb_const_bool(p->module, t_llvm_bool, true);
  6237. } else if (op_kind == Token_NotEq) {
  6238. return lb_const_bool(p->module, t_llvm_bool, false);
  6239. }
  6240. } else {
  6241. lbValue tag = lb_emit_union_tag_value(p, x);
  6242. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  6243. }
  6244. } else if (is_type_typeid(t)) {
  6245. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  6246. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  6247. } else if (is_type_bit_field(t)) {
  6248. auto args = array_make<lbValue>(heap_allocator(), 2);
  6249. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  6250. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  6251. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  6252. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  6253. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  6254. return res;
  6255. } else if (is_type_soa_struct(t)) {
  6256. GB_PANIC("#soa struct nil comparison");
  6257. // Type *bt = base_type(t);
  6258. // if (bt->Struct.soa_kind == StructSoa_Slice) {
  6259. // lbValue len = lb_soa_struct_len(p, x);
  6260. // if (bt->Struct.fields.count > 1) {
  6261. // lbValue data = lb_emit_struct_ev(p, x, 0);
  6262. // if (op_kind == Token_CmpEq) {
  6263. // lbValue a = lb_emit_comp(p, Token_CmpEq, data, v_raw_nil);
  6264. // lbValue b = lb_emit_comp(p, Token_CmpEq, len, v_zero);
  6265. // return lb_emit_arith(p, Token_Or, a, b, t_bool);
  6266. // } else if (op_kind == Token_NotEq) {
  6267. // lbValue a = lb_emit_comp(p, Token_NotEq, data, v_raw_nil);
  6268. // lbValue b = lb_emit_comp(p, Token_NotEq, len, v_zero);
  6269. // return lb_emit_arith(p, Token_And, a, b, t_bool);
  6270. // }
  6271. // } else {
  6272. // return lb_emit_comp(p, op_kind, len, v_zero);
  6273. // }
  6274. // } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  6275. // lbValue cap = lb_soa_struct_len(p, x);
  6276. // if (bt->Struct.fields.count > 1) {
  6277. // lbValue data = lb_emit_struct_ev(p, x, 0);
  6278. // if (op_kind == Token_CmpEq) {
  6279. // lbValue a = lb_emit_comp(p, Token_CmpEq, data, v_raw_nil);
  6280. // lbValue b = lb_emit_comp(p, Token_CmpEq, cap, v_zero);
  6281. // return lb_emit_arith(p, Token_Or, a, b, t_bool);
  6282. // } else if (op_kind == Token_NotEq) {
  6283. // lbValue a = lb_emit_comp(p, Token_NotEq, data, v_raw_nil);
  6284. // lbValue b = lb_emit_comp(p, Token_NotEq, cap, v_zero);
  6285. // return lb_emit_arith(p, Token_And, a, b, t_bool);
  6286. // }
  6287. // } else {
  6288. // return lb_emit_comp(p, op_kind, cap, v_zero);
  6289. // }
  6290. // }
  6291. }
  6292. return {};
  6293. }
  6294. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  6295. Type *a = base_type(left.type);
  6296. Type *b = base_type(right.type);
  6297. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  6298. lbValue nil_check = {};
  6299. if (is_type_untyped_nil(left.type)) {
  6300. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  6301. } else if (is_type_untyped_nil(right.type)) {
  6302. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  6303. }
  6304. if (nil_check.value != nullptr) {
  6305. return nil_check;
  6306. }
  6307. if (are_types_identical(a, b)) {
  6308. // NOTE(bill): No need for a conversion
  6309. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  6310. left = lb_emit_conv(p, left, right.type);
  6311. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  6312. right = lb_emit_conv(p, right, left.type);
  6313. } else {
  6314. gbAllocator a = heap_allocator();
  6315. Type *lt = left.type;
  6316. Type *rt = right.type;
  6317. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  6318. Type *blt = base_type(lt);
  6319. Type *brt = base_type(rt);
  6320. GB_ASSERT(is_type_bit_field_value(blt));
  6321. GB_ASSERT(is_type_bit_field_value(brt));
  6322. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  6323. i64 bytes = bits / 8;
  6324. switch (bytes) {
  6325. case 1:
  6326. left = lb_emit_conv(p, left, t_u8);
  6327. right = lb_emit_conv(p, right, t_u8);
  6328. break;
  6329. case 2:
  6330. left = lb_emit_conv(p, left, t_u16);
  6331. right = lb_emit_conv(p, right, t_u16);
  6332. break;
  6333. case 4:
  6334. left = lb_emit_conv(p, left, t_u32);
  6335. right = lb_emit_conv(p, right, t_u32);
  6336. break;
  6337. case 8:
  6338. left = lb_emit_conv(p, left, t_u64);
  6339. right = lb_emit_conv(p, right, t_u64);
  6340. break;
  6341. default: GB_PANIC("Unknown integer size"); break;
  6342. }
  6343. }
  6344. lt = left.type;
  6345. rt = right.type;
  6346. i64 ls = type_size_of(lt);
  6347. i64 rs = type_size_of(rt);
  6348. if (ls < rs) {
  6349. left = lb_emit_conv(p, left, rt);
  6350. } else if (ls > rs) {
  6351. right = lb_emit_conv(p, right, lt);
  6352. } else {
  6353. right = lb_emit_conv(p, right, lt);
  6354. }
  6355. }
  6356. if (is_type_array(a)) {
  6357. Type *tl = base_type(a);
  6358. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  6359. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  6360. TokenKind cmp_op = Token_And;
  6361. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  6362. if (op_kind == Token_NotEq) {
  6363. res = lb_const_bool(p->module, t_llvm_bool, false);
  6364. cmp_op = Token_Or;
  6365. } else if (op_kind == Token_CmpEq) {
  6366. res = lb_const_bool(p->module, t_llvm_bool, true);
  6367. cmp_op = Token_And;
  6368. }
  6369. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  6370. i32 count = cast(i32)tl->Array.count;
  6371. if (inline_array_arith) {
  6372. // inline
  6373. lbAddr val = lb_add_local_generated(p, t_bool, false);
  6374. lb_addr_store(p, val, res);
  6375. for (i32 i = 0; i < count; i++) {
  6376. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  6377. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  6378. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  6379. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  6380. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  6381. }
  6382. return lb_addr_load(p, val);
  6383. } else {
  6384. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  6385. // TODO(bill): Test to see if this is actually faster!!!!
  6386. auto args = array_make<lbValue>(heap_allocator(), 3);
  6387. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  6388. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  6389. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  6390. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  6391. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  6392. return lb_emit_conv(p, res, t_bool);
  6393. } else {
  6394. lbAddr val = lb_add_local_generated(p, t_bool, false);
  6395. lb_addr_store(p, val, res);
  6396. auto loop_data = lb_loop_start(p, count, t_i32);
  6397. {
  6398. lbValue i = loop_data.idx;
  6399. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  6400. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  6401. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  6402. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  6403. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  6404. }
  6405. lb_loop_end(p, loop_data);
  6406. return lb_addr_load(p, val);
  6407. }
  6408. }
  6409. }
  6410. if (is_type_string(a)) {
  6411. if (is_type_cstring(a)) {
  6412. left = lb_emit_conv(p, left, t_string);
  6413. right = lb_emit_conv(p, right, t_string);
  6414. }
  6415. char const *runtime_procedure = nullptr;
  6416. switch (op_kind) {
  6417. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  6418. case Token_NotEq: runtime_procedure = "string_ne"; break;
  6419. case Token_Lt: runtime_procedure = "string_lt"; break;
  6420. case Token_Gt: runtime_procedure = "string_gt"; break;
  6421. case Token_LtEq: runtime_procedure = "string_le"; break;
  6422. case Token_GtEq: runtime_procedure = "string_gt"; break;
  6423. }
  6424. GB_ASSERT(runtime_procedure != nullptr);
  6425. auto args = array_make<lbValue>(heap_allocator(), 2);
  6426. args[0] = left;
  6427. args[1] = right;
  6428. return lb_emit_runtime_call(p, runtime_procedure, args);
  6429. }
  6430. if (is_type_complex(a)) {
  6431. char const *runtime_procedure = "";
  6432. i64 sz = 8*type_size_of(a);
  6433. switch (sz) {
  6434. case 64:
  6435. switch (op_kind) {
  6436. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  6437. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  6438. }
  6439. break;
  6440. case 128:
  6441. switch (op_kind) {
  6442. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  6443. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  6444. }
  6445. break;
  6446. }
  6447. GB_ASSERT(runtime_procedure != nullptr);
  6448. auto args = array_make<lbValue>(heap_allocator(), 2);
  6449. args[0] = left;
  6450. args[1] = right;
  6451. return lb_emit_runtime_call(p, runtime_procedure, args);
  6452. }
  6453. if (is_type_quaternion(a)) {
  6454. char const *runtime_procedure = "";
  6455. i64 sz = 8*type_size_of(a);
  6456. switch (sz) {
  6457. case 128:
  6458. switch (op_kind) {
  6459. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  6460. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  6461. }
  6462. break;
  6463. case 256:
  6464. switch (op_kind) {
  6465. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  6466. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  6467. }
  6468. break;
  6469. }
  6470. GB_ASSERT(runtime_procedure != nullptr);
  6471. auto args = array_make<lbValue>(heap_allocator(), 2);
  6472. args[0] = left;
  6473. args[1] = right;
  6474. return lb_emit_runtime_call(p, runtime_procedure, args);
  6475. }
  6476. if (is_type_bit_set(a)) {
  6477. switch (op_kind) {
  6478. case Token_Lt:
  6479. case Token_LtEq:
  6480. case Token_Gt:
  6481. case Token_GtEq:
  6482. {
  6483. Type *it = bit_set_to_int(a);
  6484. lbValue lhs = lb_emit_transmute(p, left, it);
  6485. lbValue rhs = lb_emit_transmute(p, right, it);
  6486. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  6487. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  6488. // (lhs & rhs) == lhs
  6489. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  6490. res.type = t_llvm_bool;
  6491. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  6492. // (lhs & rhs) == rhs
  6493. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  6494. res.type = t_llvm_bool;
  6495. }
  6496. // NOTE(bill): Strict subsets
  6497. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  6498. // res &~ (lhs == rhs)
  6499. lbValue eq = {};
  6500. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  6501. eq.type = t_llvm_bool;
  6502. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  6503. }
  6504. return res;
  6505. }
  6506. case Token_CmpEq:
  6507. case Token_NotEq:
  6508. {
  6509. LLVMIntPredicate pred = {};
  6510. switch (op_kind) {
  6511. case Token_CmpEq: pred = LLVMIntEQ; break;
  6512. case Token_NotEq: pred = LLVMIntNE; break;
  6513. }
  6514. lbValue res = {};
  6515. res.type = t_llvm_bool;
  6516. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  6517. return res;
  6518. }
  6519. }
  6520. }
  6521. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  6522. Type *t = left.type;
  6523. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  6524. Type *platform_type = integer_endian_type_to_platform_type(t);
  6525. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  6526. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  6527. left = x;
  6528. right = y;
  6529. }
  6530. }
  6531. lbValue res = {};
  6532. res.type = t_llvm_bool;
  6533. if (is_type_integer(left.type) ||
  6534. is_type_boolean(left.type) ||
  6535. is_type_pointer(left.type) ||
  6536. is_type_proc(left.type) ||
  6537. is_type_enum(left.type)) {
  6538. LLVMIntPredicate pred = {};
  6539. if (is_type_unsigned(left.type)) {
  6540. switch (op_kind) {
  6541. case Token_Gt: pred = LLVMIntUGT; break;
  6542. case Token_GtEq: pred = LLVMIntUGE; break;
  6543. case Token_Lt: pred = LLVMIntULT; break;
  6544. case Token_LtEq: pred = LLVMIntULE; break;
  6545. }
  6546. } else {
  6547. switch (op_kind) {
  6548. case Token_Gt: pred = LLVMIntSGT; break;
  6549. case Token_GtEq: pred = LLVMIntSGE; break;
  6550. case Token_Lt: pred = LLVMIntSLT; break;
  6551. case Token_LtEq: pred = LLVMIntSLE; break;
  6552. }
  6553. }
  6554. switch (op_kind) {
  6555. case Token_CmpEq: pred = LLVMIntEQ; break;
  6556. case Token_NotEq: pred = LLVMIntNE; break;
  6557. }
  6558. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  6559. } else if (is_type_float(left.type)) {
  6560. LLVMRealPredicate pred = {};
  6561. switch (op_kind) {
  6562. case Token_CmpEq: pred = LLVMRealOEQ; break;
  6563. case Token_Gt: pred = LLVMRealOGT; break;
  6564. case Token_GtEq: pred = LLVMRealOGE; break;
  6565. case Token_Lt: pred = LLVMRealOLT; break;
  6566. case Token_LtEq: pred = LLVMRealOLE; break;
  6567. case Token_NotEq: pred = LLVMRealONE; break;
  6568. }
  6569. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  6570. } else if (is_type_typeid(left.type)) {
  6571. LLVMIntPredicate pred = {};
  6572. switch (op_kind) {
  6573. case Token_Gt: pred = LLVMIntUGT; break;
  6574. case Token_GtEq: pred = LLVMIntUGE; break;
  6575. case Token_Lt: pred = LLVMIntULT; break;
  6576. case Token_LtEq: pred = LLVMIntULE; break;
  6577. case Token_CmpEq: pred = LLVMIntEQ; break;
  6578. case Token_NotEq: pred = LLVMIntNE; break;
  6579. }
  6580. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  6581. } else {
  6582. GB_PANIC("Unhandled comparison kind %s %.*s %s", type_to_string(left.type), LIT(token_strings[op_kind]), type_to_string(right.type));
  6583. }
  6584. return res;
  6585. }
  6586. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  6587. ast_node(pl, ProcLit, expr);
  6588. // NOTE(bill): Generate a new name
  6589. // parent$count
  6590. isize name_len = prefix_name.len + 1 + 8 + 1;
  6591. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  6592. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  6593. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  6594. String name = make_string((u8 *)name_text, name_len-1);
  6595. Type *type = type_of_expr(expr);
  6596. set_procedure_abi_types(heap_allocator(), type);
  6597. Token token = {};
  6598. token.pos = ast_token(expr).pos;
  6599. token.kind = Token_Ident;
  6600. token.string = name;
  6601. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  6602. e->decl_info = pl->decl;
  6603. lbProcedure *p = lb_create_procedure(m, e);
  6604. lbValue value = {};
  6605. value.value = p->value;
  6606. value.type = p->type;
  6607. array_add(&m->procedures_to_generate, p);
  6608. if (parent != nullptr) {
  6609. array_add(&parent->children, p);
  6610. } else {
  6611. map_set(&m->members, hash_string(name), value);
  6612. }
  6613. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  6614. return value;
  6615. }
  6616. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  6617. lbModule *m = p->module;
  6618. Type *src_type = value.type;
  6619. bool is_ptr = is_type_pointer(src_type);
  6620. bool is_tuple = true;
  6621. Type *tuple = type;
  6622. if (type->kind != Type_Tuple) {
  6623. is_tuple = false;
  6624. tuple = make_optional_ok_type(type);
  6625. }
  6626. lbAddr v = lb_add_local_generated(p, tuple, true);
  6627. if (is_ptr) {
  6628. value = lb_emit_load(p, value);
  6629. }
  6630. Type *src = base_type(type_deref(src_type));
  6631. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  6632. Type *dst = tuple->Tuple.variables[0]->type;
  6633. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  6634. lbValue tag = {};
  6635. lbValue dst_tag = {};
  6636. lbValue cond = {};
  6637. lbValue data = {};
  6638. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  6639. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  6640. if (is_type_union_maybe_pointer(src)) {
  6641. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  6642. } else {
  6643. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  6644. dst_tag = lb_const_union_tag(m, src, dst);
  6645. }
  6646. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  6647. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  6648. if (data.value != nullptr) {
  6649. GB_ASSERT(is_type_union_maybe_pointer(src));
  6650. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  6651. } else {
  6652. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  6653. }
  6654. lb_emit_if(p, cond, ok_block, end_block);
  6655. lb_start_block(p, ok_block);
  6656. if (data.value == nullptr) {
  6657. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  6658. }
  6659. lb_emit_store(p, gep0, data);
  6660. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  6661. lb_emit_jump(p, end_block);
  6662. lb_start_block(p, end_block);
  6663. if (!is_tuple) {
  6664. if (do_conversion_check) {
  6665. // NOTE(bill): Panic on invalid conversion
  6666. Type *dst_type = tuple->Tuple.variables[0]->type;
  6667. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  6668. auto args = array_make<lbValue>(heap_allocator(), 6);
  6669. args[0] = ok;
  6670. args[1] = lb_const_string(m, pos.file);
  6671. args[2] = lb_const_int(m, t_int, pos.line);
  6672. args[3] = lb_const_int(m, t_int, pos.column);
  6673. args[4] = lb_typeid(m, src_type);
  6674. args[5] = lb_typeid(m, dst_type);
  6675. lb_emit_runtime_call(p, "type_assertion_check", args);
  6676. }
  6677. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  6678. }
  6679. return lb_addr_load(p, v);
  6680. }
  6681. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  6682. lbModule *m = p->module;
  6683. Type *src_type = value.type;
  6684. if (is_type_pointer(src_type)) {
  6685. value = lb_emit_load(p, value);
  6686. }
  6687. bool is_tuple = true;
  6688. Type *tuple = type;
  6689. if (type->kind != Type_Tuple) {
  6690. is_tuple = false;
  6691. tuple = make_optional_ok_type(type);
  6692. }
  6693. Type *dst_type = tuple->Tuple.variables[0]->type;
  6694. lbAddr v = lb_add_local_generated(p, tuple, true);
  6695. lbValue dst_typeid = lb_typeid(m, dst_type);
  6696. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  6697. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  6698. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  6699. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  6700. lb_emit_if(p, cond, ok_block, end_block);
  6701. lb_start_block(p, ok_block);
  6702. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  6703. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  6704. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  6705. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  6706. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  6707. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  6708. lb_emit_jump(p, end_block);
  6709. lb_start_block(p, end_block);
  6710. if (!is_tuple) {
  6711. // NOTE(bill): Panic on invalid conversion
  6712. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  6713. auto args = array_make<lbValue>(heap_allocator(), 6);
  6714. args[0] = ok;
  6715. args[1] = lb_const_string(m, pos.file);
  6716. args[2] = lb_const_int(m, t_int, pos.line);
  6717. args[3] = lb_const_int(m, t_int, pos.column);
  6718. args[4] = any_typeid;
  6719. args[5] = dst_typeid;
  6720. lb_emit_runtime_call(p, "type_assertion_check", args);
  6721. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  6722. }
  6723. return v;
  6724. }
  6725. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  6726. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  6727. }
  6728. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  6729. lbModule *m = p->module;
  6730. expr = unparen_expr(expr);
  6731. TypeAndValue tv = type_and_value_of_expr(expr);
  6732. GB_ASSERT(tv.mode != Addressing_Invalid);
  6733. GB_ASSERT(tv.mode != Addressing_Type);
  6734. if (tv.value.kind != ExactValue_Invalid) {
  6735. // NOTE(bill): Short on constant values
  6736. return lb_const_value(p->module, tv.type, tv.value);
  6737. }
  6738. switch (expr->kind) {
  6739. case_ast_node(bl, BasicLit, expr);
  6740. TokenPos pos = bl->token.pos;
  6741. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  6742. case_end;
  6743. case_ast_node(bd, BasicDirective, expr);
  6744. TokenPos pos = bd->token.pos;
  6745. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  6746. case_end;
  6747. case_ast_node(i, Implicit, expr);
  6748. return lb_addr_load(p, lb_build_addr(p, expr));
  6749. case_end;
  6750. case_ast_node(u, Undef, expr)
  6751. lbValue res = {};
  6752. if (is_type_untyped(tv.type)) {
  6753. res.value = nullptr;
  6754. res.type = t_untyped_undef;
  6755. } else {
  6756. res.value = LLVMGetUndef(lb_type(m, tv.type));
  6757. res.type = tv.type;
  6758. }
  6759. return res;
  6760. case_end;
  6761. case_ast_node(i, Ident, expr);
  6762. Entity *e = entity_of_ident(expr);
  6763. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  6764. if (e->kind == Entity_Builtin) {
  6765. Token token = ast_token(expr);
  6766. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  6767. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  6768. LIT(token.pos.file), token.pos.line, token.pos.column);
  6769. return {};
  6770. } else if (e->kind == Entity_Nil) {
  6771. lbValue res = {};
  6772. res.value = nullptr;
  6773. res.type = e->type;
  6774. return res;
  6775. }
  6776. GB_ASSERT(e->kind != Entity_ProcGroup);
  6777. auto *found = map_get(&p->module->values, hash_entity(e));
  6778. if (found) {
  6779. auto v = *found;
  6780. // NOTE(bill): This is because pointers are already pointers in LLVM
  6781. if (is_type_proc(v.type)) {
  6782. return v;
  6783. }
  6784. return lb_emit_load(p, v);
  6785. } else if (e != nullptr && e->kind == Entity_Variable) {
  6786. return lb_addr_load(p, lb_build_addr(p, expr));
  6787. }
  6788. gb_printf_err("Error in: %.*s(%td:%td)\n", LIT(p->name), i->token.pos.line, i->token.pos.column);
  6789. GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s (%p) : %s @ %p", LIT(e->pkg->name), LIT(e->token.string), e, type_to_string(e->type), expr);
  6790. return {};
  6791. case_end;
  6792. case_ast_node(de, DerefExpr, expr);
  6793. return lb_addr_load(p, lb_build_addr(p, expr));
  6794. case_end;
  6795. case_ast_node(se, SelectorExpr, expr);
  6796. TypeAndValue tav = type_and_value_of_expr(expr);
  6797. GB_ASSERT(tav.mode != Addressing_Invalid);
  6798. return lb_addr_load(p, lb_build_addr(p, expr));
  6799. case_end;
  6800. case_ast_node(ise, ImplicitSelectorExpr, expr);
  6801. TypeAndValue tav = type_and_value_of_expr(expr);
  6802. GB_ASSERT(tav.mode == Addressing_Constant);
  6803. return lb_const_value(p->module, tv.type, tv.value);
  6804. case_end;
  6805. case_ast_node(te, TernaryExpr, expr);
  6806. LLVMValueRef incoming_values[2] = {};
  6807. LLVMBasicBlockRef incoming_blocks[2] = {};
  6808. GB_ASSERT(te->y != nullptr);
  6809. lbBlock *then = lb_create_block(p, "if.then");
  6810. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  6811. lbBlock *else_ = lb_create_block(p, "if.else");
  6812. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  6813. lb_start_block(p, then);
  6814. Type *type = default_type(type_of_expr(expr));
  6815. lb_open_scope(p);
  6816. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  6817. lb_close_scope(p, lbDeferExit_Default, nullptr);
  6818. lb_emit_jump(p, done);
  6819. lb_start_block(p, else_);
  6820. lb_open_scope(p);
  6821. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  6822. lb_close_scope(p, lbDeferExit_Default, nullptr);
  6823. lb_emit_jump(p, done);
  6824. lb_start_block(p, done);
  6825. lbValue res = {};
  6826. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  6827. res.type = type;
  6828. GB_ASSERT(p->curr_block->preds.count >= 2);
  6829. incoming_blocks[0] = p->curr_block->preds[0]->block;
  6830. incoming_blocks[1] = p->curr_block->preds[1]->block;
  6831. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  6832. return res;
  6833. case_end;
  6834. case_ast_node(te, TernaryIfExpr, expr);
  6835. LLVMValueRef incoming_values[2] = {};
  6836. LLVMBasicBlockRef incoming_blocks[2] = {};
  6837. GB_ASSERT(te->y != nullptr);
  6838. lbBlock *then = lb_create_block(p, "if.then");
  6839. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  6840. lbBlock *else_ = lb_create_block(p, "if.else");
  6841. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  6842. lb_start_block(p, then);
  6843. Type *type = default_type(type_of_expr(expr));
  6844. lb_open_scope(p);
  6845. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  6846. lb_close_scope(p, lbDeferExit_Default, nullptr);
  6847. lb_emit_jump(p, done);
  6848. lb_start_block(p, else_);
  6849. lb_open_scope(p);
  6850. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  6851. lb_close_scope(p, lbDeferExit_Default, nullptr);
  6852. lb_emit_jump(p, done);
  6853. lb_start_block(p, done);
  6854. lbValue res = {};
  6855. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  6856. res.type = type;
  6857. GB_ASSERT(p->curr_block->preds.count >= 2);
  6858. incoming_blocks[0] = p->curr_block->preds[0]->block;
  6859. incoming_blocks[1] = p->curr_block->preds[1]->block;
  6860. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  6861. return res;
  6862. case_end;
  6863. case_ast_node(te, TernaryWhenExpr, expr);
  6864. TypeAndValue tav = type_and_value_of_expr(te->cond);
  6865. GB_ASSERT(tav.mode == Addressing_Constant);
  6866. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  6867. if (tav.value.value_bool) {
  6868. return lb_build_expr(p, te->x);
  6869. } else {
  6870. return lb_build_expr(p, te->y);
  6871. }
  6872. case_end;
  6873. case_ast_node(ta, TypeAssertion, expr);
  6874. TokenPos pos = ast_token(expr).pos;
  6875. Type *type = tv.type;
  6876. lbValue e = lb_build_expr(p, ta->expr);
  6877. Type *t = type_deref(e.type);
  6878. if (is_type_union(t)) {
  6879. return lb_emit_union_cast(p, e, type, pos);
  6880. } else if (is_type_any(t)) {
  6881. return lb_emit_any_cast(p, e, type, pos);
  6882. } else {
  6883. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  6884. }
  6885. case_end;
  6886. case_ast_node(tc, TypeCast, expr);
  6887. lbValue e = lb_build_expr(p, tc->expr);
  6888. switch (tc->token.kind) {
  6889. case Token_cast:
  6890. return lb_emit_conv(p, e, tv.type);
  6891. case Token_transmute:
  6892. return lb_emit_transmute(p, e, tv.type);
  6893. }
  6894. GB_PANIC("Invalid AST TypeCast");
  6895. case_end;
  6896. case_ast_node(ac, AutoCast, expr);
  6897. return lb_build_expr(p, ac->expr);
  6898. case_end;
  6899. case_ast_node(ue, UnaryExpr, expr);
  6900. switch (ue->op.kind) {
  6901. case Token_And: {
  6902. Ast *ue_expr = unparen_expr(ue->expr);
  6903. if (ue_expr->kind == Ast_CompoundLit) {
  6904. lbValue v = lb_build_expr(p, ue->expr);
  6905. Type *type = v.type;
  6906. lbAddr addr = {};
  6907. if (p->is_startup) {
  6908. addr = lb_add_global_generated(p->module, type, v);
  6909. } else {
  6910. addr = lb_add_local_generated(p, type, false);
  6911. }
  6912. lb_addr_store(p, addr, v);
  6913. return addr.addr;
  6914. } else if (ue_expr->kind == Ast_TypeAssertion) {
  6915. gbAllocator a = heap_allocator();
  6916. GB_ASSERT(is_type_pointer(tv.type));
  6917. ast_node(ta, TypeAssertion, ue_expr);
  6918. TokenPos pos = ast_token(expr).pos;
  6919. Type *type = type_of_expr(ue_expr);
  6920. GB_ASSERT(!is_type_tuple(type));
  6921. lbValue e = lb_build_expr(p, ta->expr);
  6922. Type *t = type_deref(e.type);
  6923. if (is_type_union(t)) {
  6924. lbValue v = e;
  6925. if (!is_type_pointer(v.type)) {
  6926. v = lb_address_from_load_or_generate_local(p, v);
  6927. }
  6928. Type *src_type = type_deref(v.type);
  6929. Type *dst_type = type;
  6930. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  6931. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  6932. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  6933. auto args = array_make<lbValue>(heap_allocator(), 6);
  6934. args[0] = ok;
  6935. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  6936. args[2] = lb_const_int(p->module, t_int, pos.line);
  6937. args[3] = lb_const_int(p->module, t_int, pos.column);
  6938. args[4] = lb_typeid(p->module, src_type);
  6939. args[5] = lb_typeid(p->module, dst_type);
  6940. lb_emit_runtime_call(p, "type_assertion_check", args);
  6941. lbValue data_ptr = v;
  6942. return lb_emit_conv(p, data_ptr, tv.type);
  6943. } else if (is_type_any(t)) {
  6944. lbValue v = e;
  6945. if (is_type_pointer(v.type)) {
  6946. v = lb_emit_load(p, v);
  6947. }
  6948. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  6949. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  6950. lbValue id = lb_typeid(p->module, type);
  6951. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  6952. auto args = array_make<lbValue>(heap_allocator(), 6);
  6953. args[0] = ok;
  6954. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  6955. args[2] = lb_const_int(p->module, t_int, pos.line);
  6956. args[3] = lb_const_int(p->module, t_int, pos.column);
  6957. args[4] = any_id;
  6958. args[5] = id;
  6959. lb_emit_runtime_call(p, "type_assertion_check", args);
  6960. return lb_emit_conv(p, data_ptr, tv.type);
  6961. } else {
  6962. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  6963. }
  6964. }
  6965. return lb_build_addr_ptr(p, ue->expr);
  6966. }
  6967. default:
  6968. {
  6969. lbValue v = lb_build_expr(p, ue->expr);
  6970. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  6971. }
  6972. }
  6973. case_end;
  6974. case_ast_node(be, BinaryExpr, expr);
  6975. return lb_build_binary_expr(p, expr);
  6976. case_end;
  6977. case_ast_node(pl, ProcLit, expr);
  6978. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  6979. case_end;
  6980. case_ast_node(cl, CompoundLit, expr);
  6981. return lb_addr_load(p, lb_build_addr(p, expr));
  6982. case_end;
  6983. case_ast_node(ce, CallExpr, expr);
  6984. return lb_build_call_expr(p, expr);
  6985. case_end;
  6986. case_ast_node(se, SliceExpr, expr);
  6987. return lb_addr_load(p, lb_build_addr(p, expr));
  6988. case_end;
  6989. case_ast_node(ie, IndexExpr, expr);
  6990. return lb_addr_load(p, lb_build_addr(p, expr));
  6991. case_end;
  6992. }
  6993. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  6994. return {};
  6995. }
  6996. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  6997. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  6998. String name = e->token.string;
  6999. Entity *parent = e->using_parent;
  7000. Selection sel = lookup_field(parent->type, name, false);
  7001. GB_ASSERT(sel.entity != nullptr);
  7002. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  7003. lbValue v = {};
  7004. if (pv != nullptr) {
  7005. v = *pv;
  7006. } else {
  7007. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  7008. v = lb_build_addr_ptr(p, e->using_expr);
  7009. }
  7010. GB_ASSERT(v.value != nullptr);
  7011. GB_ASSERT(parent->type == type_deref(v.type));
  7012. return lb_emit_deep_field_gep(p, v, sel);
  7013. }
  7014. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  7015. GB_ASSERT(e != nullptr);
  7016. if (e->kind == Entity_Constant) {
  7017. Type *t = default_type(type_of_expr(expr));
  7018. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  7019. lbAddr g = lb_add_global_generated(p->module, t, v);
  7020. return g;
  7021. }
  7022. lbValue v = {};
  7023. lbValue *found = map_get(&p->module->values, hash_entity(e));
  7024. if (found) {
  7025. v = *found;
  7026. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  7027. // NOTE(bill): Calculate the using variable every time
  7028. v = lb_get_using_variable(p, e);
  7029. }
  7030. if (v.value == nullptr) {
  7031. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  7032. LIT(p->name),
  7033. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  7034. GB_PANIC("Unknown value");
  7035. }
  7036. return lb_addr(v);
  7037. }
  7038. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  7039. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  7040. gbAllocator a = heap_allocator();
  7041. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  7042. map_type = base_type(map_type);
  7043. GB_ASSERT(map_type->kind == Type_Map);
  7044. Type *key_type = map_type->Map.key;
  7045. Type *val_type = map_type->Map.value;
  7046. // NOTE(bill): Removes unnecessary allocation if split gep
  7047. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  7048. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  7049. lb_emit_store(p, gep0, m);
  7050. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_const_bool(p->module, t_bool, is_type_string(key_type)));
  7051. i64 entry_size = type_size_of (map_type->Map.entry_type);
  7052. i64 entry_align = type_align_of (map_type->Map.entry_type);
  7053. i64 value_offset = type_offset_of(map_type->Map.entry_type, 2);
  7054. i64 value_size = type_size_of (map_type->Map.value);
  7055. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  7056. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  7057. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, value_offset));
  7058. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, value_size));
  7059. return lb_addr_load(p, h);
  7060. }
  7061. lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type) {
  7062. Type *hash_type = t_u64;
  7063. lbAddr v = lb_add_local_generated(p, t_map_key, true);
  7064. Type *t = base_type(key.type);
  7065. key = lb_emit_conv(p, key, key_type);
  7066. if (is_type_integer(t)) {
  7067. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, key, hash_type));
  7068. } else if (is_type_enum(t)) {
  7069. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, key, hash_type));
  7070. } else if (is_type_typeid(t)) {
  7071. lbValue i = lb_emit_transmute(p, key, t_uint);
  7072. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, i, hash_type));
  7073. } else if (is_type_pointer(t)) {
  7074. lbValue ptr = lb_emit_conv(p, key, t_uintptr);
  7075. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, ptr, hash_type));
  7076. } else if (is_type_float(t)) {
  7077. lbValue bits = {};
  7078. i64 size = type_size_of(t);
  7079. switch (8*size) {
  7080. case 32: bits = lb_emit_transmute(p, key, t_u32); break;
  7081. case 64: bits = lb_emit_transmute(p, key, t_u64); break;
  7082. default: GB_PANIC("Unhandled float size: %lld bits", size); break;
  7083. }
  7084. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, bits, hash_type));
  7085. } else if (is_type_string(t)) {
  7086. lbValue str = lb_emit_conv(p, key, t_string);
  7087. lbValue hashed_str = {};
  7088. if (false && lb_is_const(str)) {
  7089. String value = lb_get_const_string(p->module, str);
  7090. u64 hs = fnv64a(value.text, value.len);
  7091. hashed_str = lb_const_value(p->module, t_u64, exact_value_u64(hs));
  7092. } else {
  7093. auto args = array_make<lbValue>(heap_allocator(), 1);
  7094. args[0] = str;
  7095. hashed_str = lb_emit_runtime_call(p, "default_hash_string", args);
  7096. }
  7097. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), hashed_str);
  7098. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), str);
  7099. } else {
  7100. GB_PANIC("Unhandled map key type");
  7101. }
  7102. return lb_addr_load(p, v);
  7103. }
  7104. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  7105. lbValue map_key, lbValue map_value) {
  7106. map_type = base_type(map_type);
  7107. GB_ASSERT(map_type->kind == Type_Map);
  7108. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  7109. lbValue key = lb_gen_map_key(p, map_key, map_type->Map.key);
  7110. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  7111. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  7112. lb_addr_store(p, value_addr, v);
  7113. auto args = array_make<lbValue>(heap_allocator(), 4);
  7114. args[0] = h;
  7115. args[1] = key;
  7116. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  7117. args[3] = lb_emit_source_code_location(p, nullptr);
  7118. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  7119. }
  7120. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  7121. expr = unparen_expr(expr);
  7122. switch (expr->kind) {
  7123. case_ast_node(i, Implicit, expr);
  7124. lbAddr v = {};
  7125. switch (i->kind) {
  7126. case Token_context:
  7127. v = lb_find_or_generate_context_ptr(p);
  7128. break;
  7129. }
  7130. GB_ASSERT(v.addr.value != nullptr);
  7131. return v;
  7132. case_end;
  7133. case_ast_node(i, Ident, expr);
  7134. if (is_blank_ident(expr)) {
  7135. lbAddr val = {};
  7136. return val;
  7137. }
  7138. String name = i->token.string;
  7139. Entity *e = entity_of_ident(expr);
  7140. return lb_build_addr_from_entity(p, e, expr);
  7141. case_end;
  7142. case_ast_node(se, SelectorExpr, expr);
  7143. Ast *sel = unparen_expr(se->selector);
  7144. if (sel->kind == Ast_Ident) {
  7145. String selector = sel->Ident.token.string;
  7146. TypeAndValue tav = type_and_value_of_expr(se->expr);
  7147. if (tav.mode == Addressing_Invalid) {
  7148. // NOTE(bill): Imports
  7149. Entity *imp = entity_of_ident(se->expr);
  7150. if (imp != nullptr) {
  7151. GB_ASSERT(imp->kind == Entity_ImportName);
  7152. }
  7153. return lb_build_addr(p, unparen_expr(se->selector));
  7154. }
  7155. Type *type = base_type(tav.type);
  7156. if (tav.mode == Addressing_Type) { // Addressing_Type
  7157. Selection sel = lookup_field(type, selector, true);
  7158. Entity *e = sel.entity;
  7159. GB_ASSERT(e->kind == Entity_Variable);
  7160. GB_ASSERT(e->flags & EntityFlag_TypeField);
  7161. String name = e->token.string;
  7162. /*if (name == "names") {
  7163. lbValue ti_ptr = lb_type_info(m, type);
  7164. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  7165. lbValue names_ptr = nullptr;
  7166. if (is_type_enum(type)) {
  7167. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  7168. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  7169. } else if (type->kind == Type_Struct) {
  7170. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  7171. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  7172. }
  7173. return ir_addr(names_ptr);
  7174. } else */{
  7175. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  7176. }
  7177. GB_PANIC("Unreachable");
  7178. }
  7179. Selection sel = lookup_field(type, selector, false);
  7180. GB_ASSERT(sel.entity != nullptr);
  7181. if (sel.entity->type->kind == Type_BitFieldValue) {
  7182. lbAddr addr = lb_build_addr(p, se->expr);
  7183. Type *bft = type_deref(lb_addr_type(addr));
  7184. if (sel.index.count == 1) {
  7185. GB_ASSERT(is_type_bit_field(bft));
  7186. i32 index = sel.index[0];
  7187. return lb_addr_bit_field(lb_addr_get_ptr(p, addr), index);
  7188. } else {
  7189. Selection s = sel;
  7190. s.index.count--;
  7191. i32 index = s.index[s.index.count-1];
  7192. lbValue a = lb_addr_get_ptr(p, addr);
  7193. a = lb_emit_deep_field_gep(p, a, s);
  7194. return lb_addr_bit_field(a, index);
  7195. }
  7196. } else {
  7197. lbAddr addr = lb_build_addr(p, se->expr);
  7198. if (addr.kind == lbAddr_Context) {
  7199. GB_ASSERT(sel.index.count > 0);
  7200. if (addr.ctx.sel.index.count >= 0) {
  7201. sel = selection_combine(addr.ctx.sel, sel);
  7202. }
  7203. addr.ctx.sel = sel;
  7204. addr.kind = lbAddr_Context;
  7205. return addr;
  7206. } else if (addr.kind == lbAddr_SoaVariable) {
  7207. lbValue index = addr.soa.index;
  7208. i32 first_index = sel.index[0];
  7209. Selection sub_sel = sel;
  7210. sub_sel.index.data += 1;
  7211. sub_sel.index.count -= 1;
  7212. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  7213. Type *t = base_type(type_deref(addr.addr.type));
  7214. GB_ASSERT(is_type_soa_struct(t));
  7215. // TODO(bill): Bounds check
  7216. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  7217. lbValue len = lb_soa_struct_len(p, addr.addr);
  7218. // lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  7219. }
  7220. lbValue item = {};
  7221. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7222. item = lb_emit_array_ep(p, arr, index);
  7223. } else {
  7224. item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index));
  7225. }
  7226. if (sub_sel.index.count > 0) {
  7227. item = lb_emit_deep_field_gep(p, item, sub_sel);
  7228. }
  7229. return lb_addr(item);
  7230. }
  7231. lbValue a = lb_addr_get_ptr(p, addr);
  7232. a = lb_emit_deep_field_gep(p, a, sel);
  7233. return lb_addr(a);
  7234. }
  7235. } else {
  7236. GB_PANIC("Unsupported selector expression");
  7237. }
  7238. case_end;
  7239. case_ast_node(ta, TypeAssertion, expr);
  7240. gbAllocator a = heap_allocator();
  7241. TokenPos pos = ast_token(expr).pos;
  7242. lbValue e = lb_build_expr(p, ta->expr);
  7243. Type *t = type_deref(e.type);
  7244. if (is_type_union(t)) {
  7245. Type *type = type_of_expr(expr);
  7246. lbAddr v = lb_add_local_generated(p, type, false);
  7247. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  7248. return v;
  7249. } else if (is_type_any(t)) {
  7250. Type *type = type_of_expr(expr);
  7251. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  7252. } else {
  7253. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  7254. }
  7255. case_end;
  7256. case_ast_node(ue, UnaryExpr, expr);
  7257. switch (ue->op.kind) {
  7258. case Token_And: {
  7259. return lb_build_addr(p, ue->expr);
  7260. }
  7261. default:
  7262. GB_PANIC("Invalid unary expression for lb_build_addr");
  7263. }
  7264. case_end;
  7265. case_ast_node(be, BinaryExpr, expr);
  7266. lbValue v = lb_build_expr(p, expr);
  7267. Type *t = v.type;
  7268. if (is_type_pointer(t)) {
  7269. return lb_addr(v);
  7270. }
  7271. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  7272. case_end;
  7273. case_ast_node(ie, IndexExpr, expr);
  7274. Type *t = base_type(type_of_expr(ie->expr));
  7275. gbAllocator a = heap_allocator();
  7276. bool deref = is_type_pointer(t);
  7277. t = base_type(type_deref(t));
  7278. if (is_type_soa_struct(t)) {
  7279. // SOA STRUCTURES!!!!
  7280. lbValue val = lb_build_addr_ptr(p, ie->expr);
  7281. if (deref) {
  7282. val = lb_emit_load(p, val);
  7283. }
  7284. lbValue index = lb_build_expr(p, ie->index);
  7285. return lb_addr_soa_variable(val, index, ie->index);
  7286. }
  7287. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  7288. // SOA Structures for slices/dynamic arrays
  7289. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  7290. lbValue field = lb_build_expr(p, ie->expr);
  7291. lbValue index = lb_build_expr(p, ie->index);
  7292. if (!build_context.no_bounds_check) {
  7293. // // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  7294. // GB_ASSERT(LLVMIsALoadInst(field.value));
  7295. // lbValue a = {};
  7296. // a.value = LLVMGetOperand(field.value, 0);
  7297. // a.type = alloc_type_pointer(field.type);
  7298. // irInstr *b = &a->Instr;
  7299. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  7300. // lbValue base_struct = b->StructElementPtr.address;
  7301. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  7302. // lbValue len = ir_soa_struct_len(p, base_struct);
  7303. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7304. }
  7305. lbValue val = lb_emit_ptr_offset(p, field, index);
  7306. return lb_addr(val);
  7307. }
  7308. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  7309. if (is_type_map(t)) {
  7310. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  7311. if (deref) {
  7312. map_val = lb_emit_load(p, map_val);
  7313. }
  7314. lbValue key = lb_build_expr(p, ie->index);
  7315. key = lb_emit_conv(p, key, t->Map.key);
  7316. Type *result_type = type_of_expr(expr);
  7317. return lb_addr_map(map_val, key, t, result_type);
  7318. }
  7319. lbValue using_addr = {};
  7320. switch (t->kind) {
  7321. case Type_Array: {
  7322. lbValue array = {};
  7323. if (using_addr.value != nullptr) {
  7324. array = using_addr;
  7325. } else {
  7326. array = lb_build_addr_ptr(p, ie->expr);
  7327. if (deref) {
  7328. array = lb_emit_load(p, array);
  7329. }
  7330. }
  7331. lbValue index = lb_build_expr(p, ie->index);
  7332. index = lb_emit_conv(p, index, t_int);
  7333. lbValue elem = lb_emit_array_ep(p, array, index);
  7334. auto index_tv = type_and_value_of_expr(ie->index);
  7335. if (index_tv.mode != Addressing_Constant) {
  7336. // lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  7337. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7338. }
  7339. return lb_addr(elem);
  7340. }
  7341. case Type_EnumeratedArray: {
  7342. lbValue array = {};
  7343. if (using_addr.value != nullptr) {
  7344. array = using_addr;
  7345. } else {
  7346. array = lb_build_addr_ptr(p, ie->expr);
  7347. if (deref) {
  7348. array = lb_emit_load(p, array);
  7349. }
  7350. }
  7351. Type *index_type = t->EnumeratedArray.index;
  7352. auto index_tv = type_and_value_of_expr(ie->index);
  7353. lbValue index = {};
  7354. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  7355. if (index_tv.mode == Addressing_Constant) {
  7356. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  7357. index = lb_const_value(p->module, index_type, idx);
  7358. } else {
  7359. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7360. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  7361. }
  7362. } else {
  7363. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7364. }
  7365. lbValue elem = lb_emit_array_ep(p, array, index);
  7366. if (index_tv.mode != Addressing_Constant) {
  7367. // lbValue len = ir_const_int(t->EnumeratedArray.count);
  7368. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7369. }
  7370. return lb_addr(elem);
  7371. }
  7372. case Type_Slice: {
  7373. lbValue slice = {};
  7374. if (using_addr.value != nullptr) {
  7375. slice = lb_emit_load(p, using_addr);
  7376. } else {
  7377. slice = lb_build_expr(p, ie->expr);
  7378. if (deref) {
  7379. slice = lb_emit_load(p, slice);
  7380. }
  7381. }
  7382. lbValue elem = lb_slice_elem(p, slice);
  7383. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7384. lbValue len = lb_slice_len(p, slice);
  7385. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7386. lbValue v = lb_emit_ptr_offset(p, elem, index);
  7387. return lb_addr(v);
  7388. }
  7389. case Type_DynamicArray: {
  7390. lbValue dynamic_array = {};
  7391. if (using_addr.value != nullptr) {
  7392. dynamic_array = lb_emit_load(p, using_addr);
  7393. } else {
  7394. dynamic_array = lb_build_expr(p, ie->expr);
  7395. if (deref) {
  7396. dynamic_array = lb_emit_load(p, dynamic_array);
  7397. }
  7398. }
  7399. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  7400. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  7401. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7402. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  7403. lbValue v = lb_emit_ptr_offset(p, elem, index);
  7404. return lb_addr(v);
  7405. }
  7406. case Type_Basic: { // Basic_string
  7407. lbValue str;
  7408. lbValue elem;
  7409. lbValue len;
  7410. lbValue index;
  7411. if (using_addr.value != nullptr) {
  7412. str = lb_emit_load(p, using_addr);
  7413. } else {
  7414. str = lb_build_expr(p, ie->expr);
  7415. if (deref) {
  7416. str = lb_emit_load(p, str);
  7417. }
  7418. }
  7419. elem = lb_string_elem(p, str);
  7420. len = lb_string_len(p, str);
  7421. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7422. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  7423. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  7424. }
  7425. }
  7426. case_end;
  7427. case_ast_node(se, SliceExpr, expr);
  7428. gbAllocator a = heap_allocator();
  7429. lbValue low = lb_const_int(p->module, t_int, 0);
  7430. lbValue high = {};
  7431. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  7432. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  7433. bool no_indices = se->low == nullptr && se->high == nullptr;
  7434. lbValue addr = lb_build_addr_ptr(p, se->expr);
  7435. lbValue base = lb_emit_load(p, addr);
  7436. Type *type = base_type(base.type);
  7437. if (is_type_pointer(type)) {
  7438. type = base_type(type_deref(type));
  7439. addr = base;
  7440. base = lb_emit_load(p, base);
  7441. }
  7442. // TODO(bill): Cleanup like mad!
  7443. switch (type->kind) {
  7444. case Type_Slice: {
  7445. Type *slice_type = type;
  7446. lbValue len = lb_slice_len(p, base);
  7447. if (high.value == nullptr) high = len;
  7448. if (!no_indices) {
  7449. // ir_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7450. }
  7451. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  7452. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7453. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  7454. lb_fill_slice(p, slice, elem, new_len);
  7455. return slice;
  7456. }
  7457. case Type_DynamicArray: {
  7458. Type *elem_type = type->DynamicArray.elem;
  7459. Type *slice_type = alloc_type_slice(elem_type);
  7460. lbValue len = lb_dynamic_array_len(p, base);
  7461. if (high.value == nullptr) high = len;
  7462. if (!no_indices) {
  7463. // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7464. }
  7465. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  7466. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7467. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  7468. lb_fill_slice(p, slice, elem, new_len);
  7469. return slice;
  7470. }
  7471. case Type_Array: {
  7472. Type *slice_type = alloc_type_slice(type->Array.elem);
  7473. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  7474. if (high.value == nullptr) high = len;
  7475. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  7476. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  7477. if (!low_const || !high_const) {
  7478. if (!no_indices) {
  7479. // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7480. }
  7481. }
  7482. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, addr), low);
  7483. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7484. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  7485. lb_fill_slice(p, slice, elem, new_len);
  7486. return slice;
  7487. }
  7488. case Type_Basic: {
  7489. GB_ASSERT(type == t_string);
  7490. lbValue len = lb_string_len(p, base);
  7491. if (high.value == nullptr) high = len;
  7492. if (!no_indices) {
  7493. // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7494. }
  7495. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  7496. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7497. lbAddr str = lb_add_local_generated(p, t_string, false);
  7498. lb_fill_string(p, str, elem, new_len);
  7499. return str;
  7500. }
  7501. case Type_Struct:
  7502. if (is_type_soa_struct(type)) {
  7503. lbValue len = lb_soa_struct_len(p, addr);
  7504. if (high.value == nullptr) high = len;
  7505. if (!no_indices) {
  7506. // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7507. }
  7508. #if 1
  7509. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  7510. if (type->Struct.soa_kind == StructSoa_Fixed) {
  7511. i32 field_count = cast(i32)type->Struct.fields.count;
  7512. for (i32 i = 0; i < field_count; i++) {
  7513. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  7514. lbValue field_src = lb_emit_struct_ep(p, addr, i);
  7515. field_src = lb_emit_array_ep(p, field_src, low);
  7516. lb_emit_store(p, field_dst, field_src);
  7517. }
  7518. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  7519. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7520. lb_emit_store(p, len_dst, new_len);
  7521. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  7522. if (no_indices) {
  7523. lb_addr_store(p, dst, base);
  7524. } else {
  7525. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  7526. for (i32 i = 0; i < field_count; i++) {
  7527. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  7528. lbValue field_src = lb_emit_struct_ev(p, base, i);
  7529. field_src = lb_emit_ptr_offset(p, field_src, low);
  7530. lb_emit_store(p, field_dst, field_src);
  7531. }
  7532. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  7533. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7534. lb_emit_store(p, len_dst, new_len);
  7535. }
  7536. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  7537. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  7538. for (i32 i = 0; i < field_count; i++) {
  7539. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  7540. lbValue field_src = lb_emit_struct_ev(p, base, i);
  7541. field_src = lb_emit_ptr_offset(p, field_src, low);
  7542. lb_emit_store(p, field_dst, field_src);
  7543. }
  7544. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  7545. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7546. lb_emit_store(p, len_dst, new_len);
  7547. }
  7548. return dst;
  7549. #endif
  7550. }
  7551. break;
  7552. }
  7553. GB_PANIC("Unknown slicable type");
  7554. case_end;
  7555. case_ast_node(de, DerefExpr, expr);
  7556. lbValue addr = lb_build_expr(p, de->expr);
  7557. return lb_addr(addr);
  7558. case_end;
  7559. case_ast_node(ce, CallExpr, expr);
  7560. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  7561. lbValue e = lb_build_expr(p, expr);
  7562. lbAddr v = lb_add_local_generated(p, e.type, false);
  7563. lb_addr_store(p, v, e);
  7564. return v;
  7565. case_end;
  7566. case_ast_node(cl, CompoundLit, expr);
  7567. Type *type = type_of_expr(expr);
  7568. Type *bt = base_type(type);
  7569. lbAddr v = lb_add_local_generated(p, type, true);
  7570. Type *et = nullptr;
  7571. switch (bt->kind) {
  7572. case Type_Array: et = bt->Array.elem; break;
  7573. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  7574. case Type_Slice: et = bt->Slice.elem; break;
  7575. case Type_BitSet: et = bt->BitSet.elem; break;
  7576. case Type_SimdVector: et = bt->SimdVector.elem; break;
  7577. }
  7578. String proc_name = {};
  7579. if (p->entity) {
  7580. proc_name = p->entity->token.string;
  7581. }
  7582. TokenPos pos = ast_token(expr).pos;
  7583. switch (bt->kind) {
  7584. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  7585. case Type_Struct: {
  7586. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  7587. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  7588. bool is_raw_union = is_type_raw_union(bt);
  7589. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  7590. TypeStruct *st = &bt->Struct;
  7591. if (cl->elems.count > 0) {
  7592. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7593. for_array(field_index, cl->elems) {
  7594. Ast *elem = cl->elems[field_index];
  7595. lbValue field_expr = {};
  7596. Entity *field = nullptr;
  7597. isize index = field_index;
  7598. if (elem->kind == Ast_FieldValue) {
  7599. ast_node(fv, FieldValue, elem);
  7600. String name = fv->field->Ident.token.string;
  7601. Selection sel = lookup_field(bt, name, false);
  7602. index = sel.index[0];
  7603. elem = fv->value;
  7604. TypeAndValue tav = type_and_value_of_expr(elem);
  7605. } else {
  7606. TypeAndValue tav = type_and_value_of_expr(elem);
  7607. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  7608. index = sel.index[0];
  7609. }
  7610. field = st->fields[index];
  7611. Type *ft = field->type;
  7612. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  7613. continue;
  7614. }
  7615. field_expr = lb_build_expr(p, elem);
  7616. Type *fet = field_expr.type;
  7617. GB_ASSERT(fet->kind != Type_Tuple);
  7618. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  7619. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  7620. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  7621. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  7622. lb_emit_store_union_variant(p, gep, field_expr, fet);
  7623. } else {
  7624. lbValue fv = lb_emit_conv(p, field_expr, ft);
  7625. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  7626. lb_emit_store(p, gep, fv);
  7627. }
  7628. }
  7629. }
  7630. break;
  7631. }
  7632. case Type_Map: {
  7633. if (cl->elems.count == 0) {
  7634. break;
  7635. }
  7636. gbAllocator a = heap_allocator();
  7637. {
  7638. auto args = array_make<lbValue>(a, 3);
  7639. args[0] = lb_gen_map_header(p, v.addr, type);
  7640. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  7641. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  7642. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  7643. }
  7644. for_array(field_index, cl->elems) {
  7645. Ast *elem = cl->elems[field_index];
  7646. ast_node(fv, FieldValue, elem);
  7647. lbValue key = lb_build_expr(p, fv->field);
  7648. lbValue value = lb_build_expr(p, fv->value);
  7649. lb_insert_dynamic_map_key_and_value(p, v, type, key, value);
  7650. }
  7651. break;
  7652. }
  7653. case Type_Array: {
  7654. if (cl->elems.count > 0) {
  7655. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7656. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7657. defer (array_free(&temp_data));
  7658. // NOTE(bill): Separate value, gep, store into their own chunks
  7659. for_array(i, cl->elems) {
  7660. Ast *elem = cl->elems[i];
  7661. if (elem->kind == Ast_FieldValue) {
  7662. ast_node(fv, FieldValue, elem);
  7663. if (lb_is_elem_const(fv->value, et)) {
  7664. continue;
  7665. }
  7666. if (is_ast_range(fv->field)) {
  7667. ast_node(ie, BinaryExpr, fv->field);
  7668. TypeAndValue lo_tav = ie->left->tav;
  7669. TypeAndValue hi_tav = ie->right->tav;
  7670. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7671. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7672. TokenKind op = ie->op.kind;
  7673. i64 lo = exact_value_to_i64(lo_tav.value);
  7674. i64 hi = exact_value_to_i64(hi_tav.value);
  7675. if (op == Token_Ellipsis) {
  7676. hi += 1;
  7677. }
  7678. lbValue value = lb_build_expr(p, fv->value);
  7679. for (i64 k = lo; k < hi; k++) {
  7680. lbCompoundLitElemTempData data = {};
  7681. data.value = value;
  7682. data.elem_index = cast(i32)k;
  7683. array_add(&temp_data, data);
  7684. }
  7685. } else {
  7686. auto tav = fv->field->tav;
  7687. GB_ASSERT(tav.mode == Addressing_Constant);
  7688. i64 index = exact_value_to_i64(tav.value);
  7689. lbValue value = lb_build_expr(p, fv->value);
  7690. lbCompoundLitElemTempData data = {};
  7691. data.value = lb_emit_conv(p, value, et);
  7692. data.expr = fv->value;
  7693. data.elem_index = cast(i32)index;
  7694. array_add(&temp_data, data);
  7695. }
  7696. } else {
  7697. if (lb_is_elem_const(elem, et)) {
  7698. continue;
  7699. }
  7700. lbCompoundLitElemTempData data = {};
  7701. data.expr = elem;
  7702. data.elem_index = cast(i32)i;
  7703. array_add(&temp_data, data);
  7704. }
  7705. }
  7706. for_array(i, temp_data) {
  7707. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  7708. }
  7709. for_array(i, temp_data) {
  7710. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  7711. auto return_ptr_hint_value = p->return_ptr_hint_value;
  7712. auto return_ptr_hint_used = p->return_ptr_hint_used;
  7713. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  7714. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  7715. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  7716. lbValue field_expr = temp_data[i].value;
  7717. Ast *expr = temp_data[i].expr;
  7718. p->return_ptr_hint_value = temp_data[i].gep;
  7719. p->return_ptr_hint_ast = unparen_expr(expr);
  7720. if (field_expr.value == nullptr) {
  7721. field_expr = lb_build_expr(p, expr);
  7722. }
  7723. Type *t = field_expr.type;
  7724. GB_ASSERT(t->kind != Type_Tuple);
  7725. lbValue ev = lb_emit_conv(p, field_expr, et);
  7726. if (!p->return_ptr_hint_used) {
  7727. temp_data[i].value = ev;
  7728. }
  7729. }
  7730. for_array(i, temp_data) {
  7731. if (temp_data[i].value.value != nullptr) {
  7732. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  7733. }
  7734. }
  7735. }
  7736. break;
  7737. }
  7738. case Type_EnumeratedArray: {
  7739. if (cl->elems.count > 0) {
  7740. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7741. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7742. defer (array_free(&temp_data));
  7743. // NOTE(bill): Separate value, gep, store into their own chunks
  7744. for_array(i, cl->elems) {
  7745. Ast *elem = cl->elems[i];
  7746. if (elem->kind == Ast_FieldValue) {
  7747. ast_node(fv, FieldValue, elem);
  7748. if (lb_is_elem_const(fv->value, et)) {
  7749. continue;
  7750. }
  7751. if (is_ast_range(fv->field)) {
  7752. ast_node(ie, BinaryExpr, fv->field);
  7753. TypeAndValue lo_tav = ie->left->tav;
  7754. TypeAndValue hi_tav = ie->right->tav;
  7755. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7756. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7757. TokenKind op = ie->op.kind;
  7758. i64 lo = exact_value_to_i64(lo_tav.value);
  7759. i64 hi = exact_value_to_i64(hi_tav.value);
  7760. if (op == Token_Ellipsis) {
  7761. hi += 1;
  7762. }
  7763. lbValue value = lb_build_expr(p, fv->value);
  7764. for (i64 k = lo; k < hi; k++) {
  7765. lbCompoundLitElemTempData data = {};
  7766. data.value = value;
  7767. data.elem_index = cast(i32)k;
  7768. array_add(&temp_data, data);
  7769. }
  7770. } else {
  7771. auto tav = fv->field->tav;
  7772. GB_ASSERT(tav.mode == Addressing_Constant);
  7773. i64 index = exact_value_to_i64(tav.value);
  7774. lbValue value = lb_build_expr(p, fv->value);
  7775. lbCompoundLitElemTempData data = {};
  7776. data.value = lb_emit_conv(p, value, et);
  7777. data.expr = fv->value;
  7778. data.elem_index = cast(i32)index;
  7779. array_add(&temp_data, data);
  7780. }
  7781. } else {
  7782. if (lb_is_elem_const(elem, et)) {
  7783. continue;
  7784. }
  7785. lbCompoundLitElemTempData data = {};
  7786. data.expr = elem;
  7787. data.elem_index = cast(i32)i;
  7788. array_add(&temp_data, data);
  7789. }
  7790. }
  7791. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  7792. for_array(i, temp_data) {
  7793. i32 index = temp_data[i].elem_index - index_offset;
  7794. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  7795. }
  7796. for_array(i, temp_data) {
  7797. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  7798. auto return_ptr_hint_value = p->return_ptr_hint_value;
  7799. auto return_ptr_hint_used = p->return_ptr_hint_used;
  7800. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  7801. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  7802. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  7803. lbValue field_expr = temp_data[i].value;
  7804. Ast *expr = temp_data[i].expr;
  7805. p->return_ptr_hint_value = temp_data[i].gep;
  7806. p->return_ptr_hint_ast = unparen_expr(expr);
  7807. if (field_expr.value == nullptr) {
  7808. field_expr = lb_build_expr(p, expr);
  7809. }
  7810. Type *t = field_expr.type;
  7811. GB_ASSERT(t->kind != Type_Tuple);
  7812. lbValue ev = lb_emit_conv(p, field_expr, et);
  7813. if (!p->return_ptr_hint_used) {
  7814. temp_data[i].value = ev;
  7815. }
  7816. }
  7817. for_array(i, temp_data) {
  7818. if (temp_data[i].value.value != nullptr) {
  7819. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  7820. }
  7821. }
  7822. }
  7823. break;
  7824. }
  7825. case Type_Slice: {
  7826. if (cl->elems.count > 0) {
  7827. Type *elem_type = bt->Slice.elem;
  7828. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  7829. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  7830. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  7831. lbValue data = lb_slice_elem(p, slice);
  7832. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7833. defer (array_free(&temp_data));
  7834. for_array(i, cl->elems) {
  7835. Ast *elem = cl->elems[i];
  7836. if (elem->kind == Ast_FieldValue) {
  7837. ast_node(fv, FieldValue, elem);
  7838. if (lb_is_elem_const(fv->value, et)) {
  7839. continue;
  7840. }
  7841. if (is_ast_range(fv->field)) {
  7842. ast_node(ie, BinaryExpr, fv->field);
  7843. TypeAndValue lo_tav = ie->left->tav;
  7844. TypeAndValue hi_tav = ie->right->tav;
  7845. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7846. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7847. TokenKind op = ie->op.kind;
  7848. i64 lo = exact_value_to_i64(lo_tav.value);
  7849. i64 hi = exact_value_to_i64(hi_tav.value);
  7850. if (op == Token_Ellipsis) {
  7851. hi += 1;
  7852. }
  7853. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  7854. for (i64 k = lo; k < hi; k++) {
  7855. lbCompoundLitElemTempData data = {};
  7856. data.value = value;
  7857. data.elem_index = cast(i32)k;
  7858. array_add(&temp_data, data);
  7859. }
  7860. } else {
  7861. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  7862. i64 index = exact_value_to_i64(fv->field->tav.value);
  7863. lbValue field_expr = lb_build_expr(p, fv->value);
  7864. GB_ASSERT(!is_type_tuple(field_expr.type));
  7865. lbValue ev = lb_emit_conv(p, field_expr, et);
  7866. lbCompoundLitElemTempData data = {};
  7867. data.value = ev;
  7868. data.elem_index = cast(i32)index;
  7869. array_add(&temp_data, data);
  7870. }
  7871. } else {
  7872. if (lb_is_elem_const(elem, et)) {
  7873. continue;
  7874. }
  7875. lbValue field_expr = lb_build_expr(p, elem);
  7876. GB_ASSERT(!is_type_tuple(field_expr.type));
  7877. lbValue ev = lb_emit_conv(p, field_expr, et);
  7878. lbCompoundLitElemTempData data = {};
  7879. data.value = ev;
  7880. data.elem_index = cast(i32)i;
  7881. array_add(&temp_data, data);
  7882. }
  7883. }
  7884. for_array(i, temp_data) {
  7885. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  7886. }
  7887. for_array(i, temp_data) {
  7888. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  7889. }
  7890. {
  7891. GB_ASSERT(lb_is_const(slice));
  7892. unsigned indices[1] = {1};
  7893. lbValue count = {};
  7894. count.type = t_int;
  7895. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  7896. lb_fill_slice(p, v, data, count);
  7897. }
  7898. }
  7899. break;
  7900. }
  7901. case Type_DynamicArray: {
  7902. if (cl->elems.count == 0) {
  7903. break;
  7904. }
  7905. Type *et = bt->DynamicArray.elem;
  7906. gbAllocator a = heap_allocator();
  7907. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  7908. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  7909. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  7910. {
  7911. auto args = array_make<lbValue>(a, 5);
  7912. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  7913. args[1] = size;
  7914. args[2] = align;
  7915. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  7916. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  7917. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  7918. }
  7919. lbValue items = lb_generate_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  7920. for_array(i, cl->elems) {
  7921. Ast *elem = cl->elems[i];
  7922. if (elem->kind == Ast_FieldValue) {
  7923. ast_node(fv, FieldValue, elem);
  7924. if (is_ast_range(fv->field)) {
  7925. ast_node(ie, BinaryExpr, fv->field);
  7926. TypeAndValue lo_tav = ie->left->tav;
  7927. TypeAndValue hi_tav = ie->right->tav;
  7928. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7929. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7930. TokenKind op = ie->op.kind;
  7931. i64 lo = exact_value_to_i64(lo_tav.value);
  7932. i64 hi = exact_value_to_i64(hi_tav.value);
  7933. if (op == Token_Ellipsis) {
  7934. hi += 1;
  7935. }
  7936. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  7937. for (i64 k = lo; k < hi; k++) {
  7938. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  7939. lb_emit_store(p, ep, value);
  7940. }
  7941. } else {
  7942. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  7943. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  7944. lbValue ev = lb_build_expr(p, fv->value);
  7945. lbValue value = lb_emit_conv(p, ev, et);
  7946. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  7947. lb_emit_store(p, ep, value);
  7948. }
  7949. } else {
  7950. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  7951. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  7952. lb_emit_store(p, ep, value);
  7953. }
  7954. }
  7955. {
  7956. auto args = array_make<lbValue>(a, 6);
  7957. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  7958. args[1] = size;
  7959. args[2] = align;
  7960. args[3] = lb_emit_conv(p, items, t_rawptr);
  7961. args[4] = lb_const_int(p->module, t_int, item_count);
  7962. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  7963. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  7964. }
  7965. break;
  7966. }
  7967. case Type_Basic: {
  7968. GB_ASSERT(is_type_any(bt));
  7969. if (cl->elems.count > 0) {
  7970. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7971. String field_names[2] = {
  7972. str_lit("data"),
  7973. str_lit("id"),
  7974. };
  7975. Type *field_types[2] = {
  7976. t_rawptr,
  7977. t_typeid,
  7978. };
  7979. for_array(field_index, cl->elems) {
  7980. Ast *elem = cl->elems[field_index];
  7981. lbValue field_expr = {};
  7982. isize index = field_index;
  7983. if (elem->kind == Ast_FieldValue) {
  7984. ast_node(fv, FieldValue, elem);
  7985. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  7986. index = sel.index[0];
  7987. elem = fv->value;
  7988. } else {
  7989. TypeAndValue tav = type_and_value_of_expr(elem);
  7990. Selection sel = lookup_field(bt, field_names[field_index], false);
  7991. index = sel.index[0];
  7992. }
  7993. field_expr = lb_build_expr(p, elem);
  7994. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  7995. Type *ft = field_types[index];
  7996. lbValue fv = lb_emit_conv(p, field_expr, ft);
  7997. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  7998. lb_emit_store(p, gep, fv);
  7999. }
  8000. }
  8001. break;
  8002. }
  8003. case Type_BitSet: {
  8004. i64 sz = type_size_of(type);
  8005. if (cl->elems.count > 0 && sz > 0) {
  8006. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  8007. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  8008. for_array(i, cl->elems) {
  8009. Ast *elem = cl->elems[i];
  8010. GB_ASSERT(elem->kind != Ast_FieldValue);
  8011. if (lb_is_elem_const(elem, et)) {
  8012. continue;
  8013. }
  8014. lbValue expr = lb_build_expr(p, elem);
  8015. GB_ASSERT(expr.type->kind != Type_Tuple);
  8016. Type *it = bit_set_to_int(bt);
  8017. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  8018. lbValue e = lb_emit_conv(p, expr, it);
  8019. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  8020. e = lb_emit_arith(p, Token_Shl, one, e, it);
  8021. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  8022. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  8023. new_value = lb_emit_transmute(p, new_value, type);
  8024. lb_addr_store(p, v, new_value);
  8025. }
  8026. }
  8027. break;
  8028. }
  8029. }
  8030. return v;
  8031. case_end;
  8032. case_ast_node(tc, TypeCast, expr);
  8033. Type *type = type_of_expr(expr);
  8034. lbValue x = lb_build_expr(p, tc->expr);
  8035. lbValue e = {};
  8036. switch (tc->token.kind) {
  8037. case Token_cast:
  8038. e = lb_emit_conv(p, x, type);
  8039. break;
  8040. case Token_transmute:
  8041. e = lb_emit_transmute(p, x, type);
  8042. break;
  8043. default:
  8044. GB_PANIC("Invalid AST TypeCast");
  8045. }
  8046. lbAddr v = lb_add_local_generated(p, type, false);
  8047. lb_addr_store(p, v, e);
  8048. return v;
  8049. case_end;
  8050. case_ast_node(ac, AutoCast, expr);
  8051. return lb_build_addr(p, ac->expr);
  8052. case_end;
  8053. }
  8054. TokenPos token_pos = ast_token(expr).pos;
  8055. GB_PANIC("Unexpected address expression\n"
  8056. "\tAst: %.*s @ "
  8057. "%.*s(%td:%td)\n",
  8058. LIT(ast_strings[expr->kind]),
  8059. LIT(token_pos.file), token_pos.line, token_pos.column);
  8060. return {};
  8061. }
  8062. void lb_init_module(lbModule *m, Checker *c) {
  8063. m->info = &c->info;
  8064. m->ctx = LLVMGetGlobalContext();
  8065. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  8066. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  8067. gb_mutex_init(&m->mutex);
  8068. gbAllocator a = heap_allocator();
  8069. map_init(&m->types, a);
  8070. map_init(&m->values, a);
  8071. map_init(&m->members, a);
  8072. map_init(&m->procedure_values, a);
  8073. map_init(&m->procedures, a);
  8074. map_init(&m->const_strings, a);
  8075. map_init(&m->anonymous_proc_lits, a);
  8076. array_init(&m->procedures_to_generate, a);
  8077. array_init(&m->foreign_library_paths, a);
  8078. map_init(&m->debug_values, a);
  8079. }
  8080. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  8081. if (global_error_collector.count != 0) {
  8082. return false;
  8083. }
  8084. isize tc = c->parser->total_token_count;
  8085. if (tc < 2) {
  8086. return false;
  8087. }
  8088. String init_fullpath = c->parser->init_fullpath;
  8089. if (build_context.out_filepath.len == 0) {
  8090. gen->output_name = remove_directory_from_path(init_fullpath);
  8091. gen->output_name = remove_extension_from_path(gen->output_name);
  8092. gen->output_base = gen->output_name;
  8093. } else {
  8094. gen->output_name = build_context.out_filepath;
  8095. isize pos = string_extension_position(gen->output_name);
  8096. if (pos < 0) {
  8097. gen->output_base = gen->output_name;
  8098. } else {
  8099. gen->output_base = substring(gen->output_name, 0, pos);
  8100. }
  8101. }
  8102. gbAllocator ha = heap_allocator();
  8103. array_init(&gen->output_object_paths, ha);
  8104. gen->output_base = path_to_full_path(ha, gen->output_base);
  8105. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  8106. output_file_path = gb_string_appendc(output_file_path, ".obj");
  8107. defer (gb_string_free(output_file_path));
  8108. gen->info = &c->info;
  8109. lb_init_module(&gen->module, c);
  8110. return true;
  8111. }
  8112. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  8113. GB_ASSERT(type != nullptr);
  8114. type = default_type(type);
  8115. isize max_len = 7+8+1;
  8116. u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len);
  8117. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  8118. m->global_generated_index++;
  8119. String name = make_string(str, len-1);
  8120. Scope *scope = nullptr;
  8121. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  8122. lbValue g = {};
  8123. g.type = alloc_type_pointer(type);
  8124. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  8125. if (value.value != nullptr) {
  8126. GB_ASSERT(LLVMIsConstant(value.value));
  8127. LLVMSetInitializer(g.value, value.value);
  8128. } else {
  8129. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  8130. }
  8131. lb_add_entity(m, e, g);
  8132. lb_add_member(m, name, g);
  8133. return lb_addr(g);
  8134. }
  8135. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  8136. AstPackage *p = m->info->runtime_package;
  8137. Entity *e = scope_lookup_current(p->scope, name);
  8138. lbValue *found = map_get(&m->values, hash_entity(e));
  8139. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  8140. lbValue value = *found;
  8141. return value;
  8142. }
  8143. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  8144. i32 index = cast(i32)lb_type_info_index(m->info, type);
  8145. GB_ASSERT(index >= 0);
  8146. // gb_printf_err("%d %s\n", index, type_to_string(type));
  8147. LLVMValueRef indices[2] = {
  8148. LLVMConstInt(lb_type(m, t_int), 0, false),
  8149. LLVMConstInt(lb_type(m, t_int), index, false),
  8150. };
  8151. lbValue res = {};
  8152. res.type = t_type_info_ptr;
  8153. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  8154. return res;
  8155. }
  8156. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  8157. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  8158. lb_global_type_info_member_types_index += cast(i32)count;
  8159. return offset;
  8160. }
  8161. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  8162. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  8163. lb_global_type_info_member_names_index += cast(i32)count;
  8164. return offset;
  8165. }
  8166. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  8167. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  8168. lb_global_type_info_member_offsets_index += cast(i32)count;
  8169. return offset;
  8170. }
  8171. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  8172. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  8173. lb_global_type_info_member_usings_index += cast(i32)count;
  8174. return offset;
  8175. }
  8176. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  8177. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  8178. lb_global_type_info_member_tags_index += cast(i32)count;
  8179. return offset;
  8180. }
  8181. lbValue lb_generate_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  8182. gbAllocator a = heap_allocator();
  8183. Token token = {Token_Ident};
  8184. isize name_len = prefix.len + 1 + 20;
  8185. auto suffix_id = cast(unsigned long long)id;
  8186. char *text = gb_alloc_array(a, char, name_len+1);
  8187. gb_snprintf(text, name_len,
  8188. "%.*s-%llu", LIT(prefix), suffix_id);
  8189. text[name_len] = 0;
  8190. String s = make_string_c(text);
  8191. Type *t = alloc_type_array(elem_type, count);
  8192. lbValue g = {};
  8193. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  8194. g.type = alloc_type_pointer(t);
  8195. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  8196. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  8197. map_set(&m->members, hash_string(s), g);
  8198. return g;
  8199. }
  8200. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  8201. lbModule *m = p->module;
  8202. LLVMContextRef ctx = m->ctx;
  8203. gbAllocator a = heap_allocator();
  8204. CheckerInfo *info = m->info;
  8205. {
  8206. // NOTE(bill): Set the type_table slice with the global backing array
  8207. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  8208. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  8209. GB_ASSERT(is_type_array(type));
  8210. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  8211. LLVMValueRef values[2] = {
  8212. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  8213. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  8214. };
  8215. LLVMValueRef slice = LLVMConstStructInContext(ctx, values, gb_count_of(values), false);
  8216. LLVMSetInitializer(global_type_table.value, slice);
  8217. }
  8218. // Useful types
  8219. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  8220. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  8221. i32 type_info_member_types_index = 0;
  8222. i32 type_info_member_names_index = 0;
  8223. i32 type_info_member_offsets_index = 0;
  8224. for_array(type_info_type_index, info->type_info_types) {
  8225. Type *t = info->type_info_types[type_info_type_index];
  8226. t = default_type(t);
  8227. if (t == t_invalid) {
  8228. continue;
  8229. }
  8230. isize entry_index = lb_type_info_index(info, t, false);
  8231. if (entry_index <= 0) {
  8232. continue;
  8233. }
  8234. lbValue tag = {};
  8235. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  8236. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 3);
  8237. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  8238. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  8239. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), lb_typeid(m, t));
  8240. switch (t->kind) {
  8241. case Type_Named: {
  8242. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  8243. LLVMValueRef vals[2] = {
  8244. lb_const_string(p->module, t->Named.type_name->token.string).value,
  8245. lb_get_type_info_ptr(m, t->Named.base).value,
  8246. };
  8247. lbValue res = {};
  8248. res.type = type_deref(tag.type);
  8249. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8250. lb_emit_store(p, tag, res);
  8251. break;
  8252. }
  8253. case Type_Basic:
  8254. switch (t->Basic.kind) {
  8255. case Basic_bool:
  8256. case Basic_b8:
  8257. case Basic_b16:
  8258. case Basic_b32:
  8259. case Basic_b64:
  8260. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  8261. break;
  8262. case Basic_i8:
  8263. case Basic_u8:
  8264. case Basic_i16:
  8265. case Basic_u16:
  8266. case Basic_i32:
  8267. case Basic_u32:
  8268. case Basic_i64:
  8269. case Basic_u64:
  8270. case Basic_i128:
  8271. case Basic_u128:
  8272. case Basic_i16le:
  8273. case Basic_u16le:
  8274. case Basic_i32le:
  8275. case Basic_u32le:
  8276. case Basic_i64le:
  8277. case Basic_u64le:
  8278. case Basic_i128le:
  8279. case Basic_u128le:
  8280. case Basic_i16be:
  8281. case Basic_u16be:
  8282. case Basic_i32be:
  8283. case Basic_u32be:
  8284. case Basic_i64be:
  8285. case Basic_u64be:
  8286. case Basic_i128be:
  8287. case Basic_u128be:
  8288. case Basic_int:
  8289. case Basic_uint:
  8290. case Basic_uintptr: {
  8291. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  8292. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  8293. // NOTE(bill): This is matches the runtime layout
  8294. u8 endianness_value = 0;
  8295. if (t->Basic.flags & BasicFlag_EndianLittle) {
  8296. endianness_value = 1;
  8297. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  8298. endianness_value = 2;
  8299. }
  8300. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  8301. LLVMValueRef vals[2] = {
  8302. is_signed.value,
  8303. endianness.value,
  8304. };
  8305. lbValue res = {};
  8306. res.type = type_deref(tag.type);
  8307. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8308. lb_emit_store(p, tag, res);
  8309. break;
  8310. }
  8311. case Basic_rune:
  8312. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  8313. break;
  8314. // case Basic_f16:
  8315. case Basic_f32:
  8316. case Basic_f64:
  8317. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  8318. break;
  8319. // case Basic_complex32:
  8320. case Basic_complex64:
  8321. case Basic_complex128:
  8322. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  8323. break;
  8324. case Basic_quaternion128:
  8325. case Basic_quaternion256:
  8326. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  8327. break;
  8328. case Basic_rawptr:
  8329. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  8330. break;
  8331. case Basic_string:
  8332. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  8333. break;
  8334. case Basic_cstring:
  8335. {
  8336. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  8337. LLVMValueRef vals[1] = {
  8338. lb_const_bool(m, t_bool, true).value,
  8339. };
  8340. lbValue res = {};
  8341. res.type = type_deref(tag.type);
  8342. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8343. lb_emit_store(p, tag, res);
  8344. }
  8345. break;
  8346. case Basic_any:
  8347. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  8348. break;
  8349. case Basic_typeid:
  8350. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  8351. break;
  8352. }
  8353. break;
  8354. case Type_Pointer: {
  8355. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  8356. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  8357. LLVMValueRef vals[1] = {
  8358. gep.value,
  8359. };
  8360. lbValue res = {};
  8361. res.type = type_deref(tag.type);
  8362. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8363. lb_emit_store(p, tag, res);
  8364. break;
  8365. }
  8366. case Type_Array: {
  8367. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  8368. i64 ez = type_size_of(t->Array.elem);
  8369. LLVMValueRef vals[3] = {
  8370. lb_get_type_info_ptr(m, t->Array.elem).value,
  8371. lb_const_int(m, t_int, ez).value,
  8372. lb_const_int(m, t_int, t->Array.count).value,
  8373. };
  8374. lbValue res = {};
  8375. res.type = type_deref(tag.type);
  8376. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8377. lb_emit_store(p, tag, res);
  8378. break;
  8379. }
  8380. case Type_EnumeratedArray: {
  8381. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  8382. LLVMValueRef vals[6] = {
  8383. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  8384. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  8385. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  8386. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  8387. // Unions
  8388. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  8389. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  8390. };
  8391. lbValue res = {};
  8392. res.type = type_deref(tag.type);
  8393. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8394. lb_emit_store(p, tag, res);
  8395. // NOTE(bill): Union assignment
  8396. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  8397. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  8398. lbValue min_v = lb_const_value(m, core_type(t->EnumeratedArray.index), t->EnumeratedArray.min_value);
  8399. lbValue max_v = lb_const_value(m, core_type(t->EnumeratedArray.index), t->EnumeratedArray.max_value);
  8400. lb_emit_store_union_variant(p, min_value, min_v, min_v.type);
  8401. lb_emit_store_union_variant(p, max_value, max_v, max_v.type);
  8402. break;
  8403. }
  8404. case Type_DynamicArray: {
  8405. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  8406. LLVMValueRef vals[2] = {
  8407. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  8408. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  8409. };
  8410. lbValue res = {};
  8411. res.type = type_deref(tag.type);
  8412. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8413. lb_emit_store(p, tag, res);
  8414. break;
  8415. }
  8416. case Type_Slice: {
  8417. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  8418. LLVMValueRef vals[2] = {
  8419. lb_get_type_info_ptr(m, t->Slice.elem).value,
  8420. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  8421. };
  8422. lbValue res = {};
  8423. res.type = type_deref(tag.type);
  8424. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8425. lb_emit_store(p, tag, res);
  8426. break;
  8427. }
  8428. case Type_Proc: {
  8429. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  8430. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  8431. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  8432. if (t->Proc.params != nullptr) {
  8433. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  8434. }
  8435. if (t->Proc.results != nullptr) {
  8436. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  8437. }
  8438. LLVMValueRef vals[4] = {
  8439. params,
  8440. results,
  8441. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  8442. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  8443. };
  8444. lbValue res = {};
  8445. res.type = type_deref(tag.type);
  8446. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8447. lb_emit_store(p, tag, res);
  8448. break;
  8449. }
  8450. case Type_Tuple: {
  8451. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  8452. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  8453. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  8454. for_array(i, t->Tuple.variables) {
  8455. // NOTE(bill): offset is not used for tuples
  8456. Entity *f = t->Tuple.variables[i];
  8457. lbValue index = lb_const_int(m, t_int, i);
  8458. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  8459. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  8460. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  8461. if (f->token.string.len > 0) {
  8462. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  8463. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  8464. }
  8465. }
  8466. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  8467. LLVMValueRef types_slice = llvm_const_slice(memory_types, count);
  8468. LLVMValueRef names_slice = llvm_const_slice(memory_names, count);
  8469. LLVMValueRef vals[2] = {
  8470. types_slice,
  8471. names_slice,
  8472. };
  8473. lbValue res = {};
  8474. res.type = type_deref(tag.type);
  8475. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8476. lb_emit_store(p, tag, res);
  8477. break;
  8478. }
  8479. case Type_Enum:
  8480. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  8481. {
  8482. GB_ASSERT(t->Enum.base_type != nullptr);
  8483. GB_ASSERT(type_size_of(t_type_info_enum_value) == 16);
  8484. LLVMValueRef vals[3] = {};
  8485. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  8486. if (t->Enum.fields.count > 0) {
  8487. auto fields = t->Enum.fields;
  8488. lbValue name_array = lb_generate_array(m, t_string, fields.count,
  8489. str_lit("$enum_names"), cast(i64)entry_index);
  8490. lbValue value_array = lb_generate_array(m, t_type_info_enum_value, fields.count,
  8491. str_lit("$enum_values"), cast(i64)entry_index);
  8492. LLVMValueRef *name_values = gb_alloc_array(heap_allocator(), LLVMValueRef, fields.count);
  8493. LLVMValueRef *value_values = gb_alloc_array(heap_allocator(), LLVMValueRef, fields.count);
  8494. defer (gb_free(heap_allocator(), name_values));
  8495. defer (gb_free(heap_allocator(), value_values));
  8496. GB_ASSERT(is_type_integer(t->Enum.base_type));
  8497. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  8498. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  8499. LLVMTypeRef u64_type = lb_type(m, t_u64);
  8500. for_array(i, fields) {
  8501. ExactValue value = fields[i]->Constant.value;
  8502. lbValue v = lb_const_value(m, t->Enum.base_type, value);
  8503. LLVMValueRef zv = LLVMConstZExt(v.value, u64_type);
  8504. lbValue tag = lb_const_union_tag(m, t_type_info_enum_value, v.type);
  8505. LLVMValueRef vals[3] = {
  8506. LLVMConstNull(align_type),
  8507. zv,
  8508. tag.value,
  8509. };
  8510. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  8511. value_values[i] = LLVMConstStruct(vals, gb_count_of(vals), false);
  8512. }
  8513. LLVMValueRef name_init = LLVMConstArray(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  8514. LLVMValueRef value_init = LLVMConstArray(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  8515. LLVMSetInitializer(name_array.value, name_init);
  8516. LLVMSetInitializer(value_array.value, value_init);
  8517. lbValue v_count = lb_const_int(m, t_int, fields.count);
  8518. vals[1] = llvm_const_slice(lb_array_elem(p, name_array), v_count);
  8519. vals[2] = llvm_const_slice(lb_array_elem(p, value_array), v_count);
  8520. } else {
  8521. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  8522. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  8523. }
  8524. lbValue res = {};
  8525. res.type = type_deref(tag.type);
  8526. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8527. lb_emit_store(p, tag, res);
  8528. }
  8529. break;
  8530. case Type_Union: {
  8531. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  8532. {
  8533. LLVMValueRef vals[6] = {};
  8534. isize variant_count = gb_max(0, t->Union.variants.count);
  8535. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  8536. // NOTE(bill): Zeroth is nil so ignore it
  8537. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  8538. Type *vt = t->Union.variants[variant_index];
  8539. lbValue tip = lb_get_type_info_ptr(m, vt);
  8540. lbValue index = lb_const_int(m, t_int, variant_index);
  8541. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  8542. lb_emit_store(p, type_info, lb_type_info(m, vt));
  8543. }
  8544. lbValue count = lb_const_int(m, t_int, variant_count);
  8545. vals[0] = llvm_const_slice(memory_types, count);
  8546. i64 tag_size = union_tag_size(t);
  8547. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  8548. if (tag_size > 0) {
  8549. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  8550. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  8551. } else {
  8552. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  8553. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  8554. }
  8555. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  8556. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  8557. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  8558. lbValue res = {};
  8559. res.type = type_deref(tag.type);
  8560. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8561. lb_emit_store(p, tag, res);
  8562. }
  8563. break;
  8564. }
  8565. case Type_Struct: {
  8566. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  8567. LLVMValueRef vals[11] = {};
  8568. {
  8569. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  8570. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  8571. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  8572. vals[5] = is_packed.value;
  8573. vals[6] = is_raw_union.value;
  8574. vals[7] = is_custom_align.value;
  8575. if (t->Struct.soa_kind != StructSoa_None) {
  8576. lbValue kind = lb_emit_struct_ep(p, tag, 8);
  8577. Type *kind_type = type_deref(kind.type);
  8578. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  8579. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  8580. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  8581. vals[8] = soa_kind.value;
  8582. vals[9] = soa_type.value;
  8583. vals[10] = soa_len.value;
  8584. }
  8585. }
  8586. isize count = t->Struct.fields.count;
  8587. if (count > 0) {
  8588. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  8589. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  8590. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  8591. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  8592. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  8593. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  8594. for (isize source_index = 0; source_index < count; source_index++) {
  8595. // TODO(bill): Order fields in source order not layout order
  8596. Entity *f = t->Struct.fields[source_index];
  8597. lbValue tip = lb_get_type_info_ptr(m, f->type);
  8598. i64 foffset = 0;
  8599. if (!t->Struct.is_raw_union) {
  8600. foffset = t->Struct.offsets[f->Variable.field_index];
  8601. }
  8602. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  8603. lbValue index = lb_const_int(m, t_int, source_index);
  8604. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  8605. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  8606. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  8607. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  8608. if (f->token.string.len > 0) {
  8609. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  8610. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  8611. }
  8612. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  8613. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  8614. if (t->Struct.tags.count > 0) {
  8615. String tag_string = t->Struct.tags[source_index];
  8616. if (tag_string.len > 0) {
  8617. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  8618. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  8619. }
  8620. }
  8621. }
  8622. lbValue cv = lb_const_int(m, t_int, count);
  8623. vals[0] = llvm_const_slice(memory_types, cv);
  8624. vals[1] = llvm_const_slice(memory_names, cv);
  8625. vals[2] = llvm_const_slice(memory_offsets, cv);
  8626. vals[3] = llvm_const_slice(memory_usings, cv);
  8627. vals[4] = llvm_const_slice(memory_tags, cv);
  8628. }
  8629. for (isize i = 0; i < gb_count_of(vals); i++) {
  8630. if (vals[i] == nullptr) {
  8631. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  8632. }
  8633. }
  8634. lbValue res = {};
  8635. res.type = type_deref(tag.type);
  8636. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8637. lb_emit_store(p, tag, res);
  8638. break;
  8639. }
  8640. case Type_Map: {
  8641. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  8642. init_map_internal_types(t);
  8643. LLVMValueRef vals[3] = {
  8644. lb_get_type_info_ptr(m, t->Map.key).value,
  8645. lb_get_type_info_ptr(m, t->Map.value).value,
  8646. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  8647. };
  8648. lbValue res = {};
  8649. res.type = type_deref(tag.type);
  8650. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8651. lb_emit_store(p, tag, res);
  8652. break;
  8653. }
  8654. case Type_BitField: {
  8655. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_field_ptr);
  8656. // names: []string;
  8657. // bits: []u32;
  8658. // offsets: []u32;
  8659. isize count = t->BitField.fields.count;
  8660. if (count > 0) {
  8661. auto fields = t->BitField.fields;
  8662. lbValue name_array = lb_generate_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  8663. lbValue bit_array = lb_generate_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  8664. lbValue offset_array = lb_generate_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  8665. for (isize i = 0; i < count; i++) {
  8666. Entity *f = fields[i];
  8667. GB_ASSERT(f->type != nullptr);
  8668. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  8669. lbValue name_ep = lb_emit_array_epi(p, name_array, cast(i32)i);
  8670. lbValue bit_ep = lb_emit_array_epi(p, bit_array, cast(i32)i);
  8671. lbValue offset_ep = lb_emit_array_epi(p, offset_array, cast(i32)i);
  8672. lb_emit_store(p, name_ep, lb_const_string(m, f->token.string));
  8673. lb_emit_store(p, bit_ep, lb_const_int(m, t_i32, f->type->BitFieldValue.bits));
  8674. lb_emit_store(p, offset_ep, lb_const_int(m, t_i32, t->BitField.offsets[i]));
  8675. }
  8676. lbValue v_count = lb_const_int(m, t_int, count);
  8677. lbValue name_array_elem = lb_array_elem(p, name_array);
  8678. lbValue bit_array_elem = lb_array_elem(p, bit_array);
  8679. lbValue offset_array_elem = lb_array_elem(p, offset_array);
  8680. LLVMValueRef vals[3] = {
  8681. llvm_const_slice(name_array_elem, v_count),
  8682. llvm_const_slice(bit_array_elem, v_count),
  8683. llvm_const_slice(offset_array_elem, v_count),
  8684. };
  8685. lbValue res = {};
  8686. res.type = type_deref(tag.type);
  8687. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8688. lb_emit_store(p, tag, res);
  8689. }
  8690. break;
  8691. }
  8692. case Type_BitSet:
  8693. {
  8694. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  8695. GB_ASSERT(is_type_typed(t->BitSet.elem));
  8696. LLVMValueRef vals[4] = {
  8697. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  8698. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  8699. lb_const_int(m, t_i64, t->BitSet.lower).value,
  8700. lb_const_int(m, t_i64, t->BitSet.upper).value,
  8701. };
  8702. if (t->BitSet.underlying != nullptr) {
  8703. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  8704. }
  8705. lbValue res = {};
  8706. res.type = type_deref(tag.type);
  8707. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8708. lb_emit_store(p, tag, res);
  8709. }
  8710. break;
  8711. case Type_Opaque:
  8712. {
  8713. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_opaque_ptr);
  8714. LLVMValueRef vals[1] = {
  8715. lb_get_type_info_ptr(m, t->Opaque.elem).value,
  8716. };
  8717. lbValue res = {};
  8718. res.type = type_deref(tag.type);
  8719. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8720. lb_emit_store(p, tag, res);
  8721. }
  8722. break;
  8723. case Type_SimdVector:
  8724. {
  8725. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  8726. LLVMValueRef vals[4] = {};
  8727. if (t->SimdVector.is_x86_mmx) {
  8728. vals[3] = lb_const_bool(m, t_bool, true).value;
  8729. } else {
  8730. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  8731. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  8732. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  8733. }
  8734. lbValue res = {};
  8735. res.type = type_deref(tag.type);
  8736. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  8737. lb_emit_store(p, tag, res);
  8738. }
  8739. break;
  8740. }
  8741. if (tag.value != nullptr) {
  8742. Type *tag_type = type_deref(tag.type);
  8743. GB_ASSERT(is_type_named(tag_type));
  8744. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  8745. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  8746. } else {
  8747. if (t != t_llvm_bool) {
  8748. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  8749. }
  8750. }
  8751. }
  8752. }
  8753. void lb_generate_code(lbGenerator *gen) {
  8754. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  8755. TIME_SECTION("LLVM Initializtion");
  8756. lbModule *m = &gen->module;
  8757. LLVMModuleRef mod = gen->module.mod;
  8758. CheckerInfo *info = gen->info;
  8759. Arena temp_arena = {};
  8760. arena_init(&temp_arena, heap_allocator());
  8761. gbAllocator temp_allocator = arena_allocator(&temp_arena);
  8762. gen->module.global_default_context = lb_add_global_generated(m, t_context, {});
  8763. gen->module.global_default_context.kind = lbAddr_Context;
  8764. auto *min_dep_set = &info->minimum_dependency_set;
  8765. LLVMInitializeAllTargetInfos();
  8766. LLVMInitializeAllTargets();
  8767. LLVMInitializeAllTargetMCs();
  8768. LLVMInitializeAllAsmPrinters();
  8769. LLVMInitializeAllAsmParsers();
  8770. LLVMInitializeAllDisassemblers();
  8771. LLVMInitializeNativeTarget();
  8772. char const *target_triple = "x86_64-pc-windows-msvc";
  8773. char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128";
  8774. LLVMSetTarget(mod, target_triple);
  8775. LLVMTargetRef target = {};
  8776. char *llvm_error = nullptr;
  8777. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  8778. GB_ASSERT(target != nullptr);
  8779. TIME_SECTION("LLVM Create Target Machine");
  8780. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault);
  8781. defer (LLVMDisposeTargetMachine(target_machine));
  8782. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  8783. { // Debug Info
  8784. for_array(i, info->files.entries) {
  8785. AstFile *f = info->files.entries[i].value;
  8786. String fullpath = f->fullpath;
  8787. String filename = filename_from_path(fullpath);
  8788. String directory = directory_from_path(fullpath);
  8789. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  8790. cast(char const *)filename.text, filename.len,
  8791. cast(char const *)directory.text, directory.len);
  8792. map_set(&m->debug_values, hash_pointer(f), res);
  8793. f->llvm_metadata = res;
  8794. }
  8795. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC,
  8796. cast(LLVMMetadataRef)m->info->files.entries[0].value->llvm_metadata,
  8797. "odin", 4,
  8798. false, "", 0,
  8799. 1, "", 0,
  8800. LLVMDWARFEmissionFull, 0, true,
  8801. true
  8802. );
  8803. }
  8804. TIME_SECTION("LLVM Global Variables");
  8805. {
  8806. { // Add type info data
  8807. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  8808. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  8809. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  8810. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  8811. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8812. LLVMSetLinkage(g, LLVMInternalLinkage);
  8813. lbValue value = {};
  8814. value.value = g;
  8815. value.type = alloc_type_pointer(t);
  8816. lb_global_type_info_data = lb_addr(value);
  8817. }
  8818. { // Type info member buffer
  8819. // NOTE(bill): Removes need for heap allocation by making it global memory
  8820. isize count = 0;
  8821. for_array(entry_index, m->info->type_info_types) {
  8822. Type *t = m->info->type_info_types[entry_index];
  8823. isize index = lb_type_info_index(m->info, t, false);
  8824. if (index < 0) {
  8825. continue;
  8826. }
  8827. switch (t->kind) {
  8828. case Type_Union:
  8829. count += t->Union.variants.count;
  8830. break;
  8831. case Type_Struct:
  8832. count += t->Struct.fields.count;
  8833. break;
  8834. case Type_Tuple:
  8835. count += t->Tuple.variables.count;
  8836. break;
  8837. }
  8838. }
  8839. if (count > 0) {
  8840. {
  8841. char const *name = LB_TYPE_INFO_TYPES_NAME;
  8842. Type *t = alloc_type_array(t_type_info_ptr, count);
  8843. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8844. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8845. LLVMSetLinkage(g, LLVMInternalLinkage);
  8846. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  8847. }
  8848. {
  8849. char const *name = LB_TYPE_INFO_NAMES_NAME;
  8850. Type *t = alloc_type_array(t_string, count);
  8851. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8852. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8853. LLVMSetLinkage(g, LLVMInternalLinkage);
  8854. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  8855. }
  8856. {
  8857. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  8858. Type *t = alloc_type_array(t_uintptr, count);
  8859. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8860. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8861. LLVMSetLinkage(g, LLVMInternalLinkage);
  8862. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  8863. }
  8864. {
  8865. char const *name = LB_TYPE_INFO_USINGS_NAME;
  8866. Type *t = alloc_type_array(t_bool, count);
  8867. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8868. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8869. LLVMSetLinkage(g, LLVMInternalLinkage);
  8870. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  8871. }
  8872. {
  8873. char const *name = LB_TYPE_INFO_TAGS_NAME;
  8874. Type *t = alloc_type_array(t_string, count);
  8875. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8876. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8877. LLVMSetLinkage(g, LLVMInternalLinkage);
  8878. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  8879. }
  8880. }
  8881. }
  8882. }
  8883. isize global_variable_max_count = 0;
  8884. Entity *entry_point = info->entry_point;
  8885. bool has_dll_main = false;
  8886. bool has_win_main = false;
  8887. for_array(i, info->entities) {
  8888. Entity *e = info->entities[i];
  8889. String name = e->token.string;
  8890. bool is_global = e->pkg != nullptr;
  8891. if (e->kind == Entity_Variable) {
  8892. global_variable_max_count++;
  8893. } else if (e->kind == Entity_Procedure && !is_global) {
  8894. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  8895. GB_ASSERT(e == entry_point);
  8896. // entry_point = e;
  8897. }
  8898. if (e->Procedure.is_export ||
  8899. (e->Procedure.link_name.len > 0) ||
  8900. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  8901. if (!has_dll_main && name == "DllMain") {
  8902. has_dll_main = true;
  8903. } else if (!has_win_main && name == "WinMain") {
  8904. has_win_main = true;
  8905. }
  8906. }
  8907. }
  8908. }
  8909. struct GlobalVariable {
  8910. lbValue var;
  8911. lbValue init;
  8912. DeclInfo *decl;
  8913. };
  8914. auto global_variables = array_make<GlobalVariable>(heap_allocator(), 0, global_variable_max_count);
  8915. for_array(i, info->variable_init_order) {
  8916. DeclInfo *d = info->variable_init_order[i];
  8917. Entity *e = d->entity;
  8918. if ((e->scope->flags & ScopeFlag_File) == 0) {
  8919. continue;
  8920. }
  8921. if (!ptr_set_exists(min_dep_set, e)) {
  8922. continue;
  8923. }
  8924. DeclInfo *decl = decl_info_of_entity(e);
  8925. if (decl == nullptr) {
  8926. continue;
  8927. }
  8928. GB_ASSERT(e->kind == Entity_Variable);
  8929. bool is_foreign = e->Variable.is_foreign;
  8930. bool is_export = e->Variable.is_export;
  8931. String name = lb_get_entity_name(m, e);
  8932. lbValue g = {};
  8933. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(heap_allocator(), name));
  8934. g.type = alloc_type_pointer(e->type);
  8935. if (e->Variable.thread_local_model != "") {
  8936. LLVMSetThreadLocal(g.value, true);
  8937. String m = e->Variable.thread_local_model;
  8938. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  8939. if (m == "default") {
  8940. mode = LLVMGeneralDynamicTLSModel;
  8941. } else if (m == "localdynamic") {
  8942. mode = LLVMLocalDynamicTLSModel;
  8943. } else if (m == "initialexec") {
  8944. mode = LLVMInitialExecTLSModel;
  8945. } else if (m == "localexec") {
  8946. mode = LLVMLocalExecTLSModel;
  8947. } else {
  8948. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  8949. }
  8950. LLVMSetThreadLocalMode(g.value, mode);
  8951. }
  8952. if (is_foreign) {
  8953. LLVMSetExternallyInitialized(g.value, true);
  8954. } else {
  8955. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  8956. }
  8957. if (is_export) {
  8958. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  8959. }
  8960. GlobalVariable var = {};
  8961. var.var = g;
  8962. var.decl = decl;
  8963. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  8964. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  8965. if (tav.mode != Addressing_Invalid) {
  8966. if (tav.value.kind != ExactValue_Invalid) {
  8967. ExactValue v = tav.value;
  8968. lbValue init = lb_const_value(m, tav.type, v);
  8969. LLVMSetInitializer(g.value, init.value);
  8970. }
  8971. }
  8972. }
  8973. array_add(&global_variables, var);
  8974. lb_add_entity(m, e, g);
  8975. lb_add_member(m, name, g);
  8976. }
  8977. TIME_SECTION("LLVM Global Procedures and Types");
  8978. for_array(i, info->entities) {
  8979. // arena_free_all(&temp_arena);
  8980. // gbAllocator a = temp_allocator;
  8981. Entity *e = info->entities[i];
  8982. String name = e->token.string;
  8983. DeclInfo *decl = e->decl_info;
  8984. Scope * scope = e->scope;
  8985. if ((scope->flags & ScopeFlag_File) == 0) {
  8986. continue;
  8987. }
  8988. Scope *package_scope = scope->parent;
  8989. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  8990. switch (e->kind) {
  8991. case Entity_Variable:
  8992. // NOTE(bill): Handled above as it requires a specific load order
  8993. continue;
  8994. case Entity_ProcGroup:
  8995. continue;
  8996. case Entity_TypeName:
  8997. case Entity_Procedure:
  8998. break;
  8999. }
  9000. bool polymorphic_struct = false;
  9001. if (e->type != nullptr && e->kind == Entity_TypeName) {
  9002. Type *bt = base_type(e->type);
  9003. if (bt->kind == Type_Struct) {
  9004. polymorphic_struct = is_type_polymorphic(bt);
  9005. }
  9006. }
  9007. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  9008. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  9009. continue;
  9010. }
  9011. String mangled_name = lb_get_entity_name(m, e);
  9012. switch (e->kind) {
  9013. case Entity_TypeName:
  9014. lb_type(m, e->type);
  9015. break;
  9016. case Entity_Procedure:
  9017. {
  9018. lbProcedure *p = lb_create_procedure(m, e);
  9019. array_add(&m->procedures_to_generate, p);
  9020. }
  9021. break;
  9022. }
  9023. }
  9024. TIME_SECTION("LLVM Procedure Generation");
  9025. for_array(i, m->procedures_to_generate) {
  9026. lbProcedure *p = m->procedures_to_generate[i];
  9027. if (p->is_done) {
  9028. continue;
  9029. }
  9030. if (p->body != nullptr) { // Build Procedure
  9031. lb_begin_procedure_body(p);
  9032. lb_build_stmt(p, p->body);
  9033. lb_end_procedure_body(p);
  9034. p->is_done = true;
  9035. }
  9036. lb_end_procedure(p);
  9037. // Add Flags
  9038. if (p->body != nullptr) {
  9039. if (p->name == "memcpy" || p->name == "memmove" ||
  9040. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  9041. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  9042. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  9043. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  9044. }
  9045. }
  9046. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  9047. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  9048. LLVMDumpValue(p->value);
  9049. gb_printf_err("\n\n\n\n");
  9050. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  9051. }
  9052. }
  9053. TIME_SECTION("LLVM Function Pass");
  9054. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  9055. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  9056. defer (LLVMDisposePassManager(default_function_pass_manager));
  9057. {
  9058. LLVMAddMemCpyOptPass(default_function_pass_manager);
  9059. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  9060. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  9061. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager);
  9062. LLVMAddConstantPropagationPass(default_function_pass_manager);
  9063. LLVMAddAggressiveDCEPass(default_function_pass_manager);
  9064. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  9065. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  9066. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager);
  9067. }
  9068. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  9069. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  9070. {
  9071. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  9072. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  9073. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager_without_memcpy);
  9074. LLVMAddConstantPropagationPass(default_function_pass_manager_without_memcpy);
  9075. LLVMAddAggressiveDCEPass(default_function_pass_manager_without_memcpy);
  9076. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  9077. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  9078. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager_without_memcpy);
  9079. }
  9080. for_array(i, m->procedures_to_generate) {
  9081. lbProcedure *p = m->procedures_to_generate[i];
  9082. if (p->body != nullptr) { // Build Procedure
  9083. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  9084. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  9085. } else {
  9086. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  9087. }
  9088. }
  9089. }
  9090. TIME_SECTION("LLVM Runtime Creation");
  9091. lbProcedure *startup_type_info = nullptr;
  9092. lbProcedure *startup_context = nullptr;
  9093. lbProcedure *startup_runtime = nullptr;
  9094. { // Startup Type Info
  9095. Type *params = alloc_type_tuple();
  9096. Type *results = alloc_type_tuple();
  9097. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  9098. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  9099. p->is_startup = true;
  9100. startup_type_info = p;
  9101. lb_begin_procedure_body(p);
  9102. lb_setup_type_info_data(p);
  9103. lb_end_procedure_body(p);
  9104. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  9105. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  9106. LLVMDumpValue(p->value);
  9107. gb_printf_err("\n\n\n\n");
  9108. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  9109. }
  9110. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  9111. }
  9112. { // Startup Context
  9113. Type *params = alloc_type_tuple();
  9114. Type *results = alloc_type_tuple();
  9115. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  9116. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_CONTEXT_PROC_NAME), proc_type);
  9117. p->is_startup = true;
  9118. startup_context = p;
  9119. lb_begin_procedure_body(p);
  9120. lb_emit_init_context(p, p->module->global_default_context);
  9121. lb_end_procedure_body(p);
  9122. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  9123. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  9124. LLVMDumpValue(p->value);
  9125. gb_printf_err("\n\n\n\n");
  9126. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  9127. }
  9128. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  9129. }
  9130. { // Startup Runtime
  9131. Type *params = alloc_type_tuple();
  9132. Type *results = alloc_type_tuple();
  9133. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  9134. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  9135. p->is_startup = true;
  9136. startup_runtime = p;
  9137. lb_begin_procedure_body(p);
  9138. for_array(i, global_variables) {
  9139. auto *var = &global_variables[i];
  9140. if (var->decl->init_expr != nullptr) {
  9141. var->init = lb_build_expr(p, var->decl->init_expr);
  9142. }
  9143. Entity *e = var->decl->entity;
  9144. GB_ASSERT(e->kind == Entity_Variable);
  9145. if (e->Variable.is_foreign) {
  9146. Entity *fl = e->Procedure.foreign_library;
  9147. lb_add_foreign_library_path(m, fl);
  9148. }
  9149. if (e->flags & EntityFlag_Static) {
  9150. LLVMSetLinkage(var->var.value, LLVMInternalLinkage);
  9151. }
  9152. if (var->init.value != nullptr) {
  9153. Type *t = type_deref(var->var.type);
  9154. if (is_type_any(t)) {
  9155. // NOTE(bill): Edge case for 'any' type
  9156. Type *var_type = default_type(var->init.type);
  9157. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  9158. lb_addr_store(p, g, var->init);
  9159. lbValue gp = lb_addr_get_ptr(p, g);
  9160. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  9161. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  9162. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  9163. lb_emit_store(p, ti, lb_type_info(m, var_type));
  9164. } else {
  9165. lb_emit_store(p, var->var, lb_emit_conv(p, var->init, t));
  9166. }
  9167. }
  9168. }
  9169. lb_end_procedure_body(p);
  9170. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  9171. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  9172. LLVMDumpValue(p->value);
  9173. gb_printf_err("\n\n\n\n");
  9174. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  9175. }
  9176. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  9177. /*{
  9178. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  9179. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  9180. instr != last_instr;
  9181. instr = LLVMGetNextInstruction(instr)) {
  9182. if (LLVMIsAAllocaInst(instr)) {
  9183. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  9184. LLVMValueRef sz_val = LLVMSizeOf(type);
  9185. GB_ASSERT(LLVMIsConstant(sz_val));
  9186. gb_printf_err(">> 0x%p\n", sz_val);
  9187. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  9188. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  9189. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  9190. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  9191. gb_printf_err(">> %ll\n", sz);
  9192. }
  9193. }
  9194. }*/
  9195. }
  9196. if (!(build_context.is_dll && !has_dll_main)) {
  9197. Type *params = alloc_type_tuple();
  9198. Type *results = alloc_type_tuple();
  9199. array_init(&params->Tuple.variables, heap_allocator(), 2);
  9200. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  9201. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  9202. array_init(&results->Tuple.variables, heap_allocator(), 1);
  9203. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  9204. Type *proc_type = alloc_type_proc(nullptr, params, 2, results, 1, false, ProcCC_CDecl);
  9205. lbProcedure *p = lb_create_dummy_procedure(m, str_lit("main"), proc_type);
  9206. p->is_startup = true;
  9207. lb_begin_procedure_body(p);
  9208. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  9209. GB_ASSERT(found != nullptr);
  9210. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  9211. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_context->type)), startup_context->value, nullptr, 0, "");
  9212. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  9213. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  9214. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  9215. lb_end_procedure_body(p);
  9216. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  9217. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  9218. LLVMDumpValue(p->value);
  9219. gb_printf_err("\n\n\n\n");
  9220. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  9221. }
  9222. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  9223. }
  9224. TIME_SECTION("LLVM Module Pass");
  9225. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  9226. defer (LLVMDisposePassManager(module_pass_manager));
  9227. LLVMAddAlwaysInlinerPass(module_pass_manager);
  9228. LLVMAddStripDeadPrototypesPass(module_pass_manager);
  9229. // LLVMAddConstantMergePass(module_pass_manager);
  9230. LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate();
  9231. defer (LLVMPassManagerBuilderDispose(pass_manager_builder));
  9232. LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, build_context.optimization_level);
  9233. LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, build_context.optimization_level);
  9234. LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false);
  9235. LLVMRunPassManager(module_pass_manager, mod);
  9236. llvm_error = nullptr;
  9237. defer (LLVMDisposeMessage(llvm_error));
  9238. String filepath_ll = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".ll"));
  9239. defer (gb_free(heap_allocator(), filepath_ll.text));
  9240. String filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".obj"));
  9241. if (build_context.keep_temp_files) {
  9242. TIME_SECTION("LLVM Print Module to File");
  9243. LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error);
  9244. // exit(1);
  9245. }
  9246. LLVMDIBuilderFinalize(m->debug_builder);
  9247. LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error);
  9248. llvm_error = nullptr;
  9249. TIME_SECTION("LLVM Object Generation");
  9250. LLVMBool was_an_error = LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, LLVMObjectFile, &llvm_error);
  9251. if (was_an_error) {
  9252. gb_printf_err("LLVM Error: %s\n", llvm_error);
  9253. gb_exit(1);
  9254. return;
  9255. }
  9256. array_add(&gen->output_object_paths, filepath_obj);
  9257. #undef TIME_SECTION
  9258. }