llvm_backend.cpp 389 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580
  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_zero(lbModule *m) {
  30. return LLVMConstInt(lb_type(m, t_int), 0, false);
  31. }
  32. LLVMValueRef llvm_one(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. bool lb_is_instr_terminating(LLVMValueRef instr) {
  47. if (instr != nullptr) {
  48. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  49. switch (op) {
  50. case LLVMRet:
  51. case LLVMBr:
  52. case LLVMSwitch:
  53. case LLVMIndirectBr:
  54. case LLVMInvoke:
  55. case LLVMUnreachable:
  56. case LLVMCallBr:
  57. return true;
  58. }
  59. }
  60. return false;
  61. }
  62. lbAddr lb_addr(lbValue addr) {
  63. lbAddr v = {lbAddr_Default, addr};
  64. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  65. GB_ASSERT(is_type_pointer(addr.type));
  66. v.kind = lbAddr_RelativePointer;
  67. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  68. GB_ASSERT(is_type_pointer(addr.type));
  69. v.kind = lbAddr_RelativeSlice;
  70. }
  71. return v;
  72. }
  73. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  74. lbAddr v = {lbAddr_Map, addr};
  75. v.map.key = map_key;
  76. v.map.type = map_type;
  77. v.map.result = map_result;
  78. return v;
  79. }
  80. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  81. lbAddr v = {lbAddr_SoaVariable, addr};
  82. v.soa.index = index;
  83. v.soa.index_expr = index_expr;
  84. return v;
  85. }
  86. lbAddr lb_addr_bit_field(lbValue value, i32 index) {
  87. lbAddr addr = {};
  88. addr.kind = lbAddr_BitField;
  89. addr.addr = value;
  90. addr.bit_field.value_index = index;
  91. return addr;
  92. }
  93. Type *lb_addr_type(lbAddr const &addr) {
  94. if (addr.addr.value == nullptr) {
  95. return nullptr;
  96. }
  97. if (addr.kind == lbAddr_Map) {
  98. Type *t = base_type(addr.map.type);
  99. GB_ASSERT(is_type_map(t));
  100. return t->Map.value;
  101. }
  102. return type_deref(addr.addr.type);
  103. }
  104. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  105. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  106. }
  107. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  108. if (addr.addr.value == nullptr) {
  109. GB_PANIC("Illegal addr -> nullptr");
  110. return {};
  111. }
  112. switch (addr.kind) {
  113. case lbAddr_Map: {
  114. Type *map_type = base_type(addr.map.type);
  115. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  116. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  117. auto args = array_make<lbValue>(heap_allocator(), 2);
  118. args[0] = h;
  119. args[1] = key;
  120. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  121. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  122. }
  123. case lbAddr_RelativePointer: {
  124. Type *rel_ptr = base_type(lb_addr_type(addr));
  125. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  126. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  127. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  128. offset = lb_emit_load(p, offset);
  129. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  130. offset = lb_emit_conv(p, offset, t_i64);
  131. }
  132. offset = lb_emit_conv(p, offset, t_uintptr);
  133. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  134. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  135. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  136. // NOTE(bill): nil check
  137. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  138. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  139. return final_ptr;
  140. }
  141. case lbAddr_BitField: {
  142. lbValue v = lb_addr_load(p, addr);
  143. return lb_address_from_load_or_generate_local(p, v);
  144. }
  145. case lbAddr_Context:
  146. GB_PANIC("lbAddr_Context should be handled elsewhere");
  147. }
  148. return addr.addr;
  149. }
  150. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  151. lbAddr addr = lb_build_addr(p, expr);
  152. return lb_addr_get_ptr(p, addr);
  153. }
  154. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  155. if (build_context.no_bounds_check) {
  156. return;
  157. }
  158. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  159. return;
  160. }
  161. index = lb_emit_conv(p, index, t_int);
  162. len = lb_emit_conv(p, len, t_int);
  163. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  164. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  165. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  166. auto args = array_make<lbValue>(heap_allocator(), 5);
  167. args[0] = file;
  168. args[1] = line;
  169. args[2] = column;
  170. args[3] = index;
  171. args[4] = len;
  172. lb_emit_runtime_call(p, "bounds_check_error", args);
  173. }
  174. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  175. if (build_context.no_bounds_check) {
  176. return;
  177. }
  178. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  179. return;
  180. }
  181. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  182. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  183. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  184. high = lb_emit_conv(p, high, t_int);
  185. if (!lower_value_used) {
  186. auto args = array_make<lbValue>(heap_allocator(), 5);
  187. args[0] = file;
  188. args[1] = line;
  189. args[2] = column;
  190. args[3] = high;
  191. args[4] = len;
  192. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  193. } else {
  194. // No need to convert unless used
  195. low = lb_emit_conv(p, low, t_int);
  196. auto args = array_make<lbValue>(heap_allocator(), 6);
  197. args[0] = file;
  198. args[1] = line;
  199. args[2] = column;
  200. args[3] = low;
  201. args[4] = high;
  202. args[5] = len;
  203. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  204. }
  205. }
  206. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  207. if (addr.addr.value == nullptr) {
  208. return;
  209. }
  210. GB_ASSERT(value.type != nullptr);
  211. if (is_type_untyped_undef(value.type)) {
  212. Type *t = lb_addr_type(addr);
  213. value.type = t;
  214. value.value = LLVMGetUndef(lb_type(p->module, t));
  215. } else if (is_type_untyped_nil(value.type)) {
  216. Type *t = lb_addr_type(addr);
  217. value.type = t;
  218. value.value = LLVMConstNull(lb_type(p->module, t));
  219. }
  220. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  221. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  222. }
  223. if (addr.kind == lbAddr_RelativePointer) {
  224. Type *rel_ptr = base_type(lb_addr_type(addr));
  225. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  226. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  227. GB_ASSERT(is_type_pointer(addr.addr.type));
  228. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  229. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  230. lbValue offset = {};
  231. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  232. offset.type = t_uintptr;
  233. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  234. offset = lb_emit_conv(p, offset, t_i64);
  235. }
  236. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  237. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  238. offset = lb_emit_select(p,
  239. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  240. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  241. offset
  242. );
  243. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  244. return;
  245. } else if (addr.kind == lbAddr_RelativeSlice) {
  246. Type *rel_ptr = base_type(lb_addr_type(addr));
  247. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  248. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  249. GB_ASSERT(is_type_pointer(addr.addr.type));
  250. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  251. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  252. lbValue offset = {};
  253. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  254. offset.type = t_uintptr;
  255. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  256. offset = lb_emit_conv(p, offset, t_i64);
  257. }
  258. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  259. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  260. offset = lb_emit_select(p,
  261. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  262. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  263. offset
  264. );
  265. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  266. lbValue len = lb_slice_len(p, value);
  267. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  268. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  269. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  270. return;
  271. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  272. lbValue ptr = addr.addr;
  273. lbValue index = addr.index_set.index;
  274. Ast *node = addr.index_set.node;
  275. ast_node(ce, CallExpr, node);
  276. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  277. proc_type = base_type(proc_type);
  278. GB_ASSERT(is_type_proc(proc_type));
  279. TypeProc *pt = &proc_type->Proc;
  280. isize arg_count = 3;
  281. isize param_count = 0;
  282. if (pt->params) {
  283. GB_ASSERT(pt->params->kind == Type_Tuple);
  284. param_count = pt->params->Tuple.variables.count;
  285. }
  286. auto args = array_make<lbValue>(heap_allocator(), gb_max(arg_count, param_count));
  287. args[0] = ptr;
  288. args[1] = index;
  289. args[2] = value;
  290. isize arg_index = arg_count;
  291. if (arg_count < param_count) {
  292. lbModule *m = p->module;
  293. String proc_name = {};
  294. if (p->entity != nullptr) {
  295. proc_name = p->entity->token.string;
  296. }
  297. TokenPos pos = ast_token(ce->proc).pos;
  298. TypeTuple *param_tuple = &pt->params->Tuple;
  299. isize end = cast(isize)param_count;
  300. while (arg_index < end) {
  301. Entity *e = param_tuple->variables[arg_index];
  302. GB_ASSERT(e->kind == Entity_Variable);
  303. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  304. }
  305. }
  306. Entity *e = entity_from_expr(ce->proc);
  307. GB_ASSERT(e != nullptr);
  308. GB_ASSERT(is_type_polymorphic(e->type));
  309. {
  310. lbValue *found = nullptr;
  311. if (p->module != e->code_gen_module) {
  312. gb_mutex_lock(&p->module->mutex);
  313. }
  314. found = map_get(&e->code_gen_module->values, hash_entity(e));
  315. if (p->module != e->code_gen_module) {
  316. gb_mutex_unlock(&p->module->mutex);
  317. }
  318. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  319. lb_emit_call(p, *found, args);
  320. }
  321. return;
  322. } else if (addr.kind == lbAddr_Map) {
  323. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  324. return;
  325. } else if (addr.kind == lbAddr_BitField) {
  326. Type *bft = base_type(type_deref(addr.addr.type));
  327. GB_ASSERT(is_type_bit_field(bft));
  328. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  329. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  330. if (size_in_bits == 0) {
  331. return;
  332. }
  333. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  334. LLVMTypeRef dst_type = LLVMIntTypeInContext(p->module->ctx, size_in_bits);
  335. LLVMValueRef src = LLVMBuildIntCast2(p->builder, value.value, dst_type, false, "");
  336. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  337. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  338. LLVMBuildStore(p->builder, src, field_ptr);
  339. return;
  340. } else if (addr.kind == lbAddr_Context) {
  341. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  342. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  343. lb_addr_store(p, next_addr, old);
  344. lb_push_context_onto_stack(p, next_addr);
  345. lbValue next = lb_addr_get_ptr(p, next_addr);
  346. if (addr.ctx.sel.index.count > 0) {
  347. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  348. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  349. lb_emit_store(p, lhs, rhs);
  350. } else {
  351. lbValue lhs = next;
  352. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  353. lb_emit_store(p, lhs, rhs);
  354. }
  355. return;
  356. } else if (addr.kind == lbAddr_SoaVariable) {
  357. Type *t = type_deref(addr.addr.type);
  358. t = base_type(t);
  359. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  360. value = lb_emit_conv(p, value, t->Struct.soa_elem);
  361. lbValue index = addr.soa.index;
  362. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  363. Type *t = base_type(type_deref(addr.addr.type));
  364. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  365. i64 count = t->Struct.soa_count;
  366. lbValue len = lb_const_int(p->module, t_int, count);
  367. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  368. }
  369. for_array(i, t->Struct.fields) {
  370. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  371. dst = lb_emit_array_ep(p, dst, index);
  372. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  373. lb_emit_store(p, dst, src);
  374. }
  375. return;
  376. }
  377. GB_ASSERT(value.value != nullptr);
  378. value = lb_emit_conv(p, value, lb_addr_type(addr));
  379. LLVMBuildStore(p->builder, value.value, addr.addr.value);
  380. }
  381. void lb_const_store(lbValue ptr, lbValue value) {
  382. GB_ASSERT(lb_is_const(ptr));
  383. GB_ASSERT(lb_is_const(value));
  384. GB_ASSERT(is_type_pointer(ptr.type));
  385. LLVMSetInitializer(ptr.value, value.value);
  386. }
  387. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  388. GB_ASSERT(value.value != nullptr);
  389. Type *a = type_deref(ptr.type);
  390. if (is_type_boolean(a)) {
  391. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  392. value = lb_emit_conv(p, value, a);
  393. }
  394. Type *ca = core_type(a);
  395. if (ca->kind == Type_Basic) {
  396. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  397. } else {
  398. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  399. }
  400. LLVMBuildStore(p->builder, value.value, ptr.value);
  401. }
  402. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  403. lbModule *m = p->module;
  404. GB_ASSERT(value.value != nullptr);
  405. Type *t = type_deref(value.type);
  406. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(m, t), value.value, "");
  407. return lbValue{v, t};
  408. }
  409. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  410. GB_ASSERT(addr.addr.value != nullptr);
  411. if (addr.kind == lbAddr_RelativePointer) {
  412. Type *rel_ptr = base_type(lb_addr_type(addr));
  413. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  414. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  415. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  416. offset = lb_emit_load(p, offset);
  417. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  418. offset = lb_emit_conv(p, offset, t_i64);
  419. }
  420. offset = lb_emit_conv(p, offset, t_uintptr);
  421. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  422. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  423. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  424. // NOTE(bill): nil check
  425. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  426. lbValue final_ptr = {};
  427. final_ptr.type = absolute_ptr.type;
  428. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  429. return lb_emit_load(p, final_ptr);
  430. } else if (addr.kind == lbAddr_RelativeSlice) {
  431. Type *rel_ptr = base_type(lb_addr_type(addr));
  432. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  433. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  434. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  435. lbValue offset = lb_emit_load(p, offset_ptr);
  436. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  437. offset = lb_emit_conv(p, offset, t_i64);
  438. }
  439. offset = lb_emit_conv(p, offset, t_uintptr);
  440. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  441. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  442. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  443. Type *slice_elem = slice_type->Slice.elem;
  444. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  445. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  446. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  447. // NOTE(bill): nil check
  448. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  449. lbValue data = {};
  450. data.type = absolute_ptr.type;
  451. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  452. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  453. len = lb_emit_conv(p, len, t_int);
  454. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  455. lb_fill_slice(p, slice, data, len);
  456. return lb_addr_load(p, slice);
  457. } else if (addr.kind == lbAddr_Map) {
  458. Type *map_type = base_type(addr.map.type);
  459. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  460. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  461. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  462. auto args = array_make<lbValue>(heap_allocator(), 2);
  463. args[0] = h;
  464. args[1] = key;
  465. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  466. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  467. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  468. lbBlock *then = lb_create_block(p, "map.get.then");
  469. lbBlock *done = lb_create_block(p, "map.get.done");
  470. lb_emit_if(p, ok, then, done);
  471. lb_start_block(p, then);
  472. {
  473. // TODO(bill): mem copy it instead?
  474. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  475. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  476. lb_emit_store(p, gep0, lb_emit_load(p, value));
  477. }
  478. lb_emit_jump(p, done);
  479. lb_start_block(p, done);
  480. if (is_type_tuple(addr.map.result)) {
  481. return lb_addr_load(p, v);
  482. } else {
  483. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  484. return lb_emit_load(p, single);
  485. }
  486. } else if (addr.kind == lbAddr_BitField) {
  487. Type *bft = base_type(type_deref(addr.addr.type));
  488. GB_ASSERT(is_type_bit_field(bft));
  489. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  490. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  491. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  492. if (size_in_bytes == 0) {
  493. GB_ASSERT(size_in_bits == 0);
  494. lbValue res = {};
  495. res.type = t_i32;
  496. res.value = LLVMConstInt(lb_type(p->module, res.type), 0, false);
  497. return res;
  498. }
  499. Type *int_type = nullptr;
  500. switch (size_in_bytes) {
  501. case 1: int_type = t_u8; break;
  502. case 2: int_type = t_u16; break;
  503. case 4: int_type = t_u32; break;
  504. case 8: int_type = t_u64; break;
  505. case 16: int_type = t_u128; break;
  506. }
  507. GB_ASSERT(int_type != nullptr);
  508. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  509. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  510. LLVMValueRef field = LLVMBuildLoad(p->builder, field_ptr, "");
  511. lbValue res = {};
  512. res.type = int_type;
  513. res.value = LLVMBuildZExtOrBitCast(p->builder, field, lb_type(p->module, int_type), "");
  514. return res;
  515. } else if (addr.kind == lbAddr_Context) {
  516. if (addr.ctx.sel.index.count > 0) {
  517. lbValue a = addr.addr;
  518. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  519. return lb_emit_load(p, b);
  520. } else {
  521. return lb_emit_load(p, addr.addr);
  522. }
  523. } else if (addr.kind == lbAddr_SoaVariable) {
  524. Type *t = type_deref(addr.addr.type);
  525. t = base_type(t);
  526. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  527. Type *elem = t->Struct.soa_elem;
  528. lbValue len = {};
  529. if (t->Struct.soa_kind == StructSoa_Fixed) {
  530. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  531. } else {
  532. lbValue v = lb_emit_load(p, addr.addr);
  533. len = lb_soa_struct_len(p, v);
  534. }
  535. lbAddr res = lb_add_local_generated(p, elem, true);
  536. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  537. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  538. }
  539. if (t->Struct.soa_kind == StructSoa_Fixed) {
  540. for_array(i, t->Struct.fields) {
  541. Entity *field = t->Struct.fields[i];
  542. Type *base_type = field->type;
  543. GB_ASSERT(base_type->kind == Type_Array);
  544. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  545. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  546. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  547. lbValue src = lb_emit_load(p, src_ptr);
  548. lb_emit_store(p, dst, src);
  549. }
  550. } else {
  551. isize field_count = t->Struct.fields.count;
  552. if (t->Struct.soa_kind == StructSoa_Slice) {
  553. field_count -= 1;
  554. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  555. field_count -= 3;
  556. }
  557. for (isize i = 0; i < field_count; i++) {
  558. Entity *field = t->Struct.fields[i];
  559. Type *base_type = field->type;
  560. GB_ASSERT(base_type->kind == Type_Pointer);
  561. Type *elem = base_type->Pointer.elem;
  562. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  563. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  564. src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index);
  565. lbValue src = lb_emit_load(p, src_ptr);
  566. src = lb_emit_load(p, src);
  567. lb_emit_store(p, dst, src);
  568. }
  569. }
  570. return lb_addr_load(p, res);
  571. }
  572. if (is_type_proc(addr.addr.type)) {
  573. return addr.addr;
  574. }
  575. return lb_emit_load(p, addr.addr);
  576. }
  577. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  578. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  579. }
  580. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  581. Type *t = u.type;
  582. GB_ASSERT_MSG(is_type_pointer(t) &&
  583. is_type_union(type_deref(t)), "%s", type_to_string(t));
  584. Type *ut = type_deref(t);
  585. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  586. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  587. GB_ASSERT(type_size_of(ut) > 0);
  588. Type *tag_type = union_tag_type(ut);
  589. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  590. unsigned element_count = LLVMCountStructElementTypes(uvt);
  591. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  592. lbValue tag_ptr = {};
  593. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  594. tag_ptr.type = alloc_type_pointer(tag_type);
  595. return tag_ptr;
  596. }
  597. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  598. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  599. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  600. return lb_emit_load(p, tag_ptr);
  601. }
  602. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  603. Type *t = type_deref(parent.type);
  604. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  605. // No tag needed!
  606. } else {
  607. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  608. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  609. }
  610. }
  611. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  612. gbAllocator a = heap_allocator();
  613. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  614. lb_emit_store(p, underlying, variant);
  615. lb_emit_store_union_variant_tag(p, parent, variant_type);
  616. }
  617. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  618. unsigned field_count = LLVMCountStructElementTypes(src);
  619. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  620. LLVMGetStructElementTypes(src, fields);
  621. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  622. gb_free(heap_allocator(), fields);
  623. }
  624. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  625. switch (alignment) {
  626. case 1:
  627. return LLVMArrayType(lb_type(m, t_u8), 0);
  628. case 2:
  629. return LLVMArrayType(lb_type(m, t_u16), 0);
  630. case 4:
  631. return LLVMArrayType(lb_type(m, t_u32), 0);
  632. case 8:
  633. return LLVMArrayType(lb_type(m, t_u64), 0);
  634. case 16:
  635. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  636. default:
  637. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  638. break;
  639. }
  640. return nullptr;
  641. }
  642. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  643. if (!elem_type_can_be_constant(elem_type)) {
  644. return false;
  645. }
  646. if (elem->kind == Ast_FieldValue) {
  647. elem = elem->FieldValue.value;
  648. }
  649. TypeAndValue tav = type_and_value_of_expr(elem);
  650. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  651. return tav.value.kind != ExactValue_Invalid;
  652. }
  653. String lb_mangle_name(lbModule *m, Entity *e) {
  654. gbAllocator a = heap_allocator();
  655. String name = e->token.string;
  656. AstPackage *pkg = e->pkg;
  657. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  658. String pkgn = pkg->name;
  659. GB_ASSERT(!rune_is_digit(pkgn[0]));
  660. if (pkgn == "llvm") {
  661. pkgn = str_lit("llvm$");
  662. }
  663. isize max_len = pkgn.len + 1 + name.len + 1;
  664. bool require_suffix_id = is_type_polymorphic(e->type, true);
  665. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  666. require_suffix_id = true;
  667. } else if (is_blank_ident(e->token)) {
  668. require_suffix_id = true;
  669. }if (e->flags & EntityFlag_NotExported) {
  670. require_suffix_id = true;
  671. }
  672. if (require_suffix_id) {
  673. max_len += 21;
  674. }
  675. char *new_name = gb_alloc_array(a, char, max_len);
  676. isize new_name_len = gb_snprintf(
  677. new_name, max_len,
  678. "%.*s.%.*s", LIT(pkgn), LIT(name)
  679. );
  680. if (require_suffix_id) {
  681. char *str = new_name + new_name_len-1;
  682. isize len = max_len-new_name_len;
  683. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  684. new_name_len += extra-1;
  685. }
  686. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  687. return mangled_name;
  688. }
  689. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  690. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  691. // and as a result, the declaration does not have time to determine what it should be
  692. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  693. if (e->TypeName.ir_mangled_name.len != 0) {
  694. return e->TypeName.ir_mangled_name;
  695. }
  696. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  697. if (p == nullptr) {
  698. Entity *proc = nullptr;
  699. if (e->parent_proc_decl != nullptr) {
  700. proc = e->parent_proc_decl->entity;
  701. } else {
  702. Scope *scope = e->scope;
  703. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  704. scope = scope->parent;
  705. }
  706. GB_ASSERT(scope != nullptr);
  707. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  708. proc = scope->procedure_entity;
  709. }
  710. GB_ASSERT(proc->kind == Entity_Procedure);
  711. if (proc->code_gen_procedure != nullptr) {
  712. p = proc->code_gen_procedure;
  713. }
  714. }
  715. // NOTE(bill): Generate a new name
  716. // parent_proc.name-guid
  717. String ts_name = e->token.string;
  718. if (p != nullptr) {
  719. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  720. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  721. u32 guid = ++p->module->nested_type_name_guid;
  722. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  723. String name = make_string(cast(u8 *)name_text, name_len-1);
  724. e->TypeName.ir_mangled_name = name;
  725. return name;
  726. } else {
  727. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  728. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  729. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  730. static u32 guid = 0;
  731. guid += 1;
  732. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  733. String name = make_string(cast(u8 *)name_text, name_len-1);
  734. e->TypeName.ir_mangled_name = name;
  735. return name;
  736. }
  737. }
  738. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  739. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  740. return e->TypeName.ir_mangled_name;
  741. }
  742. GB_ASSERT(e != nullptr);
  743. if (e->pkg == nullptr) {
  744. return e->token.string;
  745. }
  746. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  747. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  748. }
  749. String name = {};
  750. bool no_name_mangle = false;
  751. if (e->kind == Entity_Variable) {
  752. bool is_foreign = e->Variable.is_foreign;
  753. bool is_export = e->Variable.is_export;
  754. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  755. if (e->Variable.link_name.len > 0) {
  756. return e->Variable.link_name;
  757. }
  758. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  759. return e->Procedure.link_name;
  760. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  761. no_name_mangle = true;
  762. }
  763. if (!no_name_mangle) {
  764. name = lb_mangle_name(m, e);
  765. }
  766. if (name.len == 0) {
  767. name = e->token.string;
  768. }
  769. if (e->kind == Entity_TypeName) {
  770. if ((e->scope->flags & ScopeFlag_File) == 0) {
  771. gb_printf_err("<<< %.*s %.*s %p\n", LIT(e->token.string), LIT(name), e);
  772. }
  773. e->TypeName.ir_mangled_name = name;
  774. } else if (e->kind == Entity_Procedure) {
  775. e->Procedure.link_name = name;
  776. }
  777. return name;
  778. }
  779. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  780. Type *original_type = type;
  781. LLVMContextRef ctx = m->ctx;
  782. i64 size = type_size_of(type); // Check size
  783. GB_ASSERT(type != t_invalid);
  784. switch (type->kind) {
  785. case Type_Basic:
  786. switch (type->Basic.kind) {
  787. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  788. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  789. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  790. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  791. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  792. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  793. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  794. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  795. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  796. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  797. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  798. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  799. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  800. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  801. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  802. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  803. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  804. // Basic_f16,
  805. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  806. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  807. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  808. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  809. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  810. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  811. // Basic_complex32,
  812. case Basic_complex64:
  813. {
  814. char const *name = "..complex64";
  815. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  816. if (type != nullptr) {
  817. return type;
  818. }
  819. type = LLVMStructCreateNamed(ctx, name);
  820. LLVMTypeRef fields[2] = {
  821. lb_type(m, t_f32),
  822. lb_type(m, t_f32),
  823. };
  824. LLVMStructSetBody(type, fields, 2, false);
  825. return type;
  826. }
  827. case Basic_complex128:
  828. {
  829. char const *name = "..complex128";
  830. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  831. if (type != nullptr) {
  832. return type;
  833. }
  834. type = LLVMStructCreateNamed(ctx, name);
  835. LLVMTypeRef fields[2] = {
  836. lb_type(m, t_f64),
  837. lb_type(m, t_f64),
  838. };
  839. LLVMStructSetBody(type, fields, 2, false);
  840. return type;
  841. }
  842. case Basic_quaternion128:
  843. {
  844. char const *name = "..quaternion128";
  845. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  846. if (type != nullptr) {
  847. return type;
  848. }
  849. type = LLVMStructCreateNamed(ctx, name);
  850. LLVMTypeRef fields[4] = {
  851. lb_type(m, t_f32),
  852. lb_type(m, t_f32),
  853. lb_type(m, t_f32),
  854. lb_type(m, t_f32),
  855. };
  856. LLVMStructSetBody(type, fields, 4, false);
  857. return type;
  858. }
  859. case Basic_quaternion256:
  860. {
  861. char const *name = "..quaternion256";
  862. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  863. if (type != nullptr) {
  864. return type;
  865. }
  866. type = LLVMStructCreateNamed(ctx, name);
  867. LLVMTypeRef fields[4] = {
  868. lb_type(m, t_f64),
  869. lb_type(m, t_f64),
  870. lb_type(m, t_f64),
  871. lb_type(m, t_f64),
  872. };
  873. LLVMStructSetBody(type, fields, 4, false);
  874. return type;
  875. }
  876. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  877. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  878. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  879. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  880. case Basic_string:
  881. {
  882. char const *name = "..string";
  883. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  884. if (type != nullptr) {
  885. return type;
  886. }
  887. type = LLVMStructCreateNamed(ctx, name);
  888. LLVMTypeRef fields[2] = {
  889. LLVMPointerType(lb_type(m, t_u8), 0),
  890. lb_type(m, t_int),
  891. };
  892. LLVMStructSetBody(type, fields, 2, false);
  893. return type;
  894. }
  895. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  896. case Basic_any:
  897. {
  898. char const *name = "..any";
  899. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  900. if (type != nullptr) {
  901. return type;
  902. }
  903. type = LLVMStructCreateNamed(ctx, name);
  904. LLVMTypeRef fields[2] = {
  905. lb_type(m, t_rawptr),
  906. lb_type(m, t_typeid),
  907. };
  908. LLVMStructSetBody(type, fields, 2, false);
  909. return type;
  910. }
  911. case Basic_typeid: return LLVMIntType(8*cast(unsigned)build_context.word_size);
  912. // Endian Specific Types
  913. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  914. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  915. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  916. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  917. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  918. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  919. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  920. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  921. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  922. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  923. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  924. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  925. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  926. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  927. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  928. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  929. // Untyped types
  930. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  931. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  932. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  933. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  934. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  935. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  936. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  937. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  938. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  939. }
  940. break;
  941. case Type_Named:
  942. {
  943. Type *base = base_type(type->Named.base);
  944. switch (base->kind) {
  945. case Type_Basic:
  946. return lb_type(m, base);
  947. case Type_Named:
  948. case Type_Generic:
  949. case Type_BitFieldValue:
  950. GB_PANIC("INVALID TYPE");
  951. break;
  952. case Type_Opaque:
  953. return lb_type(m, base->Opaque.elem);
  954. case Type_Pointer:
  955. case Type_Array:
  956. case Type_EnumeratedArray:
  957. case Type_Slice:
  958. case Type_DynamicArray:
  959. case Type_Map:
  960. case Type_Enum:
  961. case Type_BitSet:
  962. case Type_SimdVector:
  963. return lb_type(m, base);
  964. // TODO(bill): Deal with this correctly. Can this be named?
  965. case Type_Proc:
  966. return lb_type(m, base);
  967. case Type_Tuple:
  968. return lb_type(m, base);
  969. }
  970. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  971. if (found) {
  972. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  973. if (kind == LLVMStructTypeKind) {
  974. char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  975. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  976. if (llvm_type != nullptr) {
  977. return llvm_type;
  978. }
  979. llvm_type = LLVMStructCreateNamed(ctx, name);
  980. map_set(&m->types, hash_type(type), llvm_type);
  981. lb_clone_struct_type(llvm_type, *found);
  982. return llvm_type;
  983. }
  984. }
  985. switch (base->kind) {
  986. case Type_Struct:
  987. case Type_Union:
  988. case Type_BitField:
  989. {
  990. char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  991. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  992. if (llvm_type != nullptr) {
  993. return llvm_type;
  994. }
  995. llvm_type = LLVMStructCreateNamed(ctx, name);
  996. map_set(&m->types, hash_type(type), llvm_type);
  997. lb_clone_struct_type(llvm_type, lb_type(m, base));
  998. return llvm_type;
  999. }
  1000. }
  1001. return lb_type(m, base);
  1002. }
  1003. case Type_Pointer:
  1004. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1005. case Type_Opaque:
  1006. return lb_type(m, base_type(type));
  1007. case Type_Array:
  1008. return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1009. case Type_EnumeratedArray:
  1010. return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1011. case Type_Slice:
  1012. {
  1013. LLVMTypeRef fields[2] = {
  1014. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1015. lb_type(m, t_int), // len
  1016. };
  1017. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1018. }
  1019. break;
  1020. case Type_DynamicArray:
  1021. {
  1022. LLVMTypeRef fields[4] = {
  1023. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1024. lb_type(m, t_int), // len
  1025. lb_type(m, t_int), // cap
  1026. lb_type(m, t_allocator), // allocator
  1027. };
  1028. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1029. }
  1030. break;
  1031. case Type_Map:
  1032. return lb_type(m, type->Map.internal_type);
  1033. case Type_Struct:
  1034. {
  1035. if (type->Struct.is_raw_union) {
  1036. unsigned field_count = 2;
  1037. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1038. i64 alignment = type_align_of(type);
  1039. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1040. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1041. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1042. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1043. }
  1044. isize offset = 0;
  1045. if (type->Struct.custom_align > 0) {
  1046. offset = 1;
  1047. }
  1048. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1049. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1050. GB_ASSERT(fields != nullptr);
  1051. defer (gb_free(heap_allocator(), fields));
  1052. for_array(i, type->Struct.fields) {
  1053. Entity *field = type->Struct.fields[i];
  1054. fields[i+offset] = lb_type(m, field->type);
  1055. }
  1056. if (type->Struct.custom_align > 0) {
  1057. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1058. }
  1059. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1060. }
  1061. break;
  1062. case Type_Union:
  1063. if (type->Union.variants.count == 0) {
  1064. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1065. } else {
  1066. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1067. // LLVM takes the first element's alignment as the entire alignment (like C)
  1068. i64 align = type_align_of(type);
  1069. i64 size = type_size_of(type);
  1070. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1071. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1072. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1073. }
  1074. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1075. LLVMTypeRef fields[3] = {};
  1076. unsigned field_count = 1;
  1077. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1078. if (is_type_union_maybe_pointer(type)) {
  1079. field_count += 1;
  1080. fields[1] = lb_type(m, type->Union.variants[0]);
  1081. } else {
  1082. field_count += 2;
  1083. if (block_size == align) {
  1084. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1085. } else {
  1086. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1087. }
  1088. fields[2] = lb_type(m, union_tag_type(type));
  1089. }
  1090. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1091. }
  1092. break;
  1093. case Type_Enum:
  1094. return lb_type(m, base_enum_type(type));
  1095. case Type_Tuple:
  1096. if (type->Tuple.variables.count == 1) {
  1097. return lb_type(m, type->Tuple.variables[0]->type);
  1098. } else {
  1099. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1100. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1101. defer (gb_free(heap_allocator(), fields));
  1102. for_array(i, type->Tuple.variables) {
  1103. Entity *field = type->Tuple.variables[i];
  1104. fields[i] = lb_type(m, field->type);
  1105. }
  1106. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1107. }
  1108. case Type_Proc:
  1109. {
  1110. set_procedure_abi_types(heap_allocator(), type);
  1111. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1112. if (type->Proc.return_by_pointer) {
  1113. // Void
  1114. } else if (type->Proc.abi_compat_result_type != nullptr) {
  1115. return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1116. }
  1117. isize extra_param_count = 0;
  1118. if (type->Proc.return_by_pointer) {
  1119. extra_param_count += 1;
  1120. }
  1121. if (type->Proc.calling_convention == ProcCC_Odin) {
  1122. extra_param_count += 1;
  1123. }
  1124. isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1125. auto param_types = array_make<LLVMTypeRef>(heap_allocator(), 0, param_count);
  1126. defer (array_free(&param_types));
  1127. if (type->Proc.return_by_pointer) {
  1128. array_add(&param_types, LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0));
  1129. }
  1130. for_array(i, type->Proc.abi_compat_params) {
  1131. Type *param = type->Proc.abi_compat_params[i];
  1132. if (param == nullptr) {
  1133. continue;
  1134. }
  1135. if (type->Proc.params->Tuple.variables[i]->flags & EntityFlag_CVarArg) {
  1136. GB_ASSERT(i+1 == type->Proc.abi_compat_params.count);
  1137. break;
  1138. }
  1139. if (is_type_tuple(param)) {
  1140. param = base_type(param);
  1141. for_array(j, param->Tuple.variables) {
  1142. Entity *v = param->Tuple.variables[j];
  1143. if (v->kind != Entity_Variable) {
  1144. // Sanity check
  1145. continue;
  1146. }
  1147. array_add(&param_types, lb_type(m, v->type));
  1148. }
  1149. } else {
  1150. array_add(&param_types, lb_type(m, param));
  1151. }
  1152. }
  1153. if (type->Proc.calling_convention == ProcCC_Odin) {
  1154. array_add(&param_types, lb_type(m, t_context_ptr));
  1155. }
  1156. LLVMTypeRef t = LLVMFunctionType(return_type, param_types.data, cast(unsigned)param_types.count, type->Proc.c_vararg);
  1157. return LLVMPointerType(t, 0);
  1158. }
  1159. break;
  1160. case Type_BitFieldValue:
  1161. return LLVMIntType(type->BitFieldValue.bits);
  1162. case Type_BitField:
  1163. {
  1164. LLVMTypeRef internal_type = nullptr;
  1165. {
  1166. GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  1167. unsigned field_count = cast(unsigned)type->BitField.fields.count;
  1168. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1169. defer (gb_free(heap_allocator(), fields));
  1170. for_array(i, type->BitField.sizes) {
  1171. u32 size = type->BitField.sizes[i];
  1172. fields[i] = LLVMIntType(size);
  1173. }
  1174. internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  1175. }
  1176. unsigned field_count = 2;
  1177. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1178. i64 alignment = 1;
  1179. if (type->BitField.custom_align > 0) {
  1180. alignment = type->BitField.custom_align;
  1181. }
  1182. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1183. fields[1] = internal_type;
  1184. return LLVMStructTypeInContext(ctx, fields, field_count, true);
  1185. }
  1186. break;
  1187. case Type_BitSet:
  1188. return LLVMIntType(8*cast(unsigned)type_size_of(type));
  1189. case Type_SimdVector:
  1190. if (type->SimdVector.is_x86_mmx) {
  1191. return LLVMX86MMXTypeInContext(ctx);
  1192. }
  1193. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1194. case Type_RelativePointer:
  1195. return lb_type_internal(m, type->RelativePointer.base_integer);
  1196. case Type_RelativeSlice:
  1197. {
  1198. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1199. unsigned field_count = 2;
  1200. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1201. fields[0] = base_integer;
  1202. fields[1] = base_integer;
  1203. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1204. }
  1205. }
  1206. GB_PANIC("Invalid type %s", type_to_string(type));
  1207. return LLVMInt32TypeInContext(ctx);
  1208. }
  1209. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1210. type = default_type(type);
  1211. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1212. if (found) {
  1213. return *found;
  1214. }
  1215. LLVMTypeRef llvm_type = lb_type_internal(m, type);
  1216. map_set(&m->types, hash_type(type), llvm_type);
  1217. return llvm_type;
  1218. }
  1219. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1220. Type *original_type = type;
  1221. LLVMContextRef ctx = m->ctx;
  1222. i64 size = type_size_of(type); // Check size
  1223. GB_ASSERT(type != t_invalid);
  1224. switch (type->kind) {
  1225. case Type_Basic:
  1226. switch (type->Basic.kind) {
  1227. case Basic_llvm_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "llvm bool", 9, 1, 0, LLVMDIFlagZero);
  1228. case Basic_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "bool", 4, 8, 0, LLVMDIFlagZero);
  1229. case Basic_b8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b8", 2, 8, 0, LLVMDIFlagZero);
  1230. case Basic_b16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b16", 3, 16, 0, LLVMDIFlagZero);
  1231. case Basic_b32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b32", 3, 32, 0, LLVMDIFlagZero);
  1232. case Basic_b64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b64", 3, 64, 0, LLVMDIFlagZero);
  1233. case Basic_i8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i8", 2, 8, 0, LLVMDIFlagZero);
  1234. case Basic_u8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u8", 2, 8, 0, LLVMDIFlagZero);
  1235. case Basic_i16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16", 3, 16, 0, LLVMDIFlagZero);
  1236. case Basic_u16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16", 3, 16, 0, LLVMDIFlagZero);
  1237. case Basic_i32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32", 3, 32, 0, LLVMDIFlagZero);
  1238. case Basic_u32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32", 3, 32, 0, LLVMDIFlagZero);
  1239. case Basic_i64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64", 3, 64, 0, LLVMDIFlagZero);
  1240. case Basic_u64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64", 3, 64, 0, LLVMDIFlagZero);
  1241. case Basic_i128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128", 4, 128, 0, LLVMDIFlagZero);
  1242. case Basic_u128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128", 4, 128, 0, LLVMDIFlagZero);
  1243. case Basic_rune: return LLVMDIBuilderCreateBasicType(m->debug_builder, "rune", 4, 32, 0, LLVMDIFlagZero);
  1244. // Basic_f16,
  1245. case Basic_f32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f32", 3, 32, 0, LLVMDIFlagZero);
  1246. case Basic_f64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f64", 3, 64, 0, LLVMDIFlagZero);
  1247. // Basic_complex32,
  1248. case Basic_complex64:
  1249. {
  1250. return nullptr;
  1251. // char const *name = "..complex64";
  1252. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1253. // if (type != nullptr) {
  1254. // return type;
  1255. // }
  1256. // type = LLVMStructCreateNamed(ctx, name);
  1257. // LLVMTypeRef fields[2] = {
  1258. // lb_type(m, t_f32),
  1259. // lb_type(m, t_f32),
  1260. // };
  1261. // LLVMStructSetBody(type, fields, 2, false);
  1262. // return type;
  1263. }
  1264. case Basic_complex128:
  1265. {
  1266. return nullptr;
  1267. // char const *name = "..complex128";
  1268. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1269. // if (type != nullptr) {
  1270. // return type;
  1271. // }
  1272. // type = LLVMStructCreateNamed(ctx, name);
  1273. // LLVMTypeRef fields[2] = {
  1274. // lb_type(m, t_f64),
  1275. // lb_type(m, t_f64),
  1276. // };
  1277. // LLVMStructSetBody(type, fields, 2, false);
  1278. // return type;
  1279. }
  1280. case Basic_quaternion128:
  1281. {
  1282. return nullptr;
  1283. // char const *name = "..quaternion128";
  1284. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1285. // if (type != nullptr) {
  1286. // return type;
  1287. // }
  1288. // type = LLVMStructCreateNamed(ctx, name);
  1289. // LLVMTypeRef fields[4] = {
  1290. // lb_type(m, t_f32),
  1291. // lb_type(m, t_f32),
  1292. // lb_type(m, t_f32),
  1293. // lb_type(m, t_f32),
  1294. // };
  1295. // LLVMStructSetBody(type, fields, 4, false);
  1296. // return type;
  1297. }
  1298. case Basic_quaternion256:
  1299. {
  1300. return nullptr;
  1301. // char const *name = "..quaternion256";
  1302. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1303. // if (type != nullptr) {
  1304. // return type;
  1305. // }
  1306. // type = LLVMStructCreateNamed(ctx, name);
  1307. // LLVMTypeRef fields[4] = {
  1308. // lb_type(m, t_f64),
  1309. // lb_type(m, t_f64),
  1310. // lb_type(m, t_f64),
  1311. // lb_type(m, t_f64),
  1312. // };
  1313. // LLVMStructSetBody(type, fields, 4, false);
  1314. // return type;
  1315. }
  1316. case Basic_int: return LLVMDIBuilderCreateBasicType(m->debug_builder, "int", 3, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1317. case Basic_uint: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uint", 4, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1318. case Basic_uintptr: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uintptr", 7, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1319. case Basic_rawptr:
  1320. return nullptr;
  1321. // return LLVMPointerType(LLVMInt8Type(), 0);
  1322. case Basic_string:
  1323. {
  1324. return nullptr;
  1325. // char const *name = "..string";
  1326. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1327. // if (type != nullptr) {
  1328. // return type;
  1329. // }
  1330. // type = LLVMStructCreateNamed(ctx, name);
  1331. // LLVMTypeRef fields[2] = {
  1332. // LLVMPointerType(lb_type(m, t_u8), 0),
  1333. // lb_type(m, t_int),
  1334. // };
  1335. // LLVMStructSetBody(type, fields, 2, false);
  1336. // return type;
  1337. }
  1338. case Basic_cstring:
  1339. return nullptr;
  1340. // return LLVMPointerType(LLVMInt8Type(), 0);
  1341. case Basic_any:
  1342. {
  1343. return nullptr;
  1344. // char const *name = "..any";
  1345. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1346. // if (type != nullptr) {
  1347. // return type;
  1348. // }
  1349. // type = LLVMStructCreateNamed(ctx, name);
  1350. // LLVMTypeRef fields[2] = {
  1351. // lb_type(m, t_rawptr),
  1352. // lb_type(m, t_typeid),
  1353. // };
  1354. // LLVMStructSetBody(type, fields, 2, false);
  1355. // return type;
  1356. }
  1357. case Basic_typeid: return LLVMDIBuilderCreateBasicType(m->debug_builder, "typeid", 6, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1358. // Endian Specific Types
  1359. case Basic_i16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1360. case Basic_u16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1361. case Basic_i32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1362. case Basic_u32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1363. case Basic_i64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1364. case Basic_u64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1365. case Basic_i128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1366. case Basic_u128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1367. case Basic_i16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1368. case Basic_u16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1369. case Basic_i32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1370. case Basic_u32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1371. case Basic_i64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1372. case Basic_u64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1373. case Basic_i128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1374. case Basic_u128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1375. // Untyped types
  1376. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1377. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1378. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1379. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1380. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1381. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1382. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1383. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1384. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1385. }
  1386. break;
  1387. case Type_Named:
  1388. {
  1389. return nullptr;
  1390. // Type *base = base_type(type->Named.base);
  1391. // switch (base->kind) {
  1392. // case Type_Basic:
  1393. // return lb_type(m, base);
  1394. // case Type_Named:
  1395. // case Type_Generic:
  1396. // case Type_BitFieldValue:
  1397. // GB_PANIC("INVALID TYPE");
  1398. // break;
  1399. // case Type_Opaque:
  1400. // return lb_type(m, base->Opaque.elem);
  1401. // case Type_Pointer:
  1402. // case Type_Array:
  1403. // case Type_EnumeratedArray:
  1404. // case Type_Slice:
  1405. // case Type_DynamicArray:
  1406. // case Type_Map:
  1407. // case Type_Enum:
  1408. // case Type_BitSet:
  1409. // case Type_SimdVector:
  1410. // return lb_type(m, base);
  1411. // // TODO(bill): Deal with this correctly. Can this be named?
  1412. // case Type_Proc:
  1413. // return lb_type(m, base);
  1414. // case Type_Tuple:
  1415. // return lb_type(m, base);
  1416. // }
  1417. // LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1418. // if (found) {
  1419. // LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1420. // if (kind == LLVMStructTypeKind) {
  1421. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1422. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1423. // if (llvm_type != nullptr) {
  1424. // return llvm_type;
  1425. // }
  1426. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1427. // map_set(&m->types, hash_type(type), llvm_type);
  1428. // lb_clone_struct_type(llvm_type, *found);
  1429. // return llvm_type;
  1430. // }
  1431. // }
  1432. // switch (base->kind) {
  1433. // case Type_Struct:
  1434. // case Type_Union:
  1435. // case Type_BitField:
  1436. // {
  1437. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1438. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1439. // if (llvm_type != nullptr) {
  1440. // return llvm_type;
  1441. // }
  1442. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1443. // map_set(&m->types, hash_type(type), llvm_type);
  1444. // lb_clone_struct_type(llvm_type, lb_type(m, base));
  1445. // return llvm_type;
  1446. // }
  1447. // }
  1448. // return lb_type(m, base);
  1449. }
  1450. case Type_Pointer:
  1451. return nullptr;
  1452. // return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1453. case Type_Opaque:
  1454. return nullptr;
  1455. // return lb_type(m, base_type(type));
  1456. case Type_Array:
  1457. return nullptr;
  1458. // return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1459. case Type_EnumeratedArray:
  1460. return nullptr;
  1461. // return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1462. case Type_Slice:
  1463. {
  1464. return nullptr;
  1465. // LLVMTypeRef fields[2] = {
  1466. // LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1467. // lb_type(m, t_int), // len
  1468. // };
  1469. // return LLVMStructTypeInContext(ctx, fields, 2, false);
  1470. }
  1471. break;
  1472. case Type_DynamicArray:
  1473. {
  1474. return nullptr;
  1475. // LLVMTypeRef fields[4] = {
  1476. // LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1477. // lb_type(m, t_int), // len
  1478. // lb_type(m, t_int), // cap
  1479. // lb_type(m, t_allocator), // allocator
  1480. // };
  1481. // return LLVMStructTypeInContext(ctx, fields, 4, false);
  1482. }
  1483. break;
  1484. case Type_Map:
  1485. return nullptr;
  1486. // return lb_type(m, type->Map.internal_type);
  1487. case Type_Struct:
  1488. {
  1489. return nullptr;
  1490. // if (type->Struct.is_raw_union) {
  1491. // unsigned field_count = 2;
  1492. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1493. // i64 alignment = type_align_of(type);
  1494. // unsigned size_of_union = cast(unsigned)type_size_of(type);
  1495. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1496. // fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1497. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1498. // }
  1499. // isize offset = 0;
  1500. // if (type->Struct.custom_align > 0) {
  1501. // offset = 1;
  1502. // }
  1503. // unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1504. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1505. // GB_ASSERT(fields != nullptr);
  1506. // defer (gb_free(heap_allocator(), fields));
  1507. // for_array(i, type->Struct.fields) {
  1508. // Entity *field = type->Struct.fields[i];
  1509. // fields[i+offset] = lb_type(m, field->type);
  1510. // }
  1511. // if (type->Struct.custom_align > 0) {
  1512. // fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1513. // }
  1514. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1515. }
  1516. break;
  1517. case Type_Union:
  1518. return nullptr;
  1519. // if (type->Union.variants.count == 0) {
  1520. // return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1521. // } else {
  1522. // // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1523. // // LLVM takes the first element's alignment as the entire alignment (like C)
  1524. // i64 align = type_align_of(type);
  1525. // i64 size = type_size_of(type);
  1526. // if (is_type_union_maybe_pointer_original_alignment(type)) {
  1527. // LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1528. // return LLVMStructTypeInContext(ctx, fields, 1, false);
  1529. // }
  1530. // unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1531. // LLVMTypeRef fields[3] = {};
  1532. // unsigned field_count = 1;
  1533. // fields[0] = lb_alignment_prefix_type_hack(m, align);
  1534. // if (is_type_union_maybe_pointer(type)) {
  1535. // field_count += 1;
  1536. // fields[1] = lb_type(m, type->Union.variants[0]);
  1537. // } else {
  1538. // field_count += 2;
  1539. // if (block_size == align) {
  1540. // fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1541. // } else {
  1542. // fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1543. // }
  1544. // fields[2] = lb_type(m, union_tag_type(type));
  1545. // }
  1546. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1547. // }
  1548. // break;
  1549. case Type_Enum:
  1550. return nullptr;
  1551. // return lb_type(m, base_enum_type(type));
  1552. case Type_Tuple:
  1553. return nullptr;
  1554. // if (type->Tuple.variables.count == 1) {
  1555. // return lb_type(m, type->Tuple.variables[0]->type);
  1556. // } else {
  1557. // unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1558. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1559. // defer (gb_free(heap_allocator(), fields));
  1560. // for_array(i, type->Tuple.variables) {
  1561. // Entity *field = type->Tuple.variables[i];
  1562. // fields[i] = lb_type(m, field->type);
  1563. // }
  1564. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1565. // }
  1566. case Type_Proc:
  1567. {
  1568. return nullptr;
  1569. // set_procedure_abi_types(heap_allocator(), type);
  1570. // LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1571. // isize offset = 0;
  1572. // if (type->Proc.return_by_pointer) {
  1573. // offset = 1;
  1574. // } else if (type->Proc.abi_compat_result_type != nullptr) {
  1575. // return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1576. // }
  1577. // isize extra_param_count = offset;
  1578. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1579. // extra_param_count += 1;
  1580. // }
  1581. // isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1582. // LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1583. // defer (gb_free(heap_allocator(), param_types));
  1584. // isize param_index = offset;
  1585. // for_array(i, type->Proc.abi_compat_params) {
  1586. // Type *param = type->Proc.abi_compat_params[i];
  1587. // if (param == nullptr) {
  1588. // continue;
  1589. // }
  1590. // param_types[param_index++] = lb_type(m, param);
  1591. // }
  1592. // if (type->Proc.return_by_pointer) {
  1593. // param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0);
  1594. // }
  1595. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1596. // param_types[param_index++] = lb_type(m, t_context_ptr);
  1597. // }
  1598. // LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg);
  1599. // return LLVMPointerType(t, 0);
  1600. }
  1601. break;
  1602. case Type_BitFieldValue:
  1603. return nullptr;
  1604. // return LLVMIntType(type->BitFieldValue.bits);
  1605. case Type_BitField:
  1606. {
  1607. return nullptr;
  1608. // LLVMTypeRef internal_type = nullptr;
  1609. // {
  1610. // GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  1611. // unsigned field_count = cast(unsigned)type->BitField.fields.count;
  1612. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1613. // defer (gb_free(heap_allocator(), fields));
  1614. // for_array(i, type->BitField.sizes) {
  1615. // u32 size = type->BitField.sizes[i];
  1616. // fields[i] = LLVMIntType(size);
  1617. // }
  1618. // internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  1619. // }
  1620. // unsigned field_count = 2;
  1621. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1622. // i64 alignment = 1;
  1623. // if (type->BitField.custom_align > 0) {
  1624. // alignment = type->BitField.custom_align;
  1625. // }
  1626. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1627. // fields[1] = internal_type;
  1628. // return LLVMStructTypeInContext(ctx, fields, field_count, true);
  1629. }
  1630. break;
  1631. case Type_BitSet:
  1632. return nullptr;
  1633. // return LLVMIntType(8*cast(unsigned)type_size_of(type));
  1634. case Type_SimdVector:
  1635. return nullptr;
  1636. // if (type->SimdVector.is_x86_mmx) {
  1637. // return LLVMX86MMXTypeInContext(ctx);
  1638. // }
  1639. // return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1640. }
  1641. GB_PANIC("Invalid type %s", type_to_string(type));
  1642. return nullptr;
  1643. }
  1644. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1645. LLVMTypeRef t = lb_type(m, type);
  1646. LLVMMetadataRef *found = map_get(&m->debug_values, hash_pointer(t));
  1647. if (found != nullptr) {
  1648. return *found;
  1649. }
  1650. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1651. map_set(&m->debug_values, hash_pointer(t), dt);
  1652. return dt;
  1653. }
  1654. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1655. if (e != nullptr) {
  1656. map_set(&m->values, hash_entity(e), val);
  1657. }
  1658. }
  1659. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1660. if (name.len > 0) {
  1661. string_map_set(&m->members, name, val);
  1662. }
  1663. }
  1664. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1665. string_map_set(&m->members, key, val);
  1666. }
  1667. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1668. if (p->entity != nullptr) {
  1669. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1670. }
  1671. string_map_set(&m->procedures, p->name, p);
  1672. }
  1673. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  1674. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  1675. LLVMValueRef values[2] = {
  1676. str_elem.value,
  1677. str_len.value,
  1678. };
  1679. lbValue res = {};
  1680. res.type = t_string;
  1681. res.value = LLVMConstNamedStruct(lb_type(p->module, t_string), values, gb_count_of(values));
  1682. return res;
  1683. } else {
  1684. lbAddr res = lb_add_local_generated(p, t_string, false);
  1685. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  1686. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  1687. return lb_addr_load(p, res);
  1688. }
  1689. }
  1690. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1691. unsigned kind = LLVMGetEnumAttributeKindForName(name, gb_strlen(name));
  1692. GB_ASSERT(kind != 0);
  1693. return LLVMCreateEnumAttribute(ctx, kind, value);
  1694. }
  1695. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1696. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1697. GB_ASSERT(attr != nullptr);
  1698. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1699. }
  1700. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1701. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  1702. }
  1703. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  1704. GB_ASSERT(entity != nullptr);
  1705. String link_name = lb_get_entity_name(m, entity);
  1706. {
  1707. StringHashKey key = string_hash_string(link_name);
  1708. lbValue *found = string_map_get(&m->members, key);
  1709. if (found) {
  1710. lb_add_entity(m, entity, *found);
  1711. lbProcedure **p_found = string_map_get(&m->procedures, key);
  1712. GB_ASSERT(p_found != nullptr);
  1713. return *p_found;
  1714. }
  1715. }
  1716. lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure);
  1717. p->module = m;
  1718. entity->code_gen_module = m;
  1719. entity->code_gen_procedure = p;
  1720. p->entity = entity;
  1721. p->name = link_name;
  1722. DeclInfo *decl = entity->decl_info;
  1723. ast_node(pl, ProcLit, decl->proc_lit);
  1724. Type *pt = base_type(entity->type);
  1725. GB_ASSERT(pt->kind == Type_Proc);
  1726. set_procedure_abi_types(heap_allocator(), entity->type);
  1727. p->type = entity->type;
  1728. p->type_expr = decl->type_expr;
  1729. p->body = pl->body;
  1730. p->tags = pt->Proc.tags;
  1731. p->inlining = ProcInlining_none;
  1732. p->is_foreign = entity->Procedure.is_foreign;
  1733. p->is_export = entity->Procedure.is_export;
  1734. p->is_entry_point = false;
  1735. gbAllocator a = heap_allocator();
  1736. p->children.allocator = a;
  1737. p->params.allocator = a;
  1738. p->defer_stmts.allocator = a;
  1739. p->blocks.allocator = a;
  1740. p->branch_blocks.allocator = a;
  1741. p->context_stack.allocator = a;
  1742. if (p->is_foreign) {
  1743. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  1744. }
  1745. char *c_link_name = alloc_cstring(heap_allocator(), p->name);
  1746. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1747. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1748. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1749. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1750. // TODO(bill): Clean up this logic
  1751. if (build_context.metrics.os != TargetOs_js) {
  1752. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1753. }
  1754. LLVMSetFunctionCallConv(p->value, cc_kind);
  1755. lbValue proc_value = {p->value, p->type};
  1756. lb_add_entity(m, entity, proc_value);
  1757. lb_add_member(m, p->name, proc_value);
  1758. lb_add_procedure_value(m, p);
  1759. if (p->is_export) {
  1760. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  1761. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  1762. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  1763. if (build_context.metrics.os == TargetOs_js) {
  1764. char const *export_name = alloc_cstring(heap_allocator(), p->name);
  1765. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  1766. }
  1767. }
  1768. if (p->is_foreign) {
  1769. if (build_context.metrics.os == TargetOs_js) {
  1770. char const *import_name = alloc_cstring(heap_allocator(), p->name);
  1771. char const *module_name = "env";
  1772. if (entity->Procedure.foreign_library != nullptr) {
  1773. Entity *foreign_library = entity->Procedure.foreign_library;
  1774. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  1775. if (foreign_library->LibraryName.paths.count > 0) {
  1776. module_name = alloc_cstring(heap_allocator(), foreign_library->LibraryName.paths[0]);
  1777. }
  1778. }
  1779. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  1780. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  1781. }
  1782. }
  1783. // NOTE(bill): offset==0 is the return value
  1784. isize offset = 1;
  1785. if (pt->Proc.return_by_pointer) {
  1786. lb_add_proc_attribute_at_index(p, 1, "sret");
  1787. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1788. offset = 2;
  1789. }
  1790. isize parameter_index = 0;
  1791. if (pt->Proc.param_count) {
  1792. TypeTuple *params = &pt->Proc.params->Tuple;
  1793. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1794. Entity *e = params->variables[i];
  1795. Type *original_type = e->type;
  1796. Type *abi_type = pt->Proc.abi_compat_params[i];
  1797. if (e->kind != Entity_Variable) continue;
  1798. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1799. continue;
  1800. }
  1801. if (is_type_tuple(abi_type)) {
  1802. for_array(j, abi_type->Tuple.variables) {
  1803. Type *tft = abi_type->Tuple.variables[j]->type;
  1804. if (e->flags&EntityFlag_NoAlias) {
  1805. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1806. }
  1807. }
  1808. parameter_index += abi_type->Tuple.variables.count;
  1809. } else {
  1810. if (e->flags&EntityFlag_NoAlias) {
  1811. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1812. }
  1813. parameter_index += 1;
  1814. }
  1815. }
  1816. }
  1817. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1818. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1819. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1820. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1821. }
  1822. { // Debug Information
  1823. unsigned line = cast(unsigned)entity->token.pos.line;
  1824. LLVMMetadataRef file = nullptr;
  1825. if (entity->file != nullptr) {
  1826. cast(LLVMMetadataRef)entity->file->llvm_metadata;
  1827. }
  1828. LLVMMetadataRef scope = nullptr;
  1829. LLVMMetadataRef type = nullptr;
  1830. // type = LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, nullptr, 0, LLVMDIFlagZero);
  1831. LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  1832. cast(char const *)entity->token.string.text, entity->token.string.len,
  1833. cast(char const *)p->name.text, p->name.len,
  1834. file, line, type,
  1835. true, p->body == nullptr,
  1836. line, LLVMDIFlagZero, false
  1837. );
  1838. GB_ASSERT(res != nullptr);
  1839. map_set(&m->debug_values, hash_pointer(p), res);
  1840. }
  1841. return p;
  1842. }
  1843. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  1844. {
  1845. lbValue *found = string_map_get(&m->members, link_name);
  1846. GB_ASSERT(found == nullptr);
  1847. }
  1848. lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure);
  1849. p->module = m;
  1850. p->name = link_name;
  1851. p->type = type;
  1852. p->type_expr = nullptr;
  1853. p->body = nullptr;
  1854. p->tags = 0;
  1855. p->inlining = ProcInlining_none;
  1856. p->is_foreign = false;
  1857. p->is_export = false;
  1858. p->is_entry_point = false;
  1859. gbAllocator a = heap_allocator();
  1860. p->children.allocator = a;
  1861. p->params.allocator = a;
  1862. p->defer_stmts.allocator = a;
  1863. p->blocks.allocator = a;
  1864. p->branch_blocks.allocator = a;
  1865. p->context_stack.allocator = a;
  1866. char *c_link_name = alloc_cstring(heap_allocator(), p->name);
  1867. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1868. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1869. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1870. Type *pt = p->type;
  1871. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1872. // TODO(bill): Clean up this logic
  1873. if (build_context.metrics.os != TargetOs_js) {
  1874. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1875. }
  1876. LLVMSetFunctionCallConv(p->value, cc_kind);
  1877. lbValue proc_value = {p->value, p->type};
  1878. lb_add_member(m, p->name, proc_value);
  1879. lb_add_procedure_value(m, p);
  1880. // NOTE(bill): offset==0 is the return value
  1881. isize offset = 1;
  1882. if (pt->Proc.return_by_pointer) {
  1883. lb_add_proc_attribute_at_index(p, 1, "sret");
  1884. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1885. offset = 2;
  1886. }
  1887. isize parameter_index = 0;
  1888. if (pt->Proc.param_count) {
  1889. TypeTuple *params = &pt->Proc.params->Tuple;
  1890. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1891. Entity *e = params->variables[i];
  1892. Type *original_type = e->type;
  1893. Type *abi_type = pt->Proc.abi_compat_params[i];
  1894. if (e->kind != Entity_Variable) continue;
  1895. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1896. continue;
  1897. }
  1898. if (is_type_tuple(abi_type)) {
  1899. for_array(j, abi_type->Tuple.variables) {
  1900. Type *tft = abi_type->Tuple.variables[j]->type;
  1901. if (e->flags&EntityFlag_NoAlias) {
  1902. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1903. }
  1904. }
  1905. parameter_index += abi_type->Tuple.variables.count;
  1906. } else {
  1907. if (e->flags&EntityFlag_NoAlias) {
  1908. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1909. }
  1910. parameter_index += 1;
  1911. }
  1912. }
  1913. }
  1914. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1915. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1916. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1917. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1918. }
  1919. return p;
  1920. }
  1921. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  1922. lbParamPasskind kind = lbParamPass_Value;
  1923. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  1924. if (is_type_pointer(abi_type)) {
  1925. GB_ASSERT(e->kind == Entity_Variable);
  1926. Type *av = core_type(type_deref(abi_type));
  1927. if (are_types_identical(av, core_type(e->type))) {
  1928. kind = lbParamPass_Pointer;
  1929. if (e->flags&EntityFlag_Value) {
  1930. kind = lbParamPass_ConstRef;
  1931. }
  1932. } else {
  1933. kind = lbParamPass_BitCast;
  1934. }
  1935. } else if (is_type_integer(abi_type)) {
  1936. kind = lbParamPass_Integer;
  1937. } else if (abi_type == t_llvm_bool) {
  1938. kind = lbParamPass_Value;
  1939. } else if (is_type_boolean(abi_type)) {
  1940. kind = lbParamPass_Integer;
  1941. } else if (is_type_simd_vector(abi_type)) {
  1942. kind = lbParamPass_BitCast;
  1943. } else if (is_type_float(abi_type)) {
  1944. kind = lbParamPass_BitCast;
  1945. } else if (is_type_tuple(abi_type)) {
  1946. kind = lbParamPass_Tuple;
  1947. } else if (is_type_proc(abi_type)) {
  1948. kind = lbParamPass_Value;
  1949. } else {
  1950. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  1951. }
  1952. }
  1953. if (kind_) *kind_ = kind;
  1954. lbValue res = {};
  1955. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  1956. res.type = abi_type;
  1957. return res;
  1958. }
  1959. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  1960. lbParamPasskind kind = lbParamPass_Value;
  1961. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  1962. array_add(&p->params, v);
  1963. lbValue res = {};
  1964. switch (kind) {
  1965. case lbParamPass_Value: {
  1966. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1967. lbValue x = v;
  1968. if (abi_type == t_llvm_bool) {
  1969. x = lb_emit_conv(p, x, t_bool);
  1970. }
  1971. lb_addr_store(p, l, x);
  1972. return x;
  1973. }
  1974. case lbParamPass_Pointer:
  1975. lb_add_entity(p->module, e, v);
  1976. return lb_emit_load(p, v);
  1977. case lbParamPass_Integer: {
  1978. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1979. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  1980. lb_emit_store(p, iptr, v);
  1981. return lb_addr_load(p, l);
  1982. }
  1983. case lbParamPass_ConstRef:
  1984. lb_add_entity(p->module, e, v);
  1985. return lb_emit_load(p, v);
  1986. case lbParamPass_BitCast: {
  1987. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1988. lbValue x = lb_emit_transmute(p, v, e->type);
  1989. lb_addr_store(p, l, x);
  1990. return x;
  1991. }
  1992. case lbParamPass_Tuple: {
  1993. lbAddr l = lb_add_local(p, e->type, e, true, index);
  1994. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  1995. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  1996. if (abi_type->Tuple.variables.count > 0) {
  1997. array_pop(&p->params);
  1998. }
  1999. for_array(i, abi_type->Tuple.variables) {
  2000. Type *t = abi_type->Tuple.variables[i]->type;
  2001. GB_ASSERT(!is_type_tuple(t));
  2002. lbParamPasskind elem_kind = lbParamPass_Value;
  2003. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  2004. array_add(&p->params, elem);
  2005. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2006. lb_emit_store(p, dst, elem);
  2007. }
  2008. return lb_addr_load(p, l);
  2009. }
  2010. }
  2011. GB_PANIC("Unreachable");
  2012. return {};
  2013. }
  2014. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2015. GB_ASSERT(b != nullptr);
  2016. if (!b->appended) {
  2017. b->appended = true;
  2018. LLVMAppendExistingBasicBlock(p->value, b->block);
  2019. }
  2020. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2021. p->curr_block = b;
  2022. }
  2023. void lb_begin_procedure_body(lbProcedure *p) {
  2024. DeclInfo *decl = decl_info_of_entity(p->entity);
  2025. if (decl != nullptr) {
  2026. for_array(i, decl->labels) {
  2027. BlockLabel bl = decl->labels[i];
  2028. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2029. array_add(&p->branch_blocks, bb);
  2030. }
  2031. }
  2032. if (p->tags != 0) {
  2033. u64 in = p->tags;
  2034. u64 out = p->module->state_flags;
  2035. if (in & ProcTag_bounds_check) {
  2036. out |= StateFlag_bounds_check;
  2037. out &= ~StateFlag_no_bounds_check;
  2038. } else if (in & ProcTag_no_bounds_check) {
  2039. out |= StateFlag_no_bounds_check;
  2040. out &= ~StateFlag_bounds_check;
  2041. }
  2042. p->module->state_flags = out;
  2043. }
  2044. p->builder = LLVMCreateBuilder();
  2045. p->decl_block = lb_create_block(p, "decls", true);
  2046. p->entry_block = lb_create_block(p, "entry", true);
  2047. lb_start_block(p, p->entry_block);
  2048. GB_ASSERT(p->type != nullptr);
  2049. i32 parameter_index = 0;
  2050. lbValue return_ptr_value = {};
  2051. if (p->type->Proc.return_by_pointer) {
  2052. // NOTE(bill): this must be parameter 0
  2053. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2054. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2055. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2056. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2057. return_ptr_value.type = ptr_type;
  2058. p->return_ptr = lb_addr(return_ptr_value);
  2059. lb_add_entity(p->module, e, return_ptr_value);
  2060. parameter_index += 1;
  2061. }
  2062. if (p->type->Proc.params != nullptr) {
  2063. TypeTuple *params = &p->type->Proc.params->Tuple;
  2064. auto abi_types = p->type->Proc.abi_compat_params;
  2065. for_array(i, params->variables) {
  2066. Entity *e = params->variables[i];
  2067. if (e->kind != Entity_Variable) {
  2068. continue;
  2069. }
  2070. Type *abi_type = e->type;
  2071. if (abi_types.count > 0) {
  2072. abi_type = abi_types[i];
  2073. }
  2074. if (e->token.string != "") {
  2075. lb_add_param(p, e, nullptr, abi_type, parameter_index);
  2076. }
  2077. if (is_type_tuple(abi_type)) {
  2078. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  2079. } else {
  2080. parameter_index += 1;
  2081. }
  2082. }
  2083. }
  2084. if (p->type->Proc.has_named_results) {
  2085. GB_ASSERT(p->type->Proc.result_count > 0);
  2086. TypeTuple *results = &p->type->Proc.results->Tuple;
  2087. for_array(i, results->variables) {
  2088. Entity *e = results->variables[i];
  2089. GB_ASSERT(e->kind == Entity_Variable);
  2090. if (e->token.string != "") {
  2091. GB_ASSERT(!is_blank_ident(e->token));
  2092. lbAddr res = {};
  2093. if (p->type->Proc.return_by_pointer) {
  2094. lbValue ptr = return_ptr_value;
  2095. if (results->variables.count != 1) {
  2096. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2097. }
  2098. res = lb_addr(ptr);
  2099. lb_add_entity(p->module, e, ptr);
  2100. } else {
  2101. res = lb_add_local(p, e->type, e);
  2102. }
  2103. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2104. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2105. lb_addr_store(p, res, c);
  2106. }
  2107. }
  2108. }
  2109. }
  2110. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2111. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  2112. e->flags |= EntityFlag_NoAlias;
  2113. lbValue param = {};
  2114. param.value = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  2115. param.type = e->type;
  2116. lb_add_entity(p->module, e, param);
  2117. lbAddr ctx_addr = {};
  2118. ctx_addr.kind = lbAddr_Context;
  2119. ctx_addr.addr = param;
  2120. lbContextData ctx = {ctx_addr, p->scope_index};
  2121. array_add(&p->context_stack, ctx);
  2122. }
  2123. lb_start_block(p, p->entry_block);
  2124. }
  2125. void lb_end_procedure_body(lbProcedure *p) {
  2126. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2127. LLVMBuildBr(p->builder, p->entry_block->block);
  2128. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2129. if (p->type->Proc.result_count == 0) {
  2130. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2131. if (!lb_is_instr_terminating(instr)) {
  2132. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2133. LLVMBuildRetVoid(p->builder);
  2134. }
  2135. } else {
  2136. if (p->curr_block->preds.count == 0) {
  2137. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2138. if (instr == nullptr) {
  2139. // NOTE(bill): Remove dead trailing block
  2140. LLVMDeleteBasicBlock(p->curr_block->block);
  2141. }
  2142. }
  2143. }
  2144. p->curr_block = nullptr;
  2145. p->module->state_flags = 0;
  2146. }
  2147. void lb_end_procedure(lbProcedure *p) {
  2148. LLVMDisposeBuilder(p->builder);
  2149. }
  2150. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2151. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2152. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2153. array_add(&from->succs, to);
  2154. array_add(&to->preds, from);
  2155. }
  2156. }
  2157. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2158. lbBlock *b = gb_alloc_item(heap_allocator(), lbBlock);
  2159. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2160. b->appended = false;
  2161. if (append) {
  2162. b->appended = true;
  2163. LLVMAppendExistingBasicBlock(p->value, b->block);
  2164. }
  2165. b->scope = p->curr_scope;
  2166. b->scope_index = p->scope_index;
  2167. b->preds.allocator = heap_allocator();
  2168. b->succs.allocator = heap_allocator();
  2169. array_add(&p->blocks, b);
  2170. return b;
  2171. }
  2172. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2173. if (p->curr_block == nullptr) {
  2174. return;
  2175. }
  2176. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2177. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2178. return;
  2179. }
  2180. lb_add_edge(p->curr_block, target_block);
  2181. LLVMBuildBr(p->builder, target_block->block);
  2182. p->curr_block = nullptr;
  2183. }
  2184. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2185. lbBlock *b = p->curr_block;
  2186. if (b == nullptr) {
  2187. return;
  2188. }
  2189. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2190. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2191. return;
  2192. }
  2193. lb_add_edge(b, true_block);
  2194. lb_add_edge(b, false_block);
  2195. LLVMValueRef cv = cond.value;
  2196. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2197. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2198. }
  2199. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2200. GB_ASSERT(cond != nullptr);
  2201. GB_ASSERT(true_block != nullptr);
  2202. GB_ASSERT(false_block != nullptr);
  2203. switch (cond->kind) {
  2204. case_ast_node(pe, ParenExpr, cond);
  2205. return lb_build_cond(p, pe->expr, true_block, false_block);
  2206. case_end;
  2207. case_ast_node(ue, UnaryExpr, cond);
  2208. if (ue->op.kind == Token_Not) {
  2209. return lb_build_cond(p, ue->expr, false_block, true_block);
  2210. }
  2211. case_end;
  2212. case_ast_node(be, BinaryExpr, cond);
  2213. if (be->op.kind == Token_CmpAnd) {
  2214. lbBlock *block = lb_create_block(p, "cmp.and");
  2215. lb_build_cond(p, be->left, block, false_block);
  2216. lb_start_block(p, block);
  2217. return lb_build_cond(p, be->right, true_block, false_block);
  2218. } else if (be->op.kind == Token_CmpOr) {
  2219. lbBlock *block = lb_create_block(p, "cmp.or");
  2220. lb_build_cond(p, be->left, true_block, block);
  2221. lb_start_block(p, block);
  2222. return lb_build_cond(p, be->right, true_block, false_block);
  2223. }
  2224. case_end;
  2225. }
  2226. lbValue v = lb_build_expr(p, cond);
  2227. // v = lb_emit_conv(p, v, t_bool);
  2228. v = lb_emit_conv(p, v, t_llvm_bool);
  2229. lb_emit_if(p, v, true_block, false_block);
  2230. return v;
  2231. }
  2232. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2233. GB_ASSERT(p->decl_block != p->curr_block);
  2234. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2235. char const *name = "";
  2236. if (e != nullptr) {
  2237. // name = alloc_cstring(heap_allocator(), e->token.string);
  2238. }
  2239. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2240. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2241. LLVMSetAlignment(ptr, 16); // TODO(bill): Make this configurable
  2242. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2243. if (zero_init) {
  2244. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2245. }
  2246. lbValue val = {};
  2247. val.value = ptr;
  2248. val.type = alloc_type_pointer(type);
  2249. if (e != nullptr) {
  2250. lb_add_entity(p->module, e, val);
  2251. }
  2252. return lb_addr(val);
  2253. }
  2254. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2255. return lb_add_local(p, type, nullptr, zero_init);
  2256. }
  2257. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2258. GB_ASSERT(pd->body != nullptr);
  2259. lbModule *m = p->module;
  2260. auto *min_dep_set = &m->info->minimum_dependency_set;
  2261. if (ptr_set_exists(min_dep_set, e) == false) {
  2262. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2263. return;
  2264. }
  2265. // NOTE(bill): Generate a new name
  2266. // parent.name-guid
  2267. String original_name = e->token.string;
  2268. String pd_name = original_name;
  2269. if (e->Procedure.link_name.len > 0) {
  2270. pd_name = e->Procedure.link_name;
  2271. }
  2272. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2273. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  2274. i32 guid = cast(i32)p->children.count;
  2275. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2276. String name = make_string(cast(u8 *)name_text, name_len-1);
  2277. set_procedure_abi_types(heap_allocator(), e->type);
  2278. e->Procedure.link_name = name;
  2279. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2280. e->code_gen_procedure = nested_proc;
  2281. lbValue value = {};
  2282. value.value = nested_proc->value;
  2283. value.type = nested_proc->type;
  2284. lb_add_entity(m, e, value);
  2285. array_add(&p->children, nested_proc);
  2286. array_add(&m->procedures_to_generate, nested_proc);
  2287. }
  2288. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2289. if (e == nullptr) {
  2290. return;
  2291. }
  2292. GB_ASSERT(e->kind == Entity_LibraryName);
  2293. GB_ASSERT(e->flags & EntityFlag_Used);
  2294. for_array(i, e->LibraryName.paths) {
  2295. String library_path = e->LibraryName.paths[i];
  2296. if (library_path.len == 0) {
  2297. continue;
  2298. }
  2299. bool ok = true;
  2300. for_array(path_index, m->foreign_library_paths) {
  2301. String path = m->foreign_library_paths[path_index];
  2302. #if defined(GB_SYSTEM_WINDOWS)
  2303. if (str_eq_ignore_case(path, library_path)) {
  2304. #else
  2305. if (str_eq(path, library_path)) {
  2306. #endif
  2307. ok = false;
  2308. break;
  2309. }
  2310. }
  2311. if (ok) {
  2312. array_add(&m->foreign_library_paths, library_path);
  2313. }
  2314. }
  2315. }
  2316. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2317. if (vd == nullptr || vd->is_mutable) {
  2318. return;
  2319. }
  2320. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2321. static i32 global_guid = 0;
  2322. for_array(i, vd->names) {
  2323. Ast *ident = vd->names[i];
  2324. GB_ASSERT(ident->kind == Ast_Ident);
  2325. Entity *e = entity_of_node(ident);
  2326. GB_ASSERT(e != nullptr);
  2327. if (e->kind != Entity_TypeName) {
  2328. continue;
  2329. }
  2330. bool polymorphic_struct = false;
  2331. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2332. Type *bt = base_type(e->type);
  2333. if (bt->kind == Type_Struct) {
  2334. polymorphic_struct = bt->Struct.is_polymorphic;
  2335. }
  2336. }
  2337. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2338. continue;
  2339. }
  2340. if (e->TypeName.ir_mangled_name.len != 0) {
  2341. // NOTE(bill): Already set
  2342. continue;
  2343. }
  2344. lb_set_nested_type_name_ir_mangled_name(e, p);
  2345. }
  2346. for_array(i, vd->names) {
  2347. Ast *ident = vd->names[i];
  2348. GB_ASSERT(ident->kind == Ast_Ident);
  2349. Entity *e = entity_of_node(ident);
  2350. GB_ASSERT(e != nullptr);
  2351. if (e->kind != Entity_Procedure) {
  2352. continue;
  2353. }
  2354. CheckerInfo *info = p->module->info;
  2355. DeclInfo *decl = decl_info_of_entity(e);
  2356. ast_node(pl, ProcLit, decl->proc_lit);
  2357. if (pl->body != nullptr) {
  2358. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2359. if (found) {
  2360. auto procs = *found;
  2361. for_array(i, procs) {
  2362. Entity *e = procs[i];
  2363. if (!ptr_set_exists(min_dep_set, e)) {
  2364. continue;
  2365. }
  2366. DeclInfo *d = decl_info_of_entity(e);
  2367. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2368. }
  2369. } else {
  2370. lb_build_nested_proc(p, pl, e);
  2371. }
  2372. } else {
  2373. // FFI - Foreign function interace
  2374. String original_name = e->token.string;
  2375. String name = original_name;
  2376. if (e->Procedure.is_foreign) {
  2377. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2378. }
  2379. if (e->Procedure.link_name.len > 0) {
  2380. name = e->Procedure.link_name;
  2381. }
  2382. lbValue *prev_value = string_map_get(&p->module->members, name);
  2383. if (prev_value != nullptr) {
  2384. // NOTE(bill): Don't do mutliple declarations in the IR
  2385. return;
  2386. }
  2387. set_procedure_abi_types(heap_allocator(), e->type);
  2388. e->Procedure.link_name = name;
  2389. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2390. lbValue value = {};
  2391. value.value = nested_proc->value;
  2392. value.type = nested_proc->type;
  2393. array_add(&p->module->procedures_to_generate, nested_proc);
  2394. if (p != nullptr) {
  2395. array_add(&p->children, nested_proc);
  2396. } else {
  2397. string_map_set(&p->module->members, name, value);
  2398. }
  2399. }
  2400. }
  2401. }
  2402. void lb_build_stmt_list(lbProcedure *p, Array<Ast *> const &stmts) {
  2403. for_array(i, stmts) {
  2404. Ast *stmt = stmts[i];
  2405. switch (stmt->kind) {
  2406. case_ast_node(vd, ValueDecl, stmt);
  2407. lb_build_constant_value_decl(p, vd);
  2408. case_end;
  2409. case_ast_node(fb, ForeignBlockDecl, stmt);
  2410. ast_node(block, BlockStmt, fb->body);
  2411. lb_build_stmt_list(p, block->stmts);
  2412. case_end;
  2413. }
  2414. }
  2415. for_array(i, stmts) {
  2416. lb_build_stmt(p, stmts[i]);
  2417. }
  2418. }
  2419. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  2420. GB_ASSERT(ident->kind == Ast_Ident);
  2421. Entity *e = entity_of_node(ident);
  2422. GB_ASSERT(e->kind == Entity_Label);
  2423. for_array(i, p->branch_blocks) {
  2424. lbBranchBlocks *b = &p->branch_blocks[i];
  2425. if (b->label == e->Label.node) {
  2426. return *b;
  2427. }
  2428. }
  2429. GB_PANIC("Unreachable");
  2430. lbBranchBlocks empty = {};
  2431. return empty;
  2432. }
  2433. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  2434. lbTargetList *tl = gb_alloc_item(heap_allocator(), lbTargetList);
  2435. tl->prev = p->target_list;
  2436. tl->break_ = break_;
  2437. tl->continue_ = continue_;
  2438. tl->fallthrough_ = fallthrough_;
  2439. p->target_list = tl;
  2440. if (label != nullptr) { // Set label blocks
  2441. GB_ASSERT(label->kind == Ast_Label);
  2442. for_array(i, p->branch_blocks) {
  2443. lbBranchBlocks *b = &p->branch_blocks[i];
  2444. GB_ASSERT(b->label != nullptr && label != nullptr);
  2445. GB_ASSERT(b->label->kind == Ast_Label);
  2446. if (b->label == label) {
  2447. b->break_ = break_;
  2448. b->continue_ = continue_;
  2449. return tl;
  2450. }
  2451. }
  2452. GB_PANIC("Unreachable");
  2453. }
  2454. return tl;
  2455. }
  2456. void lb_pop_target_list(lbProcedure *p) {
  2457. p->target_list = p->target_list->prev;
  2458. }
  2459. void lb_open_scope(lbProcedure *p) {
  2460. p->scope_index += 1;
  2461. }
  2462. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  2463. lb_emit_defer_stmts(p, kind, block);
  2464. GB_ASSERT(p->scope_index > 0);
  2465. // NOTE(bill): Remove `context`s made in that scope
  2466. while (p->context_stack.count > 0) {
  2467. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  2468. if (ctx->scope_index >= p->scope_index) {
  2469. array_pop(&p->context_stack);
  2470. } else {
  2471. break;
  2472. }
  2473. }
  2474. p->scope_index -= 1;
  2475. }
  2476. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  2477. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  2478. GB_ASSERT(is_type_boolean(tv.type));
  2479. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  2480. if (tv.value.value_bool) {
  2481. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  2482. } else if (ws->else_stmt) {
  2483. switch (ws->else_stmt->kind) {
  2484. case Ast_BlockStmt:
  2485. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  2486. break;
  2487. case Ast_WhenStmt:
  2488. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  2489. break;
  2490. default:
  2491. GB_PANIC("Invalid 'else' statement in 'when' statement");
  2492. break;
  2493. }
  2494. }
  2495. }
  2496. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  2497. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2498. lbModule *m = p->module;
  2499. lbValue count = {};
  2500. Type *expr_type = base_type(type_deref(expr.type));
  2501. switch (expr_type->kind) {
  2502. case Type_Array:
  2503. count = lb_const_int(m, t_int, expr_type->Array.count);
  2504. break;
  2505. }
  2506. lbValue val = {};
  2507. lbValue idx = {};
  2508. lbBlock *loop = nullptr;
  2509. lbBlock *done = nullptr;
  2510. lbBlock *body = nullptr;
  2511. lbAddr index = lb_add_local_generated(p, t_int, false);
  2512. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  2513. loop = lb_create_block(p, "for.index.loop");
  2514. lb_emit_jump(p, loop);
  2515. lb_start_block(p, loop);
  2516. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  2517. lb_addr_store(p, index, incr);
  2518. body = lb_create_block(p, "for.index.body");
  2519. done = lb_create_block(p, "for.index.done");
  2520. if (count.value == nullptr) {
  2521. GB_ASSERT(count_ptr.value != nullptr);
  2522. count = lb_emit_load(p, count_ptr);
  2523. }
  2524. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  2525. lb_emit_if(p, cond, body, done);
  2526. lb_start_block(p, body);
  2527. idx = lb_addr_load(p, index);
  2528. switch (expr_type->kind) {
  2529. case Type_Array: {
  2530. if (val_type != nullptr) {
  2531. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2532. }
  2533. break;
  2534. }
  2535. case Type_EnumeratedArray: {
  2536. if (val_type != nullptr) {
  2537. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2538. // NOTE(bill): Override the idx value for the enumeration
  2539. Type *index_type = expr_type->EnumeratedArray.index;
  2540. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  2541. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  2542. }
  2543. }
  2544. break;
  2545. }
  2546. case Type_Slice: {
  2547. if (val_type != nullptr) {
  2548. lbValue elem = lb_slice_elem(p, expr);
  2549. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2550. }
  2551. break;
  2552. }
  2553. case Type_DynamicArray: {
  2554. if (val_type != nullptr) {
  2555. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  2556. elem = lb_emit_load(p, elem);
  2557. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2558. }
  2559. break;
  2560. }
  2561. case Type_Map: {
  2562. lbValue entries = lb_map_entries_ptr(p, expr);
  2563. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  2564. elem = lb_emit_load(p, elem);
  2565. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  2566. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  2567. lbValue key_raw = lb_emit_struct_ep(p, entry, 0);
  2568. key_raw = lb_emit_struct_ep(p, key_raw, 1);
  2569. lbValue key = lb_emit_conv(p, key_raw, alloc_type_pointer(expr_type->Map.key));
  2570. idx = lb_emit_load(p, key);
  2571. break;
  2572. }
  2573. default:
  2574. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  2575. break;
  2576. }
  2577. if (val_) *val_ = val;
  2578. if (idx_) *idx_ = idx;
  2579. if (loop_) *loop_ = loop;
  2580. if (done_) *done_ = done;
  2581. }
  2582. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  2583. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2584. lbModule *m = p->module;
  2585. lbValue count = lb_const_int(m, t_int, 0);
  2586. Type *expr_type = base_type(expr.type);
  2587. switch (expr_type->kind) {
  2588. case Type_Basic:
  2589. count = lb_string_len(p, expr);
  2590. break;
  2591. default:
  2592. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  2593. break;
  2594. }
  2595. lbValue val = {};
  2596. lbValue idx = {};
  2597. lbBlock *loop = nullptr;
  2598. lbBlock *done = nullptr;
  2599. lbBlock *body = nullptr;
  2600. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2601. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2602. loop = lb_create_block(p, "for.string.loop");
  2603. lb_emit_jump(p, loop);
  2604. lb_start_block(p, loop);
  2605. body = lb_create_block(p, "for.string.body");
  2606. done = lb_create_block(p, "for.string.done");
  2607. lbValue offset = lb_addr_load(p, offset_);
  2608. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  2609. lb_emit_if(p, cond, body, done);
  2610. lb_start_block(p, body);
  2611. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  2612. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  2613. auto args = array_make<lbValue>(heap_allocator(), 1);
  2614. args[0] = lb_emit_string(p, str_elem, str_len);
  2615. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  2616. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  2617. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  2618. idx = offset;
  2619. if (val_type != nullptr) {
  2620. val = lb_emit_struct_ev(p, rune_and_len, 0);
  2621. }
  2622. if (val_) *val_ = val;
  2623. if (idx_) *idx_ = idx;
  2624. if (loop_) *loop_ = loop;
  2625. if (done_) *done_ = done;
  2626. }
  2627. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  2628. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2629. lbModule *m = p->module;
  2630. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  2631. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  2632. lbValue lower = lb_build_expr(p, node->left);
  2633. lbValue upper = {};
  2634. lbValue val = {};
  2635. lbValue idx = {};
  2636. lbBlock *loop = nullptr;
  2637. lbBlock *done = nullptr;
  2638. lbBlock *body = nullptr;
  2639. if (val_type == nullptr) {
  2640. val_type = lower.type;
  2641. }
  2642. lbAddr value = lb_add_local_generated(p, val_type, false);
  2643. lb_addr_store(p, value, lower);
  2644. lbAddr index = lb_add_local_generated(p, t_int, false);
  2645. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  2646. loop = lb_create_block(p, "for.interval.loop");
  2647. lb_emit_jump(p, loop);
  2648. lb_start_block(p, loop);
  2649. body = lb_create_block(p, "for.interval.body");
  2650. done = lb_create_block(p, "for.interval.done");
  2651. TokenKind op = Token_Lt;
  2652. switch (node->op.kind) {
  2653. case Token_Ellipsis: op = Token_LtEq; break;
  2654. case Token_RangeHalf: op = Token_Lt; break;
  2655. default: GB_PANIC("Invalid interval operator"); break;
  2656. }
  2657. upper = lb_build_expr(p, node->right);
  2658. lbValue curr_value = lb_addr_load(p, value);
  2659. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  2660. lb_emit_if(p, cond, body, done);
  2661. lb_start_block(p, body);
  2662. val = lb_addr_load(p, value);
  2663. idx = lb_addr_load(p, index);
  2664. lb_emit_increment(p, value.addr);
  2665. lb_emit_increment(p, index.addr);
  2666. if (val_) *val_ = val;
  2667. if (idx_) *idx_ = idx;
  2668. if (loop_) *loop_ = loop;
  2669. if (done_) *done_ = done;
  2670. }
  2671. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2672. lbModule *m = p->module;
  2673. Type *t = enum_type;
  2674. GB_ASSERT(is_type_enum(t));
  2675. Type *enum_ptr = alloc_type_pointer(t);
  2676. t = base_type(t);
  2677. Type *core_elem = core_type(t);
  2678. GB_ASSERT(t->kind == Type_Enum);
  2679. i64 enum_count = t->Enum.fields.count;
  2680. lbValue max_count = lb_const_int(m, t_int, enum_count);
  2681. lbValue ti = lb_type_info(m, t);
  2682. lbValue variant = lb_emit_struct_ep(p, ti, 3);
  2683. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  2684. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  2685. lbValue values_data = lb_slice_elem(p, values);
  2686. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2687. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2688. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  2689. lb_emit_jump(p, loop);
  2690. lb_start_block(p, loop);
  2691. lbBlock *body = lb_create_block(p, "for.enum.body");
  2692. lbBlock *done = lb_create_block(p, "for.enum.done");
  2693. lbValue offset = lb_addr_load(p, offset_);
  2694. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  2695. lb_emit_if(p, cond, body, done);
  2696. lb_start_block(p, body);
  2697. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  2698. lb_emit_increment(p, offset_.addr);
  2699. lbValue val = {};
  2700. if (val_type != nullptr) {
  2701. GB_ASSERT(are_types_identical(enum_type, val_type));
  2702. if (is_type_integer(core_elem)) {
  2703. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  2704. val = lb_emit_conv(p, i, t);
  2705. } else {
  2706. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  2707. }
  2708. }
  2709. if (val_) *val_ = val;
  2710. if (idx_) *idx_ = offset;
  2711. if (loop_) *loop_ = loop;
  2712. if (done_) *done_ = done;
  2713. }
  2714. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  2715. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  2716. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  2717. lb_emit_jump(p, loop);
  2718. lb_start_block(p, loop);
  2719. lbBlock *body = lb_create_block(p, "for.tuple.body");
  2720. lbBlock *done = lb_create_block(p, "for.tuple.done");
  2721. lbValue tuple_value = lb_build_expr(p, expr);
  2722. Type *tuple = tuple_value.type;
  2723. GB_ASSERT(tuple->kind == Type_Tuple);
  2724. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  2725. i32 cond_index = tuple_count-1;
  2726. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  2727. lb_emit_if(p, cond, body, done);
  2728. lb_start_block(p, body);
  2729. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  2730. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  2731. if (loop_) *loop_ = loop;
  2732. if (done_) *done_ = done;
  2733. }
  2734. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) {
  2735. lb_open_scope(p);
  2736. Type *val0_type = nullptr;
  2737. Type *val1_type = nullptr;
  2738. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2739. val0_type = type_of_expr(rs->val0);
  2740. }
  2741. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2742. val1_type = type_of_expr(rs->val1);
  2743. }
  2744. if (val0_type != nullptr) {
  2745. Entity *e = entity_of_node(rs->val0);
  2746. lb_add_local(p, e->type, e, true);
  2747. }
  2748. if (val1_type != nullptr) {
  2749. Entity *e = entity_of_node(rs->val1);
  2750. lb_add_local(p, e->type, e, true);
  2751. }
  2752. lbValue val = {};
  2753. lbValue key = {};
  2754. lbBlock *loop = nullptr;
  2755. lbBlock *done = nullptr;
  2756. Ast *expr = unparen_expr(rs->expr);
  2757. bool is_map = false;
  2758. TypeAndValue tav = type_and_value_of_expr(expr);
  2759. if (is_ast_range(expr)) {
  2760. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  2761. } else if (tav.mode == Addressing_Type) {
  2762. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  2763. } else {
  2764. Type *expr_type = type_of_expr(expr);
  2765. Type *et = base_type(type_deref(expr_type));
  2766. switch (et->kind) {
  2767. case Type_Map: {
  2768. is_map = true;
  2769. lbValue map = lb_build_addr_ptr(p, expr);
  2770. if (is_type_pointer(type_deref(map.type))) {
  2771. map = lb_emit_load(p, map);
  2772. }
  2773. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  2774. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  2775. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  2776. break;
  2777. }
  2778. case Type_Array: {
  2779. lbValue array = lb_build_addr_ptr(p, expr);
  2780. if (is_type_pointer(type_deref(array.type))) {
  2781. array = lb_emit_load(p, array);
  2782. }
  2783. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2784. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  2785. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2786. break;
  2787. }
  2788. case Type_EnumeratedArray: {
  2789. lbValue array = lb_build_addr_ptr(p, expr);
  2790. if (is_type_pointer(type_deref(array.type))) {
  2791. array = lb_emit_load(p, array);
  2792. }
  2793. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2794. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  2795. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2796. break;
  2797. }
  2798. case Type_DynamicArray: {
  2799. lbValue count_ptr = {};
  2800. lbValue array = lb_build_addr_ptr(p, expr);
  2801. if (is_type_pointer(type_deref(array.type))) {
  2802. array = lb_emit_load(p, array);
  2803. }
  2804. count_ptr = lb_emit_struct_ep(p, array, 1);
  2805. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  2806. break;
  2807. }
  2808. case Type_Slice: {
  2809. lbValue count_ptr = {};
  2810. lbValue slice = lb_build_expr(p, expr);
  2811. if (is_type_pointer(slice.type)) {
  2812. count_ptr = lb_emit_struct_ep(p, slice, 1);
  2813. slice = lb_emit_load(p, slice);
  2814. } else {
  2815. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  2816. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  2817. }
  2818. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  2819. break;
  2820. }
  2821. case Type_Basic: {
  2822. lbValue string = lb_build_expr(p, expr);
  2823. if (is_type_pointer(string.type)) {
  2824. string = lb_emit_load(p, string);
  2825. }
  2826. if (is_type_untyped(expr_type)) {
  2827. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  2828. lb_addr_store(p, s, string);
  2829. string = lb_addr_load(p, s);
  2830. }
  2831. Type *t = base_type(string.type);
  2832. GB_ASSERT(!is_type_cstring(t));
  2833. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  2834. break;
  2835. }
  2836. case Type_Tuple:
  2837. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  2838. break;
  2839. default:
  2840. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  2841. break;
  2842. }
  2843. }
  2844. if (is_map) {
  2845. if (val0_type) lb_store_range_stmt_val(p, rs->val0, key);
  2846. if (val1_type) lb_store_range_stmt_val(p, rs->val1, val);
  2847. } else {
  2848. if (val0_type) lb_store_range_stmt_val(p, rs->val0, val);
  2849. if (val1_type) lb_store_range_stmt_val(p, rs->val1, key);
  2850. }
  2851. lb_push_target_list(p, rs->label, done, loop, nullptr);
  2852. lb_build_stmt(p, rs->body);
  2853. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2854. lb_pop_target_list(p);
  2855. lb_emit_jump(p, loop);
  2856. lb_start_block(p, done);
  2857. }
  2858. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) {
  2859. lbModule *m = p->module;
  2860. lb_open_scope(p); // Open scope here
  2861. Type *val0_type = nullptr;
  2862. Type *val1_type = nullptr;
  2863. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2864. val0_type = type_of_expr(rs->val0);
  2865. }
  2866. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2867. val1_type = type_of_expr(rs->val1);
  2868. }
  2869. if (val0_type != nullptr) {
  2870. Entity *e = entity_of_node(rs->val0);
  2871. lb_add_local(p, e->type, e, true);
  2872. }
  2873. if (val1_type != nullptr) {
  2874. Entity *e = entity_of_node(rs->val1);
  2875. lb_add_local(p, e->type, e, true);
  2876. }
  2877. lbValue val = {};
  2878. lbValue key = {};
  2879. lbBlock *loop = nullptr;
  2880. lbBlock *done = nullptr;
  2881. Ast *expr = unparen_expr(rs->expr);
  2882. TypeAndValue tav = type_and_value_of_expr(expr);
  2883. if (is_ast_range(expr)) {
  2884. lbAddr val0_addr = {};
  2885. lbAddr val1_addr = {};
  2886. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2887. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2888. TokenKind op = expr->BinaryExpr.op.kind;
  2889. Ast *start_expr = expr->BinaryExpr.left;
  2890. Ast *end_expr = expr->BinaryExpr.right;
  2891. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  2892. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  2893. ExactValue start = start_expr->tav.value;
  2894. ExactValue end = end_expr->tav.value;
  2895. if (op == Token_Ellipsis) { // .. [start, end]
  2896. ExactValue index = exact_value_i64(0);
  2897. for (ExactValue val = start;
  2898. compare_exact_values(Token_LtEq, val, end);
  2899. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2900. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2901. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2902. lb_build_stmt(p, rs->body);
  2903. }
  2904. } else if (op == Token_RangeHalf) { // ..< [start, end)
  2905. ExactValue index = exact_value_i64(0);
  2906. for (ExactValue val = start;
  2907. compare_exact_values(Token_Lt, val, end);
  2908. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2909. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2910. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2911. lb_build_stmt(p, rs->body);
  2912. }
  2913. }
  2914. } else if (tav.mode == Addressing_Type) {
  2915. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  2916. Type *et = type_deref(tav.type);
  2917. Type *bet = base_type(et);
  2918. lbAddr val0_addr = {};
  2919. lbAddr val1_addr = {};
  2920. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2921. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2922. for_array(i, bet->Enum.fields) {
  2923. Entity *field = bet->Enum.fields[i];
  2924. GB_ASSERT(field->kind == Entity_Constant);
  2925. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  2926. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2927. lb_build_stmt(p, rs->body);
  2928. }
  2929. } else {
  2930. lbAddr val0_addr = {};
  2931. lbAddr val1_addr = {};
  2932. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2933. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2934. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  2935. Type *t = base_type(expr->tav.type);
  2936. switch (t->kind) {
  2937. case Type_Basic:
  2938. GB_ASSERT(is_type_string(t));
  2939. {
  2940. ExactValue value = expr->tav.value;
  2941. GB_ASSERT(value.kind == ExactValue_String);
  2942. String str = value.value_string;
  2943. Rune codepoint = 0;
  2944. isize offset = 0;
  2945. do {
  2946. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  2947. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  2948. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  2949. lb_build_stmt(p, rs->body);
  2950. offset += width;
  2951. } while (offset < str.len);
  2952. }
  2953. break;
  2954. case Type_Array:
  2955. if (t->Array.count > 0) {
  2956. lbValue val = lb_build_expr(p, expr);
  2957. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2958. for (i64 i = 0; i < t->Array.count; i++) {
  2959. if (val0_type) {
  2960. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2961. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2962. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2963. }
  2964. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2965. lb_build_stmt(p, rs->body);
  2966. }
  2967. }
  2968. break;
  2969. case Type_EnumeratedArray:
  2970. if (t->EnumeratedArray.count > 0) {
  2971. lbValue val = lb_build_expr(p, expr);
  2972. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2973. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  2974. if (val0_type) {
  2975. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2976. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2977. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2978. }
  2979. if (val1_type) {
  2980. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  2981. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  2982. }
  2983. lb_build_stmt(p, rs->body);
  2984. }
  2985. }
  2986. break;
  2987. default:
  2988. GB_PANIC("Invalid inline for type");
  2989. break;
  2990. }
  2991. }
  2992. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2993. }
  2994. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) {
  2995. if (ss->init != nullptr) {
  2996. lb_build_stmt(p, ss->init);
  2997. }
  2998. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  2999. if (ss->tag != nullptr) {
  3000. tag = lb_build_expr(p, ss->tag);
  3001. }
  3002. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3003. ast_node(body, BlockStmt, ss->body);
  3004. Array<Ast *> default_stmts = {};
  3005. lbBlock *default_fall = nullptr;
  3006. lbBlock *default_block = nullptr;
  3007. lbBlock *fall = nullptr;
  3008. isize case_count = body->stmts.count;
  3009. for_array(i, body->stmts) {
  3010. Ast *clause = body->stmts[i];
  3011. ast_node(cc, CaseClause, clause);
  3012. lbBlock *body = fall;
  3013. if (body == nullptr) {
  3014. body = lb_create_block(p, "switch.case.body");
  3015. }
  3016. fall = done;
  3017. if (i+1 < case_count) {
  3018. fall = lb_create_block(p, "switch.fall.body");
  3019. }
  3020. if (cc->list.count == 0) {
  3021. // default case
  3022. default_stmts = cc->stmts;
  3023. default_fall = fall;
  3024. default_block = body;
  3025. continue;
  3026. }
  3027. lbBlock *next_cond = nullptr;
  3028. for_array(j, cc->list) {
  3029. Ast *expr = unparen_expr(cc->list[j]);
  3030. next_cond = lb_create_block(p, "switch.case.next");
  3031. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3032. if (is_ast_range(expr)) {
  3033. ast_node(ie, BinaryExpr, expr);
  3034. TokenKind op = Token_Invalid;
  3035. switch (ie->op.kind) {
  3036. case Token_Ellipsis: op = Token_LtEq; break;
  3037. case Token_RangeHalf: op = Token_Lt; break;
  3038. default: GB_PANIC("Invalid interval operator"); break;
  3039. }
  3040. lbValue lhs = lb_build_expr(p, ie->left);
  3041. lbValue rhs = lb_build_expr(p, ie->right);
  3042. // TODO(bill): do short circuit here
  3043. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3044. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3045. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3046. } else {
  3047. if (expr->tav.mode == Addressing_Type) {
  3048. GB_ASSERT(is_type_typeid(tag.type));
  3049. lbValue e = lb_typeid(p->module, expr->tav.type);
  3050. e = lb_emit_conv(p, e, tag.type);
  3051. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3052. } else {
  3053. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3054. }
  3055. }
  3056. lb_emit_if(p, cond, body, next_cond);
  3057. lb_start_block(p, next_cond);
  3058. }
  3059. lb_start_block(p, body);
  3060. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3061. lb_open_scope(p);
  3062. lb_build_stmt_list(p, cc->stmts);
  3063. lb_close_scope(p, lbDeferExit_Default, body);
  3064. lb_pop_target_list(p);
  3065. lb_emit_jump(p, done);
  3066. lb_start_block(p, next_cond);
  3067. }
  3068. if (default_block != nullptr) {
  3069. lb_emit_jump(p, default_block);
  3070. lb_start_block(p, default_block);
  3071. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3072. lb_open_scope(p);
  3073. lb_build_stmt_list(p, default_stmts);
  3074. lb_close_scope(p, lbDeferExit_Default, default_block);
  3075. lb_pop_target_list(p);
  3076. }
  3077. lb_emit_jump(p, done);
  3078. lb_start_block(p, done);
  3079. }
  3080. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3081. Entity *e = implicit_entity_of_node(clause);
  3082. GB_ASSERT(e != nullptr);
  3083. if (e->flags & EntityFlag_Value) {
  3084. // by value
  3085. GB_ASSERT(are_types_identical(e->type, value.type));
  3086. lbAddr x = lb_add_local(p, e->type, e, false);
  3087. lb_addr_store(p, x, value);
  3088. } else {
  3089. // by reference
  3090. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3091. lb_add_entity(p->module, e, value);
  3092. }
  3093. }
  3094. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3095. Entity *e = entity_of_node(stmt_val);
  3096. if (e == nullptr) {
  3097. return {};
  3098. }
  3099. if ((e->flags & EntityFlag_Value) == 0) {
  3100. if (LLVMIsALoadInst(value.value)) {
  3101. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3102. lb_add_entity(p->module, e, ptr);
  3103. return lb_addr(ptr);
  3104. }
  3105. }
  3106. // by value
  3107. lbAddr addr = lb_add_local(p, e->type, e, false);
  3108. lb_addr_store(p, addr, value);
  3109. return addr;
  3110. }
  3111. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3112. ast_node(cc, CaseClause, clause);
  3113. lb_push_target_list(p, label, done, nullptr, nullptr);
  3114. lb_open_scope(p);
  3115. lb_build_stmt_list(p, cc->stmts);
  3116. lb_close_scope(p, lbDeferExit_Default, body);
  3117. lb_pop_target_list(p);
  3118. lb_emit_jump(p, done);
  3119. }
  3120. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3121. lbModule *m = p->module;
  3122. ast_node(as, AssignStmt, ss->tag);
  3123. GB_ASSERT(as->lhs.count == 1);
  3124. GB_ASSERT(as->rhs.count == 1);
  3125. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3126. bool is_parent_ptr = is_type_pointer(parent.type);
  3127. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3128. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3129. lbValue parent_value = parent;
  3130. lbValue parent_ptr = parent;
  3131. if (!is_parent_ptr) {
  3132. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3133. }
  3134. lbValue tag_index = {};
  3135. lbValue union_data = {};
  3136. if (switch_kind == TypeSwitch_Union) {
  3137. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3138. tag_index = lb_emit_load(p, tag_ptr);
  3139. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3140. }
  3141. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3142. lb_emit_jump(p, start_block);
  3143. lb_start_block(p, start_block);
  3144. // NOTE(bill): Append this later
  3145. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3146. Ast *default_ = nullptr;
  3147. ast_node(body, BlockStmt, ss->body);
  3148. gb_local_persist i32 weird_count = 0;
  3149. for_array(i, body->stmts) {
  3150. Ast *clause = body->stmts[i];
  3151. ast_node(cc, CaseClause, clause);
  3152. if (cc->list.count == 0) {
  3153. default_ = clause;
  3154. continue;
  3155. }
  3156. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3157. lbBlock *next = nullptr;
  3158. Type *case_type = nullptr;
  3159. for_array(type_index, cc->list) {
  3160. next = lb_create_block(p, "typeswitch.next");
  3161. case_type = type_of_expr(cc->list[type_index]);
  3162. lbValue cond = {};
  3163. if (switch_kind == TypeSwitch_Union) {
  3164. Type *ut = base_type(type_deref(parent.type));
  3165. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3166. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3167. } else if (switch_kind == TypeSwitch_Any) {
  3168. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3169. lbValue case_typeid = lb_typeid(m, case_type);
  3170. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3171. }
  3172. GB_ASSERT(cond.value != nullptr);
  3173. lb_emit_if(p, cond, body, next);
  3174. lb_start_block(p, next);
  3175. }
  3176. Entity *case_entity = implicit_entity_of_node(clause);
  3177. lbValue value = parent_value;
  3178. lb_start_block(p, body);
  3179. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3180. if (cc->list.count == 1) {
  3181. lbValue data = {};
  3182. if (switch_kind == TypeSwitch_Union) {
  3183. data = union_data;
  3184. } else if (switch_kind == TypeSwitch_Any) {
  3185. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3186. data = any_data;
  3187. }
  3188. Type *ct = case_entity->type;
  3189. Type *ct_ptr = alloc_type_pointer(ct);
  3190. value = lb_emit_conv(p, data, ct_ptr);
  3191. if (!by_reference) {
  3192. value = lb_emit_load(p, value);
  3193. }
  3194. }
  3195. lb_store_type_case_implicit(p, clause, value);
  3196. lb_type_case_body(p, ss->label, clause, body, done);
  3197. lb_start_block(p, next);
  3198. }
  3199. if (default_ != nullptr) {
  3200. lb_store_type_case_implicit(p, default_, parent_value);
  3201. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3202. } else {
  3203. lb_emit_jump(p, done);
  3204. }
  3205. lb_start_block(p, done);
  3206. }
  3207. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3208. lbModule *m = p->module;
  3209. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3210. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3211. type = default_type(type);
  3212. lbValue short_circuit = {};
  3213. if (op == Token_CmpAnd) {
  3214. lb_build_cond(p, left, rhs, done);
  3215. short_circuit = lb_const_bool(m, type, false);
  3216. } else if (op == Token_CmpOr) {
  3217. lb_build_cond(p, left, done, rhs);
  3218. short_circuit = lb_const_bool(m, type, true);
  3219. }
  3220. if (rhs->preds.count == 0) {
  3221. lb_start_block(p, done);
  3222. return short_circuit;
  3223. }
  3224. if (done->preds.count == 0) {
  3225. lb_start_block(p, rhs);
  3226. return lb_build_expr(p, right);
  3227. }
  3228. Array<LLVMValueRef> incoming_values = {};
  3229. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3230. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3231. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3232. for_array(i, done->preds) {
  3233. incoming_values[i] = short_circuit.value;
  3234. incoming_blocks[i] = done->preds[i]->block;
  3235. }
  3236. lb_start_block(p, rhs);
  3237. lbValue edge = lb_build_expr(p, right);
  3238. incoming_values[done->preds.count] = edge.value;
  3239. incoming_blocks[done->preds.count] = p->curr_block->block;
  3240. lb_emit_jump(p, done);
  3241. lb_start_block(p, done);
  3242. lbValue res = {};
  3243. res.type = type;
  3244. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3245. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3246. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3247. return res;
  3248. }
  3249. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3250. Ast *prev_stmt = p->curr_stmt;
  3251. defer (p->curr_stmt = prev_stmt);
  3252. p->curr_stmt = node;
  3253. if (p->curr_block != nullptr) {
  3254. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  3255. if (lb_is_instr_terminating(last_instr)) {
  3256. return;
  3257. }
  3258. }
  3259. u64 prev_state_flags = p->module->state_flags;
  3260. defer (p->module->state_flags = prev_state_flags);
  3261. if (node->state_flags != 0) {
  3262. u64 in = node->state_flags;
  3263. u64 out = p->module->state_flags;
  3264. if (in & StateFlag_bounds_check) {
  3265. out |= StateFlag_bounds_check;
  3266. out &= ~StateFlag_no_bounds_check;
  3267. } else if (in & StateFlag_no_bounds_check) {
  3268. out |= StateFlag_no_bounds_check;
  3269. out &= ~StateFlag_bounds_check;
  3270. }
  3271. p->module->state_flags = out;
  3272. }
  3273. switch (node->kind) {
  3274. case_ast_node(bs, EmptyStmt, node);
  3275. case_end;
  3276. case_ast_node(us, UsingStmt, node);
  3277. case_end;
  3278. case_ast_node(ws, WhenStmt, node);
  3279. lb_build_when_stmt(p, ws);
  3280. case_end;
  3281. case_ast_node(bs, BlockStmt, node);
  3282. if (bs->label != nullptr) {
  3283. lbBlock *done = lb_create_block(p, "block.done");
  3284. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3285. tl->is_block = true;
  3286. lb_open_scope(p);
  3287. lb_build_stmt_list(p, bs->stmts);
  3288. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3289. lb_emit_jump(p, done);
  3290. lb_start_block(p, done);
  3291. } else {
  3292. lb_open_scope(p);
  3293. lb_build_stmt_list(p, bs->stmts);
  3294. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3295. }
  3296. case_end;
  3297. case_ast_node(vd, ValueDecl, node);
  3298. if (!vd->is_mutable) {
  3299. return;
  3300. }
  3301. bool is_static = false;
  3302. if (vd->names.count > 0) {
  3303. Entity *e = entity_of_node(vd->names[0]);
  3304. if (e->flags & EntityFlag_Static) {
  3305. // NOTE(bill): If one of the entities is static, they all are
  3306. is_static = true;
  3307. }
  3308. }
  3309. if (is_static) {
  3310. for_array(i, vd->names) {
  3311. lbValue value = {};
  3312. if (vd->values.count > 0) {
  3313. GB_ASSERT(vd->names.count == vd->values.count);
  3314. Ast *ast_value = vd->values[i];
  3315. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  3316. ast_value->tav.mode == Addressing_Invalid);
  3317. bool allow_local = false;
  3318. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  3319. }
  3320. Ast *ident = vd->names[i];
  3321. GB_ASSERT(!is_blank_ident(ident));
  3322. Entity *e = entity_of_node(ident);
  3323. GB_ASSERT(e->flags & EntityFlag_Static);
  3324. String name = e->token.string;
  3325. String mangled_name = {};
  3326. {
  3327. gbString str = gb_string_make_length(heap_allocator(), p->name.text, p->name.len);
  3328. str = gb_string_appendc(str, "-");
  3329. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  3330. mangled_name.text = cast(u8 *)str;
  3331. mangled_name.len = gb_string_length(str);
  3332. }
  3333. char *c_name = alloc_cstring(heap_allocator(), mangled_name);
  3334. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  3335. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  3336. if (value.value != nullptr) {
  3337. LLVMSetInitializer(global, value.value);
  3338. } else {
  3339. }
  3340. if (e->Variable.thread_local_model != "") {
  3341. LLVMSetThreadLocal(global, true);
  3342. String m = e->Variable.thread_local_model;
  3343. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  3344. if (m == "default") {
  3345. mode = LLVMGeneralDynamicTLSModel;
  3346. } else if (m == "localdynamic") {
  3347. mode = LLVMLocalDynamicTLSModel;
  3348. } else if (m == "initialexec") {
  3349. mode = LLVMInitialExecTLSModel;
  3350. } else if (m == "localexec") {
  3351. mode = LLVMLocalExecTLSModel;
  3352. } else {
  3353. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  3354. }
  3355. LLVMSetThreadLocalMode(global, mode);
  3356. } else {
  3357. LLVMSetLinkage(global, LLVMInternalLinkage);
  3358. }
  3359. lbValue global_val = {global, alloc_type_pointer(e->type)};
  3360. lb_add_entity(p->module, e, global_val);
  3361. lb_add_member(p->module, mangled_name, global_val);
  3362. }
  3363. return;
  3364. }
  3365. if (vd->values.count == 0) { // declared and zero-initialized
  3366. for_array(i, vd->names) {
  3367. Ast *name = vd->names[i];
  3368. if (!is_blank_ident(name)) {
  3369. Entity *e = entity_of_node(name);
  3370. lb_add_local(p, e->type, e, true);
  3371. }
  3372. }
  3373. } else { // Tuple(s)
  3374. auto lvals = array_make<lbAddr>(heap_allocator(), 0, vd->names.count);
  3375. auto inits = array_make<lbValue>(heap_allocator(), 0, vd->names.count);
  3376. for_array(i, vd->names) {
  3377. Ast *name = vd->names[i];
  3378. lbAddr lval = {};
  3379. if (!is_blank_ident(name)) {
  3380. Entity *e = entity_of_node(name);
  3381. lval = lb_add_local(p, e->type, e, false);
  3382. }
  3383. array_add(&lvals, lval);
  3384. }
  3385. for_array(i, vd->values) {
  3386. lbValue init = lb_build_expr(p, vd->values[i]);
  3387. Type *t = init.type;
  3388. if (t->kind == Type_Tuple) {
  3389. for_array(i, t->Tuple.variables) {
  3390. Entity *e = t->Tuple.variables[i];
  3391. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3392. array_add(&inits, v);
  3393. }
  3394. } else {
  3395. array_add(&inits, init);
  3396. }
  3397. }
  3398. for_array(i, inits) {
  3399. lbAddr lval = lvals[i];
  3400. lbValue init = inits[i];
  3401. lb_addr_store(p, lval, init);
  3402. }
  3403. }
  3404. case_end;
  3405. case_ast_node(as, AssignStmt, node);
  3406. if (as->op.kind == Token_Eq) {
  3407. auto lvals = array_make<lbAddr>(heap_allocator(), 0, as->lhs.count);
  3408. for_array(i, as->lhs) {
  3409. Ast *lhs = as->lhs[i];
  3410. lbAddr lval = {};
  3411. if (!is_blank_ident(lhs)) {
  3412. lval = lb_build_addr(p, lhs);
  3413. }
  3414. array_add(&lvals, lval);
  3415. }
  3416. if (as->lhs.count == as->rhs.count) {
  3417. if (as->lhs.count == 1) {
  3418. lbAddr lval = lvals[0];
  3419. Ast *rhs = as->rhs[0];
  3420. lbValue init = lb_build_expr(p, rhs);
  3421. lb_addr_store(p, lvals[0], init);
  3422. } else {
  3423. auto inits = array_make<lbValue>(heap_allocator(), 0, lvals.count);
  3424. for_array(i, as->rhs) {
  3425. lbValue init = lb_build_expr(p, as->rhs[i]);
  3426. array_add(&inits, init);
  3427. }
  3428. for_array(i, inits) {
  3429. lbAddr lval = lvals[i];
  3430. lbValue init = inits[i];
  3431. lb_addr_store(p, lval, init);
  3432. }
  3433. }
  3434. } else {
  3435. auto inits = array_make<lbValue>(heap_allocator(), 0, lvals.count);
  3436. for_array(i, as->rhs) {
  3437. lbValue init = lb_build_expr(p, as->rhs[i]);
  3438. Type *t = init.type;
  3439. // TODO(bill): refactor for code reuse as this is repeated a bit
  3440. if (t->kind == Type_Tuple) {
  3441. for_array(i, t->Tuple.variables) {
  3442. Entity *e = t->Tuple.variables[i];
  3443. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3444. array_add(&inits, v);
  3445. }
  3446. } else {
  3447. array_add(&inits, init);
  3448. }
  3449. }
  3450. for_array(i, inits) {
  3451. lbAddr lval = lvals[i];
  3452. lbValue init = inits[i];
  3453. lb_addr_store(p, lval, init);
  3454. }
  3455. }
  3456. } else {
  3457. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  3458. // +=, -=, etc
  3459. i32 op = cast(i32)as->op.kind;
  3460. op += Token_Add - Token_AddEq; // Convert += to +
  3461. if (op == Token_CmpAnd || op == Token_CmpOr) {
  3462. Type *type = as->lhs[0]->tav.type;
  3463. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  3464. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3465. lb_addr_store(p, lhs, new_value);
  3466. } else {
  3467. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3468. lbValue value = lb_build_expr(p, as->rhs[0]);
  3469. lbValue old_value = lb_addr_load(p, lhs);
  3470. Type *type = old_value.type;
  3471. lbValue change = lb_emit_conv(p, value, type);
  3472. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  3473. lb_addr_store(p, lhs, new_value);
  3474. }
  3475. return;
  3476. }
  3477. case_end;
  3478. case_ast_node(es, ExprStmt, node);
  3479. lb_build_expr(p, es->expr);
  3480. case_end;
  3481. case_ast_node(ds, DeferStmt, node);
  3482. isize scope_index = p->scope_index;
  3483. lb_add_defer_node(p, scope_index, ds->stmt);
  3484. case_end;
  3485. case_ast_node(rs, ReturnStmt, node);
  3486. lbValue res = {};
  3487. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  3488. isize return_count = p->type->Proc.result_count;
  3489. isize res_count = rs->results.count;
  3490. if (return_count == 0) {
  3491. // No return values
  3492. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3493. LLVMBuildRetVoid(p->builder);
  3494. return;
  3495. } else if (return_count == 1) {
  3496. Entity *e = tuple->variables[0];
  3497. if (res_count == 0) {
  3498. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3499. GB_ASSERT(found);
  3500. res = lb_emit_load(p, *found);
  3501. } else {
  3502. res = lb_build_expr(p, rs->results[0]);
  3503. res = lb_emit_conv(p, res, e->type);
  3504. }
  3505. if (p->type->Proc.has_named_results) {
  3506. // NOTE(bill): store the named values before returning
  3507. if (e->token.string != "") {
  3508. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3509. GB_ASSERT(found != nullptr);
  3510. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  3511. }
  3512. }
  3513. } else {
  3514. auto results = array_make<lbValue>(heap_allocator(), 0, return_count);
  3515. if (res_count != 0) {
  3516. for (isize res_index = 0; res_index < res_count; res_index++) {
  3517. lbValue res = lb_build_expr(p, rs->results[res_index]);
  3518. Type *t = res.type;
  3519. if (t->kind == Type_Tuple) {
  3520. for_array(i, t->Tuple.variables) {
  3521. Entity *e = t->Tuple.variables[i];
  3522. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  3523. array_add(&results, v);
  3524. }
  3525. } else {
  3526. array_add(&results, res);
  3527. }
  3528. }
  3529. } else {
  3530. for (isize res_index = 0; res_index < return_count; res_index++) {
  3531. Entity *e = tuple->variables[res_index];
  3532. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3533. GB_ASSERT(found);
  3534. lbValue res = lb_emit_load(p, *found);
  3535. array_add(&results, res);
  3536. }
  3537. }
  3538. GB_ASSERT(results.count == return_count);
  3539. if (p->type->Proc.has_named_results) {
  3540. // NOTE(bill): store the named values before returning
  3541. for_array(i, p->type->Proc.results->Tuple.variables) {
  3542. Entity *e = p->type->Proc.results->Tuple.variables[i];
  3543. if (e->kind != Entity_Variable) {
  3544. continue;
  3545. }
  3546. if (e->token.string == "") {
  3547. continue;
  3548. }
  3549. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3550. GB_ASSERT(found != nullptr);
  3551. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  3552. }
  3553. }
  3554. Type *ret_type = p->type->Proc.results;
  3555. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3556. res = lb_add_local_generated(p, ret_type, false).addr;
  3557. for_array(i, results) {
  3558. Entity *e = tuple->variables[i];
  3559. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  3560. lbValue val = lb_emit_conv(p, results[i], e->type);
  3561. lb_emit_store(p, field, val);
  3562. }
  3563. res = lb_emit_load(p, res);
  3564. }
  3565. if (p->type->Proc.return_by_pointer) {
  3566. if (res.value != nullptr) {
  3567. lb_addr_store(p, p->return_ptr, res);
  3568. } else {
  3569. lb_addr_store(p, p->return_ptr, lb_const_nil(p->module, p->type->Proc.abi_compat_result_type));
  3570. }
  3571. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3572. LLVMBuildRetVoid(p->builder);
  3573. } else {
  3574. GB_ASSERT_MSG(res.value != nullptr, "%.*s", LIT(p->name));
  3575. Type *abi_rt = p->type->Proc.abi_compat_result_type;
  3576. if (!are_types_identical(res.type, abi_rt)) {
  3577. res = lb_emit_transmute(p, res, abi_rt);
  3578. }
  3579. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3580. LLVMBuildRet(p->builder, res.value);
  3581. }
  3582. case_end;
  3583. case_ast_node(is, IfStmt, node);
  3584. lb_open_scope(p); // Scope #1
  3585. if (is->init != nullptr) {
  3586. // TODO(bill): Should this have a separate block to begin with?
  3587. #if 1
  3588. lbBlock *init = lb_create_block(p, "if.init");
  3589. lb_emit_jump(p, init);
  3590. lb_start_block(p, init);
  3591. #endif
  3592. lb_build_stmt(p, is->init);
  3593. }
  3594. lbBlock *then = lb_create_block(p, "if.then");
  3595. lbBlock *done = lb_create_block(p, "if.done");
  3596. lbBlock *else_ = done;
  3597. if (is->else_stmt != nullptr) {
  3598. else_ = lb_create_block(p, "if.else");
  3599. }
  3600. lb_build_cond(p, is->cond, then, else_);
  3601. lb_start_block(p, then);
  3602. if (is->label != nullptr) {
  3603. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  3604. tl->is_block = true;
  3605. }
  3606. lb_build_stmt(p, is->body);
  3607. lb_emit_jump(p, done);
  3608. if (is->else_stmt != nullptr) {
  3609. lb_start_block(p, else_);
  3610. lb_open_scope(p);
  3611. lb_build_stmt(p, is->else_stmt);
  3612. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3613. lb_emit_jump(p, done);
  3614. }
  3615. lb_start_block(p, done);
  3616. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3617. case_end;
  3618. case_ast_node(fs, ForStmt, node);
  3619. lb_open_scope(p); // Open Scope here
  3620. if (fs->init != nullptr) {
  3621. #if 1
  3622. lbBlock *init = lb_create_block(p, "for.init");
  3623. lb_emit_jump(p, init);
  3624. lb_start_block(p, init);
  3625. #endif
  3626. lb_build_stmt(p, fs->init);
  3627. }
  3628. lbBlock *body = lb_create_block(p, "for.body");
  3629. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  3630. lbBlock *loop = body;
  3631. if (fs->cond != nullptr) {
  3632. loop = lb_create_block(p, "for.loop");
  3633. }
  3634. lbBlock *post = loop;
  3635. if (fs->post != nullptr) {
  3636. post = lb_create_block(p, "for.post");
  3637. }
  3638. lb_emit_jump(p, loop);
  3639. lb_start_block(p, loop);
  3640. if (loop != body) {
  3641. lb_build_cond(p, fs->cond, body, done);
  3642. lb_start_block(p, body);
  3643. }
  3644. lb_push_target_list(p, fs->label, done, post, nullptr);
  3645. lb_build_stmt(p, fs->body);
  3646. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3647. lb_pop_target_list(p);
  3648. lb_emit_jump(p, post);
  3649. if (fs->post != nullptr) {
  3650. lb_start_block(p, post);
  3651. lb_build_stmt(p, fs->post);
  3652. lb_emit_jump(p, loop);
  3653. }
  3654. lb_start_block(p, done);
  3655. case_end;
  3656. case_ast_node(rs, RangeStmt, node);
  3657. lb_build_range_stmt(p, rs);
  3658. case_end;
  3659. case_ast_node(rs, InlineRangeStmt, node);
  3660. lb_build_inline_range_stmt(p, rs);
  3661. case_end;
  3662. case_ast_node(ss, SwitchStmt, node);
  3663. lb_build_switch_stmt(p, ss);
  3664. case_end;
  3665. case_ast_node(ss, TypeSwitchStmt, node);
  3666. lb_build_type_switch_stmt(p, ss);
  3667. case_end;
  3668. case_ast_node(bs, BranchStmt, node);
  3669. lbBlock *block = nullptr;
  3670. if (bs->label != nullptr) {
  3671. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  3672. switch (bs->token.kind) {
  3673. case Token_break: block = bb.break_; break;
  3674. case Token_continue: block = bb.continue_; break;
  3675. case Token_fallthrough:
  3676. GB_PANIC("fallthrough cannot have a label");
  3677. break;
  3678. }
  3679. } else {
  3680. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  3681. if (t->is_block) {
  3682. continue;
  3683. }
  3684. switch (bs->token.kind) {
  3685. case Token_break: block = t->break_; break;
  3686. case Token_continue: block = t->continue_; break;
  3687. case Token_fallthrough: block = t->fallthrough_; break;
  3688. }
  3689. }
  3690. }
  3691. if (block != nullptr) {
  3692. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  3693. }
  3694. lb_emit_jump(p, block);
  3695. case_end;
  3696. }
  3697. }
  3698. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  3699. cond = lb_emit_conv(p, cond, t_llvm_bool);
  3700. lbValue res = {};
  3701. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  3702. res.type = x.type;
  3703. return res;
  3704. }
  3705. lbValue lb_const_nil(lbModule *m, Type *type) {
  3706. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  3707. return lbValue{v, type};
  3708. }
  3709. lbValue lb_const_undef(lbModule *m, Type *type) {
  3710. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  3711. return lbValue{v, type};
  3712. }
  3713. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  3714. lbValue res = {};
  3715. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  3716. res.type = type;
  3717. return res;
  3718. }
  3719. lbValue lb_const_string(lbModule *m, String const &value) {
  3720. return lb_const_value(m, t_string, exact_value_string(value));
  3721. }
  3722. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  3723. lbValue res = {};
  3724. res.value = LLVMConstInt(lb_type(m, type), value, false);
  3725. res.type = type;
  3726. return res;
  3727. }
  3728. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  3729. GB_ASSERT(type_size_of(type) == 4);
  3730. u32 u = bit_cast<u32>(f);
  3731. if (is_type_different_to_arch_endianness(type)) {
  3732. u = gb_endian_swap32(u);
  3733. }
  3734. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  3735. return LLVMConstBitCast(i, lb_type(m, type));
  3736. }
  3737. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  3738. x = lb_emit_conv(p, x, t);
  3739. y = lb_emit_conv(p, y, t);
  3740. if (is_type_float(t)) {
  3741. gbAllocator a = heap_allocator();
  3742. i64 sz = 8*type_size_of(t);
  3743. auto args = array_make<lbValue>(heap_allocator(), 2);
  3744. args[0] = x;
  3745. args[1] = y;
  3746. switch (sz) {
  3747. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  3748. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  3749. }
  3750. GB_PANIC("Unknown float type");
  3751. }
  3752. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  3753. }
  3754. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  3755. x = lb_emit_conv(p, x, t);
  3756. y = lb_emit_conv(p, y, t);
  3757. if (is_type_float(t)) {
  3758. gbAllocator a = heap_allocator();
  3759. i64 sz = 8*type_size_of(t);
  3760. auto args = array_make<lbValue>(heap_allocator(), 2);
  3761. args[0] = x;
  3762. args[1] = y;
  3763. switch (sz) {
  3764. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  3765. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  3766. }
  3767. GB_PANIC("Unknown float type");
  3768. }
  3769. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  3770. }
  3771. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  3772. lbValue z = {};
  3773. z = lb_emit_max(p, t, x, min);
  3774. z = lb_emit_min(p, t, z, max);
  3775. return z;
  3776. }
  3777. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  3778. StringHashKey key = string_hash_string(str);
  3779. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  3780. if (found != nullptr) {
  3781. return *found;
  3782. } else {
  3783. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  3784. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  3785. cast(char const *)str.text,
  3786. cast(unsigned)str.len,
  3787. false);
  3788. isize max_len = 7+8+1;
  3789. char *name = gb_alloc_array(heap_allocator(), char, max_len);
  3790. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  3791. len -= 1;
  3792. m->global_array_index++;
  3793. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  3794. LLVMSetInitializer(global_data, data);
  3795. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  3796. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3797. string_map_set(&m->const_strings, key, ptr);
  3798. return ptr;
  3799. }
  3800. }
  3801. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  3802. LLVMValueRef ptr = nullptr;
  3803. if (str.len != 0) {
  3804. ptr = lb_find_or_add_entity_string_ptr(m, str);
  3805. } else {
  3806. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  3807. }
  3808. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  3809. LLVMValueRef values[2] = {ptr, str_len};
  3810. lbValue res = {};
  3811. res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2);
  3812. res.type = t_string;
  3813. return res;
  3814. }
  3815. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  3816. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  3817. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  3818. cast(char const *)str.text,
  3819. cast(unsigned)str.len,
  3820. false);
  3821. char *name = nullptr;
  3822. {
  3823. isize max_len = 7+8+1;
  3824. name = gb_alloc_array(heap_allocator(), char, max_len);
  3825. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  3826. len -= 1;
  3827. m->global_array_index++;
  3828. }
  3829. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  3830. LLVMSetInitializer(global_data, data);
  3831. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  3832. LLVMValueRef ptr = nullptr;
  3833. if (str.len != 0) {
  3834. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3835. } else {
  3836. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  3837. }
  3838. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  3839. LLVMValueRef values[2] = {ptr, len};
  3840. lbValue res = {};
  3841. res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2);
  3842. res.type = t_u8_slice;
  3843. return res;
  3844. }
  3845. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  3846. isize index = type_info_index(info, type, false);
  3847. if (index >= 0) {
  3848. auto *set = &info->minimum_dependency_type_info_set;
  3849. for_array(i, set->entries) {
  3850. if (set->entries[i].ptr == index) {
  3851. return i+1;
  3852. }
  3853. }
  3854. }
  3855. if (err_on_not_found) {
  3856. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  3857. }
  3858. return -1;
  3859. }
  3860. lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type) {
  3861. type = default_type(type);
  3862. u64 id = cast(u64)lb_type_info_index(m->info, type);
  3863. GB_ASSERT(id >= 0);
  3864. u64 kind = Typeid_Invalid;
  3865. u64 named = is_type_named(type) && type->kind != Type_Basic;
  3866. u64 special = 0;
  3867. u64 reserved = 0;
  3868. Type *bt = base_type(type);
  3869. TypeKind tk = bt->kind;
  3870. switch (tk) {
  3871. case Type_Basic: {
  3872. u32 flags = bt->Basic.flags;
  3873. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  3874. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  3875. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  3876. if (flags & BasicFlag_Float) kind = Typeid_Float;
  3877. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  3878. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  3879. if (flags & BasicFlag_String) kind = Typeid_String;
  3880. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  3881. } break;
  3882. case Type_Pointer: kind = Typeid_Pointer; break;
  3883. case Type_Array: kind = Typeid_Array; break;
  3884. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  3885. case Type_Slice: kind = Typeid_Slice; break;
  3886. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  3887. case Type_Map: kind = Typeid_Map; break;
  3888. case Type_Struct: kind = Typeid_Struct; break;
  3889. case Type_Enum: kind = Typeid_Enum; break;
  3890. case Type_Union: kind = Typeid_Union; break;
  3891. case Type_Tuple: kind = Typeid_Tuple; break;
  3892. case Type_Proc: kind = Typeid_Procedure; break;
  3893. case Type_BitField: kind = Typeid_Bit_Field; break;
  3894. case Type_BitSet: kind = Typeid_Bit_Set; break;
  3895. case Type_Opaque: kind = Typeid_Opaque; break;
  3896. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  3897. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  3898. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  3899. }
  3900. if (is_type_cstring(type)) {
  3901. special = 1;
  3902. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  3903. special = 1;
  3904. }
  3905. u64 data = 0;
  3906. if (build_context.word_size == 4) {
  3907. data |= (id &~ (1u<<24)) << 0u; // index
  3908. data |= (kind &~ (1u<<5)) << 24u; // kind
  3909. data |= (named &~ (1u<<1)) << 29u; // kind
  3910. data |= (special &~ (1u<<1)) << 30u; // kind
  3911. data |= (reserved &~ (1u<<1)) << 31u; // kind
  3912. } else {
  3913. GB_ASSERT(build_context.word_size == 8);
  3914. data |= (id &~ (1ull<<56)) << 0ul; // index
  3915. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  3916. data |= (named &~ (1ull<<1)) << 61ull; // kind
  3917. data |= (special &~ (1ull<<1)) << 62ull; // kind
  3918. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  3919. }
  3920. lbValue res = {};
  3921. res.value = LLVMConstInt(lb_type(m, typeid_type), data, false);
  3922. res.type = typeid_type;
  3923. return res;
  3924. }
  3925. lbValue lb_type_info(lbModule *m, Type *type) {
  3926. type = default_type(type);
  3927. isize index = lb_type_info_index(m->info, type);
  3928. GB_ASSERT(index >= 0);
  3929. LLVMTypeRef it = lb_type(m, t_int);
  3930. LLVMValueRef indices[2] = {
  3931. LLVMConstInt(it, 0, false),
  3932. LLVMConstInt(it, index, true),
  3933. };
  3934. lbValue value = {};
  3935. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  3936. value.type = t_type_info_ptr;
  3937. return value;
  3938. }
  3939. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  3940. LLVMContextRef ctx = m->ctx;
  3941. type = default_type(type);
  3942. Type *original_type = type;
  3943. lbValue res = {};
  3944. res.type = original_type;
  3945. type = core_type(type);
  3946. value = convert_exact_value_for_type(value, type);
  3947. if (value.kind == ExactValue_Typeid) {
  3948. return lb_typeid(m, value.value_typeid, original_type);
  3949. }
  3950. if (value.kind == ExactValue_Invalid) {
  3951. return lb_const_nil(m, type);
  3952. }
  3953. if (value.kind == ExactValue_Procedure) {
  3954. Ast *expr = unparen_expr(value.value_procedure);
  3955. if (expr->kind == Ast_ProcLit) {
  3956. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  3957. }
  3958. Entity *e = entity_from_expr(expr);
  3959. e = strip_entity_wrapping(e);
  3960. GB_ASSERT(e != nullptr);
  3961. auto *found = map_get(&m->values, hash_entity(e));
  3962. if (found) {
  3963. return *found;
  3964. }
  3965. GB_PANIC("Error in: %.*s(%td:%td), missing procedure %.*s\n", LIT(e->token.pos.file), e->token.pos.line, e->token.pos.column, LIT(e->token.string));
  3966. }
  3967. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  3968. if (is_type_slice(type)) {
  3969. if (value.kind == ExactValue_String) {
  3970. GB_ASSERT(is_type_u8_slice(type));
  3971. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  3972. return res;
  3973. } else {
  3974. ast_node(cl, CompoundLit, value.value_compound);
  3975. isize count = cl->elems.count;
  3976. if (count == 0) {
  3977. return lb_const_nil(m, type);
  3978. }
  3979. count = gb_max(cl->max_count, count);
  3980. Type *elem = base_type(type)->Slice.elem;
  3981. Type *t = alloc_type_array(elem, count);
  3982. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  3983. LLVMValueRef array_data = nullptr;
  3984. if (allow_local && m->curr_procedure != nullptr) {
  3985. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  3986. // its backing data on the stack
  3987. lbProcedure *p = m->curr_procedure;
  3988. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  3989. LLVMTypeRef llvm_type = lb_type(m, t);
  3990. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  3991. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  3992. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  3993. LLVMBuildStore(p->builder, backing_array.value, array_data);
  3994. {
  3995. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  3996. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  3997. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  3998. lbAddr slice = lb_add_local_generated(p, type, false);
  3999. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4000. return lb_addr_load(p, slice);
  4001. }
  4002. } else {
  4003. isize max_len = 7+8+1;
  4004. char *str = gb_alloc_array(heap_allocator(), char, max_len);
  4005. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4006. m->global_array_index++;
  4007. String name = make_string(cast(u8 *)str, len-1);
  4008. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4009. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4010. LLVMSetInitializer(array_data, backing_array.value);
  4011. lbValue g = {};
  4012. g.value = array_data;
  4013. g.type = t;
  4014. lb_add_entity(m, e, g);
  4015. lb_add_member(m, name, g);
  4016. {
  4017. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4018. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4019. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4020. LLVMValueRef values[2] = {ptr, len};
  4021. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4022. return res;
  4023. }
  4024. }
  4025. }
  4026. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4027. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4028. cast(char const *)value.value_string.text,
  4029. cast(unsigned)value.value_string.len,
  4030. false);
  4031. res.value = data;
  4032. return res;
  4033. } else if (is_type_array(type) &&
  4034. value.kind != ExactValue_Invalid &&
  4035. value.kind != ExactValue_String &&
  4036. value.kind != ExactValue_Compound) {
  4037. i64 count = type->Array.count;
  4038. Type *elem = type->Array.elem;
  4039. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4040. LLVMValueRef *elems = gb_alloc_array(heap_allocator(), LLVMValueRef, count);
  4041. for (i64 i = 0; i < count; i++) {
  4042. elems[i] = single_elem.value;
  4043. }
  4044. res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)count);
  4045. return res;
  4046. }
  4047. switch (value.kind) {
  4048. case ExactValue_Invalid:
  4049. res.value = LLVMConstNull(lb_type(m, original_type));
  4050. return res;
  4051. case ExactValue_Bool:
  4052. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4053. return res;
  4054. case ExactValue_String:
  4055. {
  4056. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4057. lbValue res = {};
  4058. res.type = default_type(original_type);
  4059. if (is_type_cstring(res.type)) {
  4060. res.value = ptr;
  4061. } else {
  4062. if (value.value_string.len == 0) {
  4063. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4064. }
  4065. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4066. LLVMValueRef values[2] = {ptr, str_len};
  4067. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4068. }
  4069. return res;
  4070. }
  4071. case ExactValue_Integer:
  4072. if (is_type_pointer(type)) {
  4073. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  4074. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  4075. } else {
  4076. unsigned len = cast(unsigned)value.value_integer.len;
  4077. if (len == 0) {
  4078. u64 word = 0;
  4079. res.value = LLVMConstNull(lb_type(m, original_type));
  4080. } else {
  4081. u64 *words = big_int_ptr(&value.value_integer);
  4082. if (is_type_different_to_arch_endianness(type)) {
  4083. // NOTE(bill): Swap byte order for different endianness
  4084. i64 sz = type_size_of(type);
  4085. isize byte_len = gb_size_of(u64)*len;
  4086. u8 *old_bytes = cast(u8 *)words;
  4087. // TODO(bill): Use a different allocator here for a temporary allocation
  4088. u8 *new_bytes = cast(u8 *)gb_alloc_align(heap_allocator(), byte_len, gb_align_of(u64));
  4089. for (i64 i = 0; i < sz; i++) {
  4090. new_bytes[i] = old_bytes[sz-1-i];
  4091. }
  4092. words = cast(u64 *)new_bytes;
  4093. }
  4094. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4095. if (value.value_integer.neg) {
  4096. res.value = LLVMConstNeg(res.value);
  4097. }
  4098. }
  4099. }
  4100. return res;
  4101. case ExactValue_Float:
  4102. if (type_size_of(type) == 4) {
  4103. f32 f = cast(f32)value.value_float;
  4104. res.value = lb_const_f32(m, f, type);
  4105. return res;
  4106. }
  4107. if (is_type_different_to_arch_endianness(type)) {
  4108. u64 u = bit_cast<u64>(value.value_float);
  4109. u = gb_endian_swap64(u);
  4110. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4111. } else {
  4112. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4113. }
  4114. return res;
  4115. case ExactValue_Complex:
  4116. {
  4117. LLVMValueRef values[2] = {};
  4118. switch (8*type_size_of(type)) {
  4119. case 64:
  4120. values[0] = lb_const_f32(m, cast(f32)value.value_complex.real);
  4121. values[1] = lb_const_f32(m, cast(f32)value.value_complex.imag);
  4122. break;
  4123. case 128:
  4124. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.real);
  4125. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.imag);
  4126. break;
  4127. }
  4128. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4129. return res;
  4130. }
  4131. break;
  4132. case ExactValue_Quaternion:
  4133. {
  4134. LLVMValueRef values[4] = {};
  4135. switch (8*type_size_of(type)) {
  4136. case 128:
  4137. // @QuaternionLayout
  4138. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion.real);
  4139. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion.imag);
  4140. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion.jmag);
  4141. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion.kmag);
  4142. break;
  4143. case 256:
  4144. // @QuaternionLayout
  4145. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.real);
  4146. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.imag);
  4147. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.jmag);
  4148. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.kmag);
  4149. break;
  4150. }
  4151. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 4);
  4152. return res;
  4153. }
  4154. break;
  4155. case ExactValue_Pointer:
  4156. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4157. return res;
  4158. case ExactValue_Compound:
  4159. if (is_type_slice(type)) {
  4160. return lb_const_value(m, type, value, allow_local);
  4161. } else if (is_type_array(type)) {
  4162. ast_node(cl, CompoundLit, value.value_compound);
  4163. Type *elem_type = type->Array.elem;
  4164. isize elem_count = cl->elems.count;
  4165. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4166. return lb_const_nil(m, original_type);
  4167. }
  4168. if (cl->elems[0]->kind == Ast_FieldValue) {
  4169. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4170. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count);
  4171. defer (gb_free(heap_allocator(), values));
  4172. isize value_index = 0;
  4173. for (i64 i = 0; i < type->Array.count; i++) {
  4174. bool found = false;
  4175. for (isize j = 0; j < elem_count; j++) {
  4176. Ast *elem = cl->elems[j];
  4177. ast_node(fv, FieldValue, elem);
  4178. if (is_ast_range(fv->field)) {
  4179. ast_node(ie, BinaryExpr, fv->field);
  4180. TypeAndValue lo_tav = ie->left->tav;
  4181. TypeAndValue hi_tav = ie->right->tav;
  4182. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4183. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4184. TokenKind op = ie->op.kind;
  4185. i64 lo = exact_value_to_i64(lo_tav.value);
  4186. i64 hi = exact_value_to_i64(hi_tav.value);
  4187. if (op == Token_Ellipsis) {
  4188. hi += 1;
  4189. }
  4190. if (lo == i) {
  4191. TypeAndValue tav = fv->value->tav;
  4192. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4193. for (i64 k = lo; k < hi; k++) {
  4194. values[value_index++] = val;
  4195. }
  4196. found = true;
  4197. i += (hi-lo-1);
  4198. break;
  4199. }
  4200. } else {
  4201. TypeAndValue index_tav = fv->field->tav;
  4202. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4203. i64 index = exact_value_to_i64(index_tav.value);
  4204. if (index == i) {
  4205. TypeAndValue tav = fv->value->tav;
  4206. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4207. values[value_index++] = val;
  4208. found = true;
  4209. break;
  4210. }
  4211. }
  4212. }
  4213. if (!found) {
  4214. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4215. }
  4216. }
  4217. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  4218. return res;
  4219. } else {
  4220. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  4221. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count);
  4222. defer (gb_free(heap_allocator(), values));
  4223. for (isize i = 0; i < elem_count; i++) {
  4224. TypeAndValue tav = cl->elems[i]->tav;
  4225. GB_ASSERT(tav.mode != Addressing_Invalid);
  4226. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4227. }
  4228. for (isize i = elem_count; i < type->Array.count; i++) {
  4229. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4230. }
  4231. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  4232. return res;
  4233. }
  4234. } else if (is_type_enumerated_array(type)) {
  4235. ast_node(cl, CompoundLit, value.value_compound);
  4236. Type *elem_type = type->EnumeratedArray.elem;
  4237. isize elem_count = cl->elems.count;
  4238. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4239. return lb_const_nil(m, original_type);
  4240. }
  4241. if (cl->elems[0]->kind == Ast_FieldValue) {
  4242. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4243. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4244. defer (gb_free(heap_allocator(), values));
  4245. isize value_index = 0;
  4246. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  4247. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  4248. for (i64 i = total_lo; i <= total_hi; i++) {
  4249. bool found = false;
  4250. for (isize j = 0; j < elem_count; j++) {
  4251. Ast *elem = cl->elems[j];
  4252. ast_node(fv, FieldValue, elem);
  4253. if (is_ast_range(fv->field)) {
  4254. ast_node(ie, BinaryExpr, fv->field);
  4255. TypeAndValue lo_tav = ie->left->tav;
  4256. TypeAndValue hi_tav = ie->right->tav;
  4257. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4258. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4259. TokenKind op = ie->op.kind;
  4260. i64 lo = exact_value_to_i64(lo_tav.value);
  4261. i64 hi = exact_value_to_i64(hi_tav.value);
  4262. if (op == Token_Ellipsis) {
  4263. hi += 1;
  4264. }
  4265. if (lo == i) {
  4266. TypeAndValue tav = fv->value->tav;
  4267. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4268. for (i64 k = lo; k < hi; k++) {
  4269. values[value_index++] = val;
  4270. }
  4271. found = true;
  4272. i += (hi-lo-1);
  4273. break;
  4274. }
  4275. } else {
  4276. TypeAndValue index_tav = fv->field->tav;
  4277. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4278. i64 index = exact_value_to_i64(index_tav.value);
  4279. if (index == i) {
  4280. TypeAndValue tav = fv->value->tav;
  4281. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4282. values[value_index++] = val;
  4283. found = true;
  4284. break;
  4285. }
  4286. }
  4287. }
  4288. if (!found) {
  4289. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4290. }
  4291. }
  4292. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  4293. return res;
  4294. } else {
  4295. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  4296. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4297. defer (gb_free(heap_allocator(), values));
  4298. for (isize i = 0; i < elem_count; i++) {
  4299. TypeAndValue tav = cl->elems[i]->tav;
  4300. GB_ASSERT(tav.mode != Addressing_Invalid);
  4301. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4302. }
  4303. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  4304. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4305. }
  4306. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  4307. return res;
  4308. }
  4309. } else if (is_type_simd_vector(type)) {
  4310. ast_node(cl, CompoundLit, value.value_compound);
  4311. Type *elem_type = type->SimdVector.elem;
  4312. isize elem_count = cl->elems.count;
  4313. if (elem_count == 0) {
  4314. return lb_const_nil(m, original_type);
  4315. }
  4316. GB_ASSERT(elem_type_can_be_constant(elem_type));
  4317. isize total_elem_count = type->SimdVector.count;
  4318. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, total_elem_count);
  4319. defer (gb_free(heap_allocator(), values));
  4320. for (isize i = 0; i < elem_count; i++) {
  4321. TypeAndValue tav = cl->elems[i]->tav;
  4322. GB_ASSERT(tav.mode != Addressing_Invalid);
  4323. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4324. }
  4325. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  4326. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4327. }
  4328. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  4329. return res;
  4330. } else if (is_type_struct(type)) {
  4331. ast_node(cl, CompoundLit, value.value_compound);
  4332. if (cl->elems.count == 0) {
  4333. return lb_const_nil(m, original_type);
  4334. }
  4335. isize offset = 0;
  4336. if (type->Struct.custom_align > 0) {
  4337. offset = 1;
  4338. }
  4339. isize value_count = type->Struct.fields.count + offset;
  4340. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, value_count);
  4341. bool *visited = gb_alloc_array(heap_allocator(), bool, value_count);
  4342. defer (gb_free(heap_allocator(), values));
  4343. defer (gb_free(heap_allocator(), visited));
  4344. if (cl->elems.count > 0) {
  4345. if (cl->elems[0]->kind == Ast_FieldValue) {
  4346. isize elem_count = cl->elems.count;
  4347. for (isize i = 0; i < elem_count; i++) {
  4348. ast_node(fv, FieldValue, cl->elems[i]);
  4349. String name = fv->field->Ident.token.string;
  4350. TypeAndValue tav = fv->value->tav;
  4351. GB_ASSERT(tav.mode != Addressing_Invalid);
  4352. Selection sel = lookup_field(type, name, false);
  4353. Entity *f = type->Struct.fields[sel.index[0]];
  4354. if (elem_type_can_be_constant(f->type)) {
  4355. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  4356. visited[offset+f->Variable.field_index] = true;
  4357. }
  4358. }
  4359. } else {
  4360. for_array(i, cl->elems) {
  4361. Entity *f = type->Struct.fields[i];
  4362. TypeAndValue tav = cl->elems[i]->tav;
  4363. ExactValue val = {};
  4364. if (tav.mode != Addressing_Invalid) {
  4365. val = tav.value;
  4366. }
  4367. if (elem_type_can_be_constant(f->type)) {
  4368. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  4369. visited[offset+f->Variable.field_index] = true;
  4370. }
  4371. }
  4372. }
  4373. }
  4374. for (isize i = 0; i < type->Struct.fields.count; i++) {
  4375. if (!visited[offset+i]) {
  4376. GB_ASSERT(values[offset+i] == nullptr);
  4377. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  4378. }
  4379. }
  4380. if (type->Struct.custom_align > 0) {
  4381. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  4382. }
  4383. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, cast(unsigned)value_count);
  4384. return res;
  4385. } else if (is_type_bit_set(type)) {
  4386. ast_node(cl, CompoundLit, value.value_compound);
  4387. if (cl->elems.count == 0) {
  4388. return lb_const_nil(m, original_type);
  4389. }
  4390. i64 sz = type_size_of(type);
  4391. if (sz == 0) {
  4392. return lb_const_nil(m, original_type);
  4393. }
  4394. u64 bits = 0;
  4395. for_array(i, cl->elems) {
  4396. Ast *e = cl->elems[i];
  4397. GB_ASSERT(e->kind != Ast_FieldValue);
  4398. TypeAndValue tav = e->tav;
  4399. if (tav.mode != Addressing_Constant) {
  4400. continue;
  4401. }
  4402. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  4403. i64 v = big_int_to_i64(&tav.value.value_integer);
  4404. i64 lower = type->BitSet.lower;
  4405. bits |= 1ull<<cast(u64)(v-lower);
  4406. }
  4407. if (is_type_different_to_arch_endianness(type)) {
  4408. i64 size = type_size_of(type);
  4409. switch (size) {
  4410. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  4411. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  4412. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  4413. }
  4414. }
  4415. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  4416. return res;
  4417. } else {
  4418. return lb_const_nil(m, original_type);
  4419. }
  4420. break;
  4421. case ExactValue_Procedure:
  4422. {
  4423. Ast *expr = value.value_procedure;
  4424. GB_ASSERT(expr != nullptr);
  4425. if (expr->kind == Ast_ProcLit) {
  4426. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4427. }
  4428. }
  4429. break;
  4430. case ExactValue_Typeid:
  4431. return lb_typeid(m, value.value_typeid, original_type);
  4432. }
  4433. return lb_const_nil(m, original_type);
  4434. }
  4435. u64 lb_generate_source_code_location_hash(TokenPos const &pos) {
  4436. u64 h = 0xcbf29ce484222325;
  4437. for (isize i = 0; i < pos.file.len; i++) {
  4438. h = (h ^ u64(pos.file[i])) * 0x100000001b3;
  4439. }
  4440. h = h ^ (u64(pos.line) * 0x100000001b3);
  4441. h = h ^ (u64(pos.column) * 0x100000001b3);
  4442. return h;
  4443. }
  4444. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  4445. lbModule *m = p->module;
  4446. LLVMValueRef fields[5] = {};
  4447. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value;
  4448. fields[1]/*line*/ = lb_const_int(m, t_int, pos.line).value;
  4449. fields[2]/*column*/ = lb_const_int(m, t_int, pos.column).value;
  4450. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  4451. fields[4]/*hash*/ = lb_const_int(m, t_u64, lb_generate_source_code_location_hash(pos)).value;
  4452. lbValue res = {};
  4453. res.value = LLVMConstNamedStruct(lb_type(m, t_source_code_location), fields, 5);
  4454. res.type = t_source_code_location;
  4455. return res;
  4456. }
  4457. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  4458. String proc_name = {};
  4459. if (p->entity) {
  4460. proc_name = p->entity->token.string;
  4461. }
  4462. TokenPos pos = {};
  4463. if (node) {
  4464. pos = ast_token(node).pos;
  4465. }
  4466. return lb_emit_source_code_location(p, proc_name, pos);
  4467. }
  4468. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  4469. switch (op) {
  4470. case Token_Add:
  4471. return x;
  4472. case Token_Not: // Boolean not
  4473. case Token_Xor: // Bitwise not
  4474. case Token_Sub: // Number negation
  4475. break;
  4476. case Token_Pointer:
  4477. GB_PANIC("This should be handled elsewhere");
  4478. break;
  4479. }
  4480. if (is_type_array(x.type)) {
  4481. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  4482. Type *tl = base_type(x.type);
  4483. lbValue val = lb_address_from_load_or_generate_local(p, x);
  4484. GB_ASSERT(is_type_array(type));
  4485. Type *elem_type = base_array_type(type);
  4486. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4487. lbAddr res_addr = lb_add_local_generated(p, type, false);
  4488. lbValue res = lb_addr_get_ptr(p, res_addr);
  4489. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4490. i32 count = cast(i32)tl->Array.count;
  4491. if (inline_array_arith) {
  4492. // inline
  4493. for (i32 i = 0; i < count; i++) {
  4494. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  4495. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4496. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  4497. }
  4498. } else {
  4499. auto loop_data = lb_loop_start(p, count, t_i32);
  4500. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  4501. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4502. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  4503. lb_loop_end(p, loop_data);
  4504. }
  4505. return lb_emit_load(p, res);
  4506. }
  4507. if (op == Token_Xor) {
  4508. lbValue cmp = {};
  4509. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  4510. cmp.type = x.type;
  4511. return lb_emit_conv(p, cmp, type);
  4512. }
  4513. if (op == Token_Not) {
  4514. lbValue cmp = {};
  4515. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  4516. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  4517. cmp.type = t_llvm_bool;
  4518. return lb_emit_conv(p, cmp, type);
  4519. }
  4520. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4521. Type *platform_type = integer_endian_type_to_platform_type(type);
  4522. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4523. lbValue res = {};
  4524. res.value = LLVMBuildNeg(p->builder, v.value, "");
  4525. res.type = platform_type;
  4526. return lb_emit_byte_swap(p, res, type);
  4527. }
  4528. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4529. Type *platform_type = integer_endian_type_to_platform_type(type);
  4530. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4531. lbValue res = {};
  4532. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  4533. res.type = platform_type;
  4534. return lb_emit_byte_swap(p, res, type);
  4535. }
  4536. lbValue res = {};
  4537. switch (op) {
  4538. case Token_Not: // Boolean not
  4539. case Token_Xor: // Bitwise not
  4540. res.value = LLVMBuildNot(p->builder, x.value, "");
  4541. res.type = x.type;
  4542. return res;
  4543. case Token_Sub: // Number negation
  4544. if (is_type_integer(x.type)) {
  4545. res.value = LLVMBuildNeg(p->builder, x.value, "");
  4546. } else if (is_type_float(x.type)) {
  4547. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  4548. } else if (is_type_complex(x.type)) {
  4549. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4550. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4551. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4552. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4553. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4554. return lb_addr_load(p, addr);
  4555. } else if (is_type_quaternion(x.type)) {
  4556. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4557. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4558. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  4559. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  4560. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4561. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4562. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4563. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  4564. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  4565. return lb_addr_load(p, addr);
  4566. } else {
  4567. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  4568. }
  4569. res.type = x.type;
  4570. return res;
  4571. }
  4572. return res;
  4573. }
  4574. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  4575. lbModule *m = p->module;
  4576. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  4577. lhs = lb_emit_conv(p, lhs, type);
  4578. rhs = lb_emit_conv(p, rhs, type);
  4579. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  4580. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4581. GB_ASSERT(is_type_array(type));
  4582. Type *elem_type = base_array_type(type);
  4583. lbAddr res = lb_add_local_generated(p, type, false);
  4584. i64 count = base_type(type)->Array.count;
  4585. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4586. if (inline_array_arith) {
  4587. for (i64 i = 0; i < count; i++) {
  4588. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  4589. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  4590. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  4591. lbValue a = lb_emit_load(p, a_ptr);
  4592. lbValue b = lb_emit_load(p, b_ptr);
  4593. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4594. lb_emit_store(p, dst_ptr, c);
  4595. }
  4596. } else {
  4597. auto loop_data = lb_loop_start(p, count, t_i32);
  4598. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  4599. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  4600. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  4601. lbValue a = lb_emit_load(p, a_ptr);
  4602. lbValue b = lb_emit_load(p, b_ptr);
  4603. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4604. lb_emit_store(p, dst_ptr, c);
  4605. lb_loop_end(p, loop_data);
  4606. }
  4607. return lb_addr_load(p, res);
  4608. } else if (is_type_complex(type)) {
  4609. lhs = lb_emit_conv(p, lhs, type);
  4610. rhs = lb_emit_conv(p, rhs, type);
  4611. Type *ft = base_complex_elem_type(type);
  4612. if (op == Token_Quo) {
  4613. auto args = array_make<lbValue>(heap_allocator(), 2);
  4614. args[0] = lhs;
  4615. args[1] = rhs;
  4616. switch (type_size_of(ft)) {
  4617. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  4618. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  4619. default: GB_PANIC("Unknown float type"); break;
  4620. }
  4621. }
  4622. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4623. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  4624. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  4625. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  4626. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  4627. lbValue real = {};
  4628. lbValue imag = {};
  4629. switch (op) {
  4630. case Token_Add:
  4631. real = lb_emit_arith(p, Token_Add, a, c, ft);
  4632. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  4633. break;
  4634. case Token_Sub:
  4635. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  4636. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  4637. break;
  4638. case Token_Mul: {
  4639. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  4640. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  4641. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  4642. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  4643. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  4644. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  4645. break;
  4646. }
  4647. }
  4648. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  4649. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  4650. return lb_addr_load(p, res);
  4651. } else if (is_type_quaternion(type)) {
  4652. lhs = lb_emit_conv(p, lhs, type);
  4653. rhs = lb_emit_conv(p, rhs, type);
  4654. Type *ft = base_complex_elem_type(type);
  4655. if (op == Token_Add || op == Token_Sub) {
  4656. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4657. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  4658. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  4659. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  4660. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  4661. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  4662. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  4663. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  4664. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  4665. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  4666. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  4667. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  4668. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  4669. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  4670. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  4671. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  4672. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  4673. return lb_addr_load(p, res);
  4674. } else if (op == Token_Mul) {
  4675. auto args = array_make<lbValue>(heap_allocator(), 2);
  4676. args[0] = lhs;
  4677. args[1] = rhs;
  4678. switch (8*type_size_of(ft)) {
  4679. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  4680. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  4681. default: GB_PANIC("Unknown float type"); break;
  4682. }
  4683. } else if (op == Token_Quo) {
  4684. auto args = array_make<lbValue>(heap_allocator(), 2);
  4685. args[0] = lhs;
  4686. args[1] = rhs;
  4687. switch (8*type_size_of(ft)) {
  4688. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  4689. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  4690. default: GB_PANIC("Unknown float type"); break;
  4691. }
  4692. }
  4693. }
  4694. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4695. switch (op) {
  4696. case Token_AndNot:
  4697. case Token_And:
  4698. case Token_Or:
  4699. case Token_Xor:
  4700. goto handle_op;
  4701. }
  4702. Type *platform_type = integer_endian_type_to_platform_type(type);
  4703. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4704. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4705. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  4706. return lb_emit_byte_swap(p, res, type);
  4707. }
  4708. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4709. Type *platform_type = integer_endian_type_to_platform_type(type);
  4710. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4711. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4712. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  4713. return lb_emit_byte_swap(p, res, type);
  4714. }
  4715. handle_op:
  4716. lhs = lb_emit_conv(p, lhs, type);
  4717. rhs = lb_emit_conv(p, rhs, type);
  4718. lbValue res = {};
  4719. res.type = type;
  4720. switch (op) {
  4721. case Token_Add:
  4722. if (is_type_float(type)) {
  4723. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  4724. return res;
  4725. }
  4726. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  4727. return res;
  4728. case Token_Sub:
  4729. if (is_type_float(type)) {
  4730. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  4731. return res;
  4732. }
  4733. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  4734. return res;
  4735. case Token_Mul:
  4736. if (is_type_float(type)) {
  4737. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  4738. return res;
  4739. }
  4740. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  4741. return res;
  4742. case Token_Quo:
  4743. if (is_type_float(type)) {
  4744. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  4745. return res;
  4746. } else if (is_type_unsigned(type)) {
  4747. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  4748. return res;
  4749. }
  4750. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  4751. return res;
  4752. case Token_Mod:
  4753. if (is_type_float(type)) {
  4754. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  4755. return res;
  4756. } else if (is_type_unsigned(type)) {
  4757. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  4758. return res;
  4759. }
  4760. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  4761. return res;
  4762. case Token_ModMod:
  4763. if (is_type_unsigned(type)) {
  4764. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  4765. return res;
  4766. } else {
  4767. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  4768. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  4769. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  4770. res.value = c;
  4771. return res;
  4772. }
  4773. case Token_And:
  4774. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  4775. return res;
  4776. case Token_Or:
  4777. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  4778. return res;
  4779. case Token_Xor:
  4780. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  4781. return res;
  4782. case Token_Shl:
  4783. {
  4784. rhs = lb_emit_conv(p, rhs, lhs.type);
  4785. LLVMValueRef lhsval = lhs.value;
  4786. LLVMValueRef bits = rhs.value;
  4787. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  4788. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  4789. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  4790. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  4791. res.value = LLVMBuildSelect(p->builder, less_equal_width, res.value, zero, "");
  4792. return res;
  4793. }
  4794. case Token_Shr:
  4795. {
  4796. rhs = lb_emit_conv(p, rhs, lhs.type);
  4797. LLVMValueRef lhsval = lhs.value;
  4798. LLVMValueRef bits = rhs.value;
  4799. bool is_unsigned = is_type_unsigned(type);
  4800. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  4801. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  4802. bits = LLVMBuildSelect(p->builder, less_equal_width, bits, max, "");
  4803. if (is_unsigned) {
  4804. res.value = LLVMBuildLShr(p->builder, lhs.value, bits, "");
  4805. } else {
  4806. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  4807. }
  4808. return res;
  4809. }
  4810. case Token_AndNot:
  4811. {
  4812. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  4813. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  4814. return res;
  4815. }
  4816. break;
  4817. }
  4818. GB_PANIC("unhandled operator of lb_emit_arith");
  4819. return {};
  4820. }
  4821. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  4822. ast_node(be, BinaryExpr, expr);
  4823. TypeAndValue tv = type_and_value_of_expr(expr);
  4824. switch (be->op.kind) {
  4825. case Token_Add:
  4826. case Token_Sub:
  4827. case Token_Mul:
  4828. case Token_Quo:
  4829. case Token_Mod:
  4830. case Token_ModMod:
  4831. case Token_And:
  4832. case Token_Or:
  4833. case Token_Xor:
  4834. case Token_AndNot:
  4835. case Token_Shl:
  4836. case Token_Shr: {
  4837. Type *type = default_type(tv.type);
  4838. lbValue left = lb_build_expr(p, be->left);
  4839. lbValue right = lb_build_expr(p, be->right);
  4840. return lb_emit_arith(p, be->op.kind, left, right, type);
  4841. }
  4842. case Token_CmpEq:
  4843. case Token_NotEq:
  4844. case Token_Lt:
  4845. case Token_LtEq:
  4846. case Token_Gt:
  4847. case Token_GtEq:
  4848. {
  4849. lbValue left = {};
  4850. lbValue right = {};
  4851. if (be->left->tav.mode == Addressing_Type) {
  4852. left = lb_typeid(p->module, be->left->tav.type, t_typeid);
  4853. }
  4854. if (be->right->tav.mode == Addressing_Type) {
  4855. right = lb_typeid(p->module, be->right->tav.type, t_typeid);
  4856. }
  4857. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  4858. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  4859. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  4860. Type *type = default_type(tv.type);
  4861. return lb_emit_conv(p, cmp, type);
  4862. }
  4863. case Token_CmpAnd:
  4864. case Token_CmpOr:
  4865. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  4866. case Token_in:
  4867. case Token_not_in:
  4868. {
  4869. lbValue left = lb_build_expr(p, be->left);
  4870. Type *type = default_type(tv.type);
  4871. lbValue right = lb_build_expr(p, be->right);
  4872. Type *rt = base_type(right.type);
  4873. switch (rt->kind) {
  4874. case Type_Map:
  4875. {
  4876. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  4877. lbValue h = lb_gen_map_header(p, addr, rt);
  4878. lbValue key = lb_gen_map_key(p, left, rt->Map.key);
  4879. auto args = array_make<lbValue>(heap_allocator(), 2);
  4880. args[0] = h;
  4881. args[1] = key;
  4882. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  4883. if (be->op.kind == Token_in) {
  4884. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  4885. } else {
  4886. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  4887. }
  4888. }
  4889. break;
  4890. case Type_BitSet:
  4891. {
  4892. Type *key_type = rt->BitSet.elem;
  4893. GB_ASSERT(are_types_identical(left.type, key_type));
  4894. Type *it = bit_set_to_int(rt);
  4895. left = lb_emit_conv(p, left, it);
  4896. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  4897. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  4898. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  4899. bit = lb_emit_conv(p, bit, it);
  4900. lbValue old_value = lb_emit_transmute(p, right, it);
  4901. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  4902. if (be->op.kind == Token_in) {
  4903. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  4904. } else {
  4905. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  4906. }
  4907. }
  4908. break;
  4909. default:
  4910. GB_PANIC("Invalid 'in' type");
  4911. }
  4912. break;
  4913. }
  4914. break;
  4915. default:
  4916. GB_PANIC("Invalid binary expression");
  4917. break;
  4918. }
  4919. return {};
  4920. }
  4921. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  4922. Type *prev_src = src;
  4923. // Type *prev_dst = dst;
  4924. src = base_type(type_deref(src));
  4925. // dst = base_type(type_deref(dst));
  4926. bool src_is_ptr = src != prev_src;
  4927. // bool dst_is_ptr = dst != prev_dst;
  4928. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  4929. for_array(i, src->Struct.fields) {
  4930. Entity *f = src->Struct.fields[i];
  4931. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  4932. if (are_types_identical(dst, f->type)) {
  4933. return f->token.string;
  4934. }
  4935. if (src_is_ptr && is_type_pointer(dst)) {
  4936. if (are_types_identical(type_deref(dst), f->type)) {
  4937. return f->token.string;
  4938. }
  4939. }
  4940. if (is_type_struct(f->type)) {
  4941. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  4942. if (name.len > 0) {
  4943. return name;
  4944. }
  4945. }
  4946. }
  4947. }
  4948. return str_lit("");
  4949. }
  4950. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  4951. GB_ASSERT(is_type_pointer(value.type));
  4952. GB_ASSERT(is_type_pointer(t));
  4953. GB_ASSERT(lb_is_const(value));
  4954. lbValue res = {};
  4955. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  4956. res.type = t;
  4957. return res;
  4958. }
  4959. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  4960. lbModule *m = p->module;
  4961. t = reduce_tuple_to_single_type(t);
  4962. Type *src_type = value.type;
  4963. if (are_types_identical(t, src_type)) {
  4964. return value;
  4965. }
  4966. Type *src = core_type(src_type);
  4967. Type *dst = core_type(t);
  4968. GB_ASSERT(src != nullptr);
  4969. GB_ASSERT(dst != nullptr);
  4970. if (is_type_untyped_nil(src)) {
  4971. return lb_const_nil(m, t);
  4972. }
  4973. if (is_type_untyped_undef(src)) {
  4974. return lb_const_undef(m, t);
  4975. }
  4976. if (LLVMIsConstant(value.value)) {
  4977. if (is_type_any(dst)) {
  4978. Type *st = default_type(src_type);
  4979. lbAddr default_value = lb_add_local_generated(p, st, false);
  4980. lb_addr_store(p, default_value, value);
  4981. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  4982. lbValue id = lb_typeid(m, st);
  4983. lbAddr res = lb_add_local_generated(p, t, false);
  4984. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  4985. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  4986. lb_emit_store(p, a0, data);
  4987. lb_emit_store(p, a1, id);
  4988. return lb_addr_load(p, res);
  4989. } else if (dst->kind == Type_Basic) {
  4990. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  4991. String str = lb_get_const_string(m, value);
  4992. lbValue res = {};
  4993. res.type = t;
  4994. res.value = llvm_cstring(m, str);
  4995. return res;
  4996. }
  4997. // if (is_type_float(dst)) {
  4998. // return value;
  4999. // } else if (is_type_integer(dst)) {
  5000. // return value;
  5001. // }
  5002. // ExactValue ev = value->Constant.value;
  5003. // if (is_type_float(dst)) {
  5004. // ev = exact_value_to_float(ev);
  5005. // } else if (is_type_complex(dst)) {
  5006. // ev = exact_value_to_complex(ev);
  5007. // } else if (is_type_quaternion(dst)) {
  5008. // ev = exact_value_to_quaternion(ev);
  5009. // } else if (is_type_string(dst)) {
  5010. // // Handled elsewhere
  5011. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5012. // } else if (is_type_integer(dst)) {
  5013. // ev = exact_value_to_integer(ev);
  5014. // } else if (is_type_pointer(dst)) {
  5015. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5016. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5017. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5018. // }
  5019. // return lb_const_value(p->module, t, ev);
  5020. }
  5021. }
  5022. if (are_types_identical(src, dst)) {
  5023. if (!are_types_identical(src_type, t)) {
  5024. return lb_emit_transmute(p, value, t);
  5025. }
  5026. return value;
  5027. }
  5028. // bool <-> llvm bool
  5029. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5030. lbValue res = {};
  5031. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5032. res.type = dst;
  5033. return res;
  5034. }
  5035. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5036. lbValue res = {};
  5037. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5038. res.type = dst;
  5039. return res;
  5040. }
  5041. // integer -> integer
  5042. if (is_type_integer(src) && is_type_integer(dst)) {
  5043. GB_ASSERT(src->kind == Type_Basic &&
  5044. dst->kind == Type_Basic);
  5045. i64 sz = type_size_of(default_type(src));
  5046. i64 dz = type_size_of(default_type(dst));
  5047. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5048. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5049. value = lb_emit_byte_swap(p, value, platform_src_type);
  5050. }
  5051. LLVMOpcode op = LLVMTrunc;
  5052. if (dz < sz) {
  5053. op = LLVMTrunc;
  5054. } else if (dz == sz) {
  5055. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5056. // NOTE(bill): Copy the value just for type correctness
  5057. op = LLVMBitCast;
  5058. } else if (dz > sz) {
  5059. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5060. }
  5061. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5062. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5063. lbValue res = {};
  5064. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5065. res.type = t;
  5066. return lb_emit_byte_swap(p, res, t);
  5067. } else {
  5068. lbValue res = {};
  5069. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5070. res.type = t;
  5071. return res;
  5072. }
  5073. }
  5074. // boolean -> boolean/integer
  5075. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5076. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5077. lbValue res = {};
  5078. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5079. res.type = t;
  5080. return res;
  5081. }
  5082. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5083. return lb_emit_transmute(p, value, dst);
  5084. }
  5085. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5086. return lb_emit_transmute(p, value, dst);
  5087. }
  5088. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5089. return lb_emit_transmute(p, value, dst);
  5090. }
  5091. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5092. return lb_emit_transmute(p, value, dst);
  5093. }
  5094. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5095. lbValue c = lb_emit_conv(p, value, t_cstring);
  5096. auto args = array_make<lbValue>(heap_allocator(), 1);
  5097. args[0] = c;
  5098. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5099. return lb_emit_conv(p, s, dst);
  5100. }
  5101. // integer -> boolean
  5102. if (is_type_integer(src) && is_type_boolean(dst)) {
  5103. lbValue res = {};
  5104. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5105. res.type = t_llvm_bool;
  5106. return lb_emit_conv(p, res, t);
  5107. }
  5108. // float -> float
  5109. if (is_type_float(src) && is_type_float(dst)) {
  5110. gbAllocator a = heap_allocator();
  5111. i64 sz = type_size_of(src);
  5112. i64 dz = type_size_of(dst);
  5113. if (dz == sz) {
  5114. if (types_have_same_internal_endian(src, dst)) {
  5115. lbValue res = {};
  5116. res.type = t;
  5117. res.value = value.value;
  5118. return res;
  5119. } else {
  5120. return lb_emit_byte_swap(p, value, t);
  5121. }
  5122. }
  5123. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5124. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5125. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5126. lbValue res = {};
  5127. res = lb_emit_conv(p, value, platform_src_type);
  5128. res = lb_emit_conv(p, res, platform_dst_type);
  5129. if (is_type_different_to_arch_endianness(dst)) {
  5130. res = lb_emit_byte_swap(p, res, t);
  5131. }
  5132. return lb_emit_conv(p, res, t);
  5133. }
  5134. lbValue res = {};
  5135. res.type = t;
  5136. if (dz >= sz) {
  5137. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  5138. } else {
  5139. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  5140. }
  5141. return res;
  5142. }
  5143. if (is_type_complex(src) && is_type_complex(dst)) {
  5144. Type *ft = base_complex_elem_type(dst);
  5145. lbAddr gen = lb_add_local_generated(p, dst, false);
  5146. lbValue gp = lb_addr_get_ptr(p, gen);
  5147. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5148. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5149. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5150. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  5151. return lb_addr_load(p, gen);
  5152. }
  5153. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5154. // @QuaternionLayout
  5155. Type *ft = base_complex_elem_type(dst);
  5156. lbAddr gen = lb_add_local_generated(p, dst, false);
  5157. lbValue gp = lb_addr_get_ptr(p, gen);
  5158. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5159. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5160. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  5161. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  5162. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  5163. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  5164. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  5165. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  5166. return lb_addr_load(p, gen);
  5167. }
  5168. if (is_type_float(src) && is_type_complex(dst)) {
  5169. Type *ft = base_complex_elem_type(dst);
  5170. lbAddr gen = lb_add_local_generated(p, dst, true);
  5171. lbValue gp = lb_addr_get_ptr(p, gen);
  5172. lbValue real = lb_emit_conv(p, value, ft);
  5173. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5174. return lb_addr_load(p, gen);
  5175. }
  5176. if (is_type_float(src) && is_type_quaternion(dst)) {
  5177. Type *ft = base_complex_elem_type(dst);
  5178. lbAddr gen = lb_add_local_generated(p, dst, true);
  5179. lbValue gp = lb_addr_get_ptr(p, gen);
  5180. lbValue real = lb_emit_conv(p, value, ft);
  5181. // @QuaternionLayout
  5182. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5183. return lb_addr_load(p, gen);
  5184. }
  5185. if (is_type_complex(src) && is_type_quaternion(dst)) {
  5186. Type *ft = base_complex_elem_type(dst);
  5187. lbAddr gen = lb_add_local_generated(p, dst, true);
  5188. lbValue gp = lb_addr_get_ptr(p, gen);
  5189. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5190. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5191. // @QuaternionLayout
  5192. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5193. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  5194. return lb_addr_load(p, gen);
  5195. }
  5196. // float <-> integer
  5197. if (is_type_float(src) && is_type_integer(dst)) {
  5198. lbValue res = {};
  5199. res.type = t;
  5200. if (is_type_unsigned(dst)) {
  5201. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  5202. } else {
  5203. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  5204. }
  5205. return res;
  5206. }
  5207. if (is_type_integer(src) && is_type_float(dst)) {
  5208. lbValue res = {};
  5209. res.type = t;
  5210. if (is_type_unsigned(src)) {
  5211. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  5212. } else {
  5213. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  5214. }
  5215. return res;
  5216. }
  5217. // Pointer <-> uintptr
  5218. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5219. lbValue res = {};
  5220. res.type = t;
  5221. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5222. return res;
  5223. }
  5224. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5225. lbValue res = {};
  5226. res.type = t;
  5227. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5228. return res;
  5229. }
  5230. #if 1
  5231. if (is_type_union(dst)) {
  5232. for_array(i, dst->Union.variants) {
  5233. Type *vt = dst->Union.variants[i];
  5234. if (are_types_identical(vt, src_type)) {
  5235. lbAddr parent = lb_add_local_generated(p, t, true);
  5236. lb_emit_store_union_variant(p, parent.addr, value, vt);
  5237. return lb_addr_load(p, parent);
  5238. }
  5239. }
  5240. }
  5241. #endif
  5242. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  5243. // subtype polymorphism casting
  5244. if (check_is_assignable_to_using_subtype(src_type, t)) {
  5245. Type *st = type_deref(src_type);
  5246. Type *pst = st;
  5247. st = type_deref(st);
  5248. bool st_is_ptr = is_type_pointer(src_type);
  5249. st = base_type(st);
  5250. Type *dt = t;
  5251. bool dt_is_ptr = type_deref(dt) != dt;
  5252. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  5253. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  5254. if (field_name.len > 0) {
  5255. // NOTE(bill): It can be casted
  5256. Selection sel = lookup_field(st, field_name, false, true);
  5257. if (sel.entity != nullptr) {
  5258. if (st_is_ptr) {
  5259. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  5260. Type *rt = res.type;
  5261. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5262. res = lb_emit_load(p, res);
  5263. }
  5264. return res;
  5265. } else {
  5266. if (is_type_pointer(value.type)) {
  5267. Type *rt = value.type;
  5268. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5269. value = lb_emit_load(p, value);
  5270. } else {
  5271. value = lb_emit_deep_field_gep(p, value, sel);
  5272. return lb_emit_load(p, value);
  5273. }
  5274. }
  5275. return lb_emit_deep_field_ev(p, value, sel);
  5276. }
  5277. } else {
  5278. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  5279. }
  5280. }
  5281. }
  5282. // Pointer <-> Pointer
  5283. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5284. lbValue res = {};
  5285. res.type = t;
  5286. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5287. return res;
  5288. }
  5289. // proc <-> proc
  5290. if (is_type_proc(src) && is_type_proc(dst)) {
  5291. lbValue res = {};
  5292. res.type = t;
  5293. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5294. return res;
  5295. }
  5296. // pointer -> proc
  5297. if (is_type_pointer(src) && is_type_proc(dst)) {
  5298. lbValue res = {};
  5299. res.type = t;
  5300. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5301. return res;
  5302. }
  5303. // proc -> pointer
  5304. if (is_type_proc(src) && is_type_pointer(dst)) {
  5305. lbValue res = {};
  5306. res.type = t;
  5307. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5308. return res;
  5309. }
  5310. // []byte/[]u8 <-> string
  5311. if (is_type_u8_slice(src) && is_type_string(dst)) {
  5312. return lb_emit_transmute(p, value, t);
  5313. }
  5314. if (is_type_string(src) && is_type_u8_slice(dst)) {
  5315. return lb_emit_transmute(p, value, t);
  5316. }
  5317. if (is_type_array(dst)) {
  5318. Type *elem = dst->Array.elem;
  5319. lbValue e = lb_emit_conv(p, value, elem);
  5320. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5321. lbAddr v = lb_add_local_generated(p, t, false);
  5322. isize index_count = cast(isize)dst->Array.count;
  5323. for (isize i = 0; i < index_count; i++) {
  5324. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  5325. lb_emit_store(p, elem, e);
  5326. }
  5327. return lb_addr_load(p, v);
  5328. }
  5329. if (is_type_any(dst)) {
  5330. if (is_type_untyped_nil(src)) {
  5331. return lb_const_nil(p->module, t);
  5332. }
  5333. if (is_type_untyped_undef(src)) {
  5334. return lb_const_undef(p->module, t);
  5335. }
  5336. lbAddr result = lb_add_local_generated(p, t, true);
  5337. Type *st = default_type(src_type);
  5338. lbValue data = lb_address_from_load_or_generate_local(p, value);
  5339. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  5340. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  5341. data = lb_emit_conv(p, data, t_rawptr);
  5342. lbValue id = lb_typeid(p->module, st);
  5343. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  5344. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  5345. lb_emit_store(p, any_data, data);
  5346. lb_emit_store(p, any_id, id);
  5347. return lb_addr_load(p, result);
  5348. }
  5349. if (is_type_untyped(src)) {
  5350. if (is_type_string(src) && is_type_string(dst)) {
  5351. lbAddr result = lb_add_local_generated(p, t, false);
  5352. lb_addr_store(p, result, value);
  5353. return lb_addr_load(p, result);
  5354. }
  5355. }
  5356. gb_printf_err("%.*s\n", LIT(p->name));
  5357. gb_printf_err("lb_emit_conv: src -> dst\n");
  5358. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  5359. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  5360. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  5361. gb_printf_err("Not Identical %p != %p\n", src, dst);
  5362. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  5363. type_to_string(src_type), type_to_string(t),
  5364. LIT(p->name));
  5365. return {};
  5366. }
  5367. bool lb_is_type_aggregate(Type *t) {
  5368. t = base_type(t);
  5369. switch (t->kind) {
  5370. case Type_Basic:
  5371. switch (t->Basic.kind) {
  5372. case Basic_string:
  5373. case Basic_any:
  5374. return true;
  5375. // case Basic_complex32:
  5376. case Basic_complex64:
  5377. case Basic_complex128:
  5378. case Basic_quaternion128:
  5379. case Basic_quaternion256:
  5380. return true;
  5381. }
  5382. break;
  5383. case Type_Pointer:
  5384. return false;
  5385. case Type_Array:
  5386. case Type_Slice:
  5387. case Type_Struct:
  5388. case Type_Union:
  5389. case Type_Tuple:
  5390. case Type_DynamicArray:
  5391. case Type_Map:
  5392. case Type_BitField:
  5393. case Type_SimdVector:
  5394. return true;
  5395. case Type_Named:
  5396. return lb_is_type_aggregate(t->Named.base);
  5397. }
  5398. return false;
  5399. }
  5400. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  5401. Type *src_type = value.type;
  5402. if (are_types_identical(t, src_type)) {
  5403. return value;
  5404. }
  5405. lbValue res = {};
  5406. res.type = t;
  5407. Type *src = base_type(src_type);
  5408. Type *dst = base_type(t);
  5409. lbModule *m = p->module;
  5410. i64 sz = type_size_of(src);
  5411. i64 dz = type_size_of(dst);
  5412. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  5413. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  5414. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5415. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5416. return res;
  5417. }
  5418. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5419. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5420. return res;
  5421. }
  5422. if (is_type_uintptr(src) && is_type_proc(dst)) {
  5423. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5424. return res;
  5425. }
  5426. if (is_type_proc(src) && is_type_uintptr(dst)) {
  5427. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5428. return res;
  5429. }
  5430. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  5431. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5432. return res;
  5433. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  5434. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5435. return res;
  5436. }
  5437. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5438. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  5439. return res;
  5440. }
  5441. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  5442. lbValue s = lb_address_from_load_or_generate_local(p, value);
  5443. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  5444. return lb_emit_load(p, d);
  5445. }
  5446. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  5447. // GB_PANIC("lb_emit_transmute");
  5448. return res;
  5449. }
  5450. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  5451. GB_ASSERT(addr.kind == lbAddr_Context);
  5452. GB_ASSERT(addr.ctx.sel.index.count == 0);
  5453. lbModule *m = p->module;
  5454. gbAllocator a = heap_allocator();
  5455. auto args = array_make<lbValue>(a, 1);
  5456. args[0] = addr.addr;
  5457. lb_emit_runtime_call(p, "__init_context", args);
  5458. }
  5459. void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  5460. ctx.kind = lbAddr_Context;
  5461. lbContextData cd = {ctx, p->scope_index};
  5462. array_add(&p->context_stack, cd);
  5463. }
  5464. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  5465. if (p->context_stack.count > 0) {
  5466. return p->context_stack[p->context_stack.count-1].ctx;
  5467. }
  5468. Type *pt = base_type(p->type);
  5469. GB_ASSERT(pt->kind == Type_Proc);
  5470. {
  5471. lbAddr c = lb_add_local_generated(p, t_context, false);
  5472. c.kind = lbAddr_Context;
  5473. lb_emit_init_context(p, c);
  5474. lb_push_context_onto_stack(p, c);
  5475. return c;
  5476. }
  5477. }
  5478. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  5479. if (LLVMIsALoadInst(value.value)) {
  5480. lbValue res = {};
  5481. res.value = LLVMGetOperand(value.value, 0);
  5482. res.type = alloc_type_pointer(value.type);
  5483. return res;
  5484. }
  5485. GB_ASSERT(is_type_typed(value.type));
  5486. lbAddr res = lb_add_local_generated(p, value.type, false);
  5487. lb_addr_store(p, res, value);
  5488. return res.addr;
  5489. }
  5490. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  5491. if (LLVMIsALoadInst(value.value)) {
  5492. lbValue res = {};
  5493. res.value = LLVMGetOperand(value.value, 0);
  5494. res.type = alloc_type_pointer(value.type);
  5495. return res;
  5496. }
  5497. GB_PANIC("lb_address_from_load");
  5498. return {};
  5499. }
  5500. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  5501. i64 type_alignment = type_align_of(new_type);
  5502. if (alignment < type_alignment) {
  5503. alignment = type_alignment;
  5504. }
  5505. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  5506. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  5507. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  5508. lb_addr_store(p, ptr, val);
  5509. ptr.kind = lbAddr_Context;
  5510. return ptr.addr;
  5511. }
  5512. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  5513. gbAllocator a = heap_allocator();
  5514. GB_ASSERT(is_type_pointer(s.type));
  5515. Type *t = base_type(type_deref(s.type));
  5516. Type *result_type = nullptr;
  5517. if (t->kind == Type_Opaque) {
  5518. t = t->Opaque.elem;
  5519. }
  5520. if (is_type_relative_pointer(t)) {
  5521. s = lb_addr_get_ptr(p, lb_addr(s));
  5522. }
  5523. if (is_type_struct(t)) {
  5524. result_type = get_struct_field_type(t, index);
  5525. } else if (is_type_union(t)) {
  5526. GB_ASSERT(index == -1);
  5527. return lb_emit_union_tag_ptr(p, s);
  5528. } else if (is_type_tuple(t)) {
  5529. GB_ASSERT(t->Tuple.variables.count > 0);
  5530. result_type = t->Tuple.variables[index]->type;
  5531. } else if (is_type_complex(t)) {
  5532. Type *ft = base_complex_elem_type(t);
  5533. switch (index) {
  5534. case 0: result_type = ft; break;
  5535. case 1: result_type = ft; break;
  5536. }
  5537. } else if (is_type_quaternion(t)) {
  5538. Type *ft = base_complex_elem_type(t);
  5539. switch (index) {
  5540. case 0: result_type = ft; break;
  5541. case 1: result_type = ft; break;
  5542. case 2: result_type = ft; break;
  5543. case 3: result_type = ft; break;
  5544. }
  5545. } else if (is_type_slice(t)) {
  5546. switch (index) {
  5547. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5548. case 1: result_type = t_int; break;
  5549. }
  5550. } else if (is_type_string(t)) {
  5551. switch (index) {
  5552. case 0: result_type = t_u8_ptr; break;
  5553. case 1: result_type = t_int; break;
  5554. }
  5555. } else if (is_type_any(t)) {
  5556. switch (index) {
  5557. case 0: result_type = t_rawptr; break;
  5558. case 1: result_type = t_typeid; break;
  5559. }
  5560. } else if (is_type_dynamic_array(t)) {
  5561. switch (index) {
  5562. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5563. case 1: result_type = t_int; break;
  5564. case 2: result_type = t_int; break;
  5565. case 3: result_type = t_allocator; break;
  5566. }
  5567. } else if (is_type_map(t)) {
  5568. init_map_internal_types(t);
  5569. Type *itp = alloc_type_pointer(t->Map.internal_type);
  5570. s = lb_emit_transmute(p, s, itp);
  5571. Type *gst = t->Map.internal_type;
  5572. GB_ASSERT(gst->kind == Type_Struct);
  5573. switch (index) {
  5574. case 0: result_type = get_struct_field_type(gst, 0); break;
  5575. case 1: result_type = get_struct_field_type(gst, 1); break;
  5576. }
  5577. } else if (is_type_array(t)) {
  5578. return lb_emit_array_epi(p, s, index);
  5579. } else if (is_type_relative_slice(t)) {
  5580. switch (index) {
  5581. case 0: result_type = t->RelativeSlice.base_integer; break;
  5582. case 1: result_type = t->RelativeSlice.base_integer; break;
  5583. }
  5584. } else {
  5585. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  5586. }
  5587. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  5588. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5589. index += 1;
  5590. }
  5591. if (lb_is_const(s)) {
  5592. lbModule *m = p->module;
  5593. lbValue res = {};
  5594. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  5595. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  5596. res.type = alloc_type_pointer(result_type);
  5597. return res;
  5598. } else {
  5599. lbValue res = {};
  5600. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  5601. res.type = alloc_type_pointer(result_type);
  5602. return res;
  5603. }
  5604. }
  5605. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  5606. if (LLVMIsALoadInst(s.value)) {
  5607. lbValue res = {};
  5608. res.value = LLVMGetOperand(s.value, 0);
  5609. res.type = alloc_type_pointer(s.type);
  5610. lbValue ptr = lb_emit_struct_ep(p, res, index);
  5611. return lb_emit_load(p, ptr);
  5612. }
  5613. gbAllocator a = heap_allocator();
  5614. Type *t = base_type(s.type);
  5615. Type *result_type = nullptr;
  5616. switch (t->kind) {
  5617. case Type_Basic:
  5618. switch (t->Basic.kind) {
  5619. case Basic_string:
  5620. switch (index) {
  5621. case 0: result_type = t_u8_ptr; break;
  5622. case 1: result_type = t_int; break;
  5623. }
  5624. break;
  5625. case Basic_any:
  5626. switch (index) {
  5627. case 0: result_type = t_rawptr; break;
  5628. case 1: result_type = t_typeid; break;
  5629. }
  5630. break;
  5631. case Basic_complex64: case Basic_complex128:
  5632. {
  5633. Type *ft = base_complex_elem_type(t);
  5634. switch (index) {
  5635. case 0: result_type = ft; break;
  5636. case 1: result_type = ft; break;
  5637. }
  5638. break;
  5639. }
  5640. case Basic_quaternion128: case Basic_quaternion256:
  5641. {
  5642. Type *ft = base_complex_elem_type(t);
  5643. switch (index) {
  5644. case 0: result_type = ft; break;
  5645. case 1: result_type = ft; break;
  5646. case 2: result_type = ft; break;
  5647. case 3: result_type = ft; break;
  5648. }
  5649. break;
  5650. }
  5651. }
  5652. break;
  5653. case Type_Struct:
  5654. result_type = get_struct_field_type(t, index);
  5655. break;
  5656. case Type_Union:
  5657. GB_ASSERT(index == -1);
  5658. // return lb_emit_union_tag_value(p, s);
  5659. GB_PANIC("lb_emit_union_tag_value");
  5660. case Type_Tuple:
  5661. GB_ASSERT(t->Tuple.variables.count > 0);
  5662. result_type = t->Tuple.variables[index]->type;
  5663. if (t->Tuple.variables.count == 1) {
  5664. return s;
  5665. }
  5666. break;
  5667. case Type_Slice:
  5668. switch (index) {
  5669. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5670. case 1: result_type = t_int; break;
  5671. }
  5672. break;
  5673. case Type_DynamicArray:
  5674. switch (index) {
  5675. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5676. case 1: result_type = t_int; break;
  5677. case 2: result_type = t_int; break;
  5678. case 3: result_type = t_allocator; break;
  5679. }
  5680. break;
  5681. case Type_Map:
  5682. {
  5683. init_map_internal_types(t);
  5684. Type *gst = t->Map.generated_struct_type;
  5685. switch (index) {
  5686. case 0: result_type = get_struct_field_type(gst, 0); break;
  5687. case 1: result_type = get_struct_field_type(gst, 1); break;
  5688. }
  5689. }
  5690. break;
  5691. case Type_Array:
  5692. result_type = t->Array.elem;
  5693. break;
  5694. default:
  5695. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  5696. break;
  5697. }
  5698. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  5699. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5700. index += 1;
  5701. }
  5702. lbValue res = {};
  5703. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  5704. res.type = result_type;
  5705. return res;
  5706. }
  5707. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  5708. GB_ASSERT(sel.index.count > 0);
  5709. Type *type = type_deref(e.type);
  5710. gbAllocator a = heap_allocator();
  5711. for_array(i, sel.index) {
  5712. i32 index = cast(i32)sel.index[i];
  5713. if (is_type_pointer(type)) {
  5714. type = type_deref(type);
  5715. e = lb_emit_load(p, e);
  5716. }
  5717. type = core_type(type);
  5718. if (type->kind == Type_Opaque) {
  5719. type = type->Opaque.elem;
  5720. }
  5721. if (is_type_quaternion(type)) {
  5722. e = lb_emit_struct_ep(p, e, index);
  5723. } else if (is_type_raw_union(type)) {
  5724. type = get_struct_field_type(type, index);
  5725. GB_ASSERT(is_type_pointer(e.type));
  5726. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  5727. } else if (is_type_struct(type)) {
  5728. type = get_struct_field_type(type, index);
  5729. e = lb_emit_struct_ep(p, e, index);
  5730. } else if (type->kind == Type_Union) {
  5731. GB_ASSERT(index == -1);
  5732. type = t_type_info_ptr;
  5733. e = lb_emit_struct_ep(p, e, index);
  5734. } else if (type->kind == Type_Tuple) {
  5735. type = type->Tuple.variables[index]->type;
  5736. e = lb_emit_struct_ep(p, e, index);
  5737. } else if (type->kind == Type_Basic) {
  5738. switch (type->Basic.kind) {
  5739. case Basic_any: {
  5740. if (index == 0) {
  5741. type = t_rawptr;
  5742. } else if (index == 1) {
  5743. type = t_type_info_ptr;
  5744. }
  5745. e = lb_emit_struct_ep(p, e, index);
  5746. break;
  5747. }
  5748. case Basic_string:
  5749. e = lb_emit_struct_ep(p, e, index);
  5750. break;
  5751. default:
  5752. GB_PANIC("un-gep-able type %s", type_to_string(type));
  5753. break;
  5754. }
  5755. } else if (type->kind == Type_Slice) {
  5756. e = lb_emit_struct_ep(p, e, index);
  5757. } else if (type->kind == Type_DynamicArray) {
  5758. e = lb_emit_struct_ep(p, e, index);
  5759. } else if (type->kind == Type_Array) {
  5760. e = lb_emit_array_epi(p, e, index);
  5761. } else if (type->kind == Type_Map) {
  5762. e = lb_emit_struct_ep(p, e, index);
  5763. } else if (type->kind == Type_RelativePointer) {
  5764. e = lb_emit_struct_ep(p, e, index);
  5765. } else {
  5766. GB_PANIC("un-gep-able type %s", type_to_string(type));
  5767. }
  5768. }
  5769. return e;
  5770. }
  5771. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  5772. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  5773. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  5774. return lb_emit_load(p, res);
  5775. }
  5776. void lb_build_defer_stmt(lbProcedure *p, lbDefer d) {
  5777. // NOTE(bill): The prev block may defer injection before it's terminator
  5778. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  5779. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  5780. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  5781. return;
  5782. }
  5783. isize prev_context_stack_count = p->context_stack.count;
  5784. defer (p->context_stack.count = prev_context_stack_count);
  5785. p->context_stack.count = d.context_stack_count;
  5786. lbBlock *b = lb_create_block(p, "defer");
  5787. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  5788. lb_emit_jump(p, b);
  5789. }
  5790. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  5791. lb_emit_jump(p, b);
  5792. }
  5793. lb_start_block(p, b);
  5794. if (d.kind == lbDefer_Node) {
  5795. lb_build_stmt(p, d.stmt);
  5796. } else if (d.kind == lbDefer_Instr) {
  5797. // NOTE(bill): Need to make a new copy
  5798. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  5799. LLVMInsertIntoBuilder(p->builder, instr);
  5800. } else if (d.kind == lbDefer_Proc) {
  5801. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  5802. }
  5803. }
  5804. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  5805. isize count = p->defer_stmts.count;
  5806. isize i = count;
  5807. while (i --> 0) {
  5808. lbDefer d = p->defer_stmts[i];
  5809. isize prev_context_stack_count = p->context_stack.count;
  5810. defer (p->context_stack.count = prev_context_stack_count);
  5811. p->context_stack.count = d.context_stack_count;
  5812. if (kind == lbDeferExit_Default) {
  5813. if (p->scope_index == d.scope_index &&
  5814. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  5815. lb_build_defer_stmt(p, d);
  5816. array_pop(&p->defer_stmts);
  5817. continue;
  5818. } else {
  5819. break;
  5820. }
  5821. } else if (kind == lbDeferExit_Return) {
  5822. lb_build_defer_stmt(p, d);
  5823. } else if (kind == lbDeferExit_Branch) {
  5824. GB_ASSERT(block != nullptr);
  5825. isize lower_limit = block->scope_index;
  5826. if (lower_limit < d.scope_index) {
  5827. lb_build_defer_stmt(p, d);
  5828. }
  5829. }
  5830. }
  5831. }
  5832. lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  5833. lbDefer d = {lbDefer_Node};
  5834. d.scope_index = scope_index;
  5835. d.context_stack_count = p->context_stack.count;
  5836. d.block = p->curr_block;
  5837. d.stmt = stmt;
  5838. array_add(&p->defer_stmts, d);
  5839. return d;
  5840. }
  5841. lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  5842. lbDefer d = {lbDefer_Proc};
  5843. d.scope_index = p->scope_index;
  5844. d.block = p->curr_block;
  5845. d.proc.deferred = deferred;
  5846. d.proc.result_as_args = result_as_args;
  5847. array_add(&p->defer_stmts, d);
  5848. return d;
  5849. }
  5850. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  5851. Array<lbValue> array = {};
  5852. Type *t = base_type(value.type);
  5853. if (t == nullptr) {
  5854. // Do nothing
  5855. } else if (is_type_tuple(t)) {
  5856. GB_ASSERT(t->kind == Type_Tuple);
  5857. auto *rt = &t->Tuple;
  5858. if (rt->variables.count > 0) {
  5859. array = array_make<lbValue>(heap_allocator(), rt->variables.count);
  5860. for_array(i, rt->variables) {
  5861. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  5862. array[i] = elem;
  5863. }
  5864. }
  5865. } else {
  5866. array = array_make<lbValue>(heap_allocator(), 1);
  5867. array[0] = value;
  5868. }
  5869. return array;
  5870. }
  5871. 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) {
  5872. unsigned arg_count = cast(unsigned)processed_args.count;
  5873. if (return_ptr.value != nullptr) {
  5874. arg_count += 1;
  5875. }
  5876. if (context_ptr.addr.value != nullptr) {
  5877. arg_count += 1;
  5878. }
  5879. LLVMValueRef *args = gb_alloc_array(heap_allocator(), LLVMValueRef, arg_count);
  5880. isize arg_index = 0;
  5881. if (return_ptr.value != nullptr) {
  5882. args[arg_index++] = return_ptr.value;
  5883. }
  5884. for_array(i, processed_args) {
  5885. lbValue arg = processed_args[i];
  5886. args[arg_index++] = arg.value;
  5887. }
  5888. if (context_ptr.addr.value != nullptr) {
  5889. args[arg_index++] = context_ptr.addr.value;
  5890. }
  5891. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  5892. GB_ASSERT(curr_block != p->decl_block->block);
  5893. LLVMValueRef ret = LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(p->module, value.type)), value.value, args, arg_count, "");;
  5894. lbValue res = {};
  5895. res.value = ret;
  5896. res.type = abi_rt;
  5897. return res;
  5898. }
  5899. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  5900. String name = make_string_c(c_name);
  5901. AstPackage *pkg = p->module->info->runtime_package;
  5902. Entity *e = scope_lookup_current(pkg->scope, name);
  5903. lbValue *found = nullptr;
  5904. if (p->module != e->code_gen_module) {
  5905. gb_mutex_lock(&p->module->mutex);
  5906. }
  5907. found = map_get(&e->code_gen_module->values, hash_entity(e));
  5908. if (p->module != e->code_gen_module) {
  5909. gb_mutex_unlock(&p->module->mutex);
  5910. }
  5911. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  5912. return lb_emit_call(p, *found, args);
  5913. }
  5914. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  5915. lbModule *m = p->module;
  5916. Type *pt = base_type(value.type);
  5917. GB_ASSERT(pt->kind == Type_Proc);
  5918. Type *results = pt->Proc.results;
  5919. if (p->entity != nullptr) {
  5920. if (p->entity->flags & EntityFlag_Disabled) {
  5921. return {};
  5922. }
  5923. }
  5924. lbAddr context_ptr = {};
  5925. if (pt->Proc.calling_convention == ProcCC_Odin) {
  5926. context_ptr = lb_find_or_generate_context_ptr(p);
  5927. }
  5928. defer (if (pt->Proc.diverging) {
  5929. LLVMBuildUnreachable(p->builder);
  5930. });
  5931. set_procedure_abi_types(heap_allocator(), pt);
  5932. bool is_c_vararg = pt->Proc.c_vararg;
  5933. isize param_count = pt->Proc.param_count;
  5934. if (is_c_vararg) {
  5935. GB_ASSERT(param_count-1 <= args.count);
  5936. param_count -= 1;
  5937. } else {
  5938. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  5939. }
  5940. auto processed_args = array_make<lbValue>(heap_allocator(), 0, args.count);
  5941. for (isize i = 0; i < param_count; i++) {
  5942. Entity *e = pt->Proc.params->Tuple.variables[i];
  5943. if (e->kind != Entity_Variable) {
  5944. // array_add(&processed_args, args[i]);
  5945. continue;
  5946. }
  5947. GB_ASSERT(e->flags & EntityFlag_Param);
  5948. Type *original_type = e->type;
  5949. Type *new_type = pt->Proc.abi_compat_params[i];
  5950. Type *arg_type = args[i].type;
  5951. if (are_types_identical(arg_type, new_type)) {
  5952. // NOTE(bill): Done
  5953. array_add(&processed_args, args[i]);
  5954. } else if (!are_types_identical(original_type, new_type)) {
  5955. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  5956. Type *av = core_type(type_deref(new_type));
  5957. if (are_types_identical(av, core_type(original_type))) {
  5958. if (e->flags&EntityFlag_ImplicitReference) {
  5959. array_add(&processed_args, lb_address_from_load_or_generate_local(p, args[i]));
  5960. } else if (!is_type_pointer(arg_type)) {
  5961. array_add(&processed_args, lb_copy_value_to_ptr(p, args[i], original_type, 16));
  5962. }
  5963. } else {
  5964. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  5965. }
  5966. } else if (new_type == t_llvm_bool) {
  5967. array_add(&processed_args, lb_emit_conv(p, args[i], new_type));
  5968. } else if (is_type_integer(new_type) || is_type_float(new_type) || is_type_boolean(new_type)) {
  5969. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  5970. } else if (is_type_simd_vector(new_type)) {
  5971. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  5972. } else if (is_type_tuple(new_type)) {
  5973. Type *abi_type = pt->Proc.abi_compat_params[i];
  5974. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  5975. lbValue x = {};
  5976. i64 st_sz = type_size_of(st);
  5977. i64 arg_sz = type_size_of(args[i].type);
  5978. if (st_sz == arg_sz) {
  5979. x = lb_emit_transmute(p, args[i], st);
  5980. } else {
  5981. // NOTE(bill): struct{f32, f32, f32} != struct{#simd[2]f32, f32}
  5982. GB_ASSERT(st_sz > arg_sz);
  5983. lbAddr xx = lb_add_local_generated(p, st, false);
  5984. lbValue pp = lb_emit_conv(p, xx.addr, alloc_type_pointer(args[i].type));
  5985. lb_emit_store(p, pp, args[i]);
  5986. x = lb_addr_load(p, xx);
  5987. }
  5988. for (isize j = 0; j < new_type->Tuple.variables.count; j++) {
  5989. lbValue xx = lb_emit_struct_ev(p, x, cast(i32)j);
  5990. array_add(&processed_args, xx);
  5991. }
  5992. }
  5993. } else {
  5994. lbValue x = lb_emit_conv(p, args[i], new_type);
  5995. array_add(&processed_args, x);
  5996. }
  5997. }
  5998. if (inlining == ProcInlining_none) {
  5999. inlining = p->inlining;
  6000. }
  6001. lbValue result = {};
  6002. Type *abi_rt = reduce_tuple_to_single_type(pt->Proc.abi_compat_result_type);
  6003. Type *rt = reduce_tuple_to_single_type(results);
  6004. if (pt->Proc.return_by_pointer) {
  6005. lbValue return_ptr = {};
  6006. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6007. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6008. return_ptr = p->return_ptr_hint_value;
  6009. p->return_ptr_hint_used = true;
  6010. }
  6011. }
  6012. if (return_ptr.value == nullptr) {
  6013. lbAddr r = lb_add_local_generated(p, rt, true);
  6014. return_ptr = r.addr;
  6015. }
  6016. GB_ASSERT(is_type_pointer(return_ptr.type));
  6017. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6018. result = lb_emit_load(p, return_ptr);
  6019. } else {
  6020. result = lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining);
  6021. if (abi_rt != rt) {
  6022. result = lb_emit_transmute(p, result, rt);
  6023. }
  6024. }
  6025. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  6026. if (found != nullptr) {
  6027. Entity *e = *found;
  6028. if (e != nullptr && entity_has_deferred_procedure(e)) {
  6029. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  6030. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  6031. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  6032. GB_ASSERT(deferred_found != nullptr);
  6033. lbValue deferred = *deferred_found;
  6034. auto in_args = args;
  6035. Array<lbValue> result_as_args = {};
  6036. switch (kind) {
  6037. case DeferredProcedure_none:
  6038. break;
  6039. case DeferredProcedure_in:
  6040. result_as_args = in_args;
  6041. break;
  6042. case DeferredProcedure_out:
  6043. result_as_args = lb_value_to_array(p, result);
  6044. break;
  6045. case DeferredProcedure_in_out:
  6046. {
  6047. auto out_args = lb_value_to_array(p, result);
  6048. array_init(&result_as_args, heap_allocator(), in_args.count + out_args.count);
  6049. array_copy(&result_as_args, in_args, 0);
  6050. array_copy(&result_as_args, out_args, in_args.count);
  6051. }
  6052. break;
  6053. }
  6054. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  6055. }
  6056. }
  6057. return result;
  6058. }
  6059. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  6060. Type *t = s.type;
  6061. GB_ASSERT(is_type_pointer(t));
  6062. Type *st = base_type(type_deref(t));
  6063. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6064. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  6065. LLVMValueRef indices[2] = {};
  6066. indices[0] = llvm_zero(p->module);
  6067. indices[1] = lb_emit_conv(p, index, t_int).value;
  6068. Type *ptr = base_array_type(st);
  6069. lbValue res = {};
  6070. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  6071. res.type = alloc_type_pointer(ptr);
  6072. return res;
  6073. }
  6074. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  6075. Type *t = s.type;
  6076. GB_ASSERT(is_type_pointer(t));
  6077. Type *st = base_type(type_deref(t));
  6078. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6079. GB_ASSERT(0 <= index);
  6080. Type *ptr = base_array_type(st);
  6081. LLVMValueRef indices[2] = {
  6082. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  6083. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  6084. };
  6085. lbValue res = {};
  6086. if (lb_is_const(s)) {
  6087. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6088. } else {
  6089. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  6090. }
  6091. res.type = alloc_type_pointer(ptr);
  6092. return res;
  6093. }
  6094. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  6095. LLVMValueRef indices[1] = {index.value};
  6096. lbValue res = {};
  6097. res.type = ptr.type;
  6098. if (lb_is_const(ptr) && lb_is_const(index)) {
  6099. res.value = LLVMConstGEP(ptr.value, indices, 1);
  6100. } else {
  6101. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  6102. }
  6103. return res;
  6104. }
  6105. LLVMValueRef llvm_const_slice(lbValue data, lbValue len) {
  6106. GB_ASSERT(is_type_pointer(data.type));
  6107. GB_ASSERT(are_types_identical(len.type, t_int));
  6108. LLVMValueRef vals[2] = {
  6109. data.value,
  6110. len.value,
  6111. };
  6112. return LLVMConstStruct(vals, gb_count_of(vals), false);
  6113. }
  6114. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  6115. Type *t = lb_addr_type(slice);
  6116. GB_ASSERT(is_type_slice(t));
  6117. lbValue ptr = lb_addr_get_ptr(p, slice);
  6118. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6119. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6120. }
  6121. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  6122. Type *t = lb_addr_type(string);
  6123. GB_ASSERT(is_type_string(t));
  6124. lbValue ptr = lb_addr_get_ptr(p, string);
  6125. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6126. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6127. }
  6128. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  6129. Type *t = base_type(string.type);
  6130. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  6131. return lb_emit_struct_ev(p, string, 0);
  6132. }
  6133. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  6134. Type *t = base_type(string.type);
  6135. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  6136. return lb_emit_struct_ev(p, string, 1);
  6137. }
  6138. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  6139. GB_ASSERT(is_type_cstring(value.type));
  6140. auto args = array_make<lbValue>(heap_allocator(), 1);
  6141. args[0] = lb_emit_conv(p, value, t_cstring);
  6142. return lb_emit_runtime_call(p, "cstring_len", args);
  6143. }
  6144. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  6145. Type *t = type_deref(array_ptr.type);
  6146. GB_ASSERT(is_type_array(t));
  6147. return lb_emit_struct_ep(p, array_ptr, 0);
  6148. }
  6149. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  6150. GB_ASSERT(is_type_slice(slice.type));
  6151. return lb_emit_struct_ev(p, slice, 0);
  6152. }
  6153. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  6154. GB_ASSERT(is_type_slice(slice.type));
  6155. return lb_emit_struct_ev(p, slice, 1);
  6156. }
  6157. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  6158. GB_ASSERT(is_type_dynamic_array(da.type));
  6159. return lb_emit_struct_ev(p, da, 0);
  6160. }
  6161. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  6162. GB_ASSERT(is_type_dynamic_array(da.type));
  6163. return lb_emit_struct_ev(p, da, 1);
  6164. }
  6165. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  6166. GB_ASSERT(is_type_dynamic_array(da.type));
  6167. return lb_emit_struct_ev(p, da, 2);
  6168. }
  6169. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  6170. GB_ASSERT(is_type_dynamic_array(da.type));
  6171. return lb_emit_struct_ev(p, da, 3);
  6172. }
  6173. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  6174. gbAllocator a = heap_allocator();
  6175. Type *t = base_type(value.type);
  6176. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6177. init_map_internal_types(t);
  6178. Type *gst = t->Map.generated_struct_type;
  6179. i32 index = 1;
  6180. lbValue entries = lb_emit_struct_ev(p, value, index);
  6181. return entries;
  6182. }
  6183. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  6184. gbAllocator a = heap_allocator();
  6185. Type *t = base_type(type_deref(value.type));
  6186. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6187. init_map_internal_types(t);
  6188. Type *gst = t->Map.generated_struct_type;
  6189. i32 index = 1;
  6190. lbValue entries = lb_emit_struct_ep(p, value, index);
  6191. return entries;
  6192. }
  6193. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  6194. lbValue entries = lb_map_entries(p, value);
  6195. return lb_dynamic_array_len(p, entries);
  6196. }
  6197. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  6198. lbValue entries = lb_map_entries(p, value);
  6199. return lb_dynamic_array_cap(p, entries);
  6200. }
  6201. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  6202. Type *t = base_type(value.type);
  6203. bool is_ptr = false;
  6204. if (is_type_pointer(t)) {
  6205. is_ptr = true;
  6206. t = base_type(type_deref(t));
  6207. }
  6208. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6209. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6210. }
  6211. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  6212. t->Struct.soa_kind == StructSoa_Dynamic);
  6213. isize n = 0;
  6214. Type *elem = base_type(t->Struct.soa_elem);
  6215. if (elem->kind == Type_Struct) {
  6216. n = elem->Struct.fields.count;
  6217. } else if (elem->kind == Type_Array) {
  6218. n = elem->Array.count;
  6219. } else {
  6220. GB_PANIC("Unreachable");
  6221. }
  6222. if (is_ptr) {
  6223. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6224. return lb_emit_load(p, v);
  6225. }
  6226. return lb_emit_struct_ev(p, value, cast(i32)n);
  6227. }
  6228. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  6229. Type *t = base_type(value.type);
  6230. bool is_ptr = false;
  6231. if (is_type_pointer(t)) {
  6232. is_ptr = true;
  6233. t = base_type(type_deref(t));
  6234. }
  6235. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6236. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6237. }
  6238. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  6239. isize n = 0;
  6240. Type *elem = base_type(t->Struct.soa_elem);
  6241. if (elem->kind == Type_Struct) {
  6242. n = elem->Struct.fields.count+1;
  6243. } else if (elem->kind == Type_Array) {
  6244. n = elem->Array.count+1;
  6245. } else {
  6246. GB_PANIC("Unreachable");
  6247. }
  6248. if (is_ptr) {
  6249. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6250. return lb_emit_load(p, v);
  6251. }
  6252. return lb_emit_struct_ev(p, value, cast(i32)n);
  6253. }
  6254. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  6255. ast_node(ce, CallExpr, expr);
  6256. switch (id) {
  6257. case BuiltinProc_DIRECTIVE: {
  6258. ast_node(bd, BasicDirective, ce->proc);
  6259. String name = bd->name;
  6260. GB_ASSERT(name == "location");
  6261. String procedure = p->entity->token.string;
  6262. TokenPos pos = ast_token(ce->proc).pos;
  6263. if (ce->args.count > 0) {
  6264. Ast *ident = unselector_expr(ce->args[0]);
  6265. GB_ASSERT(ident->kind == Ast_Ident);
  6266. Entity *e = entity_of_node(ident);
  6267. GB_ASSERT(e != nullptr);
  6268. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  6269. procedure = e->parent_proc_decl->entity->token.string;
  6270. } else {
  6271. procedure = str_lit("");
  6272. }
  6273. pos = e->token.pos;
  6274. }
  6275. return lb_emit_source_code_location(p, procedure, pos);
  6276. }
  6277. case BuiltinProc_type_info_of: {
  6278. Ast *arg = ce->args[0];
  6279. TypeAndValue tav = type_and_value_of_expr(arg);
  6280. if (tav.mode == Addressing_Type) {
  6281. Type *t = default_type(type_of_expr(arg));
  6282. return lb_type_info(p->module, t);
  6283. }
  6284. GB_ASSERT(is_type_typeid(tav.type));
  6285. auto args = array_make<lbValue>(heap_allocator(), 1);
  6286. args[0] = lb_build_expr(p, arg);
  6287. return lb_emit_runtime_call(p, "__type_info_of", args);
  6288. }
  6289. case BuiltinProc_typeid_of: {
  6290. Ast *arg = ce->args[0];
  6291. TypeAndValue tav = type_and_value_of_expr(arg);
  6292. if (tav.mode == Addressing_Type) {
  6293. Type *t = default_type(type_of_expr(arg));
  6294. return lb_typeid(p->module, t);
  6295. }
  6296. Type *t = base_type(tav.type);
  6297. GB_ASSERT(are_types_identical(t, t_type_info_ptr));
  6298. auto args = array_make<lbValue>(heap_allocator(), 1);
  6299. args[0] = lb_emit_conv(p, lb_build_expr(p, arg), t_type_info_ptr);
  6300. return lb_emit_runtime_call(p, "__typeid_of", args);
  6301. }
  6302. case BuiltinProc_len: {
  6303. lbValue v = lb_build_expr(p, ce->args[0]);
  6304. Type *t = base_type(v.type);
  6305. if (is_type_pointer(t)) {
  6306. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6307. v = lb_emit_load(p, v);
  6308. t = type_deref(t);
  6309. }
  6310. if (is_type_cstring(t)) {
  6311. return lb_cstring_len(p, v);
  6312. } else if (is_type_string(t)) {
  6313. return lb_string_len(p, v);
  6314. } else if (is_type_array(t)) {
  6315. GB_PANIC("Array lengths are constant");
  6316. } else if (is_type_slice(t)) {
  6317. return lb_slice_len(p, v);
  6318. } else if (is_type_dynamic_array(t)) {
  6319. return lb_dynamic_array_len(p, v);
  6320. } else if (is_type_map(t)) {
  6321. return lb_map_len(p, v);
  6322. } else if (is_type_soa_struct(t)) {
  6323. return lb_soa_struct_len(p, v);
  6324. }
  6325. GB_PANIC("Unreachable");
  6326. break;
  6327. }
  6328. case BuiltinProc_cap: {
  6329. lbValue v = lb_build_expr(p, ce->args[0]);
  6330. Type *t = base_type(v.type);
  6331. if (is_type_pointer(t)) {
  6332. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6333. v = lb_emit_load(p, v);
  6334. t = type_deref(t);
  6335. }
  6336. if (is_type_string(t)) {
  6337. GB_PANIC("Unreachable");
  6338. } else if (is_type_array(t)) {
  6339. GB_PANIC("Array lengths are constant");
  6340. } else if (is_type_slice(t)) {
  6341. return lb_slice_len(p, v);
  6342. } else if (is_type_dynamic_array(t)) {
  6343. return lb_dynamic_array_cap(p, v);
  6344. } else if (is_type_map(t)) {
  6345. return lb_map_cap(p, v);
  6346. } else if (is_type_soa_struct(t)) {
  6347. return lb_soa_struct_cap(p, v);
  6348. }
  6349. GB_PANIC("Unreachable");
  6350. break;
  6351. }
  6352. case BuiltinProc_swizzle: {
  6353. isize index_count = ce->args.count-1;
  6354. if (is_type_simd_vector(tv.type)) {
  6355. lbValue vec = lb_build_expr(p, ce->args[0]);
  6356. if (index_count == 0) {
  6357. return vec;
  6358. }
  6359. unsigned mask_len = cast(unsigned)index_count;
  6360. LLVMValueRef *mask_elems = gb_alloc_array(heap_allocator(), LLVMValueRef, index_count);
  6361. for (isize i = 1; i < ce->args.count; i++) {
  6362. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6363. GB_ASSERT(is_type_integer(tv.type));
  6364. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6365. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  6366. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  6367. }
  6368. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  6369. LLVMValueRef v1 = vec.value;
  6370. LLVMValueRef v2 = vec.value;
  6371. lbValue res = {};
  6372. res.type = tv.type;
  6373. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  6374. return res;
  6375. }
  6376. lbAddr addr = lb_build_addr(p, ce->args[0]);
  6377. if (index_count == 0) {
  6378. return lb_addr_load(p, addr);
  6379. }
  6380. lbValue src = lb_addr_get_ptr(p, addr);
  6381. // TODO(bill): Should this be zeroed or not?
  6382. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  6383. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  6384. for (i32 i = 1; i < ce->args.count; i++) {
  6385. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6386. GB_ASSERT(is_type_integer(tv.type));
  6387. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6388. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  6389. i32 dst_index = i-1;
  6390. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  6391. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  6392. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  6393. }
  6394. return lb_addr_load(p, dst);
  6395. }
  6396. case BuiltinProc_complex: {
  6397. lbValue real = lb_build_expr(p, ce->args[0]);
  6398. lbValue imag = lb_build_expr(p, ce->args[1]);
  6399. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6400. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6401. Type *ft = base_complex_elem_type(tv.type);
  6402. real = lb_emit_conv(p, real, ft);
  6403. imag = lb_emit_conv(p, imag, ft);
  6404. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  6405. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  6406. return lb_emit_load(p, dst);
  6407. }
  6408. case BuiltinProc_quaternion: {
  6409. lbValue real = lb_build_expr(p, ce->args[0]);
  6410. lbValue imag = lb_build_expr(p, ce->args[1]);
  6411. lbValue jmag = lb_build_expr(p, ce->args[2]);
  6412. lbValue kmag = lb_build_expr(p, ce->args[3]);
  6413. // @QuaternionLayout
  6414. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6415. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6416. Type *ft = base_complex_elem_type(tv.type);
  6417. real = lb_emit_conv(p, real, ft);
  6418. imag = lb_emit_conv(p, imag, ft);
  6419. jmag = lb_emit_conv(p, jmag, ft);
  6420. kmag = lb_emit_conv(p, kmag, ft);
  6421. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  6422. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  6423. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  6424. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  6425. return lb_emit_load(p, dst);
  6426. }
  6427. case BuiltinProc_real: {
  6428. lbValue val = lb_build_expr(p, ce->args[0]);
  6429. if (is_type_complex(val.type)) {
  6430. lbValue real = lb_emit_struct_ev(p, val, 0);
  6431. return lb_emit_conv(p, real, tv.type);
  6432. } else if (is_type_quaternion(val.type)) {
  6433. // @QuaternionLayout
  6434. lbValue real = lb_emit_struct_ev(p, val, 3);
  6435. return lb_emit_conv(p, real, tv.type);
  6436. }
  6437. GB_PANIC("invalid type for real");
  6438. return {};
  6439. }
  6440. case BuiltinProc_imag: {
  6441. lbValue val = lb_build_expr(p, ce->args[0]);
  6442. if (is_type_complex(val.type)) {
  6443. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6444. return lb_emit_conv(p, imag, tv.type);
  6445. } else if (is_type_quaternion(val.type)) {
  6446. // @QuaternionLayout
  6447. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6448. return lb_emit_conv(p, imag, tv.type);
  6449. }
  6450. GB_PANIC("invalid type for imag");
  6451. return {};
  6452. }
  6453. case BuiltinProc_jmag: {
  6454. lbValue val = lb_build_expr(p, ce->args[0]);
  6455. if (is_type_quaternion(val.type)) {
  6456. // @QuaternionLayout
  6457. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6458. return lb_emit_conv(p, imag, tv.type);
  6459. }
  6460. GB_PANIC("invalid type for jmag");
  6461. return {};
  6462. }
  6463. case BuiltinProc_kmag: {
  6464. lbValue val = lb_build_expr(p, ce->args[0]);
  6465. if (is_type_quaternion(val.type)) {
  6466. // @QuaternionLayout
  6467. lbValue imag = lb_emit_struct_ev(p, val, 2);
  6468. return lb_emit_conv(p, imag, tv.type);
  6469. }
  6470. GB_PANIC("invalid type for kmag");
  6471. return {};
  6472. }
  6473. case BuiltinProc_conj: {
  6474. lbValue val = lb_build_expr(p, ce->args[0]);
  6475. lbValue res = {};
  6476. Type *t = val.type;
  6477. if (is_type_complex(t)) {
  6478. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6479. lbValue real = lb_emit_struct_ev(p, val, 0);
  6480. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6481. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6482. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  6483. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  6484. } else if (is_type_quaternion(t)) {
  6485. // @QuaternionLayout
  6486. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6487. lbValue real = lb_emit_struct_ev(p, val, 3);
  6488. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6489. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  6490. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  6491. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6492. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  6493. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  6494. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  6495. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  6496. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  6497. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  6498. }
  6499. return lb_emit_load(p, res);
  6500. }
  6501. case BuiltinProc_expand_to_tuple: {
  6502. lbValue val = lb_build_expr(p, ce->args[0]);
  6503. Type *t = base_type(val.type);
  6504. if (!is_type_tuple(tv.type)) {
  6505. if (t->kind == Type_Struct) {
  6506. GB_ASSERT(t->Struct.fields.count == 1);
  6507. return lb_emit_struct_ev(p, val, 0);
  6508. } else if (t->kind == Type_Array) {
  6509. GB_ASSERT(t->Array.count == 1);
  6510. return lb_emit_array_epi(p, val, 0);
  6511. } else {
  6512. GB_PANIC("Unknown type of expand_to_tuple");
  6513. }
  6514. }
  6515. GB_ASSERT(is_type_tuple(tv.type));
  6516. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6517. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6518. if (t->kind == Type_Struct) {
  6519. for_array(src_index, t->Struct.fields) {
  6520. Entity *field = t->Struct.fields[src_index];
  6521. i32 field_index = field->Variable.field_index;
  6522. lbValue f = lb_emit_struct_ev(p, val, field_index);
  6523. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  6524. lb_emit_store(p, ep, f);
  6525. }
  6526. } else if (t->kind == Type_Array) {
  6527. // TODO(bill): Clean-up this code
  6528. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  6529. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  6530. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  6531. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  6532. lb_emit_store(p, ep, f);
  6533. }
  6534. } else {
  6535. GB_PANIC("Unknown type of expand_to_tuple");
  6536. }
  6537. return lb_emit_load(p, tuple);
  6538. }
  6539. case BuiltinProc_min: {
  6540. Type *t = type_of_expr(expr);
  6541. if (ce->args.count == 2) {
  6542. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6543. } else {
  6544. lbValue x = lb_build_expr(p, ce->args[0]);
  6545. for (isize i = 1; i < ce->args.count; i++) {
  6546. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  6547. }
  6548. return x;
  6549. }
  6550. }
  6551. case BuiltinProc_max: {
  6552. Type *t = type_of_expr(expr);
  6553. if (ce->args.count == 2) {
  6554. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6555. } else {
  6556. lbValue x = lb_build_expr(p, ce->args[0]);
  6557. for (isize i = 1; i < ce->args.count; i++) {
  6558. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  6559. }
  6560. return x;
  6561. }
  6562. }
  6563. case BuiltinProc_abs: {
  6564. gbAllocator a = heap_allocator();
  6565. lbValue x = lb_build_expr(p, ce->args[0]);
  6566. Type *t = x.type;
  6567. if (is_type_unsigned(t)) {
  6568. return x;
  6569. }
  6570. if (is_type_quaternion(t)) {
  6571. i64 sz = 8*type_size_of(t);
  6572. auto args = array_make<lbValue>(heap_allocator(), 1);
  6573. args[0] = x;
  6574. switch (sz) {
  6575. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  6576. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  6577. }
  6578. GB_PANIC("Unknown complex type");
  6579. } else if (is_type_complex(t)) {
  6580. i64 sz = 8*type_size_of(t);
  6581. auto args = array_make<lbValue>(heap_allocator(), 1);
  6582. args[0] = x;
  6583. switch (sz) {
  6584. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  6585. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  6586. }
  6587. GB_PANIC("Unknown complex type");
  6588. } else if (is_type_float(t)) {
  6589. i64 sz = 8*type_size_of(t);
  6590. auto args = array_make<lbValue>(heap_allocator(), 1);
  6591. args[0] = x;
  6592. switch (sz) {
  6593. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  6594. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  6595. }
  6596. GB_PANIC("Unknown float type");
  6597. }
  6598. lbValue zero = lb_const_nil(p->module, t);
  6599. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  6600. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  6601. return lb_emit_select(p, cond, neg, x);
  6602. }
  6603. case BuiltinProc_clamp:
  6604. return lb_emit_clamp(p, type_of_expr(expr),
  6605. lb_build_expr(p, ce->args[0]),
  6606. lb_build_expr(p, ce->args[1]),
  6607. lb_build_expr(p, ce->args[2]));
  6608. // "Intrinsics"
  6609. case BuiltinProc_alloca:
  6610. {
  6611. lbValue sz = lb_build_expr(p, ce->args[0]);
  6612. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  6613. lbValue res = {};
  6614. res.type = t_u8_ptr;
  6615. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  6616. LLVMSetAlignment(res.value, cast(unsigned)al);
  6617. return res;
  6618. }
  6619. case BuiltinProc_cpu_relax:
  6620. // TODO(bill): BuiltinProc_cpu_relax
  6621. // ir_write_str_lit(f, "call void asm sideeffect \"pause\", \"\"()");
  6622. return {};
  6623. case BuiltinProc_atomic_fence:
  6624. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  6625. return {};
  6626. case BuiltinProc_atomic_fence_acq:
  6627. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  6628. return {};
  6629. case BuiltinProc_atomic_fence_rel:
  6630. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  6631. return {};
  6632. case BuiltinProc_atomic_fence_acqrel:
  6633. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  6634. return {};
  6635. case BuiltinProc_atomic_store:
  6636. case BuiltinProc_atomic_store_rel:
  6637. case BuiltinProc_atomic_store_relaxed:
  6638. case BuiltinProc_atomic_store_unordered: {
  6639. lbValue dst = lb_build_expr(p, ce->args[0]);
  6640. lbValue val = lb_build_expr(p, ce->args[1]);
  6641. val = lb_emit_conv(p, val, type_deref(dst.type));
  6642. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  6643. switch (id) {
  6644. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  6645. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  6646. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  6647. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  6648. }
  6649. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  6650. return {};
  6651. }
  6652. case BuiltinProc_atomic_load:
  6653. case BuiltinProc_atomic_load_acq:
  6654. case BuiltinProc_atomic_load_relaxed:
  6655. case BuiltinProc_atomic_load_unordered: {
  6656. lbValue dst = lb_build_expr(p, ce->args[0]);
  6657. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  6658. switch (id) {
  6659. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  6660. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  6661. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  6662. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  6663. }
  6664. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  6665. lbValue res = {};
  6666. res.value = instr;
  6667. res.type = type_deref(dst.type);
  6668. return res;
  6669. }
  6670. case BuiltinProc_atomic_add:
  6671. case BuiltinProc_atomic_add_acq:
  6672. case BuiltinProc_atomic_add_rel:
  6673. case BuiltinProc_atomic_add_acqrel:
  6674. case BuiltinProc_atomic_add_relaxed:
  6675. case BuiltinProc_atomic_sub:
  6676. case BuiltinProc_atomic_sub_acq:
  6677. case BuiltinProc_atomic_sub_rel:
  6678. case BuiltinProc_atomic_sub_acqrel:
  6679. case BuiltinProc_atomic_sub_relaxed:
  6680. case BuiltinProc_atomic_and:
  6681. case BuiltinProc_atomic_and_acq:
  6682. case BuiltinProc_atomic_and_rel:
  6683. case BuiltinProc_atomic_and_acqrel:
  6684. case BuiltinProc_atomic_and_relaxed:
  6685. case BuiltinProc_atomic_nand:
  6686. case BuiltinProc_atomic_nand_acq:
  6687. case BuiltinProc_atomic_nand_rel:
  6688. case BuiltinProc_atomic_nand_acqrel:
  6689. case BuiltinProc_atomic_nand_relaxed:
  6690. case BuiltinProc_atomic_or:
  6691. case BuiltinProc_atomic_or_acq:
  6692. case BuiltinProc_atomic_or_rel:
  6693. case BuiltinProc_atomic_or_acqrel:
  6694. case BuiltinProc_atomic_or_relaxed:
  6695. case BuiltinProc_atomic_xor:
  6696. case BuiltinProc_atomic_xor_acq:
  6697. case BuiltinProc_atomic_xor_rel:
  6698. case BuiltinProc_atomic_xor_acqrel:
  6699. case BuiltinProc_atomic_xor_relaxed:
  6700. case BuiltinProc_atomic_xchg:
  6701. case BuiltinProc_atomic_xchg_acq:
  6702. case BuiltinProc_atomic_xchg_rel:
  6703. case BuiltinProc_atomic_xchg_acqrel:
  6704. case BuiltinProc_atomic_xchg_relaxed: {
  6705. lbValue dst = lb_build_expr(p, ce->args[0]);
  6706. lbValue val = lb_build_expr(p, ce->args[1]);
  6707. val = lb_emit_conv(p, val, type_deref(dst.type));
  6708. LLVMAtomicRMWBinOp op = {};
  6709. LLVMAtomicOrdering ordering = {};
  6710. switch (id) {
  6711. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6712. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  6713. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  6714. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6715. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  6716. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6717. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  6718. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  6719. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6720. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  6721. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6722. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  6723. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  6724. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6725. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  6726. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6727. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  6728. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  6729. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6730. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  6731. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6732. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  6733. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  6734. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6735. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  6736. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6737. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  6738. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  6739. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6740. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  6741. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6742. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  6743. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  6744. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6745. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  6746. }
  6747. lbValue res = {};
  6748. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  6749. res.type = tv.type;
  6750. return res;
  6751. }
  6752. case BuiltinProc_atomic_cxchg:
  6753. case BuiltinProc_atomic_cxchg_acq:
  6754. case BuiltinProc_atomic_cxchg_rel:
  6755. case BuiltinProc_atomic_cxchg_acqrel:
  6756. case BuiltinProc_atomic_cxchg_relaxed:
  6757. case BuiltinProc_atomic_cxchg_failrelaxed:
  6758. case BuiltinProc_atomic_cxchg_failacq:
  6759. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  6760. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  6761. case BuiltinProc_atomic_cxchgweak:
  6762. case BuiltinProc_atomic_cxchgweak_acq:
  6763. case BuiltinProc_atomic_cxchgweak_rel:
  6764. case BuiltinProc_atomic_cxchgweak_acqrel:
  6765. case BuiltinProc_atomic_cxchgweak_relaxed:
  6766. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  6767. case BuiltinProc_atomic_cxchgweak_failacq:
  6768. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  6769. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  6770. Type *type = expr->tav.type;
  6771. lbValue address = lb_build_expr(p, ce->args[0]);
  6772. Type *elem = type_deref(address.type);
  6773. lbValue old_value = lb_build_expr(p, ce->args[1]);
  6774. lbValue new_value = lb_build_expr(p, ce->args[2]);
  6775. old_value = lb_emit_conv(p, old_value, elem);
  6776. new_value = lb_emit_conv(p, new_value, elem);
  6777. LLVMAtomicOrdering success_ordering = {};
  6778. LLVMAtomicOrdering failure_ordering = {};
  6779. LLVMBool weak = false;
  6780. switch (id) {
  6781. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6782. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6783. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6784. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6785. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6786. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6787. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  6788. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6789. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6790. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6791. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6792. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6793. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6794. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6795. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6796. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  6797. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6798. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6799. }
  6800. // TODO(bill): Figure out how to make it weak
  6801. LLVMBool single_threaded = weak;
  6802. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  6803. p->builder, address.value,
  6804. old_value.value, new_value.value,
  6805. success_ordering,
  6806. failure_ordering,
  6807. single_threaded
  6808. );
  6809. GB_ASSERT(tv.type->kind == Type_Tuple);
  6810. Type *fix_typed = alloc_type_tuple();
  6811. array_init(&fix_typed->Tuple.variables, heap_allocator(), 2);
  6812. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  6813. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  6814. lbValue res = {};
  6815. res.value = value;
  6816. res.type = fix_typed;
  6817. return res;
  6818. }
  6819. }
  6820. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  6821. return {};
  6822. }
  6823. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  6824. switch (param_value.kind) {
  6825. case ParameterValue_Constant:
  6826. if (is_type_constant_type(parameter_type)) {
  6827. return lb_const_value(p->module, parameter_type, param_value.value);
  6828. } else {
  6829. ExactValue ev = param_value.value;
  6830. lbValue arg = {};
  6831. Type *type = type_of_expr(param_value.original_ast_expr);
  6832. if (type != nullptr) {
  6833. arg = lb_const_value(p->module, type, ev);
  6834. } else {
  6835. arg = lb_const_value(p->module, parameter_type, param_value.value);
  6836. }
  6837. return lb_emit_conv(p, arg, parameter_type);
  6838. }
  6839. case ParameterValue_Nil:
  6840. return lb_const_nil(p->module, parameter_type);
  6841. case ParameterValue_Location:
  6842. {
  6843. String proc_name = {};
  6844. if (p->entity != nullptr) {
  6845. proc_name = p->entity->token.string;
  6846. }
  6847. return lb_emit_source_code_location(p, proc_name, pos);
  6848. }
  6849. case ParameterValue_Value:
  6850. return lb_build_expr(p, param_value.ast_value);
  6851. }
  6852. return lb_const_nil(p->module, parameter_type);
  6853. }
  6854. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  6855. lbModule *m = p->module;
  6856. TypeAndValue tv = type_and_value_of_expr(expr);
  6857. ast_node(ce, CallExpr, expr);
  6858. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  6859. AddressingMode proc_mode = proc_tv.mode;
  6860. if (proc_mode == Addressing_Type) {
  6861. GB_ASSERT(ce->args.count == 1);
  6862. lbValue x = lb_build_expr(p, ce->args[0]);
  6863. lbValue y = lb_emit_conv(p, x, tv.type);
  6864. return y;
  6865. }
  6866. Ast *pexpr = unparen_expr(ce->proc);
  6867. if (proc_mode == Addressing_Builtin) {
  6868. Entity *e = entity_of_node(pexpr);
  6869. BuiltinProcId id = BuiltinProc_Invalid;
  6870. if (e != nullptr) {
  6871. id = cast(BuiltinProcId)e->Builtin.id;
  6872. } else {
  6873. id = BuiltinProc_DIRECTIVE;
  6874. }
  6875. return lb_build_builtin_proc(p, expr, tv, id);
  6876. }
  6877. // NOTE(bill): Regular call
  6878. lbValue value = {};
  6879. Ast *proc_expr = unparen_expr(ce->proc);
  6880. if (proc_expr->tav.mode == Addressing_Constant) {
  6881. ExactValue v = proc_expr->tav.value;
  6882. switch (v.kind) {
  6883. case ExactValue_Integer:
  6884. {
  6885. u64 u = big_int_to_u64(&v.value_integer);
  6886. lbValue x = {};
  6887. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  6888. x.type = t_uintptr;
  6889. x = lb_emit_conv(p, x, t_rawptr);
  6890. value = lb_emit_conv(p, x, proc_expr->tav.type);
  6891. break;
  6892. }
  6893. case ExactValue_Pointer:
  6894. {
  6895. u64 u = cast(u64)v.value_pointer;
  6896. lbValue x = {};
  6897. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  6898. x.type = t_uintptr;
  6899. x = lb_emit_conv(p, x, t_rawptr);
  6900. value = lb_emit_conv(p, x, proc_expr->tav.type);
  6901. break;
  6902. }
  6903. }
  6904. }
  6905. if (value.value == nullptr) {
  6906. value = lb_build_expr(p, proc_expr);
  6907. }
  6908. GB_ASSERT(value.value != nullptr);
  6909. Type *proc_type_ = base_type(value.type);
  6910. GB_ASSERT(proc_type_->kind == Type_Proc);
  6911. TypeProc *pt = &proc_type_->Proc;
  6912. set_procedure_abi_types(heap_allocator(), proc_type_);
  6913. if (is_call_expr_field_value(ce)) {
  6914. auto args = array_make<lbValue>(heap_allocator(), pt->param_count);
  6915. for_array(arg_index, ce->args) {
  6916. Ast *arg = ce->args[arg_index];
  6917. ast_node(fv, FieldValue, arg);
  6918. GB_ASSERT(fv->field->kind == Ast_Ident);
  6919. String name = fv->field->Ident.token.string;
  6920. isize index = lookup_procedure_parameter(pt, name);
  6921. GB_ASSERT(index >= 0);
  6922. TypeAndValue tav = type_and_value_of_expr(fv->value);
  6923. if (tav.mode == Addressing_Type) {
  6924. args[index] = lb_const_nil(m, tav.type);
  6925. } else {
  6926. args[index] = lb_build_expr(p, fv->value);
  6927. }
  6928. }
  6929. TypeTuple *params = &pt->params->Tuple;
  6930. for (isize i = 0; i < args.count; i++) {
  6931. Entity *e = params->variables[i];
  6932. if (e->kind == Entity_TypeName) {
  6933. args[i] = lb_const_nil(m, e->type);
  6934. } else if (e->kind == Entity_Constant) {
  6935. continue;
  6936. } else {
  6937. GB_ASSERT(e->kind == Entity_Variable);
  6938. if (args[i].value == nullptr) {
  6939. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  6940. } else {
  6941. args[i] = lb_emit_conv(p, args[i], e->type);
  6942. }
  6943. }
  6944. }
  6945. for (isize i = 0; i < args.count; i++) {
  6946. Entity *e = params->variables[i];
  6947. if (args[i].type == nullptr) {
  6948. continue;
  6949. } else if (is_type_untyped_nil(args[i].type)) {
  6950. args[i] = lb_const_nil(m, e->type);
  6951. } else if (is_type_untyped_undef(args[i].type)) {
  6952. args[i] = lb_const_undef(m, e->type);
  6953. }
  6954. }
  6955. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  6956. }
  6957. isize arg_index = 0;
  6958. isize arg_count = 0;
  6959. for_array(i, ce->args) {
  6960. Ast *arg = ce->args[i];
  6961. TypeAndValue tav = type_and_value_of_expr(arg);
  6962. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  6963. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  6964. Type *at = tav.type;
  6965. if (at->kind == Type_Tuple) {
  6966. arg_count += at->Tuple.variables.count;
  6967. } else {
  6968. arg_count++;
  6969. }
  6970. }
  6971. isize param_count = 0;
  6972. if (pt->params) {
  6973. GB_ASSERT(pt->params->kind == Type_Tuple);
  6974. param_count = pt->params->Tuple.variables.count;
  6975. }
  6976. auto args = array_make<lbValue>(heap_allocator(), cast(isize)gb_max(param_count, arg_count));
  6977. isize variadic_index = pt->variadic_index;
  6978. bool variadic = pt->variadic && variadic_index >= 0;
  6979. bool vari_expand = ce->ellipsis.pos.line != 0;
  6980. bool is_c_vararg = pt->c_vararg;
  6981. String proc_name = {};
  6982. if (p->entity != nullptr) {
  6983. proc_name = p->entity->token.string;
  6984. }
  6985. TokenPos pos = ast_token(ce->proc).pos;
  6986. TypeTuple *param_tuple = nullptr;
  6987. if (pt->params) {
  6988. GB_ASSERT(pt->params->kind == Type_Tuple);
  6989. param_tuple = &pt->params->Tuple;
  6990. }
  6991. for_array(i, ce->args) {
  6992. Ast *arg = ce->args[i];
  6993. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  6994. if (arg_tv.mode == Addressing_Type) {
  6995. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  6996. } else {
  6997. lbValue a = lb_build_expr(p, arg);
  6998. Type *at = a.type;
  6999. if (at->kind == Type_Tuple) {
  7000. for_array(i, at->Tuple.variables) {
  7001. Entity *e = at->Tuple.variables[i];
  7002. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  7003. args[arg_index++] = v;
  7004. }
  7005. } else {
  7006. args[arg_index++] = a;
  7007. }
  7008. }
  7009. }
  7010. if (param_count > 0) {
  7011. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  7012. GB_ASSERT(param_count < 1000000);
  7013. if (arg_count < param_count) {
  7014. isize end = cast(isize)param_count;
  7015. if (variadic) {
  7016. end = variadic_index;
  7017. }
  7018. while (arg_index < end) {
  7019. Entity *e = param_tuple->variables[arg_index];
  7020. GB_ASSERT(e->kind == Entity_Variable);
  7021. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7022. }
  7023. }
  7024. if (is_c_vararg) {
  7025. GB_ASSERT(variadic);
  7026. GB_ASSERT(!vari_expand);
  7027. isize i = 0;
  7028. for (; i < variadic_index; i++) {
  7029. Entity *e = param_tuple->variables[i];
  7030. if (e->kind == Entity_Variable) {
  7031. args[i] = lb_emit_conv(p, args[i], e->type);
  7032. }
  7033. }
  7034. Type *variadic_type = param_tuple->variables[i]->type;
  7035. GB_ASSERT(is_type_slice(variadic_type));
  7036. variadic_type = base_type(variadic_type)->Slice.elem;
  7037. if (!is_type_any(variadic_type)) {
  7038. for (; i < arg_count; i++) {
  7039. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7040. }
  7041. } else {
  7042. for (; i < arg_count; i++) {
  7043. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  7044. }
  7045. }
  7046. } else if (variadic) {
  7047. isize i = 0;
  7048. for (; i < variadic_index; i++) {
  7049. Entity *e = param_tuple->variables[i];
  7050. if (e->kind == Entity_Variable) {
  7051. args[i] = lb_emit_conv(p, args[i], e->type);
  7052. }
  7053. }
  7054. if (!vari_expand) {
  7055. Type *variadic_type = param_tuple->variables[i]->type;
  7056. GB_ASSERT(is_type_slice(variadic_type));
  7057. variadic_type = base_type(variadic_type)->Slice.elem;
  7058. for (; i < arg_count; i++) {
  7059. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7060. }
  7061. }
  7062. } else {
  7063. for (isize i = 0; i < param_count; i++) {
  7064. Entity *e = param_tuple->variables[i];
  7065. if (e->kind == Entity_Variable) {
  7066. if (args[i].value == nullptr) {
  7067. continue;
  7068. }
  7069. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  7070. args[i] = lb_emit_conv(p, args[i], e->type);
  7071. }
  7072. }
  7073. }
  7074. if (variadic && !vari_expand && !is_c_vararg) {
  7075. // variadic call argument generation
  7076. gbAllocator allocator = heap_allocator();
  7077. Type *slice_type = param_tuple->variables[variadic_index]->type;
  7078. Type *elem_type = base_type(slice_type)->Slice.elem;
  7079. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  7080. isize slice_len = arg_count+1 - (variadic_index+1);
  7081. if (slice_len > 0) {
  7082. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  7083. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  7084. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  7085. lb_emit_store(p, addr, args[i]);
  7086. }
  7087. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  7088. lbValue len = lb_const_int(m, t_int, slice_len);
  7089. lb_fill_slice(p, slice, base_elem, len);
  7090. }
  7091. arg_count = param_count;
  7092. args[variadic_index] = lb_addr_load(p, slice);
  7093. }
  7094. }
  7095. if (variadic && variadic_index+1 < param_count) {
  7096. for (isize i = variadic_index+1; i < param_count; i++) {
  7097. Entity *e = param_tuple->variables[i];
  7098. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7099. }
  7100. }
  7101. isize final_count = param_count;
  7102. if (is_c_vararg) {
  7103. final_count = arg_count;
  7104. }
  7105. if (param_tuple != nullptr) {
  7106. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  7107. Entity *e = param_tuple->variables[i];
  7108. if (args[i].type == nullptr) {
  7109. continue;
  7110. } else if (is_type_untyped_nil(args[i].type)) {
  7111. args[i] = lb_const_nil(m, e->type);
  7112. } else if (is_type_untyped_undef(args[i].type)) {
  7113. args[i] = lb_const_undef(m, e->type);
  7114. }
  7115. }
  7116. }
  7117. auto call_args = array_slice(args, 0, final_count);
  7118. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  7119. }
  7120. bool lb_is_const(lbValue value) {
  7121. LLVMValueRef v = value.value;
  7122. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  7123. // TODO(bill): Is this correct behaviour?
  7124. return true;
  7125. }
  7126. if (LLVMIsConstant(v)) {
  7127. return true;
  7128. }
  7129. return false;
  7130. }
  7131. bool lb_is_const_nil(lbValue value) {
  7132. LLVMValueRef v = value.value;
  7133. if (LLVMIsConstant(v)) {
  7134. if (LLVMIsAConstantAggregateZero(v)) {
  7135. return true;
  7136. } else if (LLVMIsAConstantPointerNull(v)) {
  7137. return true;
  7138. }
  7139. }
  7140. return false;
  7141. }
  7142. String lb_get_const_string(lbModule *m, lbValue value) {
  7143. GB_ASSERT(lb_is_const(value));
  7144. Type *t = base_type(value.type);
  7145. GB_ASSERT(are_types_identical(t, t_string));
  7146. unsigned ptr_indices[1] = {0};
  7147. unsigned len_indices[1] = {1};
  7148. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  7149. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  7150. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  7151. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  7152. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  7153. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  7154. size_t length = 0;
  7155. char const *text = LLVMGetAsString(underlying_ptr, &length);
  7156. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  7157. return make_string(cast(u8 const *)text, real_length);
  7158. }
  7159. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  7160. GB_ASSERT(is_type_pointer(addr.type));
  7161. Type *type = type_deref(addr.type);
  7162. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  7163. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  7164. }
  7165. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7166. AstPackage *pkg = m->info->runtime_package;
  7167. Entity *e = scope_lookup_current(pkg->scope, name);
  7168. lbValue *found = nullptr;
  7169. if (m != e->code_gen_module) {
  7170. gb_mutex_lock(&m->mutex);
  7171. }
  7172. found = map_get(&e->code_gen_module->values, hash_entity(e));
  7173. if (m != e->code_gen_module) {
  7174. gb_mutex_unlock(&m->mutex);
  7175. }
  7176. GB_ASSERT(found != nullptr);
  7177. return found->value;
  7178. }
  7179. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  7180. Type *vt = core_type(value.type);
  7181. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  7182. // TODO(bill): lb_emit_byte_swap
  7183. lbValue res = {};
  7184. res.type = platform_type;
  7185. res.value = value.value;
  7186. int sz = cast(int)type_size_of(vt);
  7187. if (sz > 1) {
  7188. if (is_type_float(platform_type)) {
  7189. String name = {};
  7190. switch (sz) {
  7191. case 4: name = str_lit("bswap_f32"); break;
  7192. case 8: name = str_lit("bswap_f64"); break;
  7193. default: GB_PANIC("unhandled byteswap size"); break;
  7194. }
  7195. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7196. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7197. } else {
  7198. GB_ASSERT(is_type_integer(platform_type));
  7199. String name = {};
  7200. switch (sz) {
  7201. case 2: name = str_lit("bswap_16"); break;
  7202. case 4: name = str_lit("bswap_32"); break;
  7203. case 8: name = str_lit("bswap_64"); break;
  7204. case 16: name = str_lit("bswap_128"); break;
  7205. default: GB_PANIC("unhandled byteswap size"); break;
  7206. }
  7207. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7208. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7209. }
  7210. }
  7211. return res;
  7212. }
  7213. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  7214. lbLoopData data = {};
  7215. lbValue max = lb_const_int(p->module, t_int, count);
  7216. data.idx_addr = lb_add_local_generated(p, index_type, true);
  7217. data.body = lb_create_block(p, "loop.body");
  7218. data.done = lb_create_block(p, "loop.done");
  7219. data.loop = lb_create_block(p, "loop.loop");
  7220. lb_emit_jump(p, data.loop);
  7221. lb_start_block(p, data.loop);
  7222. data.idx = lb_addr_load(p, data.idx_addr);
  7223. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  7224. lb_emit_if(p, cond, data.body, data.done);
  7225. lb_start_block(p, data.body);
  7226. return data;
  7227. }
  7228. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  7229. if (data.idx_addr.addr.value != nullptr) {
  7230. lb_emit_increment(p, data.idx_addr.addr);
  7231. lb_emit_jump(p, data.loop);
  7232. lb_start_block(p, data.done);
  7233. }
  7234. }
  7235. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  7236. lbValue res = {};
  7237. res.type = t_llvm_bool;
  7238. Type *t = x.type;
  7239. if (is_type_pointer(t)) {
  7240. if (op_kind == Token_CmpEq) {
  7241. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7242. } else if (op_kind == Token_NotEq) {
  7243. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7244. }
  7245. return res;
  7246. } else if (is_type_cstring(t)) {
  7247. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  7248. if (op_kind == Token_CmpEq) {
  7249. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  7250. } else if (op_kind == Token_NotEq) {
  7251. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  7252. }
  7253. return res;
  7254. } else if (is_type_proc(t)) {
  7255. if (op_kind == Token_CmpEq) {
  7256. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7257. } else if (op_kind == Token_NotEq) {
  7258. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7259. }
  7260. return res;
  7261. } else if (is_type_any(t)) {
  7262. // TODO(bill): is this correct behaviour for nil comparison for any?
  7263. lbValue data = lb_emit_struct_ev(p, x, 0);
  7264. lbValue ti = lb_emit_struct_ev(p, x, 1);
  7265. if (op_kind == Token_CmpEq) {
  7266. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  7267. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  7268. res.value = LLVMBuildOr(p->builder, a, b, "");
  7269. return res;
  7270. } else if (op_kind == Token_NotEq) {
  7271. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  7272. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  7273. res.value = LLVMBuildAnd(p->builder, a, b, "");
  7274. return res;
  7275. }
  7276. } else if (is_type_slice(t)) {
  7277. lbValue len = lb_emit_struct_ev(p, x, 1);
  7278. if (op_kind == Token_CmpEq) {
  7279. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7280. return res;
  7281. } else if (op_kind == Token_NotEq) {
  7282. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7283. return res;
  7284. }
  7285. } else if (is_type_dynamic_array(t)) {
  7286. lbValue cap = lb_emit_struct_ev(p, x, 2);
  7287. if (op_kind == Token_CmpEq) {
  7288. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7289. return res;
  7290. } else if (op_kind == Token_NotEq) {
  7291. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7292. return res;
  7293. }
  7294. } else if (is_type_map(t)) {
  7295. lbValue cap = lb_map_cap(p, x);
  7296. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  7297. } else if (is_type_union(t)) {
  7298. if (type_size_of(t) == 0) {
  7299. if (op_kind == Token_CmpEq) {
  7300. return lb_const_bool(p->module, t_llvm_bool, true);
  7301. } else if (op_kind == Token_NotEq) {
  7302. return lb_const_bool(p->module, t_llvm_bool, false);
  7303. }
  7304. } else {
  7305. lbValue tag = lb_emit_union_tag_value(p, x);
  7306. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  7307. }
  7308. } else if (is_type_typeid(t)) {
  7309. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  7310. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  7311. } else if (is_type_bit_field(t)) {
  7312. auto args = array_make<lbValue>(heap_allocator(), 2);
  7313. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7314. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7315. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7316. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7317. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7318. return res;
  7319. } else if (is_type_soa_struct(t)) {
  7320. Type *bt = base_type(t);
  7321. if (bt->Struct.soa_kind == StructSoa_Slice) {
  7322. lbValue len = lb_soa_struct_len(p, x);
  7323. if (op_kind == Token_CmpEq) {
  7324. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7325. return res;
  7326. } else if (op_kind == Token_NotEq) {
  7327. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7328. return res;
  7329. }
  7330. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  7331. lbValue cap = lb_soa_struct_cap(p, x);
  7332. if (op_kind == Token_CmpEq) {
  7333. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7334. return res;
  7335. } else if (op_kind == Token_NotEq) {
  7336. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7337. return res;
  7338. }
  7339. }
  7340. } else if (is_type_struct(t) && type_has_nil(t)) {
  7341. auto args = array_make<lbValue>(heap_allocator(), 2);
  7342. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7343. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7344. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7345. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7346. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7347. return res;
  7348. }
  7349. return {};
  7350. }
  7351. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  7352. Type *a = core_type(left.type);
  7353. Type *b = core_type(right.type);
  7354. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  7355. lbValue nil_check = {};
  7356. if (is_type_untyped_nil(left.type)) {
  7357. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  7358. } else if (is_type_untyped_nil(right.type)) {
  7359. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  7360. }
  7361. if (nil_check.value != nullptr) {
  7362. return nil_check;
  7363. }
  7364. if (are_types_identical(a, b)) {
  7365. // NOTE(bill): No need for a conversion
  7366. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  7367. left = lb_emit_conv(p, left, right.type);
  7368. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  7369. right = lb_emit_conv(p, right, left.type);
  7370. } else {
  7371. gbAllocator a = heap_allocator();
  7372. Type *lt = left.type;
  7373. Type *rt = right.type;
  7374. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  7375. Type *blt = base_type(lt);
  7376. Type *brt = base_type(rt);
  7377. GB_ASSERT(is_type_bit_field_value(blt));
  7378. GB_ASSERT(is_type_bit_field_value(brt));
  7379. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  7380. i64 bytes = bits / 8;
  7381. switch (bytes) {
  7382. case 1:
  7383. left = lb_emit_conv(p, left, t_u8);
  7384. right = lb_emit_conv(p, right, t_u8);
  7385. break;
  7386. case 2:
  7387. left = lb_emit_conv(p, left, t_u16);
  7388. right = lb_emit_conv(p, right, t_u16);
  7389. break;
  7390. case 4:
  7391. left = lb_emit_conv(p, left, t_u32);
  7392. right = lb_emit_conv(p, right, t_u32);
  7393. break;
  7394. case 8:
  7395. left = lb_emit_conv(p, left, t_u64);
  7396. right = lb_emit_conv(p, right, t_u64);
  7397. break;
  7398. default: GB_PANIC("Unknown integer size"); break;
  7399. }
  7400. }
  7401. lt = left.type;
  7402. rt = right.type;
  7403. i64 ls = type_size_of(lt);
  7404. i64 rs = type_size_of(rt);
  7405. if (ls < rs) {
  7406. left = lb_emit_conv(p, left, rt);
  7407. } else if (ls > rs) {
  7408. right = lb_emit_conv(p, right, lt);
  7409. } else {
  7410. right = lb_emit_conv(p, right, lt);
  7411. }
  7412. }
  7413. if (is_type_array(a)) {
  7414. Type *tl = base_type(a);
  7415. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  7416. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  7417. TokenKind cmp_op = Token_And;
  7418. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  7419. if (op_kind == Token_NotEq) {
  7420. res = lb_const_bool(p->module, t_llvm_bool, false);
  7421. cmp_op = Token_Or;
  7422. } else if (op_kind == Token_CmpEq) {
  7423. res = lb_const_bool(p->module, t_llvm_bool, true);
  7424. cmp_op = Token_And;
  7425. }
  7426. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  7427. i32 count = cast(i32)tl->Array.count;
  7428. if (inline_array_arith) {
  7429. // inline
  7430. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7431. lb_addr_store(p, val, res);
  7432. for (i32 i = 0; i < count; i++) {
  7433. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  7434. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  7435. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7436. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7437. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7438. }
  7439. return lb_addr_load(p, val);
  7440. } else {
  7441. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  7442. // TODO(bill): Test to see if this is actually faster!!!!
  7443. auto args = array_make<lbValue>(heap_allocator(), 3);
  7444. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7445. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  7446. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  7447. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  7448. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  7449. return lb_emit_conv(p, res, t_bool);
  7450. } else {
  7451. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7452. lb_addr_store(p, val, res);
  7453. auto loop_data = lb_loop_start(p, count, t_i32);
  7454. {
  7455. lbValue i = loop_data.idx;
  7456. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  7457. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  7458. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7459. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7460. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7461. }
  7462. lb_loop_end(p, loop_data);
  7463. return lb_addr_load(p, val);
  7464. }
  7465. }
  7466. }
  7467. if (is_type_string(a)) {
  7468. if (is_type_cstring(a)) {
  7469. left = lb_emit_conv(p, left, t_string);
  7470. right = lb_emit_conv(p, right, t_string);
  7471. }
  7472. char const *runtime_procedure = nullptr;
  7473. switch (op_kind) {
  7474. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  7475. case Token_NotEq: runtime_procedure = "string_ne"; break;
  7476. case Token_Lt: runtime_procedure = "string_lt"; break;
  7477. case Token_Gt: runtime_procedure = "string_gt"; break;
  7478. case Token_LtEq: runtime_procedure = "string_le"; break;
  7479. case Token_GtEq: runtime_procedure = "string_gt"; break;
  7480. }
  7481. GB_ASSERT(runtime_procedure != nullptr);
  7482. auto args = array_make<lbValue>(heap_allocator(), 2);
  7483. args[0] = left;
  7484. args[1] = right;
  7485. return lb_emit_runtime_call(p, runtime_procedure, args);
  7486. }
  7487. if (is_type_complex(a)) {
  7488. char const *runtime_procedure = "";
  7489. i64 sz = 8*type_size_of(a);
  7490. switch (sz) {
  7491. case 64:
  7492. switch (op_kind) {
  7493. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  7494. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  7495. }
  7496. break;
  7497. case 128:
  7498. switch (op_kind) {
  7499. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  7500. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  7501. }
  7502. break;
  7503. }
  7504. GB_ASSERT(runtime_procedure != nullptr);
  7505. auto args = array_make<lbValue>(heap_allocator(), 2);
  7506. args[0] = left;
  7507. args[1] = right;
  7508. return lb_emit_runtime_call(p, runtime_procedure, args);
  7509. }
  7510. if (is_type_quaternion(a)) {
  7511. char const *runtime_procedure = "";
  7512. i64 sz = 8*type_size_of(a);
  7513. switch (sz) {
  7514. case 128:
  7515. switch (op_kind) {
  7516. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  7517. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  7518. }
  7519. break;
  7520. case 256:
  7521. switch (op_kind) {
  7522. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  7523. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  7524. }
  7525. break;
  7526. }
  7527. GB_ASSERT(runtime_procedure != nullptr);
  7528. auto args = array_make<lbValue>(heap_allocator(), 2);
  7529. args[0] = left;
  7530. args[1] = right;
  7531. return lb_emit_runtime_call(p, runtime_procedure, args);
  7532. }
  7533. if (is_type_bit_set(a)) {
  7534. switch (op_kind) {
  7535. case Token_Lt:
  7536. case Token_LtEq:
  7537. case Token_Gt:
  7538. case Token_GtEq:
  7539. {
  7540. Type *it = bit_set_to_int(a);
  7541. lbValue lhs = lb_emit_transmute(p, left, it);
  7542. lbValue rhs = lb_emit_transmute(p, right, it);
  7543. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  7544. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  7545. // (lhs & rhs) == lhs
  7546. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  7547. res.type = t_llvm_bool;
  7548. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  7549. // (lhs & rhs) == rhs
  7550. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  7551. res.type = t_llvm_bool;
  7552. }
  7553. // NOTE(bill): Strict subsets
  7554. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  7555. // res &~ (lhs == rhs)
  7556. lbValue eq = {};
  7557. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  7558. eq.type = t_llvm_bool;
  7559. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  7560. }
  7561. return res;
  7562. }
  7563. case Token_CmpEq:
  7564. case Token_NotEq:
  7565. {
  7566. LLVMIntPredicate pred = {};
  7567. switch (op_kind) {
  7568. case Token_CmpEq: pred = LLVMIntEQ; break;
  7569. case Token_NotEq: pred = LLVMIntNE; break;
  7570. }
  7571. lbValue res = {};
  7572. res.type = t_llvm_bool;
  7573. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7574. return res;
  7575. }
  7576. }
  7577. }
  7578. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  7579. Type *t = left.type;
  7580. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  7581. Type *platform_type = integer_endian_type_to_platform_type(t);
  7582. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  7583. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  7584. left = x;
  7585. right = y;
  7586. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  7587. Type *platform_type = integer_endian_type_to_platform_type(t);
  7588. lbValue x = lb_emit_conv(p, left, platform_type);
  7589. lbValue y = lb_emit_conv(p, right, platform_type);
  7590. left = x;
  7591. right = y;
  7592. }
  7593. }
  7594. a = core_type(left.type);
  7595. b = core_type(right.type);
  7596. lbValue res = {};
  7597. res.type = t_llvm_bool;
  7598. if (is_type_integer(a) ||
  7599. is_type_boolean(a) ||
  7600. is_type_pointer(a) ||
  7601. is_type_proc(a) ||
  7602. is_type_enum(a)) {
  7603. LLVMIntPredicate pred = {};
  7604. if (is_type_unsigned(left.type)) {
  7605. switch (op_kind) {
  7606. case Token_Gt: pred = LLVMIntUGT; break;
  7607. case Token_GtEq: pred = LLVMIntUGE; break;
  7608. case Token_Lt: pred = LLVMIntULT; break;
  7609. case Token_LtEq: pred = LLVMIntULE; break;
  7610. }
  7611. } else {
  7612. switch (op_kind) {
  7613. case Token_Gt: pred = LLVMIntSGT; break;
  7614. case Token_GtEq: pred = LLVMIntSGE; break;
  7615. case Token_Lt: pred = LLVMIntSLT; break;
  7616. case Token_LtEq: pred = LLVMIntSLE; break;
  7617. }
  7618. }
  7619. switch (op_kind) {
  7620. case Token_CmpEq: pred = LLVMIntEQ; break;
  7621. case Token_NotEq: pred = LLVMIntNE; break;
  7622. }
  7623. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7624. } else if (is_type_float(a)) {
  7625. LLVMRealPredicate pred = {};
  7626. switch (op_kind) {
  7627. case Token_CmpEq: pred = LLVMRealOEQ; break;
  7628. case Token_Gt: pred = LLVMRealOGT; break;
  7629. case Token_GtEq: pred = LLVMRealOGE; break;
  7630. case Token_Lt: pred = LLVMRealOLT; break;
  7631. case Token_LtEq: pred = LLVMRealOLE; break;
  7632. case Token_NotEq: pred = LLVMRealONE; break;
  7633. }
  7634. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  7635. } else if (is_type_typeid(a)) {
  7636. LLVMIntPredicate pred = {};
  7637. switch (op_kind) {
  7638. case Token_Gt: pred = LLVMIntUGT; break;
  7639. case Token_GtEq: pred = LLVMIntUGE; break;
  7640. case Token_Lt: pred = LLVMIntULT; break;
  7641. case Token_LtEq: pred = LLVMIntULE; break;
  7642. case Token_CmpEq: pred = LLVMIntEQ; break;
  7643. case Token_NotEq: pred = LLVMIntNE; break;
  7644. }
  7645. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7646. } else {
  7647. GB_PANIC("Unhandled comparison kind %s (%s) %.*s %s (%s)", type_to_string(left.type), type_to_string(base_type(left.type)), LIT(token_strings[op_kind]), type_to_string(right.type), type_to_string(base_type(right.type)));
  7648. }
  7649. return res;
  7650. }
  7651. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  7652. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  7653. if (found != nullptr) {
  7654. lbValue value = {};
  7655. value.value = (*found)->value;
  7656. value.type = (*found)->type;
  7657. return value;
  7658. }
  7659. ast_node(pl, ProcLit, expr);
  7660. // NOTE(bill): Generate a new name
  7661. // parent$count
  7662. isize name_len = prefix_name.len + 1 + 8 + 1;
  7663. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  7664. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  7665. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  7666. String name = make_string((u8 *)name_text, name_len-1);
  7667. Type *type = type_of_expr(expr);
  7668. set_procedure_abi_types(heap_allocator(), type);
  7669. Token token = {};
  7670. token.pos = ast_token(expr).pos;
  7671. token.kind = Token_Ident;
  7672. token.string = name;
  7673. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  7674. e->decl_info = pl->decl;
  7675. lbProcedure *p = lb_create_procedure(m, e);
  7676. lbValue value = {};
  7677. value.value = p->value;
  7678. value.type = p->type;
  7679. array_add(&m->procedures_to_generate, p);
  7680. if (parent != nullptr) {
  7681. array_add(&parent->children, p);
  7682. } else {
  7683. string_map_set(&m->members, name, value);
  7684. }
  7685. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  7686. return value;
  7687. }
  7688. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  7689. lbModule *m = p->module;
  7690. Type *src_type = value.type;
  7691. bool is_ptr = is_type_pointer(src_type);
  7692. bool is_tuple = true;
  7693. Type *tuple = type;
  7694. if (type->kind != Type_Tuple) {
  7695. is_tuple = false;
  7696. tuple = make_optional_ok_type(type);
  7697. }
  7698. lbAddr v = lb_add_local_generated(p, tuple, true);
  7699. if (is_ptr) {
  7700. value = lb_emit_load(p, value);
  7701. }
  7702. Type *src = base_type(type_deref(src_type));
  7703. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  7704. Type *dst = tuple->Tuple.variables[0]->type;
  7705. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  7706. lbValue tag = {};
  7707. lbValue dst_tag = {};
  7708. lbValue cond = {};
  7709. lbValue data = {};
  7710. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  7711. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  7712. if (is_type_union_maybe_pointer(src)) {
  7713. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  7714. } else {
  7715. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  7716. dst_tag = lb_const_union_tag(m, src, dst);
  7717. }
  7718. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  7719. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  7720. if (data.value != nullptr) {
  7721. GB_ASSERT(is_type_union_maybe_pointer(src));
  7722. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  7723. } else {
  7724. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  7725. }
  7726. lb_emit_if(p, cond, ok_block, end_block);
  7727. lb_start_block(p, ok_block);
  7728. if (data.value == nullptr) {
  7729. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  7730. }
  7731. lb_emit_store(p, gep0, data);
  7732. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  7733. lb_emit_jump(p, end_block);
  7734. lb_start_block(p, end_block);
  7735. if (!is_tuple) {
  7736. if (do_conversion_check) {
  7737. // NOTE(bill): Panic on invalid conversion
  7738. Type *dst_type = tuple->Tuple.variables[0]->type;
  7739. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  7740. auto args = array_make<lbValue>(heap_allocator(), 6);
  7741. args[0] = ok;
  7742. args[1] = lb_const_string(m, pos.file);
  7743. args[2] = lb_const_int(m, t_int, pos.line);
  7744. args[3] = lb_const_int(m, t_int, pos.column);
  7745. args[4] = lb_typeid(m, src_type);
  7746. args[5] = lb_typeid(m, dst_type);
  7747. lb_emit_runtime_call(p, "type_assertion_check", args);
  7748. }
  7749. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  7750. }
  7751. return lb_addr_load(p, v);
  7752. }
  7753. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  7754. lbModule *m = p->module;
  7755. Type *src_type = value.type;
  7756. if (is_type_pointer(src_type)) {
  7757. value = lb_emit_load(p, value);
  7758. }
  7759. bool is_tuple = true;
  7760. Type *tuple = type;
  7761. if (type->kind != Type_Tuple) {
  7762. is_tuple = false;
  7763. tuple = make_optional_ok_type(type);
  7764. }
  7765. Type *dst_type = tuple->Tuple.variables[0]->type;
  7766. lbAddr v = lb_add_local_generated(p, tuple, true);
  7767. lbValue dst_typeid = lb_typeid(m, dst_type);
  7768. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  7769. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  7770. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  7771. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  7772. lb_emit_if(p, cond, ok_block, end_block);
  7773. lb_start_block(p, ok_block);
  7774. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  7775. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  7776. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  7777. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  7778. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  7779. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  7780. lb_emit_jump(p, end_block);
  7781. lb_start_block(p, end_block);
  7782. if (!is_tuple) {
  7783. // NOTE(bill): Panic on invalid conversion
  7784. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  7785. auto args = array_make<lbValue>(heap_allocator(), 6);
  7786. args[0] = ok;
  7787. args[1] = lb_const_string(m, pos.file);
  7788. args[2] = lb_const_int(m, t_int, pos.line);
  7789. args[3] = lb_const_int(m, t_int, pos.column);
  7790. args[4] = any_typeid;
  7791. args[5] = dst_typeid;
  7792. lb_emit_runtime_call(p, "type_assertion_check", args);
  7793. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  7794. }
  7795. return v;
  7796. }
  7797. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  7798. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  7799. }
  7800. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  7801. lbModule *m = p->module;
  7802. u64 prev_state_flags = p->module->state_flags;
  7803. defer (p->module->state_flags = prev_state_flags);
  7804. if (expr->state_flags != 0) {
  7805. u64 in = expr->state_flags;
  7806. u64 out = p->module->state_flags;
  7807. if (in & StateFlag_bounds_check) {
  7808. out |= StateFlag_bounds_check;
  7809. out &= ~StateFlag_no_bounds_check;
  7810. } else if (in & StateFlag_no_bounds_check) {
  7811. out |= StateFlag_no_bounds_check;
  7812. out &= ~StateFlag_bounds_check;
  7813. }
  7814. p->module->state_flags = out;
  7815. }
  7816. expr = unparen_expr(expr);
  7817. TypeAndValue tv = type_and_value_of_expr(expr);
  7818. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "%s", expr_to_string(expr));
  7819. GB_ASSERT(tv.mode != Addressing_Type);
  7820. if (tv.value.kind != ExactValue_Invalid) {
  7821. // NOTE(bill): Short on constant values
  7822. return lb_const_value(p->module, tv.type, tv.value);
  7823. }
  7824. switch (expr->kind) {
  7825. case_ast_node(bl, BasicLit, expr);
  7826. TokenPos pos = bl->token.pos;
  7827. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  7828. case_end;
  7829. case_ast_node(bd, BasicDirective, expr);
  7830. TokenPos pos = bd->token.pos;
  7831. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  7832. case_end;
  7833. case_ast_node(i, Implicit, expr);
  7834. return lb_addr_load(p, lb_build_addr(p, expr));
  7835. case_end;
  7836. case_ast_node(u, Undef, expr)
  7837. lbValue res = {};
  7838. if (is_type_untyped(tv.type)) {
  7839. res.value = nullptr;
  7840. res.type = t_untyped_undef;
  7841. } else {
  7842. res.value = LLVMGetUndef(lb_type(m, tv.type));
  7843. res.type = tv.type;
  7844. }
  7845. return res;
  7846. case_end;
  7847. case_ast_node(i, Ident, expr);
  7848. Entity *e = entity_from_expr(expr);
  7849. e = strip_entity_wrapping(e);
  7850. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  7851. if (e->kind == Entity_Builtin) {
  7852. Token token = ast_token(expr);
  7853. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  7854. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  7855. LIT(token.pos.file), token.pos.line, token.pos.column);
  7856. return {};
  7857. } else if (e->kind == Entity_Nil) {
  7858. lbValue res = {};
  7859. res.value = nullptr;
  7860. res.type = e->type;
  7861. return res;
  7862. }
  7863. GB_ASSERT(e->kind != Entity_ProcGroup);
  7864. auto *found = map_get(&p->module->values, hash_entity(e));
  7865. if (found) {
  7866. auto v = *found;
  7867. // NOTE(bill): This is because pointers are already pointers in LLVM
  7868. if (is_type_proc(v.type)) {
  7869. return v;
  7870. }
  7871. return lb_emit_load(p, v);
  7872. } else if (e != nullptr && e->kind == Entity_Variable) {
  7873. return lb_addr_load(p, lb_build_addr(p, expr));
  7874. }
  7875. gb_printf_err("Error in: %.*s(%td:%td)\n", LIT(p->name), i->token.pos.line, i->token.pos.column);
  7876. String pkg = {};
  7877. if (e->pkg) {
  7878. pkg = e->pkg->name;
  7879. }
  7880. GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s (%p) : %s @ %p", LIT(pkg), LIT(e->token.string), e, type_to_string(e->type), expr);
  7881. return {};
  7882. case_end;
  7883. case_ast_node(de, DerefExpr, expr);
  7884. return lb_addr_load(p, lb_build_addr(p, expr));
  7885. case_end;
  7886. case_ast_node(se, SelectorExpr, expr);
  7887. TypeAndValue tav = type_and_value_of_expr(expr);
  7888. GB_ASSERT(tav.mode != Addressing_Invalid);
  7889. return lb_addr_load(p, lb_build_addr(p, expr));
  7890. case_end;
  7891. case_ast_node(ise, ImplicitSelectorExpr, expr);
  7892. TypeAndValue tav = type_and_value_of_expr(expr);
  7893. GB_ASSERT(tav.mode == Addressing_Constant);
  7894. return lb_const_value(p->module, tv.type, tv.value);
  7895. case_end;
  7896. case_ast_node(se, SelectorCallExpr, expr);
  7897. GB_ASSERT(se->modified_call);
  7898. TypeAndValue tav = type_and_value_of_expr(expr);
  7899. GB_ASSERT(tav.mode != Addressing_Invalid);
  7900. return lb_build_expr(p, se->call);
  7901. case_end;
  7902. case_ast_node(te, TernaryExpr, expr);
  7903. LLVMValueRef incoming_values[2] = {};
  7904. LLVMBasicBlockRef incoming_blocks[2] = {};
  7905. GB_ASSERT(te->y != nullptr);
  7906. lbBlock *then = lb_create_block(p, "if.then");
  7907. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  7908. lbBlock *else_ = lb_create_block(p, "if.else");
  7909. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  7910. lb_start_block(p, then);
  7911. Type *type = default_type(type_of_expr(expr));
  7912. lb_open_scope(p);
  7913. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  7914. lb_close_scope(p, lbDeferExit_Default, nullptr);
  7915. lb_emit_jump(p, done);
  7916. lb_start_block(p, else_);
  7917. lb_open_scope(p);
  7918. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  7919. lb_close_scope(p, lbDeferExit_Default, nullptr);
  7920. lb_emit_jump(p, done);
  7921. lb_start_block(p, done);
  7922. lbValue res = {};
  7923. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  7924. res.type = type;
  7925. GB_ASSERT(p->curr_block->preds.count >= 2);
  7926. incoming_blocks[0] = p->curr_block->preds[0]->block;
  7927. incoming_blocks[1] = p->curr_block->preds[1]->block;
  7928. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  7929. return res;
  7930. case_end;
  7931. case_ast_node(te, TernaryIfExpr, expr);
  7932. LLVMValueRef incoming_values[2] = {};
  7933. LLVMBasicBlockRef incoming_blocks[2] = {};
  7934. GB_ASSERT(te->y != nullptr);
  7935. lbBlock *then = lb_create_block(p, "if.then");
  7936. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  7937. lbBlock *else_ = lb_create_block(p, "if.else");
  7938. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  7939. lb_start_block(p, then);
  7940. Type *type = default_type(type_of_expr(expr));
  7941. lb_open_scope(p);
  7942. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  7943. lb_close_scope(p, lbDeferExit_Default, nullptr);
  7944. lb_emit_jump(p, done);
  7945. lb_start_block(p, else_);
  7946. lb_open_scope(p);
  7947. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  7948. lb_close_scope(p, lbDeferExit_Default, nullptr);
  7949. lb_emit_jump(p, done);
  7950. lb_start_block(p, done);
  7951. lbValue res = {};
  7952. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  7953. res.type = type;
  7954. GB_ASSERT(p->curr_block->preds.count >= 2);
  7955. incoming_blocks[0] = p->curr_block->preds[0]->block;
  7956. incoming_blocks[1] = p->curr_block->preds[1]->block;
  7957. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  7958. return res;
  7959. case_end;
  7960. case_ast_node(te, TernaryWhenExpr, expr);
  7961. TypeAndValue tav = type_and_value_of_expr(te->cond);
  7962. GB_ASSERT(tav.mode == Addressing_Constant);
  7963. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  7964. if (tav.value.value_bool) {
  7965. return lb_build_expr(p, te->x);
  7966. } else {
  7967. return lb_build_expr(p, te->y);
  7968. }
  7969. case_end;
  7970. case_ast_node(ta, TypeAssertion, expr);
  7971. TokenPos pos = ast_token(expr).pos;
  7972. Type *type = tv.type;
  7973. lbValue e = lb_build_expr(p, ta->expr);
  7974. Type *t = type_deref(e.type);
  7975. if (is_type_union(t)) {
  7976. return lb_emit_union_cast(p, e, type, pos);
  7977. } else if (is_type_any(t)) {
  7978. return lb_emit_any_cast(p, e, type, pos);
  7979. } else {
  7980. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  7981. }
  7982. case_end;
  7983. case_ast_node(tc, TypeCast, expr);
  7984. lbValue e = lb_build_expr(p, tc->expr);
  7985. switch (tc->token.kind) {
  7986. case Token_cast:
  7987. return lb_emit_conv(p, e, tv.type);
  7988. case Token_transmute:
  7989. return lb_emit_transmute(p, e, tv.type);
  7990. }
  7991. GB_PANIC("Invalid AST TypeCast");
  7992. case_end;
  7993. case_ast_node(ac, AutoCast, expr);
  7994. return lb_build_expr(p, ac->expr);
  7995. case_end;
  7996. case_ast_node(ue, UnaryExpr, expr);
  7997. switch (ue->op.kind) {
  7998. case Token_And: {
  7999. Ast *ue_expr = unparen_expr(ue->expr);
  8000. if (ue_expr->kind == Ast_CompoundLit) {
  8001. lbValue v = lb_build_expr(p, ue->expr);
  8002. Type *type = v.type;
  8003. lbAddr addr = {};
  8004. if (p->is_startup) {
  8005. addr = lb_add_global_generated(p->module, type, v);
  8006. } else {
  8007. addr = lb_add_local_generated(p, type, false);
  8008. }
  8009. lb_addr_store(p, addr, v);
  8010. return addr.addr;
  8011. } else if (ue_expr->kind == Ast_TypeAssertion) {
  8012. gbAllocator a = heap_allocator();
  8013. GB_ASSERT(is_type_pointer(tv.type));
  8014. ast_node(ta, TypeAssertion, ue_expr);
  8015. TokenPos pos = ast_token(expr).pos;
  8016. Type *type = type_of_expr(ue_expr);
  8017. GB_ASSERT(!is_type_tuple(type));
  8018. lbValue e = lb_build_expr(p, ta->expr);
  8019. Type *t = type_deref(e.type);
  8020. if (is_type_union(t)) {
  8021. lbValue v = e;
  8022. if (!is_type_pointer(v.type)) {
  8023. v = lb_address_from_load_or_generate_local(p, v);
  8024. }
  8025. Type *src_type = type_deref(v.type);
  8026. Type *dst_type = type;
  8027. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  8028. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  8029. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  8030. auto args = array_make<lbValue>(heap_allocator(), 6);
  8031. args[0] = ok;
  8032. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8033. args[2] = lb_const_int(p->module, t_int, pos.line);
  8034. args[3] = lb_const_int(p->module, t_int, pos.column);
  8035. args[4] = lb_typeid(p->module, src_type);
  8036. args[5] = lb_typeid(p->module, dst_type);
  8037. lb_emit_runtime_call(p, "type_assertion_check", args);
  8038. lbValue data_ptr = v;
  8039. return lb_emit_conv(p, data_ptr, tv.type);
  8040. } else if (is_type_any(t)) {
  8041. lbValue v = e;
  8042. if (is_type_pointer(v.type)) {
  8043. v = lb_emit_load(p, v);
  8044. }
  8045. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  8046. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  8047. lbValue id = lb_typeid(p->module, type);
  8048. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  8049. auto args = array_make<lbValue>(heap_allocator(), 6);
  8050. args[0] = ok;
  8051. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8052. args[2] = lb_const_int(p->module, t_int, pos.line);
  8053. args[3] = lb_const_int(p->module, t_int, pos.column);
  8054. args[4] = any_id;
  8055. args[5] = id;
  8056. lb_emit_runtime_call(p, "type_assertion_check", args);
  8057. return lb_emit_conv(p, data_ptr, tv.type);
  8058. } else {
  8059. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  8060. }
  8061. }
  8062. return lb_build_addr_ptr(p, ue->expr);
  8063. }
  8064. default:
  8065. {
  8066. lbValue v = lb_build_expr(p, ue->expr);
  8067. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  8068. }
  8069. }
  8070. case_end;
  8071. case_ast_node(be, BinaryExpr, expr);
  8072. return lb_build_binary_expr(p, expr);
  8073. case_end;
  8074. case_ast_node(pl, ProcLit, expr);
  8075. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  8076. case_end;
  8077. case_ast_node(cl, CompoundLit, expr);
  8078. return lb_addr_load(p, lb_build_addr(p, expr));
  8079. case_end;
  8080. case_ast_node(ce, CallExpr, expr);
  8081. lbValue res = lb_build_call_expr(p, expr);
  8082. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  8083. GB_ASSERT(is_type_tuple(res.type));
  8084. GB_ASSERT(res.type->Tuple.variables.count == 2);
  8085. return lb_emit_struct_ev(p, res, 0);
  8086. }
  8087. return res;
  8088. case_end;
  8089. case_ast_node(se, SliceExpr, expr);
  8090. return lb_addr_load(p, lb_build_addr(p, expr));
  8091. case_end;
  8092. case_ast_node(ie, IndexExpr, expr);
  8093. return lb_addr_load(p, lb_build_addr(p, expr));
  8094. case_end;
  8095. }
  8096. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  8097. return {};
  8098. }
  8099. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  8100. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  8101. String name = e->token.string;
  8102. Entity *parent = e->using_parent;
  8103. Selection sel = lookup_field(parent->type, name, false);
  8104. GB_ASSERT(sel.entity != nullptr);
  8105. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  8106. lbValue v = {};
  8107. if (pv != nullptr) {
  8108. v = *pv;
  8109. } else {
  8110. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  8111. v = lb_build_addr_ptr(p, e->using_expr);
  8112. }
  8113. GB_ASSERT(v.value != nullptr);
  8114. GB_ASSERT(parent->type == type_deref(v.type));
  8115. return lb_emit_deep_field_gep(p, v, sel);
  8116. }
  8117. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  8118. GB_ASSERT(e != nullptr);
  8119. if (e->kind == Entity_Constant) {
  8120. Type *t = default_type(type_of_expr(expr));
  8121. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  8122. lbAddr g = lb_add_global_generated(p->module, t, v);
  8123. return g;
  8124. }
  8125. lbValue v = {};
  8126. lbValue *found = map_get(&p->module->values, hash_entity(e));
  8127. if (found) {
  8128. v = *found;
  8129. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  8130. // NOTE(bill): Calculate the using variable every time
  8131. v = lb_get_using_variable(p, e);
  8132. }
  8133. if (v.value == nullptr) {
  8134. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  8135. LIT(p->name),
  8136. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  8137. GB_PANIC("Unknown value");
  8138. }
  8139. return lb_addr(v);
  8140. }
  8141. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  8142. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  8143. gbAllocator a = heap_allocator();
  8144. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  8145. map_type = base_type(map_type);
  8146. GB_ASSERT(map_type->kind == Type_Map);
  8147. Type *key_type = map_type->Map.key;
  8148. Type *val_type = map_type->Map.value;
  8149. // NOTE(bill): Removes unnecessary allocation if split gep
  8150. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  8151. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  8152. lb_emit_store(p, gep0, m);
  8153. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_const_bool(p->module, t_bool, is_type_string(key_type)));
  8154. i64 entry_size = type_size_of (map_type->Map.entry_type);
  8155. i64 entry_align = type_align_of (map_type->Map.entry_type);
  8156. i64 value_offset = type_offset_of(map_type->Map.entry_type, 2);
  8157. i64 value_size = type_size_of (map_type->Map.value);
  8158. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  8159. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  8160. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, value_offset));
  8161. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, value_size));
  8162. return lb_addr_load(p, h);
  8163. }
  8164. lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type) {
  8165. Type *hash_type = t_u64;
  8166. lbAddr v = lb_add_local_generated(p, t_map_key, true);
  8167. lbValue vp = lb_addr_get_ptr(p, v);
  8168. Type *t = base_type(key.type);
  8169. key = lb_emit_conv(p, key, key_type);
  8170. if (is_type_string(t)) {
  8171. lbValue str = lb_emit_conv(p, key, t_string);
  8172. lbValue hashed_str = {};
  8173. if (lb_is_const(str)) {
  8174. String v = lb_get_const_string(p->module, str);
  8175. u64 hs = fnv64a(v.text, v.len);
  8176. hashed_str = lb_const_int(p->module, t_u64, hs);
  8177. } else {
  8178. auto args = array_make<lbValue>(heap_allocator(), 1);
  8179. args[0] = str;
  8180. hashed_str = lb_emit_runtime_call(p, "default_hash_string", args);
  8181. }
  8182. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_str);
  8183. lbValue key_data = lb_emit_struct_ep(p, vp, 1);
  8184. key_data = lb_emit_conv(p, key_data, alloc_type_pointer(key_type));
  8185. lb_emit_store(p, key_data, str);
  8186. } else {
  8187. i64 sz = type_size_of(t);
  8188. GB_ASSERT(sz <= 8);
  8189. if (sz != 0) {
  8190. auto args = array_make<lbValue>(heap_allocator(), 2);
  8191. args[0] = lb_address_from_load_or_generate_local(p, key);
  8192. args[1] = lb_const_int(p->module, t_int, sz);
  8193. lbValue hash = lb_emit_runtime_call(p, "default_hash_ptr", args);
  8194. lbValue hash_ptr = lb_emit_struct_ep(p, vp, 0);
  8195. lbValue key_data = lb_emit_struct_ep(p, vp, 1);
  8196. key_data = lb_emit_conv(p, key_data, alloc_type_pointer(key_type));
  8197. lb_emit_store(p, hash_ptr, hash);
  8198. lb_emit_store(p, key_data, key);
  8199. }
  8200. }
  8201. return lb_addr_load(p, v);
  8202. }
  8203. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  8204. lbValue map_key, lbValue map_value, Ast *node) {
  8205. map_type = base_type(map_type);
  8206. GB_ASSERT(map_type->kind == Type_Map);
  8207. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  8208. lbValue key = lb_gen_map_key(p, map_key, map_type->Map.key);
  8209. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  8210. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  8211. lb_addr_store(p, value_addr, v);
  8212. auto args = array_make<lbValue>(heap_allocator(), 4);
  8213. args[0] = h;
  8214. args[1] = key;
  8215. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  8216. args[3] = lb_emit_source_code_location(p, node);
  8217. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  8218. }
  8219. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  8220. expr = unparen_expr(expr);
  8221. switch (expr->kind) {
  8222. case_ast_node(i, Implicit, expr);
  8223. lbAddr v = {};
  8224. switch (i->kind) {
  8225. case Token_context:
  8226. v = lb_find_or_generate_context_ptr(p);
  8227. break;
  8228. }
  8229. GB_ASSERT(v.addr.value != nullptr);
  8230. return v;
  8231. case_end;
  8232. case_ast_node(i, Ident, expr);
  8233. if (is_blank_ident(expr)) {
  8234. lbAddr val = {};
  8235. return val;
  8236. }
  8237. String name = i->token.string;
  8238. Entity *e = entity_of_node(expr);
  8239. return lb_build_addr_from_entity(p, e, expr);
  8240. case_end;
  8241. case_ast_node(se, SelectorExpr, expr);
  8242. Ast *sel = unparen_expr(se->selector);
  8243. if (sel->kind == Ast_Ident) {
  8244. String selector = sel->Ident.token.string;
  8245. TypeAndValue tav = type_and_value_of_expr(se->expr);
  8246. if (tav.mode == Addressing_Invalid) {
  8247. // NOTE(bill): Imports
  8248. Entity *imp = entity_of_node(se->expr);
  8249. if (imp != nullptr) {
  8250. GB_ASSERT(imp->kind == Entity_ImportName);
  8251. }
  8252. return lb_build_addr(p, unparen_expr(se->selector));
  8253. }
  8254. Type *type = base_type(tav.type);
  8255. if (tav.mode == Addressing_Type) { // Addressing_Type
  8256. Selection sel = lookup_field(type, selector, true);
  8257. Entity *e = sel.entity;
  8258. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  8259. GB_ASSERT(e->flags & EntityFlag_TypeField);
  8260. String name = e->token.string;
  8261. /*if (name == "names") {
  8262. lbValue ti_ptr = lb_type_info(m, type);
  8263. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  8264. lbValue names_ptr = nullptr;
  8265. if (is_type_enum(type)) {
  8266. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  8267. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  8268. } else if (type->kind == Type_Struct) {
  8269. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  8270. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  8271. }
  8272. return ir_addr(names_ptr);
  8273. } else */{
  8274. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  8275. }
  8276. GB_PANIC("Unreachable");
  8277. }
  8278. Selection sel = lookup_field(type, selector, false);
  8279. GB_ASSERT(sel.entity != nullptr);
  8280. if (sel.entity->type->kind == Type_BitFieldValue) {
  8281. lbAddr addr = lb_build_addr(p, se->expr);
  8282. Type *bft = type_deref(lb_addr_type(addr));
  8283. if (sel.index.count == 1) {
  8284. GB_ASSERT(is_type_bit_field(bft));
  8285. i32 index = sel.index[0];
  8286. return lb_addr_bit_field(lb_addr_get_ptr(p, addr), index);
  8287. } else {
  8288. Selection s = sel;
  8289. s.index.count--;
  8290. i32 index = s.index[s.index.count-1];
  8291. lbValue a = lb_addr_get_ptr(p, addr);
  8292. a = lb_emit_deep_field_gep(p, a, s);
  8293. return lb_addr_bit_field(a, index);
  8294. }
  8295. } else {
  8296. lbAddr addr = lb_build_addr(p, se->expr);
  8297. if (addr.kind == lbAddr_Map) {
  8298. lbValue v = lb_addr_load(p, addr);
  8299. lbValue a = lb_address_from_load_or_generate_local(p, v);
  8300. a = lb_emit_deep_field_gep(p, a, sel);
  8301. return lb_addr(a);
  8302. } else if (addr.kind == lbAddr_Context) {
  8303. GB_ASSERT(sel.index.count > 0);
  8304. if (addr.ctx.sel.index.count >= 0) {
  8305. sel = selection_combine(addr.ctx.sel, sel);
  8306. }
  8307. addr.ctx.sel = sel;
  8308. addr.kind = lbAddr_Context;
  8309. return addr;
  8310. } else if (addr.kind == lbAddr_SoaVariable) {
  8311. lbValue index = addr.soa.index;
  8312. i32 first_index = sel.index[0];
  8313. Selection sub_sel = sel;
  8314. sub_sel.index.data += 1;
  8315. sub_sel.index.count -= 1;
  8316. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  8317. Type *t = base_type(type_deref(addr.addr.type));
  8318. GB_ASSERT(is_type_soa_struct(t));
  8319. // TODO(bill): Bounds check
  8320. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  8321. lbValue len = lb_soa_struct_len(p, addr.addr);
  8322. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  8323. }
  8324. lbValue item = {};
  8325. if (t->Struct.soa_kind == StructSoa_Fixed) {
  8326. item = lb_emit_array_ep(p, arr, index);
  8327. } else {
  8328. item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index));
  8329. }
  8330. if (sub_sel.index.count > 0) {
  8331. item = lb_emit_deep_field_gep(p, item, sub_sel);
  8332. }
  8333. return lb_addr(item);
  8334. }
  8335. lbValue a = lb_addr_get_ptr(p, addr);
  8336. a = lb_emit_deep_field_gep(p, a, sel);
  8337. return lb_addr(a);
  8338. }
  8339. } else {
  8340. GB_PANIC("Unsupported selector expression");
  8341. }
  8342. case_end;
  8343. case_ast_node(se, SelectorCallExpr, expr);
  8344. GB_ASSERT(se->modified_call);
  8345. TypeAndValue tav = type_and_value_of_expr(expr);
  8346. GB_ASSERT(tav.mode != Addressing_Invalid);
  8347. return lb_build_addr(p, se->call);
  8348. case_end;
  8349. case_ast_node(ta, TypeAssertion, expr);
  8350. gbAllocator a = heap_allocator();
  8351. TokenPos pos = ast_token(expr).pos;
  8352. lbValue e = lb_build_expr(p, ta->expr);
  8353. Type *t = type_deref(e.type);
  8354. if (is_type_union(t)) {
  8355. Type *type = type_of_expr(expr);
  8356. lbAddr v = lb_add_local_generated(p, type, false);
  8357. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  8358. return v;
  8359. } else if (is_type_any(t)) {
  8360. Type *type = type_of_expr(expr);
  8361. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  8362. } else {
  8363. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8364. }
  8365. case_end;
  8366. case_ast_node(ue, UnaryExpr, expr);
  8367. switch (ue->op.kind) {
  8368. case Token_And: {
  8369. return lb_build_addr(p, ue->expr);
  8370. }
  8371. default:
  8372. GB_PANIC("Invalid unary expression for lb_build_addr");
  8373. }
  8374. case_end;
  8375. case_ast_node(be, BinaryExpr, expr);
  8376. lbValue v = lb_build_expr(p, expr);
  8377. Type *t = v.type;
  8378. if (is_type_pointer(t)) {
  8379. return lb_addr(v);
  8380. }
  8381. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  8382. case_end;
  8383. case_ast_node(ie, IndexExpr, expr);
  8384. Type *t = base_type(type_of_expr(ie->expr));
  8385. gbAllocator a = heap_allocator();
  8386. bool deref = is_type_pointer(t);
  8387. t = base_type(type_deref(t));
  8388. if (is_type_soa_struct(t)) {
  8389. // SOA STRUCTURES!!!!
  8390. lbValue val = lb_build_addr_ptr(p, ie->expr);
  8391. if (deref) {
  8392. val = lb_emit_load(p, val);
  8393. }
  8394. lbValue index = lb_build_expr(p, ie->index);
  8395. return lb_addr_soa_variable(val, index, ie->index);
  8396. }
  8397. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  8398. // SOA Structures for slices/dynamic arrays
  8399. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  8400. lbValue field = lb_build_expr(p, ie->expr);
  8401. lbValue index = lb_build_expr(p, ie->index);
  8402. if (!build_context.no_bounds_check) {
  8403. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  8404. // GB_ASSERT(LLVMIsALoadInst(field.value));
  8405. // lbValue a = {};
  8406. // a.value = LLVMGetOperand(field.value, 0);
  8407. // a.type = alloc_type_pointer(field.type);
  8408. // irInstr *b = &a->Instr;
  8409. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  8410. // lbValue base_struct = b->StructElementPtr.address;
  8411. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  8412. // lbValue len = ir_soa_struct_len(p, base_struct);
  8413. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8414. }
  8415. lbValue val = lb_emit_ptr_offset(p, field, index);
  8416. return lb_addr(val);
  8417. }
  8418. if (!is_type_indexable(t)) {
  8419. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  8420. if (found != nullptr) {
  8421. if (found->kind == TypeAtomOp_index_get) {
  8422. return lb_build_addr(p, found->node);
  8423. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  8424. return lb_addr(lb_build_expr(p, found->node));
  8425. } else if (found->kind == TypeAtomOp_index_set) {
  8426. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  8427. if (deref) {
  8428. ptr = lb_emit_load(p, ptr);
  8429. }
  8430. lbAddr addr = {lbAddr_AtomOp_index_set};
  8431. addr.addr = ptr;
  8432. addr.index_set.index = lb_build_expr(p, ie->index);
  8433. addr.index_set.node = found->node;
  8434. return addr;
  8435. }
  8436. }
  8437. }
  8438. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  8439. if (is_type_map(t)) {
  8440. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  8441. if (deref) {
  8442. map_val = lb_emit_load(p, map_val);
  8443. }
  8444. lbValue key = lb_build_expr(p, ie->index);
  8445. key = lb_emit_conv(p, key, t->Map.key);
  8446. Type *result_type = type_of_expr(expr);
  8447. return lb_addr_map(map_val, key, t, result_type);
  8448. }
  8449. switch (t->kind) {
  8450. case Type_Array: {
  8451. lbValue array = {};
  8452. array = lb_build_addr_ptr(p, ie->expr);
  8453. if (deref) {
  8454. array = lb_emit_load(p, array);
  8455. }
  8456. lbValue index = lb_build_expr(p, ie->index);
  8457. index = lb_emit_conv(p, index, t_int);
  8458. lbValue elem = lb_emit_array_ep(p, array, index);
  8459. auto index_tv = type_and_value_of_expr(ie->index);
  8460. if (index_tv.mode != Addressing_Constant) {
  8461. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  8462. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8463. }
  8464. return lb_addr(elem);
  8465. }
  8466. case Type_EnumeratedArray: {
  8467. lbValue array = {};
  8468. array = lb_build_addr_ptr(p, ie->expr);
  8469. if (deref) {
  8470. array = lb_emit_load(p, array);
  8471. }
  8472. Type *index_type = t->EnumeratedArray.index;
  8473. auto index_tv = type_and_value_of_expr(ie->index);
  8474. lbValue index = {};
  8475. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  8476. if (index_tv.mode == Addressing_Constant) {
  8477. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  8478. index = lb_const_value(p->module, index_type, idx);
  8479. } else {
  8480. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8481. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  8482. }
  8483. } else {
  8484. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8485. }
  8486. lbValue elem = lb_emit_array_ep(p, array, index);
  8487. if (index_tv.mode != Addressing_Constant) {
  8488. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  8489. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8490. }
  8491. return lb_addr(elem);
  8492. }
  8493. case Type_Slice: {
  8494. lbValue slice = {};
  8495. slice = lb_build_expr(p, ie->expr);
  8496. if (deref) {
  8497. slice = lb_emit_load(p, slice);
  8498. }
  8499. lbValue elem = lb_slice_elem(p, slice);
  8500. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8501. lbValue len = lb_slice_len(p, slice);
  8502. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8503. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8504. return lb_addr(v);
  8505. }
  8506. case Type_RelativeSlice: {
  8507. lbAddr slice_addr = {};
  8508. if (deref) {
  8509. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  8510. } else {
  8511. slice_addr = lb_build_addr(p, ie->expr);
  8512. }
  8513. lbValue slice = lb_addr_load(p, slice_addr);
  8514. lbValue elem = lb_slice_elem(p, slice);
  8515. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8516. lbValue len = lb_slice_len(p, slice);
  8517. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8518. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8519. return lb_addr(v);
  8520. }
  8521. case Type_DynamicArray: {
  8522. lbValue dynamic_array = {};
  8523. dynamic_array = lb_build_expr(p, ie->expr);
  8524. if (deref) {
  8525. dynamic_array = lb_emit_load(p, dynamic_array);
  8526. }
  8527. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  8528. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  8529. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8530. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8531. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8532. return lb_addr(v);
  8533. }
  8534. case Type_Basic: { // Basic_string
  8535. lbValue str;
  8536. lbValue elem;
  8537. lbValue len;
  8538. lbValue index;
  8539. str = lb_build_expr(p, ie->expr);
  8540. if (deref) {
  8541. str = lb_emit_load(p, str);
  8542. }
  8543. elem = lb_string_elem(p, str);
  8544. len = lb_string_len(p, str);
  8545. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8546. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8547. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  8548. }
  8549. }
  8550. case_end;
  8551. case_ast_node(se, SliceExpr, expr);
  8552. gbAllocator a = heap_allocator();
  8553. lbValue low = lb_const_int(p->module, t_int, 0);
  8554. lbValue high = {};
  8555. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  8556. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  8557. bool no_indices = se->low == nullptr && se->high == nullptr;
  8558. {
  8559. Type *type = base_type(type_of_expr(se->expr));
  8560. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  8561. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  8562. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  8563. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  8564. if (found) {
  8565. lbValue base = lb_build_expr(p, found->node);
  8566. Type *slice_type = base.type;
  8567. lbValue len = lb_slice_len(p, base);
  8568. if (high.value == nullptr) high = len;
  8569. if (!no_indices) {
  8570. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8571. }
  8572. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  8573. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8574. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8575. lb_fill_slice(p, slice, elem, new_len);
  8576. return slice;
  8577. }
  8578. }
  8579. }
  8580. }
  8581. lbAddr addr = lb_build_addr(p, se->expr);
  8582. lbValue base = lb_addr_load(p, addr);
  8583. Type *type = base_type(base.type);
  8584. if (is_type_pointer(type)) {
  8585. type = base_type(type_deref(type));
  8586. addr = lb_addr(base);
  8587. base = lb_addr_load(p, addr);
  8588. }
  8589. switch (type->kind) {
  8590. case Type_Slice: {
  8591. Type *slice_type = type;
  8592. lbValue len = lb_slice_len(p, base);
  8593. if (high.value == nullptr) high = len;
  8594. if (!no_indices) {
  8595. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8596. }
  8597. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  8598. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8599. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8600. lb_fill_slice(p, slice, elem, new_len);
  8601. return slice;
  8602. }
  8603. case Type_RelativeSlice:
  8604. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  8605. break;
  8606. case Type_DynamicArray: {
  8607. Type *elem_type = type->DynamicArray.elem;
  8608. Type *slice_type = alloc_type_slice(elem_type);
  8609. lbValue len = lb_dynamic_array_len(p, base);
  8610. if (high.value == nullptr) high = len;
  8611. if (!no_indices) {
  8612. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8613. }
  8614. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  8615. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8616. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8617. lb_fill_slice(p, slice, elem, new_len);
  8618. return slice;
  8619. }
  8620. case Type_Array: {
  8621. Type *slice_type = alloc_type_slice(type->Array.elem);
  8622. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  8623. if (high.value == nullptr) high = len;
  8624. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  8625. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  8626. if (!low_const || !high_const) {
  8627. if (!no_indices) {
  8628. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8629. }
  8630. }
  8631. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  8632. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8633. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8634. lb_fill_slice(p, slice, elem, new_len);
  8635. return slice;
  8636. }
  8637. case Type_Basic: {
  8638. GB_ASSERT(type == t_string);
  8639. lbValue len = lb_string_len(p, base);
  8640. if (high.value == nullptr) high = len;
  8641. if (!no_indices) {
  8642. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8643. }
  8644. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  8645. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8646. lbAddr str = lb_add_local_generated(p, t_string, false);
  8647. lb_fill_string(p, str, elem, new_len);
  8648. return str;
  8649. }
  8650. case Type_Struct:
  8651. if (is_type_soa_struct(type)) {
  8652. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  8653. if (high.value == nullptr) high = len;
  8654. if (!no_indices) {
  8655. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8656. }
  8657. #if 1
  8658. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  8659. if (type->Struct.soa_kind == StructSoa_Fixed) {
  8660. i32 field_count = cast(i32)type->Struct.fields.count;
  8661. for (i32 i = 0; i < field_count; i++) {
  8662. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  8663. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  8664. field_src = lb_emit_array_ep(p, field_src, low);
  8665. lb_emit_store(p, field_dst, field_src);
  8666. }
  8667. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  8668. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8669. lb_emit_store(p, len_dst, new_len);
  8670. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  8671. if (no_indices) {
  8672. lb_addr_store(p, dst, base);
  8673. } else {
  8674. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  8675. for (i32 i = 0; i < field_count; i++) {
  8676. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  8677. lbValue field_src = lb_emit_struct_ev(p, base, i);
  8678. field_src = lb_emit_ptr_offset(p, field_src, low);
  8679. lb_emit_store(p, field_dst, field_src);
  8680. }
  8681. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  8682. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8683. lb_emit_store(p, len_dst, new_len);
  8684. }
  8685. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  8686. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  8687. for (i32 i = 0; i < field_count; i++) {
  8688. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  8689. lbValue field_src = lb_emit_struct_ev(p, base, i);
  8690. field_src = lb_emit_ptr_offset(p, field_src, low);
  8691. lb_emit_store(p, field_dst, field_src);
  8692. }
  8693. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  8694. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8695. lb_emit_store(p, len_dst, new_len);
  8696. }
  8697. return dst;
  8698. #endif
  8699. }
  8700. break;
  8701. }
  8702. GB_PANIC("Unknown slicable type");
  8703. case_end;
  8704. case_ast_node(de, DerefExpr, expr);
  8705. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  8706. lbAddr addr = lb_build_addr(p, de->expr);
  8707. addr.relative.deref = true;
  8708. return addr;
  8709. }
  8710. lbValue addr = lb_build_expr(p, de->expr);
  8711. return lb_addr(addr);
  8712. case_end;
  8713. case_ast_node(ce, CallExpr, expr);
  8714. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  8715. lbValue e = lb_build_expr(p, expr);
  8716. lbAddr v = lb_add_local_generated(p, e.type, false);
  8717. lb_addr_store(p, v, e);
  8718. return v;
  8719. case_end;
  8720. case_ast_node(cl, CompoundLit, expr);
  8721. Type *type = type_of_expr(expr);
  8722. Type *bt = base_type(type);
  8723. lbAddr v = lb_add_local_generated(p, type, true);
  8724. Type *et = nullptr;
  8725. switch (bt->kind) {
  8726. case Type_Array: et = bt->Array.elem; break;
  8727. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  8728. case Type_Slice: et = bt->Slice.elem; break;
  8729. case Type_BitSet: et = bt->BitSet.elem; break;
  8730. case Type_SimdVector: et = bt->SimdVector.elem; break;
  8731. }
  8732. String proc_name = {};
  8733. if (p->entity) {
  8734. proc_name = p->entity->token.string;
  8735. }
  8736. TokenPos pos = ast_token(expr).pos;
  8737. switch (bt->kind) {
  8738. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  8739. case Type_Struct: {
  8740. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  8741. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  8742. bool is_raw_union = is_type_raw_union(bt);
  8743. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  8744. TypeStruct *st = &bt->Struct;
  8745. if (cl->elems.count > 0) {
  8746. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  8747. for_array(field_index, cl->elems) {
  8748. Ast *elem = cl->elems[field_index];
  8749. lbValue field_expr = {};
  8750. Entity *field = nullptr;
  8751. isize index = field_index;
  8752. if (elem->kind == Ast_FieldValue) {
  8753. ast_node(fv, FieldValue, elem);
  8754. String name = fv->field->Ident.token.string;
  8755. Selection sel = lookup_field(bt, name, false);
  8756. index = sel.index[0];
  8757. elem = fv->value;
  8758. TypeAndValue tav = type_and_value_of_expr(elem);
  8759. } else {
  8760. TypeAndValue tav = type_and_value_of_expr(elem);
  8761. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  8762. index = sel.index[0];
  8763. }
  8764. field = st->fields[index];
  8765. Type *ft = field->type;
  8766. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  8767. continue;
  8768. }
  8769. field_expr = lb_build_expr(p, elem);
  8770. Type *fet = field_expr.type;
  8771. GB_ASSERT(fet->kind != Type_Tuple);
  8772. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  8773. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  8774. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  8775. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  8776. lb_emit_store_union_variant(p, gep, field_expr, fet);
  8777. } else {
  8778. lbValue fv = lb_emit_conv(p, field_expr, ft);
  8779. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  8780. lb_emit_store(p, gep, fv);
  8781. }
  8782. }
  8783. }
  8784. break;
  8785. }
  8786. case Type_Map: {
  8787. if (cl->elems.count == 0) {
  8788. break;
  8789. }
  8790. gbAllocator a = heap_allocator();
  8791. {
  8792. auto args = array_make<lbValue>(a, 3);
  8793. args[0] = lb_gen_map_header(p, v.addr, type);
  8794. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  8795. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  8796. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  8797. }
  8798. for_array(field_index, cl->elems) {
  8799. Ast *elem = cl->elems[field_index];
  8800. ast_node(fv, FieldValue, elem);
  8801. lbValue key = lb_build_expr(p, fv->field);
  8802. lbValue value = lb_build_expr(p, fv->value);
  8803. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  8804. }
  8805. break;
  8806. }
  8807. case Type_Array: {
  8808. if (cl->elems.count > 0) {
  8809. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  8810. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  8811. defer (array_free(&temp_data));
  8812. // NOTE(bill): Separate value, gep, store into their own chunks
  8813. for_array(i, cl->elems) {
  8814. Ast *elem = cl->elems[i];
  8815. if (elem->kind == Ast_FieldValue) {
  8816. ast_node(fv, FieldValue, elem);
  8817. if (lb_is_elem_const(fv->value, et)) {
  8818. continue;
  8819. }
  8820. if (is_ast_range(fv->field)) {
  8821. ast_node(ie, BinaryExpr, fv->field);
  8822. TypeAndValue lo_tav = ie->left->tav;
  8823. TypeAndValue hi_tav = ie->right->tav;
  8824. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  8825. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  8826. TokenKind op = ie->op.kind;
  8827. i64 lo = exact_value_to_i64(lo_tav.value);
  8828. i64 hi = exact_value_to_i64(hi_tav.value);
  8829. if (op == Token_Ellipsis) {
  8830. hi += 1;
  8831. }
  8832. lbValue value = lb_build_expr(p, fv->value);
  8833. for (i64 k = lo; k < hi; k++) {
  8834. lbCompoundLitElemTempData data = {};
  8835. data.value = value;
  8836. data.elem_index = cast(i32)k;
  8837. array_add(&temp_data, data);
  8838. }
  8839. } else {
  8840. auto tav = fv->field->tav;
  8841. GB_ASSERT(tav.mode == Addressing_Constant);
  8842. i64 index = exact_value_to_i64(tav.value);
  8843. lbValue value = lb_build_expr(p, fv->value);
  8844. lbCompoundLitElemTempData data = {};
  8845. data.value = lb_emit_conv(p, value, et);
  8846. data.expr = fv->value;
  8847. data.elem_index = cast(i32)index;
  8848. array_add(&temp_data, data);
  8849. }
  8850. } else {
  8851. if (lb_is_elem_const(elem, et)) {
  8852. continue;
  8853. }
  8854. lbCompoundLitElemTempData data = {};
  8855. data.expr = elem;
  8856. data.elem_index = cast(i32)i;
  8857. array_add(&temp_data, data);
  8858. }
  8859. }
  8860. for_array(i, temp_data) {
  8861. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  8862. }
  8863. for_array(i, temp_data) {
  8864. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  8865. auto return_ptr_hint_value = p->return_ptr_hint_value;
  8866. auto return_ptr_hint_used = p->return_ptr_hint_used;
  8867. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  8868. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  8869. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  8870. lbValue field_expr = temp_data[i].value;
  8871. Ast *expr = temp_data[i].expr;
  8872. p->return_ptr_hint_value = temp_data[i].gep;
  8873. p->return_ptr_hint_ast = unparen_expr(expr);
  8874. if (field_expr.value == nullptr) {
  8875. field_expr = lb_build_expr(p, expr);
  8876. }
  8877. Type *t = field_expr.type;
  8878. GB_ASSERT(t->kind != Type_Tuple);
  8879. lbValue ev = lb_emit_conv(p, field_expr, et);
  8880. if (!p->return_ptr_hint_used) {
  8881. temp_data[i].value = ev;
  8882. }
  8883. }
  8884. for_array(i, temp_data) {
  8885. if (temp_data[i].value.value != nullptr) {
  8886. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  8887. }
  8888. }
  8889. }
  8890. break;
  8891. }
  8892. case Type_EnumeratedArray: {
  8893. if (cl->elems.count > 0) {
  8894. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  8895. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  8896. defer (array_free(&temp_data));
  8897. // NOTE(bill): Separate value, gep, store into their own chunks
  8898. for_array(i, cl->elems) {
  8899. Ast *elem = cl->elems[i];
  8900. if (elem->kind == Ast_FieldValue) {
  8901. ast_node(fv, FieldValue, elem);
  8902. if (lb_is_elem_const(fv->value, et)) {
  8903. continue;
  8904. }
  8905. if (is_ast_range(fv->field)) {
  8906. ast_node(ie, BinaryExpr, fv->field);
  8907. TypeAndValue lo_tav = ie->left->tav;
  8908. TypeAndValue hi_tav = ie->right->tav;
  8909. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  8910. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  8911. TokenKind op = ie->op.kind;
  8912. i64 lo = exact_value_to_i64(lo_tav.value);
  8913. i64 hi = exact_value_to_i64(hi_tav.value);
  8914. if (op == Token_Ellipsis) {
  8915. hi += 1;
  8916. }
  8917. lbValue value = lb_build_expr(p, fv->value);
  8918. for (i64 k = lo; k < hi; k++) {
  8919. lbCompoundLitElemTempData data = {};
  8920. data.value = value;
  8921. data.elem_index = cast(i32)k;
  8922. array_add(&temp_data, data);
  8923. }
  8924. } else {
  8925. auto tav = fv->field->tav;
  8926. GB_ASSERT(tav.mode == Addressing_Constant);
  8927. i64 index = exact_value_to_i64(tav.value);
  8928. lbValue value = lb_build_expr(p, fv->value);
  8929. lbCompoundLitElemTempData data = {};
  8930. data.value = lb_emit_conv(p, value, et);
  8931. data.expr = fv->value;
  8932. data.elem_index = cast(i32)index;
  8933. array_add(&temp_data, data);
  8934. }
  8935. } else {
  8936. if (lb_is_elem_const(elem, et)) {
  8937. continue;
  8938. }
  8939. lbCompoundLitElemTempData data = {};
  8940. data.expr = elem;
  8941. data.elem_index = cast(i32)i;
  8942. array_add(&temp_data, data);
  8943. }
  8944. }
  8945. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  8946. for_array(i, temp_data) {
  8947. i32 index = temp_data[i].elem_index - index_offset;
  8948. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  8949. }
  8950. for_array(i, temp_data) {
  8951. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  8952. auto return_ptr_hint_value = p->return_ptr_hint_value;
  8953. auto return_ptr_hint_used = p->return_ptr_hint_used;
  8954. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  8955. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  8956. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  8957. lbValue field_expr = temp_data[i].value;
  8958. Ast *expr = temp_data[i].expr;
  8959. p->return_ptr_hint_value = temp_data[i].gep;
  8960. p->return_ptr_hint_ast = unparen_expr(expr);
  8961. if (field_expr.value == nullptr) {
  8962. field_expr = lb_build_expr(p, expr);
  8963. }
  8964. Type *t = field_expr.type;
  8965. GB_ASSERT(t->kind != Type_Tuple);
  8966. lbValue ev = lb_emit_conv(p, field_expr, et);
  8967. if (!p->return_ptr_hint_used) {
  8968. temp_data[i].value = ev;
  8969. }
  8970. }
  8971. for_array(i, temp_data) {
  8972. if (temp_data[i].value.value != nullptr) {
  8973. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  8974. }
  8975. }
  8976. }
  8977. break;
  8978. }
  8979. case Type_Slice: {
  8980. if (cl->elems.count > 0) {
  8981. Type *elem_type = bt->Slice.elem;
  8982. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  8983. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  8984. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  8985. lbValue data = lb_slice_elem(p, slice);
  8986. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  8987. defer (array_free(&temp_data));
  8988. for_array(i, cl->elems) {
  8989. Ast *elem = cl->elems[i];
  8990. if (elem->kind == Ast_FieldValue) {
  8991. ast_node(fv, FieldValue, elem);
  8992. if (lb_is_elem_const(fv->value, et)) {
  8993. continue;
  8994. }
  8995. if (is_ast_range(fv->field)) {
  8996. ast_node(ie, BinaryExpr, fv->field);
  8997. TypeAndValue lo_tav = ie->left->tav;
  8998. TypeAndValue hi_tav = ie->right->tav;
  8999. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9000. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9001. TokenKind op = ie->op.kind;
  9002. i64 lo = exact_value_to_i64(lo_tav.value);
  9003. i64 hi = exact_value_to_i64(hi_tav.value);
  9004. if (op == Token_Ellipsis) {
  9005. hi += 1;
  9006. }
  9007. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9008. for (i64 k = lo; k < hi; k++) {
  9009. lbCompoundLitElemTempData data = {};
  9010. data.value = value;
  9011. data.elem_index = cast(i32)k;
  9012. array_add(&temp_data, data);
  9013. }
  9014. } else {
  9015. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9016. i64 index = exact_value_to_i64(fv->field->tav.value);
  9017. lbValue field_expr = lb_build_expr(p, fv->value);
  9018. GB_ASSERT(!is_type_tuple(field_expr.type));
  9019. lbValue ev = lb_emit_conv(p, field_expr, et);
  9020. lbCompoundLitElemTempData data = {};
  9021. data.value = ev;
  9022. data.elem_index = cast(i32)index;
  9023. array_add(&temp_data, data);
  9024. }
  9025. } else {
  9026. if (lb_is_elem_const(elem, et)) {
  9027. continue;
  9028. }
  9029. lbValue field_expr = lb_build_expr(p, elem);
  9030. GB_ASSERT(!is_type_tuple(field_expr.type));
  9031. lbValue ev = lb_emit_conv(p, field_expr, et);
  9032. lbCompoundLitElemTempData data = {};
  9033. data.value = ev;
  9034. data.elem_index = cast(i32)i;
  9035. array_add(&temp_data, data);
  9036. }
  9037. }
  9038. for_array(i, temp_data) {
  9039. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  9040. }
  9041. for_array(i, temp_data) {
  9042. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9043. }
  9044. {
  9045. lbValue count = {};
  9046. count.type = t_int;
  9047. if (lb_is_const(slice)) {
  9048. unsigned indices[1] = {1};
  9049. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  9050. } else {
  9051. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  9052. }
  9053. lb_fill_slice(p, v, data, count);
  9054. }
  9055. }
  9056. break;
  9057. }
  9058. case Type_DynamicArray: {
  9059. if (cl->elems.count == 0) {
  9060. break;
  9061. }
  9062. Type *et = bt->DynamicArray.elem;
  9063. gbAllocator a = heap_allocator();
  9064. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  9065. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  9066. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  9067. {
  9068. auto args = array_make<lbValue>(a, 5);
  9069. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  9070. args[1] = size;
  9071. args[2] = align;
  9072. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  9073. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  9074. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  9075. }
  9076. lbValue items = lb_generate_local_array(p, et, item_count);
  9077. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  9078. for_array(i, cl->elems) {
  9079. Ast *elem = cl->elems[i];
  9080. if (elem->kind == Ast_FieldValue) {
  9081. ast_node(fv, FieldValue, elem);
  9082. if (is_ast_range(fv->field)) {
  9083. ast_node(ie, BinaryExpr, fv->field);
  9084. TypeAndValue lo_tav = ie->left->tav;
  9085. TypeAndValue hi_tav = ie->right->tav;
  9086. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9087. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9088. TokenKind op = ie->op.kind;
  9089. i64 lo = exact_value_to_i64(lo_tav.value);
  9090. i64 hi = exact_value_to_i64(hi_tav.value);
  9091. if (op == Token_Ellipsis) {
  9092. hi += 1;
  9093. }
  9094. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9095. for (i64 k = lo; k < hi; k++) {
  9096. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  9097. lb_emit_store(p, ep, value);
  9098. }
  9099. } else {
  9100. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9101. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  9102. lbValue ev = lb_build_expr(p, fv->value);
  9103. lbValue value = lb_emit_conv(p, ev, et);
  9104. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  9105. lb_emit_store(p, ep, value);
  9106. }
  9107. } else {
  9108. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  9109. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  9110. lb_emit_store(p, ep, value);
  9111. }
  9112. }
  9113. {
  9114. auto args = array_make<lbValue>(a, 6);
  9115. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  9116. args[1] = size;
  9117. args[2] = align;
  9118. args[3] = lb_emit_conv(p, items, t_rawptr);
  9119. args[4] = lb_const_int(p->module, t_int, item_count);
  9120. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  9121. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  9122. }
  9123. break;
  9124. }
  9125. case Type_Basic: {
  9126. GB_ASSERT(is_type_any(bt));
  9127. if (cl->elems.count > 0) {
  9128. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9129. String field_names[2] = {
  9130. str_lit("data"),
  9131. str_lit("id"),
  9132. };
  9133. Type *field_types[2] = {
  9134. t_rawptr,
  9135. t_typeid,
  9136. };
  9137. for_array(field_index, cl->elems) {
  9138. Ast *elem = cl->elems[field_index];
  9139. lbValue field_expr = {};
  9140. isize index = field_index;
  9141. if (elem->kind == Ast_FieldValue) {
  9142. ast_node(fv, FieldValue, elem);
  9143. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  9144. index = sel.index[0];
  9145. elem = fv->value;
  9146. } else {
  9147. TypeAndValue tav = type_and_value_of_expr(elem);
  9148. Selection sel = lookup_field(bt, field_names[field_index], false);
  9149. index = sel.index[0];
  9150. }
  9151. field_expr = lb_build_expr(p, elem);
  9152. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  9153. Type *ft = field_types[index];
  9154. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9155. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9156. lb_emit_store(p, gep, fv);
  9157. }
  9158. }
  9159. break;
  9160. }
  9161. case Type_BitSet: {
  9162. i64 sz = type_size_of(type);
  9163. if (cl->elems.count > 0 && sz > 0) {
  9164. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9165. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  9166. for_array(i, cl->elems) {
  9167. Ast *elem = cl->elems[i];
  9168. GB_ASSERT(elem->kind != Ast_FieldValue);
  9169. if (lb_is_elem_const(elem, et)) {
  9170. continue;
  9171. }
  9172. lbValue expr = lb_build_expr(p, elem);
  9173. GB_ASSERT(expr.type->kind != Type_Tuple);
  9174. Type *it = bit_set_to_int(bt);
  9175. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  9176. lbValue e = lb_emit_conv(p, expr, it);
  9177. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  9178. e = lb_emit_arith(p, Token_Shl, one, e, it);
  9179. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  9180. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  9181. new_value = lb_emit_transmute(p, new_value, type);
  9182. lb_addr_store(p, v, new_value);
  9183. }
  9184. }
  9185. break;
  9186. }
  9187. }
  9188. return v;
  9189. case_end;
  9190. case_ast_node(tc, TypeCast, expr);
  9191. Type *type = type_of_expr(expr);
  9192. lbValue x = lb_build_expr(p, tc->expr);
  9193. lbValue e = {};
  9194. switch (tc->token.kind) {
  9195. case Token_cast:
  9196. e = lb_emit_conv(p, x, type);
  9197. break;
  9198. case Token_transmute:
  9199. e = lb_emit_transmute(p, x, type);
  9200. break;
  9201. default:
  9202. GB_PANIC("Invalid AST TypeCast");
  9203. }
  9204. lbAddr v = lb_add_local_generated(p, type, false);
  9205. lb_addr_store(p, v, e);
  9206. return v;
  9207. case_end;
  9208. case_ast_node(ac, AutoCast, expr);
  9209. return lb_build_addr(p, ac->expr);
  9210. case_end;
  9211. }
  9212. TokenPos token_pos = ast_token(expr).pos;
  9213. GB_PANIC("Unexpected address expression\n"
  9214. "\tAst: %.*s @ "
  9215. "%.*s(%td:%td)\n",
  9216. LIT(ast_strings[expr->kind]),
  9217. LIT(token_pos.file), token_pos.line, token_pos.column);
  9218. return {};
  9219. }
  9220. void lb_init_module(lbModule *m, Checker *c) {
  9221. m->info = &c->info;
  9222. m->ctx = LLVMGetGlobalContext();
  9223. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  9224. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  9225. m->state_flags = 0;
  9226. m->state_flags |= StateFlag_bounds_check;
  9227. gb_mutex_init(&m->mutex);
  9228. gbAllocator a = heap_allocator();
  9229. map_init(&m->types, a);
  9230. map_init(&m->values, a);
  9231. string_map_init(&m->members, a);
  9232. map_init(&m->procedure_values, a);
  9233. string_map_init(&m->procedures, a);
  9234. string_map_init(&m->const_strings, a);
  9235. map_init(&m->anonymous_proc_lits, a);
  9236. array_init(&m->procedures_to_generate, a);
  9237. array_init(&m->foreign_library_paths, a);
  9238. map_init(&m->debug_values, a);
  9239. }
  9240. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  9241. if (global_error_collector.count != 0) {
  9242. return false;
  9243. }
  9244. isize tc = c->parser->total_token_count;
  9245. if (tc < 2) {
  9246. return false;
  9247. }
  9248. String init_fullpath = c->parser->init_fullpath;
  9249. if (build_context.out_filepath.len == 0) {
  9250. gen->output_name = remove_directory_from_path(init_fullpath);
  9251. gen->output_name = remove_extension_from_path(gen->output_name);
  9252. gen->output_name = string_trim_whitespace(gen->output_name);
  9253. if (gen->output_name.len == 0) {
  9254. gen->output_name = c->info.init_scope->pkg->name;
  9255. }
  9256. gen->output_base = gen->output_name;
  9257. } else {
  9258. gen->output_name = build_context.out_filepath;
  9259. gen->output_name = string_trim_whitespace(gen->output_name);
  9260. if (gen->output_name.len == 0) {
  9261. gen->output_name = c->info.init_scope->pkg->name;
  9262. }
  9263. isize pos = string_extension_position(gen->output_name);
  9264. if (pos < 0) {
  9265. gen->output_base = gen->output_name;
  9266. } else {
  9267. gen->output_base = substring(gen->output_name, 0, pos);
  9268. }
  9269. }
  9270. gbAllocator ha = heap_allocator();
  9271. array_init(&gen->output_object_paths, ha);
  9272. gen->output_base = path_to_full_path(ha, gen->output_base);
  9273. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  9274. output_file_path = gb_string_appendc(output_file_path, ".obj");
  9275. defer (gb_string_free(output_file_path));
  9276. gen->info = &c->info;
  9277. lb_init_module(&gen->module, c);
  9278. return true;
  9279. }
  9280. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  9281. GB_ASSERT(type != nullptr);
  9282. type = default_type(type);
  9283. isize max_len = 7+8+1;
  9284. u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len);
  9285. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  9286. m->global_generated_index++;
  9287. String name = make_string(str, len-1);
  9288. Scope *scope = nullptr;
  9289. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  9290. lbValue g = {};
  9291. g.type = alloc_type_pointer(type);
  9292. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  9293. if (value.value != nullptr) {
  9294. GB_ASSERT(LLVMIsConstant(value.value));
  9295. LLVMSetInitializer(g.value, value.value);
  9296. } else {
  9297. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  9298. }
  9299. lb_add_entity(m, e, g);
  9300. lb_add_member(m, name, g);
  9301. return lb_addr(g);
  9302. }
  9303. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  9304. AstPackage *p = m->info->runtime_package;
  9305. Entity *e = scope_lookup_current(p->scope, name);
  9306. lbValue *found = map_get(&m->values, hash_entity(e));
  9307. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  9308. lbValue value = *found;
  9309. return value;
  9310. }
  9311. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  9312. i32 index = cast(i32)lb_type_info_index(m->info, type);
  9313. GB_ASSERT(index >= 0);
  9314. // gb_printf_err("%d %s\n", index, type_to_string(type));
  9315. LLVMValueRef indices[2] = {
  9316. LLVMConstInt(lb_type(m, t_int), 0, false),
  9317. LLVMConstInt(lb_type(m, t_int), index, false),
  9318. };
  9319. lbValue res = {};
  9320. res.type = t_type_info_ptr;
  9321. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  9322. return res;
  9323. }
  9324. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  9325. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  9326. lb_global_type_info_member_types_index += cast(i32)count;
  9327. return offset;
  9328. }
  9329. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  9330. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  9331. lb_global_type_info_member_names_index += cast(i32)count;
  9332. return offset;
  9333. }
  9334. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  9335. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  9336. lb_global_type_info_member_offsets_index += cast(i32)count;
  9337. return offset;
  9338. }
  9339. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  9340. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  9341. lb_global_type_info_member_usings_index += cast(i32)count;
  9342. return offset;
  9343. }
  9344. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  9345. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  9346. lb_global_type_info_member_tags_index += cast(i32)count;
  9347. return offset;
  9348. }
  9349. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  9350. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  9351. return lb_addr_get_ptr(p, addr);
  9352. }
  9353. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  9354. gbAllocator a = heap_allocator();
  9355. Token token = {Token_Ident};
  9356. isize name_len = prefix.len + 1 + 20;
  9357. auto suffix_id = cast(unsigned long long)id;
  9358. char *text = gb_alloc_array(a, char, name_len+1);
  9359. gb_snprintf(text, name_len,
  9360. "%.*s-%llu", LIT(prefix), suffix_id);
  9361. text[name_len] = 0;
  9362. String s = make_string_c(text);
  9363. Type *t = alloc_type_array(elem_type, count);
  9364. lbValue g = {};
  9365. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  9366. g.type = alloc_type_pointer(t);
  9367. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  9368. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  9369. string_map_set(&m->members, s, g);
  9370. return g;
  9371. }
  9372. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  9373. lbModule *m = p->module;
  9374. LLVMContextRef ctx = m->ctx;
  9375. gbAllocator a = heap_allocator();
  9376. CheckerInfo *info = m->info;
  9377. {
  9378. // NOTE(bill): Set the type_table slice with the global backing array
  9379. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  9380. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  9381. GB_ASSERT(is_type_array(type));
  9382. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  9383. LLVMValueRef values[2] = {
  9384. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  9385. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  9386. };
  9387. LLVMValueRef slice = LLVMConstStructInContext(ctx, values, gb_count_of(values), false);
  9388. LLVMSetInitializer(global_type_table.value, slice);
  9389. }
  9390. // Useful types
  9391. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  9392. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  9393. i32 type_info_member_types_index = 0;
  9394. i32 type_info_member_names_index = 0;
  9395. i32 type_info_member_offsets_index = 0;
  9396. for_array(type_info_type_index, info->type_info_types) {
  9397. Type *t = info->type_info_types[type_info_type_index];
  9398. t = default_type(t);
  9399. if (t == t_invalid) {
  9400. continue;
  9401. }
  9402. isize entry_index = lb_type_info_index(info, t, false);
  9403. if (entry_index <= 0) {
  9404. continue;
  9405. }
  9406. lbValue tag = {};
  9407. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  9408. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 3);
  9409. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  9410. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  9411. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), lb_typeid(m, t));
  9412. switch (t->kind) {
  9413. case Type_Named: {
  9414. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  9415. LLVMValueRef vals[2] = {
  9416. lb_const_string(p->module, t->Named.type_name->token.string).value,
  9417. lb_get_type_info_ptr(m, t->Named.base).value,
  9418. };
  9419. lbValue res = {};
  9420. res.type = type_deref(tag.type);
  9421. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9422. lb_emit_store(p, tag, res);
  9423. break;
  9424. }
  9425. case Type_Basic:
  9426. switch (t->Basic.kind) {
  9427. case Basic_bool:
  9428. case Basic_b8:
  9429. case Basic_b16:
  9430. case Basic_b32:
  9431. case Basic_b64:
  9432. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  9433. break;
  9434. case Basic_i8:
  9435. case Basic_u8:
  9436. case Basic_i16:
  9437. case Basic_u16:
  9438. case Basic_i32:
  9439. case Basic_u32:
  9440. case Basic_i64:
  9441. case Basic_u64:
  9442. case Basic_i128:
  9443. case Basic_u128:
  9444. case Basic_i16le:
  9445. case Basic_u16le:
  9446. case Basic_i32le:
  9447. case Basic_u32le:
  9448. case Basic_i64le:
  9449. case Basic_u64le:
  9450. case Basic_i128le:
  9451. case Basic_u128le:
  9452. case Basic_i16be:
  9453. case Basic_u16be:
  9454. case Basic_i32be:
  9455. case Basic_u32be:
  9456. case Basic_i64be:
  9457. case Basic_u64be:
  9458. case Basic_i128be:
  9459. case Basic_u128be:
  9460. case Basic_int:
  9461. case Basic_uint:
  9462. case Basic_uintptr: {
  9463. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  9464. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  9465. // NOTE(bill): This is matches the runtime layout
  9466. u8 endianness_value = 0;
  9467. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9468. endianness_value = 1;
  9469. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9470. endianness_value = 2;
  9471. }
  9472. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  9473. LLVMValueRef vals[2] = {
  9474. is_signed.value,
  9475. endianness.value,
  9476. };
  9477. lbValue res = {};
  9478. res.type = type_deref(tag.type);
  9479. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9480. lb_emit_store(p, tag, res);
  9481. break;
  9482. }
  9483. case Basic_rune:
  9484. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  9485. break;
  9486. // case Basic_f16:
  9487. case Basic_f32:
  9488. case Basic_f64:
  9489. case Basic_f32le:
  9490. case Basic_f64le:
  9491. case Basic_f32be:
  9492. case Basic_f64be:
  9493. {
  9494. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  9495. // NOTE(bill): This is matches the runtime layout
  9496. u8 endianness_value = 0;
  9497. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9498. endianness_value = 1;
  9499. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9500. endianness_value = 2;
  9501. }
  9502. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  9503. LLVMValueRef vals[1] = {
  9504. endianness.value,
  9505. };
  9506. lbValue res = {};
  9507. res.type = type_deref(tag.type);
  9508. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9509. lb_emit_store(p, tag, res);
  9510. }
  9511. break;
  9512. // case Basic_complex32:
  9513. case Basic_complex64:
  9514. case Basic_complex128:
  9515. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  9516. break;
  9517. case Basic_quaternion128:
  9518. case Basic_quaternion256:
  9519. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  9520. break;
  9521. case Basic_rawptr:
  9522. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  9523. break;
  9524. case Basic_string:
  9525. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  9526. break;
  9527. case Basic_cstring:
  9528. {
  9529. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  9530. LLVMValueRef vals[1] = {
  9531. lb_const_bool(m, t_bool, true).value,
  9532. };
  9533. lbValue res = {};
  9534. res.type = type_deref(tag.type);
  9535. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9536. lb_emit_store(p, tag, res);
  9537. }
  9538. break;
  9539. case Basic_any:
  9540. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  9541. break;
  9542. case Basic_typeid:
  9543. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  9544. break;
  9545. }
  9546. break;
  9547. case Type_Pointer: {
  9548. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  9549. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  9550. LLVMValueRef vals[1] = {
  9551. gep.value,
  9552. };
  9553. lbValue res = {};
  9554. res.type = type_deref(tag.type);
  9555. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9556. lb_emit_store(p, tag, res);
  9557. break;
  9558. }
  9559. case Type_Array: {
  9560. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  9561. i64 ez = type_size_of(t->Array.elem);
  9562. LLVMValueRef vals[3] = {
  9563. lb_get_type_info_ptr(m, t->Array.elem).value,
  9564. lb_const_int(m, t_int, ez).value,
  9565. lb_const_int(m, t_int, t->Array.count).value,
  9566. };
  9567. lbValue res = {};
  9568. res.type = type_deref(tag.type);
  9569. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9570. lb_emit_store(p, tag, res);
  9571. break;
  9572. }
  9573. case Type_EnumeratedArray: {
  9574. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  9575. LLVMValueRef vals[6] = {
  9576. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  9577. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  9578. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  9579. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  9580. // Unions
  9581. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  9582. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  9583. };
  9584. lbValue res = {};
  9585. res.type = type_deref(tag.type);
  9586. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9587. lb_emit_store(p, tag, res);
  9588. // NOTE(bill): Union assignment
  9589. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  9590. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  9591. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  9592. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  9593. lb_emit_store(p, min_value, min_v);
  9594. lb_emit_store(p, max_value, max_v);
  9595. break;
  9596. }
  9597. case Type_DynamicArray: {
  9598. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  9599. LLVMValueRef vals[2] = {
  9600. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  9601. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  9602. };
  9603. lbValue res = {};
  9604. res.type = type_deref(tag.type);
  9605. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9606. lb_emit_store(p, tag, res);
  9607. break;
  9608. }
  9609. case Type_Slice: {
  9610. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  9611. LLVMValueRef vals[2] = {
  9612. lb_get_type_info_ptr(m, t->Slice.elem).value,
  9613. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  9614. };
  9615. lbValue res = {};
  9616. res.type = type_deref(tag.type);
  9617. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9618. lb_emit_store(p, tag, res);
  9619. break;
  9620. }
  9621. case Type_Proc: {
  9622. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  9623. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  9624. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  9625. if (t->Proc.params != nullptr) {
  9626. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  9627. }
  9628. if (t->Proc.results != nullptr) {
  9629. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  9630. }
  9631. LLVMValueRef vals[4] = {
  9632. params,
  9633. results,
  9634. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  9635. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  9636. };
  9637. lbValue res = {};
  9638. res.type = type_deref(tag.type);
  9639. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9640. lb_emit_store(p, tag, res);
  9641. break;
  9642. }
  9643. case Type_Tuple: {
  9644. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  9645. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  9646. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  9647. for_array(i, t->Tuple.variables) {
  9648. // NOTE(bill): offset is not used for tuples
  9649. Entity *f = t->Tuple.variables[i];
  9650. lbValue index = lb_const_int(m, t_int, i);
  9651. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  9652. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  9653. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  9654. if (f->token.string.len > 0) {
  9655. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  9656. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  9657. }
  9658. }
  9659. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  9660. LLVMValueRef types_slice = llvm_const_slice(memory_types, count);
  9661. LLVMValueRef names_slice = llvm_const_slice(memory_names, count);
  9662. LLVMValueRef vals[2] = {
  9663. types_slice,
  9664. names_slice,
  9665. };
  9666. lbValue res = {};
  9667. res.type = type_deref(tag.type);
  9668. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9669. lb_emit_store(p, tag, res);
  9670. break;
  9671. }
  9672. case Type_Enum:
  9673. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  9674. {
  9675. GB_ASSERT(t->Enum.base_type != nullptr);
  9676. // GB_ASSERT_MSG(type_size_of(t_type_info_enum_value) == 16, "%lld == 16", cast(long long)type_size_of(t_type_info_enum_value));
  9677. LLVMValueRef vals[3] = {};
  9678. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  9679. if (t->Enum.fields.count > 0) {
  9680. auto fields = t->Enum.fields;
  9681. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  9682. str_lit("$enum_names"), cast(i64)entry_index);
  9683. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  9684. str_lit("$enum_values"), cast(i64)entry_index);
  9685. LLVMValueRef *name_values = gb_alloc_array(heap_allocator(), LLVMValueRef, fields.count);
  9686. LLVMValueRef *value_values = gb_alloc_array(heap_allocator(), LLVMValueRef, fields.count);
  9687. defer (gb_free(heap_allocator(), name_values));
  9688. defer (gb_free(heap_allocator(), value_values));
  9689. GB_ASSERT(is_type_integer(t->Enum.base_type));
  9690. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  9691. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  9692. for_array(i, fields) {
  9693. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  9694. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  9695. }
  9696. LLVMValueRef name_init = LLVMConstArray(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  9697. LLVMValueRef value_init = LLVMConstArray(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  9698. LLVMSetInitializer(name_array.value, name_init);
  9699. LLVMSetInitializer(value_array.value, value_init);
  9700. lbValue v_count = lb_const_int(m, t_int, fields.count);
  9701. vals[1] = llvm_const_slice(lb_array_elem(p, name_array), v_count);
  9702. vals[2] = llvm_const_slice(lb_array_elem(p, value_array), v_count);
  9703. } else {
  9704. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  9705. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  9706. }
  9707. lbValue res = {};
  9708. res.type = type_deref(tag.type);
  9709. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9710. lb_emit_store(p, tag, res);
  9711. }
  9712. break;
  9713. case Type_Union: {
  9714. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  9715. {
  9716. LLVMValueRef vals[6] = {};
  9717. isize variant_count = gb_max(0, t->Union.variants.count);
  9718. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  9719. // NOTE(bill): Zeroth is nil so ignore it
  9720. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  9721. Type *vt = t->Union.variants[variant_index];
  9722. lbValue tip = lb_get_type_info_ptr(m, vt);
  9723. lbValue index = lb_const_int(m, t_int, variant_index);
  9724. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  9725. lb_emit_store(p, type_info, lb_type_info(m, vt));
  9726. }
  9727. lbValue count = lb_const_int(m, t_int, variant_count);
  9728. vals[0] = llvm_const_slice(memory_types, count);
  9729. i64 tag_size = union_tag_size(t);
  9730. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  9731. if (tag_size > 0) {
  9732. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  9733. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  9734. } else {
  9735. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  9736. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  9737. }
  9738. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  9739. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  9740. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  9741. lbValue res = {};
  9742. res.type = type_deref(tag.type);
  9743. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9744. lb_emit_store(p, tag, res);
  9745. }
  9746. break;
  9747. }
  9748. case Type_Struct: {
  9749. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  9750. LLVMValueRef vals[11] = {};
  9751. {
  9752. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  9753. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  9754. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  9755. vals[5] = is_packed.value;
  9756. vals[6] = is_raw_union.value;
  9757. vals[7] = is_custom_align.value;
  9758. if (t->Struct.soa_kind != StructSoa_None) {
  9759. lbValue kind = lb_emit_struct_ep(p, tag, 8);
  9760. Type *kind_type = type_deref(kind.type);
  9761. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  9762. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  9763. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  9764. vals[8] = soa_kind.value;
  9765. vals[9] = soa_type.value;
  9766. vals[10] = soa_len.value;
  9767. }
  9768. }
  9769. isize count = t->Struct.fields.count;
  9770. if (count > 0) {
  9771. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  9772. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  9773. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  9774. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  9775. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  9776. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  9777. for (isize source_index = 0; source_index < count; source_index++) {
  9778. // TODO(bill): Order fields in source order not layout order
  9779. Entity *f = t->Struct.fields[source_index];
  9780. lbValue tip = lb_get_type_info_ptr(m, f->type);
  9781. i64 foffset = 0;
  9782. if (!t->Struct.is_raw_union) {
  9783. foffset = t->Struct.offsets[f->Variable.field_index];
  9784. }
  9785. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  9786. lbValue index = lb_const_int(m, t_int, source_index);
  9787. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  9788. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  9789. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  9790. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  9791. if (f->token.string.len > 0) {
  9792. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  9793. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  9794. }
  9795. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  9796. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  9797. if (t->Struct.tags.count > 0) {
  9798. String tag_string = t->Struct.tags[source_index];
  9799. if (tag_string.len > 0) {
  9800. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  9801. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  9802. }
  9803. }
  9804. }
  9805. lbValue cv = lb_const_int(m, t_int, count);
  9806. vals[0] = llvm_const_slice(memory_types, cv);
  9807. vals[1] = llvm_const_slice(memory_names, cv);
  9808. vals[2] = llvm_const_slice(memory_offsets, cv);
  9809. vals[3] = llvm_const_slice(memory_usings, cv);
  9810. vals[4] = llvm_const_slice(memory_tags, cv);
  9811. }
  9812. for (isize i = 0; i < gb_count_of(vals); i++) {
  9813. if (vals[i] == nullptr) {
  9814. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  9815. }
  9816. }
  9817. lbValue res = {};
  9818. res.type = type_deref(tag.type);
  9819. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9820. lb_emit_store(p, tag, res);
  9821. break;
  9822. }
  9823. case Type_Map: {
  9824. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  9825. init_map_internal_types(t);
  9826. LLVMValueRef vals[3] = {
  9827. lb_get_type_info_ptr(m, t->Map.key).value,
  9828. lb_get_type_info_ptr(m, t->Map.value).value,
  9829. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  9830. };
  9831. lbValue res = {};
  9832. res.type = type_deref(tag.type);
  9833. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9834. lb_emit_store(p, tag, res);
  9835. break;
  9836. }
  9837. case Type_BitField: {
  9838. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_field_ptr);
  9839. // names: []string;
  9840. // bits: []u32;
  9841. // offsets: []u32;
  9842. isize count = t->BitField.fields.count;
  9843. if (count > 0) {
  9844. auto fields = t->BitField.fields;
  9845. lbValue name_array = lb_generate_global_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  9846. lbValue bit_array = lb_generate_global_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  9847. lbValue offset_array = lb_generate_global_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  9848. for (isize i = 0; i < count; i++) {
  9849. Entity *f = fields[i];
  9850. GB_ASSERT(f->type != nullptr);
  9851. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  9852. lbValue name_ep = lb_emit_array_epi(p, name_array, cast(i32)i);
  9853. lbValue bit_ep = lb_emit_array_epi(p, bit_array, cast(i32)i);
  9854. lbValue offset_ep = lb_emit_array_epi(p, offset_array, cast(i32)i);
  9855. lb_emit_store(p, name_ep, lb_const_string(m, f->token.string));
  9856. lb_emit_store(p, bit_ep, lb_const_int(m, t_i32, f->type->BitFieldValue.bits));
  9857. lb_emit_store(p, offset_ep, lb_const_int(m, t_i32, t->BitField.offsets[i]));
  9858. }
  9859. lbValue v_count = lb_const_int(m, t_int, count);
  9860. lbValue name_array_elem = lb_array_elem(p, name_array);
  9861. lbValue bit_array_elem = lb_array_elem(p, bit_array);
  9862. lbValue offset_array_elem = lb_array_elem(p, offset_array);
  9863. LLVMValueRef vals[3] = {
  9864. llvm_const_slice(name_array_elem, v_count),
  9865. llvm_const_slice(bit_array_elem, v_count),
  9866. llvm_const_slice(offset_array_elem, v_count),
  9867. };
  9868. lbValue res = {};
  9869. res.type = type_deref(tag.type);
  9870. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9871. lb_emit_store(p, tag, res);
  9872. }
  9873. break;
  9874. }
  9875. case Type_BitSet:
  9876. {
  9877. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  9878. GB_ASSERT(is_type_typed(t->BitSet.elem));
  9879. LLVMValueRef vals[4] = {
  9880. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  9881. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  9882. lb_const_int(m, t_i64, t->BitSet.lower).value,
  9883. lb_const_int(m, t_i64, t->BitSet.upper).value,
  9884. };
  9885. if (t->BitSet.underlying != nullptr) {
  9886. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  9887. }
  9888. lbValue res = {};
  9889. res.type = type_deref(tag.type);
  9890. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9891. lb_emit_store(p, tag, res);
  9892. }
  9893. break;
  9894. case Type_Opaque:
  9895. {
  9896. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_opaque_ptr);
  9897. LLVMValueRef vals[1] = {
  9898. lb_get_type_info_ptr(m, t->Opaque.elem).value,
  9899. };
  9900. lbValue res = {};
  9901. res.type = type_deref(tag.type);
  9902. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9903. lb_emit_store(p, tag, res);
  9904. }
  9905. break;
  9906. case Type_SimdVector:
  9907. {
  9908. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  9909. LLVMValueRef vals[4] = {};
  9910. if (t->SimdVector.is_x86_mmx) {
  9911. vals[3] = lb_const_bool(m, t_bool, true).value;
  9912. } else {
  9913. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  9914. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  9915. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  9916. }
  9917. lbValue res = {};
  9918. res.type = type_deref(tag.type);
  9919. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9920. lb_emit_store(p, tag, res);
  9921. }
  9922. break;
  9923. case Type_RelativePointer:
  9924. {
  9925. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  9926. LLVMValueRef vals[2] = {
  9927. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  9928. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  9929. };
  9930. lbValue res = {};
  9931. res.type = type_deref(tag.type);
  9932. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9933. lb_emit_store(p, tag, res);
  9934. }
  9935. break;
  9936. case Type_RelativeSlice:
  9937. {
  9938. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  9939. LLVMValueRef vals[2] = {
  9940. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  9941. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  9942. };
  9943. lbValue res = {};
  9944. res.type = type_deref(tag.type);
  9945. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9946. lb_emit_store(p, tag, res);
  9947. }
  9948. break;
  9949. }
  9950. if (tag.value != nullptr) {
  9951. Type *tag_type = type_deref(tag.type);
  9952. GB_ASSERT(is_type_named(tag_type));
  9953. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  9954. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  9955. } else {
  9956. if (t != t_llvm_bool) {
  9957. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  9958. }
  9959. }
  9960. }
  9961. }
  9962. void lb_generate_code(lbGenerator *gen) {
  9963. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  9964. TIME_SECTION("LLVM Initializtion");
  9965. lbModule *m = &gen->module;
  9966. LLVMModuleRef mod = gen->module.mod;
  9967. CheckerInfo *info = gen->info;
  9968. Arena temp_arena = {};
  9969. arena_init(&temp_arena, heap_allocator());
  9970. gbAllocator temp_allocator = arena_allocator(&temp_arena);
  9971. auto *min_dep_set = &info->minimum_dependency_set;
  9972. LLVMInitializeAllTargetInfos();
  9973. LLVMInitializeAllTargets();
  9974. LLVMInitializeAllTargetMCs();
  9975. LLVMInitializeAllAsmPrinters();
  9976. LLVMInitializeAllAsmParsers();
  9977. LLVMInitializeAllDisassemblers();
  9978. LLVMInitializeNativeTarget();
  9979. char const *target_triple = alloc_cstring(heap_allocator(), build_context.metrics.target_triplet);
  9980. char const *target_data_layout = alloc_cstring(heap_allocator(), build_context.metrics.target_data_layout);
  9981. LLVMSetTarget(mod, target_triple);
  9982. LLVMTargetRef target = {};
  9983. char *llvm_error = nullptr;
  9984. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  9985. GB_ASSERT(target != nullptr);
  9986. TIME_SECTION("LLVM Create Target Machine");
  9987. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  9988. if (build_context.metrics.arch == TargetArch_wasm32) {
  9989. code_mode = LLVMCodeModelJITDefault;
  9990. }
  9991. char const *host_cpu_name = LLVMGetHostCPUName();
  9992. char const *llvm_cpu = "generic";
  9993. char const *llvm_features = "";
  9994. if (build_context.microarch.len != 0) {
  9995. if (build_context.microarch == "native") {
  9996. llvm_cpu = host_cpu_name;
  9997. } else {
  9998. llvm_cpu = alloc_cstring(heap_allocator(), build_context.microarch);
  9999. }
  10000. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  10001. llvm_features = LLVMGetHostCPUFeatures();
  10002. }
  10003. }
  10004. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  10005. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  10006. switch (build_context.optimization_level) {
  10007. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  10008. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  10009. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  10010. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  10011. }
  10012. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, llvm_cpu, llvm_features, code_gen_level, LLVMRelocDefault, code_mode);
  10013. defer (LLVMDisposeTargetMachine(target_machine));
  10014. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  10015. { // Debug Info
  10016. for_array(i, info->files.entries) {
  10017. AstFile *f = info->files.entries[i].value;
  10018. String fullpath = f->fullpath;
  10019. String filename = filename_from_path(fullpath);
  10020. String directory = directory_from_path(fullpath);
  10021. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  10022. cast(char const *)filename.text, filename.len,
  10023. cast(char const *)directory.text, directory.len);
  10024. map_set(&m->debug_values, hash_pointer(f), res);
  10025. f->llvm_metadata = res;
  10026. }
  10027. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC,
  10028. cast(LLVMMetadataRef)m->info->files.entries[0].value->llvm_metadata,
  10029. "odin", 4,
  10030. false, "", 0,
  10031. 1, "", 0,
  10032. LLVMDWARFEmissionFull, 0, true,
  10033. true
  10034. );
  10035. }
  10036. TIME_SECTION("LLVM Global Variables");
  10037. {
  10038. { // Add type info data
  10039. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  10040. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  10041. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  10042. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  10043. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10044. LLVMSetLinkage(g, LLVMInternalLinkage);
  10045. lbValue value = {};
  10046. value.value = g;
  10047. value.type = alloc_type_pointer(t);
  10048. lb_global_type_info_data = lb_addr(value);
  10049. }
  10050. { // Type info member buffer
  10051. // NOTE(bill): Removes need for heap allocation by making it global memory
  10052. isize count = 0;
  10053. for_array(entry_index, m->info->type_info_types) {
  10054. Type *t = m->info->type_info_types[entry_index];
  10055. isize index = lb_type_info_index(m->info, t, false);
  10056. if (index < 0) {
  10057. continue;
  10058. }
  10059. switch (t->kind) {
  10060. case Type_Union:
  10061. count += t->Union.variants.count;
  10062. break;
  10063. case Type_Struct:
  10064. count += t->Struct.fields.count;
  10065. break;
  10066. case Type_Tuple:
  10067. count += t->Tuple.variables.count;
  10068. break;
  10069. }
  10070. }
  10071. if (count > 0) {
  10072. {
  10073. char const *name = LB_TYPE_INFO_TYPES_NAME;
  10074. Type *t = alloc_type_array(t_type_info_ptr, count);
  10075. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10076. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10077. LLVMSetLinkage(g, LLVMInternalLinkage);
  10078. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  10079. }
  10080. {
  10081. char const *name = LB_TYPE_INFO_NAMES_NAME;
  10082. Type *t = alloc_type_array(t_string, count);
  10083. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10084. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10085. LLVMSetLinkage(g, LLVMInternalLinkage);
  10086. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  10087. }
  10088. {
  10089. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  10090. Type *t = alloc_type_array(t_uintptr, count);
  10091. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10092. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10093. LLVMSetLinkage(g, LLVMInternalLinkage);
  10094. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  10095. }
  10096. {
  10097. char const *name = LB_TYPE_INFO_USINGS_NAME;
  10098. Type *t = alloc_type_array(t_bool, count);
  10099. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10100. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10101. LLVMSetLinkage(g, LLVMInternalLinkage);
  10102. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  10103. }
  10104. {
  10105. char const *name = LB_TYPE_INFO_TAGS_NAME;
  10106. Type *t = alloc_type_array(t_string, count);
  10107. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10108. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10109. LLVMSetLinkage(g, LLVMInternalLinkage);
  10110. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  10111. }
  10112. }
  10113. }
  10114. }
  10115. isize global_variable_max_count = 0;
  10116. Entity *entry_point = info->entry_point;
  10117. bool has_dll_main = false;
  10118. bool has_win_main = false;
  10119. for_array(i, info->entities) {
  10120. Entity *e = info->entities[i];
  10121. String name = e->token.string;
  10122. bool is_global = e->pkg != nullptr;
  10123. if (e->kind == Entity_Variable) {
  10124. global_variable_max_count++;
  10125. } else if (e->kind == Entity_Procedure && !is_global) {
  10126. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  10127. GB_ASSERT(e == entry_point);
  10128. // entry_point = e;
  10129. }
  10130. if (e->Procedure.is_export ||
  10131. (e->Procedure.link_name.len > 0) ||
  10132. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  10133. if (!has_dll_main && name == "DllMain") {
  10134. has_dll_main = true;
  10135. } else if (!has_win_main && name == "WinMain") {
  10136. has_win_main = true;
  10137. }
  10138. }
  10139. }
  10140. }
  10141. struct GlobalVariable {
  10142. lbValue var;
  10143. lbValue init;
  10144. DeclInfo *decl;
  10145. };
  10146. auto global_variables = array_make<GlobalVariable>(heap_allocator(), 0, global_variable_max_count);
  10147. for_array(i, info->variable_init_order) {
  10148. DeclInfo *d = info->variable_init_order[i];
  10149. Entity *e = d->entity;
  10150. if ((e->scope->flags & ScopeFlag_File) == 0) {
  10151. continue;
  10152. }
  10153. if (!ptr_set_exists(min_dep_set, e)) {
  10154. continue;
  10155. }
  10156. DeclInfo *decl = decl_info_of_entity(e);
  10157. if (decl == nullptr) {
  10158. continue;
  10159. }
  10160. GB_ASSERT(e->kind == Entity_Variable);
  10161. bool is_foreign = e->Variable.is_foreign;
  10162. bool is_export = e->Variable.is_export;
  10163. String name = lb_get_entity_name(m, e);
  10164. lbValue g = {};
  10165. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(heap_allocator(), name));
  10166. g.type = alloc_type_pointer(e->type);
  10167. if (e->Variable.thread_local_model != "") {
  10168. LLVMSetThreadLocal(g.value, true);
  10169. String m = e->Variable.thread_local_model;
  10170. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  10171. if (m == "default") {
  10172. mode = LLVMGeneralDynamicTLSModel;
  10173. } else if (m == "localdynamic") {
  10174. mode = LLVMLocalDynamicTLSModel;
  10175. } else if (m == "initialexec") {
  10176. mode = LLVMInitialExecTLSModel;
  10177. } else if (m == "localexec") {
  10178. mode = LLVMLocalExecTLSModel;
  10179. } else {
  10180. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  10181. }
  10182. LLVMSetThreadLocalMode(g.value, mode);
  10183. }
  10184. if (is_foreign) {
  10185. LLVMSetExternallyInitialized(g.value, true);
  10186. } else {
  10187. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  10188. }
  10189. if (is_export) {
  10190. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  10191. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  10192. }
  10193. GlobalVariable var = {};
  10194. var.var = g;
  10195. var.decl = decl;
  10196. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  10197. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  10198. if (tav.mode != Addressing_Invalid) {
  10199. if (tav.value.kind != ExactValue_Invalid) {
  10200. ExactValue v = tav.value;
  10201. lbValue init = lb_const_value(m, tav.type, v);
  10202. LLVMSetInitializer(g.value, init.value);
  10203. }
  10204. }
  10205. }
  10206. array_add(&global_variables, var);
  10207. lb_add_entity(m, e, g);
  10208. lb_add_member(m, name, g);
  10209. }
  10210. TIME_SECTION("LLVM Global Procedures and Types");
  10211. for_array(i, info->entities) {
  10212. // arena_free_all(&temp_arena);
  10213. // gbAllocator a = temp_allocator;
  10214. Entity *e = info->entities[i];
  10215. String name = e->token.string;
  10216. DeclInfo *decl = e->decl_info;
  10217. Scope * scope = e->scope;
  10218. if ((scope->flags & ScopeFlag_File) == 0) {
  10219. continue;
  10220. }
  10221. Scope *package_scope = scope->parent;
  10222. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  10223. switch (e->kind) {
  10224. case Entity_Variable:
  10225. // NOTE(bill): Handled above as it requires a specific load order
  10226. continue;
  10227. case Entity_ProcGroup:
  10228. continue;
  10229. case Entity_TypeName:
  10230. case Entity_Procedure:
  10231. break;
  10232. }
  10233. bool polymorphic_struct = false;
  10234. if (e->type != nullptr && e->kind == Entity_TypeName) {
  10235. Type *bt = base_type(e->type);
  10236. if (bt->kind == Type_Struct) {
  10237. polymorphic_struct = is_type_polymorphic(bt);
  10238. }
  10239. }
  10240. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  10241. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  10242. continue;
  10243. }
  10244. String mangled_name = lb_get_entity_name(m, e);
  10245. switch (e->kind) {
  10246. case Entity_TypeName:
  10247. lb_type(m, e->type);
  10248. break;
  10249. case Entity_Procedure:
  10250. {
  10251. lbProcedure *p = lb_create_procedure(m, e);
  10252. array_add(&m->procedures_to_generate, p);
  10253. }
  10254. break;
  10255. }
  10256. }
  10257. TIME_SECTION("LLVM Registry Initializtion");
  10258. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  10259. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  10260. defer (LLVMDisposePassManager(default_function_pass_manager));
  10261. /*{
  10262. LLVMAddMemCpyOptPass(default_function_pass_manager);
  10263. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10264. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  10265. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager);
  10266. LLVMAddConstantPropagationPass(default_function_pass_manager);
  10267. LLVMAddAggressiveDCEPass(default_function_pass_manager);
  10268. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  10269. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10270. LLVMAddCFGSimplificationPass(default_function_pass_manager);
  10271. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager);
  10272. if (build_context.optimization_level >= 2) {
  10273. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager);
  10274. LLVMAddEarlyCSEPass(default_function_pass_manager);
  10275. LLVMAddEarlyCSEMemSSAPass(default_function_pass_manager);
  10276. LLVMAddLowerExpectIntrinsicPass(default_function_pass_manager);
  10277. LLVMAddAlignmentFromAssumptionsPass(default_function_pass_manager);
  10278. LLVMAddLoopRotatePass(default_function_pass_manager);
  10279. LLVMAddDeadStoreEliminationPass(default_function_pass_manager);
  10280. LLVMAddScalarizerPass(default_function_pass_manager);
  10281. LLVMAddReassociatePass(default_function_pass_manager);
  10282. LLVMAddAddDiscriminatorsPass(default_function_pass_manager);
  10283. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10284. LLVMAddCorrelatedValuePropagationPass(default_function_pass_manager);
  10285. LLVMAddSLPVectorizePass(default_function_pass_manager);
  10286. LLVMAddLoopVectorizePass(default_function_pass_manager);
  10287. }
  10288. }*/
  10289. if (build_context.optimization_level == 0 && false) {
  10290. auto dfpm = default_function_pass_manager;
  10291. LLVMAddMemCpyOptPass(dfpm);
  10292. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10293. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10294. LLVMAddAggressiveInstCombinerPass(dfpm);
  10295. LLVMAddConstantPropagationPass(dfpm);
  10296. LLVMAddAggressiveDCEPass(dfpm);
  10297. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10298. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10299. LLVMAddCFGSimplificationPass(dfpm);
  10300. LLVMAddScalarizerPass(dfpm);
  10301. } else {
  10302. auto dfpm = default_function_pass_manager;
  10303. LLVMAddMemCpyOptPass(dfpm);
  10304. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10305. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10306. LLVMAddAggressiveInstCombinerPass(dfpm);
  10307. LLVMAddConstantPropagationPass(dfpm);
  10308. LLVMAddAggressiveDCEPass(dfpm);
  10309. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10310. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10311. LLVMAddCFGSimplificationPass(dfpm);
  10312. // LLVMAddInstructionCombiningPass(dfpm);
  10313. LLVMAddSLPVectorizePass(dfpm);
  10314. LLVMAddLoopVectorizePass(dfpm);
  10315. LLVMAddEarlyCSEPass(dfpm);
  10316. LLVMAddEarlyCSEMemSSAPass(dfpm);
  10317. LLVMAddScalarizerPass(dfpm);
  10318. LLVMAddLoopIdiomPass(dfpm);
  10319. // LLVMAddAggressiveInstCombinerPass(dfpm);
  10320. // LLVMAddLowerExpectIntrinsicPass(dfpm);
  10321. // LLVMAddPartiallyInlineLibCallsPass(dfpm);
  10322. // LLVMAddAlignmentFromAssumptionsPass(dfpm);
  10323. // LLVMAddDeadStoreEliminationPass(dfpm);
  10324. // LLVMAddReassociatePass(dfpm);
  10325. // LLVMAddAddDiscriminatorsPass(dfpm);
  10326. // LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10327. // LLVMAddCorrelatedValuePropagationPass(dfpm);
  10328. // LLVMAddMemCpyOptPass(dfpm);
  10329. }
  10330. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  10331. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  10332. {
  10333. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  10334. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  10335. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager_without_memcpy);
  10336. LLVMAddConstantPropagationPass(default_function_pass_manager_without_memcpy);
  10337. LLVMAddAggressiveDCEPass(default_function_pass_manager_without_memcpy);
  10338. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  10339. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  10340. LLVMAddCFGSimplificationPass(default_function_pass_manager_without_memcpy);
  10341. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager_without_memcpy);
  10342. }
  10343. TIME_SECTION("LLVM Runtime Creation");
  10344. lbProcedure *startup_type_info = nullptr;
  10345. lbProcedure *startup_runtime = nullptr;
  10346. { // Startup Type Info
  10347. Type *params = alloc_type_tuple();
  10348. Type *results = alloc_type_tuple();
  10349. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10350. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  10351. p->is_startup = true;
  10352. startup_type_info = p;
  10353. lb_begin_procedure_body(p);
  10354. lb_setup_type_info_data(p);
  10355. lb_end_procedure_body(p);
  10356. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10357. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10358. LLVMDumpValue(p->value);
  10359. gb_printf_err("\n\n\n\n");
  10360. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10361. }
  10362. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10363. }
  10364. { // Startup Runtime
  10365. Type *params = alloc_type_tuple();
  10366. Type *results = alloc_type_tuple();
  10367. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10368. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  10369. p->is_startup = true;
  10370. startup_runtime = p;
  10371. lb_begin_procedure_body(p);
  10372. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  10373. for_array(i, global_variables) {
  10374. auto *var = &global_variables[i];
  10375. if (var->decl->init_expr != nullptr) {
  10376. lbValue init = lb_build_expr(p, var->decl->init_expr);
  10377. if (!lb_is_const(init)) {
  10378. var->init = init;
  10379. }
  10380. }
  10381. Entity *e = var->decl->entity;
  10382. GB_ASSERT(e->kind == Entity_Variable);
  10383. if (e->Variable.is_foreign) {
  10384. Entity *fl = e->Procedure.foreign_library;
  10385. lb_add_foreign_library_path(m, fl);
  10386. }
  10387. if (e->flags & EntityFlag_Static) {
  10388. LLVMSetLinkage(var->var.value, LLVMInternalLinkage);
  10389. }
  10390. if (var->init.value != nullptr) {
  10391. Type *t = type_deref(var->var.type);
  10392. if (is_type_any(t)) {
  10393. // NOTE(bill): Edge case for 'any' type
  10394. Type *var_type = default_type(var->init.type);
  10395. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  10396. lb_addr_store(p, g, var->init);
  10397. lbValue gp = lb_addr_get_ptr(p, g);
  10398. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  10399. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  10400. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  10401. lb_emit_store(p, ti, lb_type_info(m, var_type));
  10402. } else {
  10403. lb_emit_store(p, var->var, lb_emit_conv(p, var->init, t));
  10404. }
  10405. }
  10406. }
  10407. lb_end_procedure_body(p);
  10408. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10409. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10410. LLVMDumpValue(p->value);
  10411. gb_printf_err("\n\n\n\n");
  10412. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10413. }
  10414. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10415. /*{
  10416. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  10417. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  10418. instr != last_instr;
  10419. instr = LLVMGetNextInstruction(instr)) {
  10420. if (LLVMIsAAllocaInst(instr)) {
  10421. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  10422. LLVMValueRef sz_val = LLVMSizeOf(type);
  10423. GB_ASSERT(LLVMIsConstant(sz_val));
  10424. gb_printf_err(">> 0x%p\n", sz_val);
  10425. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  10426. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  10427. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  10428. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  10429. gb_printf_err(">> %ll\n", sz);
  10430. }
  10431. }
  10432. }*/
  10433. }
  10434. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  10435. Type *params = alloc_type_tuple();
  10436. Type *results = alloc_type_tuple();
  10437. String name = str_lit("main");
  10438. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  10439. name = str_lit("mainCRTStartup");
  10440. } else {
  10441. array_init(&params->Tuple.variables, heap_allocator(), 2);
  10442. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  10443. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  10444. }
  10445. array_init(&results->Tuple.variables, heap_allocator(), 1);
  10446. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  10447. Type *proc_type = alloc_type_proc(nullptr,
  10448. params, params->Tuple.variables.count,
  10449. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  10450. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  10451. p->is_startup = true;
  10452. lb_begin_procedure_body(p);
  10453. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  10454. GB_ASSERT(found != nullptr);
  10455. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  10456. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  10457. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  10458. lb_end_procedure_body(p);
  10459. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10460. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10461. LLVMDumpValue(p->value);
  10462. gb_printf_err("\n\n\n\n");
  10463. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10464. }
  10465. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10466. }
  10467. TIME_SECTION("LLVM Procedure Generation");
  10468. for_array(i, m->procedures_to_generate) {
  10469. lbProcedure *p = m->procedures_to_generate[i];
  10470. if (p->is_done) {
  10471. continue;
  10472. }
  10473. if (p->body != nullptr) { // Build Procedure
  10474. m->curr_procedure = p;
  10475. lb_begin_procedure_body(p);
  10476. lb_build_stmt(p, p->body);
  10477. lb_end_procedure_body(p);
  10478. p->is_done = true;
  10479. m->curr_procedure = nullptr;
  10480. }
  10481. lb_end_procedure(p);
  10482. // Add Flags
  10483. if (p->body != nullptr) {
  10484. if (p->name == "memcpy" || p->name == "memmove" ||
  10485. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  10486. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  10487. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  10488. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  10489. }
  10490. }
  10491. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10492. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  10493. LLVMDumpValue(p->value);
  10494. gb_printf_err("\n\n\n\n");
  10495. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10496. }
  10497. }
  10498. TIME_SECTION("LLVM Function Pass");
  10499. for_array(i, m->procedures_to_generate) {
  10500. lbProcedure *p = m->procedures_to_generate[i];
  10501. if (p->body != nullptr) { // Build Procedure
  10502. for (i32 i = 0; i <= build_context.optimization_level; i++) {
  10503. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  10504. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  10505. } else {
  10506. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10507. }
  10508. }
  10509. }
  10510. }
  10511. TIME_SECTION("LLVM Module Pass");
  10512. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  10513. defer (LLVMDisposePassManager(module_pass_manager));
  10514. LLVMAddAlwaysInlinerPass(module_pass_manager);
  10515. LLVMAddStripDeadPrototypesPass(module_pass_manager);
  10516. LLVMAddAnalysisPasses(target_machine, module_pass_manager);
  10517. // if (build_context.optimization_level >= 2) {
  10518. // LLVMAddArgumentPromotionPass(module_pass_manager);
  10519. // LLVMAddConstantMergePass(module_pass_manager);
  10520. // LLVMAddGlobalDCEPass(module_pass_manager);
  10521. // LLVMAddDeadArgEliminationPass(module_pass_manager);
  10522. // }
  10523. LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate();
  10524. defer (LLVMPassManagerBuilderDispose(pass_manager_builder));
  10525. LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, build_context.optimization_level);
  10526. LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, build_context.optimization_level);
  10527. LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false);
  10528. LLVMRunPassManager(module_pass_manager, mod);
  10529. llvm_error = nullptr;
  10530. defer (LLVMDisposeMessage(llvm_error));
  10531. String filepath_ll = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".ll"));
  10532. defer (gb_free(heap_allocator(), filepath_ll.text));
  10533. String filepath_obj = {};
  10534. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  10535. if (build_context.build_mode == BuildMode_Assembly) {
  10536. filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".S"));
  10537. code_gen_file_type = LLVMAssemblyFile;
  10538. } else {
  10539. switch (build_context.metrics.os) {
  10540. case TargetOs_windows:
  10541. filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".obj"));
  10542. break;
  10543. case TargetOs_darwin:
  10544. case TargetOs_linux:
  10545. case TargetOs_essence:
  10546. filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".o"));
  10547. break;
  10548. case TargetOs_js:
  10549. filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  10550. break;
  10551. }
  10552. }
  10553. LLVMDIBuilderFinalize(m->debug_builder);
  10554. if (LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error)) {
  10555. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10556. return;
  10557. }
  10558. llvm_error = nullptr;
  10559. if (build_context.keep_temp_files) {
  10560. TIME_SECTION("LLVM Print Module to File");
  10561. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  10562. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10563. return;
  10564. }
  10565. }
  10566. TIME_SECTION("LLVM Object Generation");
  10567. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  10568. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10569. gb_exit(1);
  10570. return;
  10571. }
  10572. array_add(&gen->output_object_paths, filepath_obj);
  10573. for_array(i, m->info->required_foreign_imports_through_force) {
  10574. Entity *e = m->info->required_foreign_imports_through_force[i];
  10575. lb_add_foreign_library_path(m, e);
  10576. }
  10577. #undef TIME_SECTION
  10578. }