llvm_backend.cpp 414 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321
  1. #include "llvm_backend.hpp"
  2. #include "llvm_abi.cpp"
  3. #ifdef USE_NEW_LLVM_ABI_SYSTEM
  4. #define USE_LLVM_ABI 1
  5. #else
  6. #define USE_LLVM_ABI 0
  7. #endif
  8. gb_global lbAddr lb_global_type_info_data = {};
  9. gb_global lbAddr lb_global_type_info_member_types = {};
  10. gb_global lbAddr lb_global_type_info_member_names = {};
  11. gb_global lbAddr lb_global_type_info_member_offsets = {};
  12. gb_global lbAddr lb_global_type_info_member_usings = {};
  13. gb_global lbAddr lb_global_type_info_member_tags = {};
  14. gb_global isize lb_global_type_info_data_index = 0;
  15. gb_global isize lb_global_type_info_member_types_index = 0;
  16. gb_global isize lb_global_type_info_member_names_index = 0;
  17. gb_global isize lb_global_type_info_member_offsets_index = 0;
  18. gb_global isize lb_global_type_info_member_usings_index = 0;
  19. gb_global isize lb_global_type_info_member_tags_index = 0;
  20. struct lbLoopData {
  21. lbAddr idx_addr;
  22. lbValue idx;
  23. lbBlock *body;
  24. lbBlock *done;
  25. lbBlock *loop;
  26. };
  27. struct lbCompoundLitElemTempData {
  28. Ast * expr;
  29. lbValue value;
  30. i32 elem_index;
  31. lbValue gep;
  32. };
  33. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  34. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  35. LLVMValueRef llvm_zero(lbModule *m) {
  36. return LLVMConstInt(lb_type(m, t_int), 0, false);
  37. }
  38. LLVMValueRef llvm_one(lbModule *m) {
  39. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  40. }
  41. lbValue lb_zero(lbModule *m, Type *t) {
  42. lbValue v = {};
  43. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  44. v.type = t;
  45. return v;
  46. }
  47. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  48. lbValue v = lb_find_or_add_entity_string(m, str);
  49. unsigned indices[1] = {0};
  50. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  51. }
  52. bool lb_is_instr_terminating(LLVMValueRef instr) {
  53. if (instr != nullptr) {
  54. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  55. switch (op) {
  56. case LLVMRet:
  57. case LLVMBr:
  58. case LLVMSwitch:
  59. case LLVMIndirectBr:
  60. case LLVMInvoke:
  61. case LLVMUnreachable:
  62. case LLVMCallBr:
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. lbAddr lb_addr(lbValue addr) {
  69. lbAddr v = {lbAddr_Default, addr};
  70. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  71. GB_ASSERT(is_type_pointer(addr.type));
  72. v.kind = lbAddr_RelativePointer;
  73. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  74. GB_ASSERT(is_type_pointer(addr.type));
  75. v.kind = lbAddr_RelativeSlice;
  76. }
  77. return v;
  78. }
  79. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  80. lbAddr v = {lbAddr_Map, addr};
  81. v.map.key = map_key;
  82. v.map.type = map_type;
  83. v.map.result = map_result;
  84. return v;
  85. }
  86. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  87. lbAddr v = {lbAddr_SoaVariable, addr};
  88. v.soa.index = index;
  89. v.soa.index_expr = index_expr;
  90. return v;
  91. }
  92. lbAddr lb_addr_bit_field(lbValue value, i32 index) {
  93. lbAddr addr = {};
  94. addr.kind = lbAddr_BitField;
  95. addr.addr = value;
  96. addr.bit_field.value_index = index;
  97. return addr;
  98. }
  99. Type *lb_addr_type(lbAddr const &addr) {
  100. if (addr.addr.value == nullptr) {
  101. return nullptr;
  102. }
  103. if (addr.kind == lbAddr_Map) {
  104. Type *t = base_type(addr.map.type);
  105. GB_ASSERT(is_type_map(t));
  106. return t->Map.value;
  107. }
  108. return type_deref(addr.addr.type);
  109. }
  110. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  111. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  112. }
  113. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  114. if (addr.addr.value == nullptr) {
  115. GB_PANIC("Illegal addr -> nullptr");
  116. return {};
  117. }
  118. switch (addr.kind) {
  119. case lbAddr_Map: {
  120. Type *map_type = base_type(addr.map.type);
  121. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  122. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  123. auto args = array_make<lbValue>(permanent_allocator(), 2);
  124. args[0] = h;
  125. args[1] = key;
  126. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  127. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  128. }
  129. case lbAddr_RelativePointer: {
  130. Type *rel_ptr = base_type(lb_addr_type(addr));
  131. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  132. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  133. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  134. offset = lb_emit_load(p, offset);
  135. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  136. offset = lb_emit_conv(p, offset, t_i64);
  137. }
  138. offset = lb_emit_conv(p, offset, t_uintptr);
  139. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  140. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  141. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  142. // NOTE(bill): nil check
  143. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  144. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  145. return final_ptr;
  146. }
  147. case lbAddr_BitField: {
  148. lbValue v = lb_addr_load(p, addr);
  149. return lb_address_from_load_or_generate_local(p, v);
  150. }
  151. case lbAddr_Context:
  152. GB_PANIC("lbAddr_Context should be handled elsewhere");
  153. }
  154. return addr.addr;
  155. }
  156. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  157. lbAddr addr = lb_build_addr(p, expr);
  158. return lb_addr_get_ptr(p, addr);
  159. }
  160. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  161. if (build_context.no_bounds_check) {
  162. return;
  163. }
  164. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  165. return;
  166. }
  167. index = lb_emit_conv(p, index, t_int);
  168. len = lb_emit_conv(p, len, t_int);
  169. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  170. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  171. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  172. auto args = array_make<lbValue>(permanent_allocator(), 5);
  173. args[0] = file;
  174. args[1] = line;
  175. args[2] = column;
  176. args[3] = index;
  177. args[4] = len;
  178. lb_emit_runtime_call(p, "bounds_check_error", args);
  179. }
  180. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  181. if (build_context.no_bounds_check) {
  182. return;
  183. }
  184. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  185. return;
  186. }
  187. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  188. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  189. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  190. high = lb_emit_conv(p, high, t_int);
  191. if (!lower_value_used) {
  192. auto args = array_make<lbValue>(permanent_allocator(), 5);
  193. args[0] = file;
  194. args[1] = line;
  195. args[2] = column;
  196. args[3] = high;
  197. args[4] = len;
  198. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  199. } else {
  200. // No need to convert unless used
  201. low = lb_emit_conv(p, low, t_int);
  202. auto args = array_make<lbValue>(permanent_allocator(), 6);
  203. args[0] = file;
  204. args[1] = line;
  205. args[2] = column;
  206. args[3] = low;
  207. args[4] = high;
  208. args[5] = len;
  209. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  210. }
  211. }
  212. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  213. if (addr.addr.value == nullptr) {
  214. return;
  215. }
  216. GB_ASSERT(value.type != nullptr);
  217. if (is_type_untyped_undef(value.type)) {
  218. Type *t = lb_addr_type(addr);
  219. value.type = t;
  220. value.value = LLVMGetUndef(lb_type(p->module, t));
  221. } else if (is_type_untyped_nil(value.type)) {
  222. Type *t = lb_addr_type(addr);
  223. value.type = t;
  224. value.value = LLVMConstNull(lb_type(p->module, t));
  225. }
  226. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  227. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  228. }
  229. if (addr.kind == lbAddr_RelativePointer) {
  230. Type *rel_ptr = base_type(lb_addr_type(addr));
  231. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  232. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  233. GB_ASSERT(is_type_pointer(addr.addr.type));
  234. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  235. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  236. lbValue offset = {};
  237. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  238. offset.type = t_uintptr;
  239. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  240. offset = lb_emit_conv(p, offset, t_i64);
  241. }
  242. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  243. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  244. offset = lb_emit_select(p,
  245. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  246. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  247. offset
  248. );
  249. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  250. return;
  251. } else if (addr.kind == lbAddr_RelativeSlice) {
  252. Type *rel_ptr = base_type(lb_addr_type(addr));
  253. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  254. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  255. GB_ASSERT(is_type_pointer(addr.addr.type));
  256. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  257. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  258. lbValue offset = {};
  259. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  260. offset.type = t_uintptr;
  261. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  262. offset = lb_emit_conv(p, offset, t_i64);
  263. }
  264. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  265. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  266. offset = lb_emit_select(p,
  267. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  268. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  269. offset
  270. );
  271. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  272. lbValue len = lb_slice_len(p, value);
  273. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  274. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  275. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  276. return;
  277. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  278. lbValue ptr = addr.addr;
  279. lbValue index = addr.index_set.index;
  280. Ast *node = addr.index_set.node;
  281. ast_node(ce, CallExpr, node);
  282. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  283. proc_type = base_type(proc_type);
  284. GB_ASSERT(is_type_proc(proc_type));
  285. TypeProc *pt = &proc_type->Proc;
  286. isize arg_count = 3;
  287. isize param_count = 0;
  288. if (pt->params) {
  289. GB_ASSERT(pt->params->kind == Type_Tuple);
  290. param_count = pt->params->Tuple.variables.count;
  291. }
  292. auto args = array_make<lbValue>(permanent_allocator(), gb_max(arg_count, param_count));
  293. args[0] = ptr;
  294. args[1] = index;
  295. args[2] = value;
  296. isize arg_index = arg_count;
  297. if (arg_count < param_count) {
  298. lbModule *m = p->module;
  299. String proc_name = {};
  300. if (p->entity != nullptr) {
  301. proc_name = p->entity->token.string;
  302. }
  303. TokenPos pos = ast_token(ce->proc).pos;
  304. TypeTuple *param_tuple = &pt->params->Tuple;
  305. isize end = cast(isize)param_count;
  306. while (arg_index < end) {
  307. Entity *e = param_tuple->variables[arg_index];
  308. GB_ASSERT(e->kind == Entity_Variable);
  309. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  310. }
  311. }
  312. Entity *e = entity_from_expr(ce->proc);
  313. GB_ASSERT(e != nullptr);
  314. GB_ASSERT(is_type_polymorphic(e->type));
  315. {
  316. lbValue *found = nullptr;
  317. if (p->module != e->code_gen_module) {
  318. gb_mutex_lock(&p->module->mutex);
  319. }
  320. found = map_get(&e->code_gen_module->values, hash_entity(e));
  321. if (p->module != e->code_gen_module) {
  322. gb_mutex_unlock(&p->module->mutex);
  323. }
  324. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  325. lb_emit_call(p, *found, args);
  326. }
  327. return;
  328. } else if (addr.kind == lbAddr_Map) {
  329. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  330. return;
  331. } else if (addr.kind == lbAddr_BitField) {
  332. Type *bft = base_type(type_deref(addr.addr.type));
  333. GB_ASSERT(is_type_bit_field(bft));
  334. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  335. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  336. if (size_in_bits == 0) {
  337. return;
  338. }
  339. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  340. LLVMTypeRef dst_type = LLVMIntTypeInContext(p->module->ctx, size_in_bits);
  341. LLVMValueRef src = LLVMBuildIntCast2(p->builder, value.value, dst_type, false, "");
  342. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  343. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  344. LLVMBuildStore(p->builder, src, field_ptr);
  345. return;
  346. } else if (addr.kind == lbAddr_Context) {
  347. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  348. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  349. lb_addr_store(p, next_addr, old);
  350. lb_push_context_onto_stack(p, next_addr);
  351. lbValue next = lb_addr_get_ptr(p, next_addr);
  352. if (addr.ctx.sel.index.count > 0) {
  353. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  354. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  355. lb_emit_store(p, lhs, rhs);
  356. } else {
  357. lbValue lhs = next;
  358. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  359. lb_emit_store(p, lhs, rhs);
  360. }
  361. return;
  362. } else if (addr.kind == lbAddr_SoaVariable) {
  363. Type *t = type_deref(addr.addr.type);
  364. t = base_type(t);
  365. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  366. value = lb_emit_conv(p, value, t->Struct.soa_elem);
  367. lbValue index = addr.soa.index;
  368. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  369. Type *t = base_type(type_deref(addr.addr.type));
  370. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  371. i64 count = t->Struct.soa_count;
  372. lbValue len = lb_const_int(p->module, t_int, count);
  373. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  374. }
  375. for_array(i, t->Struct.fields) {
  376. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  377. dst = lb_emit_array_ep(p, dst, index);
  378. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  379. lb_emit_store(p, dst, src);
  380. }
  381. return;
  382. }
  383. GB_ASSERT(value.value != nullptr);
  384. value = lb_emit_conv(p, value, lb_addr_type(addr));
  385. if (USE_LLVM_ABI) {
  386. lb_emit_store(p, addr.addr, value);
  387. } else {
  388. LLVMBuildStore(p->builder, value.value, addr.addr.value);
  389. }
  390. }
  391. void lb_const_store(lbValue ptr, lbValue value) {
  392. GB_ASSERT(lb_is_const(ptr));
  393. GB_ASSERT(lb_is_const(value));
  394. GB_ASSERT(is_type_pointer(ptr.type));
  395. LLVMSetInitializer(ptr.value, value.value);
  396. }
  397. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  398. GB_ASSERT(value.value != nullptr);
  399. Type *a = type_deref(ptr.type);
  400. if (is_type_boolean(a)) {
  401. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  402. value = lb_emit_conv(p, value, a);
  403. }
  404. Type *ca = core_type(a);
  405. if (ca->kind == Type_Basic) {
  406. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  407. }
  408. if (USE_LLVM_ABI && is_type_proc(a)) {
  409. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  410. // stored as regular pointer with no procedure information
  411. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  412. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  413. LLVMBuildStore(p->builder, v, ptr.value);
  414. } else {
  415. Type *ca = core_type(a);
  416. if (ca->kind == Type_Basic) {
  417. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  418. } else {
  419. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  420. }
  421. LLVMBuildStore(p->builder, value.value, ptr.value);
  422. }
  423. }
  424. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  425. lbModule *m = p->module;
  426. GB_ASSERT(value.value != nullptr);
  427. Type *t = type_deref(value.type);
  428. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(m, t), value.value, "");
  429. return lbValue{v, t};
  430. }
  431. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  432. GB_ASSERT(addr.addr.value != nullptr);
  433. if (addr.kind == lbAddr_RelativePointer) {
  434. Type *rel_ptr = base_type(lb_addr_type(addr));
  435. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  436. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  437. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  438. offset = lb_emit_load(p, offset);
  439. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  440. offset = lb_emit_conv(p, offset, t_i64);
  441. }
  442. offset = lb_emit_conv(p, offset, t_uintptr);
  443. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  444. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  445. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  446. // NOTE(bill): nil check
  447. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  448. lbValue final_ptr = {};
  449. final_ptr.type = absolute_ptr.type;
  450. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  451. return lb_emit_load(p, final_ptr);
  452. } else if (addr.kind == lbAddr_RelativeSlice) {
  453. Type *rel_ptr = base_type(lb_addr_type(addr));
  454. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  455. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  456. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  457. lbValue offset = lb_emit_load(p, offset_ptr);
  458. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  459. offset = lb_emit_conv(p, offset, t_i64);
  460. }
  461. offset = lb_emit_conv(p, offset, t_uintptr);
  462. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  463. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  464. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  465. Type *slice_elem = slice_type->Slice.elem;
  466. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  467. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  468. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  469. // NOTE(bill): nil check
  470. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  471. lbValue data = {};
  472. data.type = absolute_ptr.type;
  473. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  474. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  475. len = lb_emit_conv(p, len, t_int);
  476. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  477. lb_fill_slice(p, slice, data, len);
  478. return lb_addr_load(p, slice);
  479. } else if (addr.kind == lbAddr_Map) {
  480. Type *map_type = base_type(addr.map.type);
  481. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  482. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  483. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  484. auto args = array_make<lbValue>(permanent_allocator(), 2);
  485. args[0] = h;
  486. args[1] = key;
  487. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  488. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  489. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  490. lbBlock *then = lb_create_block(p, "map.get.then");
  491. lbBlock *done = lb_create_block(p, "map.get.done");
  492. lb_emit_if(p, ok, then, done);
  493. lb_start_block(p, then);
  494. {
  495. // TODO(bill): mem copy it instead?
  496. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  497. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  498. lb_emit_store(p, gep0, lb_emit_load(p, value));
  499. }
  500. lb_emit_jump(p, done);
  501. lb_start_block(p, done);
  502. if (is_type_tuple(addr.map.result)) {
  503. return lb_addr_load(p, v);
  504. } else {
  505. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  506. return lb_emit_load(p, single);
  507. }
  508. } else if (addr.kind == lbAddr_BitField) {
  509. Type *bft = base_type(type_deref(addr.addr.type));
  510. GB_ASSERT(is_type_bit_field(bft));
  511. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  512. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  513. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  514. if (size_in_bytes == 0) {
  515. GB_ASSERT(size_in_bits == 0);
  516. lbValue res = {};
  517. res.type = t_i32;
  518. res.value = LLVMConstInt(lb_type(p->module, res.type), 0, false);
  519. return res;
  520. }
  521. Type *int_type = nullptr;
  522. switch (size_in_bytes) {
  523. case 1: int_type = t_u8; break;
  524. case 2: int_type = t_u16; break;
  525. case 4: int_type = t_u32; break;
  526. case 8: int_type = t_u64; break;
  527. case 16: int_type = t_u128; break;
  528. }
  529. GB_ASSERT(int_type != nullptr);
  530. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  531. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  532. LLVMValueRef field = LLVMBuildLoad(p->builder, field_ptr, "");
  533. lbValue res = {};
  534. res.type = int_type;
  535. res.value = LLVMBuildZExtOrBitCast(p->builder, field, lb_type(p->module, int_type), "");
  536. return res;
  537. } else if (addr.kind == lbAddr_Context) {
  538. if (addr.ctx.sel.index.count > 0) {
  539. lbValue a = addr.addr;
  540. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  541. return lb_emit_load(p, b);
  542. } else {
  543. return lb_emit_load(p, addr.addr);
  544. }
  545. } else if (addr.kind == lbAddr_SoaVariable) {
  546. Type *t = type_deref(addr.addr.type);
  547. t = base_type(t);
  548. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  549. Type *elem = t->Struct.soa_elem;
  550. lbValue len = {};
  551. if (t->Struct.soa_kind == StructSoa_Fixed) {
  552. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  553. } else {
  554. lbValue v = lb_emit_load(p, addr.addr);
  555. len = lb_soa_struct_len(p, v);
  556. }
  557. lbAddr res = lb_add_local_generated(p, elem, true);
  558. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  559. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  560. }
  561. if (t->Struct.soa_kind == StructSoa_Fixed) {
  562. for_array(i, t->Struct.fields) {
  563. Entity *field = t->Struct.fields[i];
  564. Type *base_type = field->type;
  565. GB_ASSERT(base_type->kind == Type_Array);
  566. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  567. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  568. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  569. lbValue src = lb_emit_load(p, src_ptr);
  570. lb_emit_store(p, dst, src);
  571. }
  572. } else {
  573. isize field_count = t->Struct.fields.count;
  574. if (t->Struct.soa_kind == StructSoa_Slice) {
  575. field_count -= 1;
  576. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  577. field_count -= 3;
  578. }
  579. for (isize i = 0; i < field_count; i++) {
  580. Entity *field = t->Struct.fields[i];
  581. Type *base_type = field->type;
  582. GB_ASSERT(base_type->kind == Type_Pointer);
  583. Type *elem = base_type->Pointer.elem;
  584. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  585. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  586. src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index);
  587. lbValue src = lb_emit_load(p, src_ptr);
  588. src = lb_emit_load(p, src);
  589. lb_emit_store(p, dst, src);
  590. }
  591. }
  592. return lb_addr_load(p, res);
  593. }
  594. if (is_type_proc(addr.addr.type)) {
  595. return addr.addr;
  596. }
  597. return lb_emit_load(p, addr.addr);
  598. }
  599. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  600. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  601. }
  602. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  603. Type *t = u.type;
  604. GB_ASSERT_MSG(is_type_pointer(t) &&
  605. is_type_union(type_deref(t)), "%s", type_to_string(t));
  606. Type *ut = type_deref(t);
  607. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  608. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  609. GB_ASSERT(type_size_of(ut) > 0);
  610. Type *tag_type = union_tag_type(ut);
  611. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  612. unsigned element_count = LLVMCountStructElementTypes(uvt);
  613. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  614. lbValue tag_ptr = {};
  615. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  616. tag_ptr.type = alloc_type_pointer(tag_type);
  617. return tag_ptr;
  618. }
  619. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  620. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  621. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  622. return lb_emit_load(p, tag_ptr);
  623. }
  624. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  625. Type *t = type_deref(parent.type);
  626. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  627. // No tag needed!
  628. } else {
  629. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  630. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  631. }
  632. }
  633. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  634. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  635. lb_emit_store(p, underlying, variant);
  636. lb_emit_store_union_variant_tag(p, parent, variant_type);
  637. }
  638. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  639. unsigned field_count = LLVMCountStructElementTypes(src);
  640. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  641. LLVMGetStructElementTypes(src, fields);
  642. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  643. }
  644. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  645. switch (alignment) {
  646. case 1:
  647. return LLVMArrayType(lb_type(m, t_u8), 0);
  648. case 2:
  649. return LLVMArrayType(lb_type(m, t_u16), 0);
  650. case 4:
  651. return LLVMArrayType(lb_type(m, t_u32), 0);
  652. case 8:
  653. return LLVMArrayType(lb_type(m, t_u64), 0);
  654. case 16:
  655. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  656. default:
  657. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  658. break;
  659. }
  660. return nullptr;
  661. }
  662. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  663. if (!elem_type_can_be_constant(elem_type)) {
  664. return false;
  665. }
  666. if (elem->kind == Ast_FieldValue) {
  667. elem = elem->FieldValue.value;
  668. }
  669. TypeAndValue tav = type_and_value_of_expr(elem);
  670. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  671. return tav.value.kind != ExactValue_Invalid;
  672. }
  673. String lb_mangle_name(lbModule *m, Entity *e) {
  674. String name = e->token.string;
  675. AstPackage *pkg = e->pkg;
  676. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  677. String pkgn = pkg->name;
  678. GB_ASSERT(!rune_is_digit(pkgn[0]));
  679. if (pkgn == "llvm") {
  680. pkgn = str_lit("llvm$");
  681. }
  682. isize max_len = pkgn.len + 1 + name.len + 1;
  683. bool require_suffix_id = is_type_polymorphic(e->type, true);
  684. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  685. require_suffix_id = true;
  686. } else if (is_blank_ident(e->token)) {
  687. require_suffix_id = true;
  688. }if (e->flags & EntityFlag_NotExported) {
  689. require_suffix_id = true;
  690. }
  691. if (require_suffix_id) {
  692. max_len += 21;
  693. }
  694. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  695. isize new_name_len = gb_snprintf(
  696. new_name, max_len,
  697. "%.*s.%.*s", LIT(pkgn), LIT(name)
  698. );
  699. if (require_suffix_id) {
  700. char *str = new_name + new_name_len-1;
  701. isize len = max_len-new_name_len;
  702. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  703. new_name_len += extra-1;
  704. }
  705. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  706. return mangled_name;
  707. }
  708. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  709. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  710. // and as a result, the declaration does not have time to determine what it should be
  711. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  712. if (e->TypeName.ir_mangled_name.len != 0) {
  713. return e->TypeName.ir_mangled_name;
  714. }
  715. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  716. if (p == nullptr) {
  717. Entity *proc = nullptr;
  718. if (e->parent_proc_decl != nullptr) {
  719. proc = e->parent_proc_decl->entity;
  720. } else {
  721. Scope *scope = e->scope;
  722. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  723. scope = scope->parent;
  724. }
  725. GB_ASSERT(scope != nullptr);
  726. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  727. proc = scope->procedure_entity;
  728. }
  729. GB_ASSERT(proc->kind == Entity_Procedure);
  730. if (proc->code_gen_procedure != nullptr) {
  731. p = proc->code_gen_procedure;
  732. }
  733. }
  734. // NOTE(bill): Generate a new name
  735. // parent_proc.name-guid
  736. String ts_name = e->token.string;
  737. if (p != nullptr) {
  738. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  739. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  740. u32 guid = ++p->module->nested_type_name_guid;
  741. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  742. String name = make_string(cast(u8 *)name_text, name_len-1);
  743. e->TypeName.ir_mangled_name = name;
  744. return name;
  745. } else {
  746. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  747. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  748. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  749. static u32 guid = 0;
  750. guid += 1;
  751. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  752. String name = make_string(cast(u8 *)name_text, name_len-1);
  753. e->TypeName.ir_mangled_name = name;
  754. return name;
  755. }
  756. }
  757. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  758. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  759. return e->TypeName.ir_mangled_name;
  760. }
  761. GB_ASSERT(e != nullptr);
  762. if (e->pkg == nullptr) {
  763. return e->token.string;
  764. }
  765. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  766. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  767. }
  768. String name = {};
  769. bool no_name_mangle = false;
  770. if (e->kind == Entity_Variable) {
  771. bool is_foreign = e->Variable.is_foreign;
  772. bool is_export = e->Variable.is_export;
  773. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  774. if (e->Variable.link_name.len > 0) {
  775. return e->Variable.link_name;
  776. }
  777. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  778. return e->Procedure.link_name;
  779. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  780. no_name_mangle = true;
  781. }
  782. if (!no_name_mangle) {
  783. name = lb_mangle_name(m, e);
  784. }
  785. if (name.len == 0) {
  786. name = e->token.string;
  787. }
  788. if (e->kind == Entity_TypeName) {
  789. if ((e->scope->flags & ScopeFlag_File) == 0) {
  790. gb_printf_err("<<< %.*s %.*s %p\n", LIT(e->token.string), LIT(name), e);
  791. }
  792. e->TypeName.ir_mangled_name = name;
  793. } else if (e->kind == Entity_Procedure) {
  794. e->Procedure.link_name = name;
  795. }
  796. return name;
  797. }
  798. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  799. Type *original_type = type;
  800. LLVMContextRef ctx = m->ctx;
  801. i64 size = type_size_of(type); // Check size
  802. GB_ASSERT(type != t_invalid);
  803. switch (type->kind) {
  804. case Type_Basic:
  805. switch (type->Basic.kind) {
  806. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  807. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  808. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  809. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  810. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  811. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  812. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  813. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  814. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  815. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  816. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  817. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  818. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  819. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  820. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  821. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  822. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  823. // Basic_f16,
  824. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  825. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  826. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  827. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  828. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  829. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  830. // Basic_complex32,
  831. case Basic_complex64:
  832. {
  833. char const *name = "..complex64";
  834. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  835. if (type != nullptr) {
  836. return type;
  837. }
  838. type = LLVMStructCreateNamed(ctx, name);
  839. LLVMTypeRef fields[2] = {
  840. lb_type(m, t_f32),
  841. lb_type(m, t_f32),
  842. };
  843. LLVMStructSetBody(type, fields, 2, false);
  844. return type;
  845. }
  846. case Basic_complex128:
  847. {
  848. char const *name = "..complex128";
  849. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  850. if (type != nullptr) {
  851. return type;
  852. }
  853. type = LLVMStructCreateNamed(ctx, name);
  854. LLVMTypeRef fields[2] = {
  855. lb_type(m, t_f64),
  856. lb_type(m, t_f64),
  857. };
  858. LLVMStructSetBody(type, fields, 2, false);
  859. return type;
  860. }
  861. case Basic_quaternion128:
  862. {
  863. char const *name = "..quaternion128";
  864. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  865. if (type != nullptr) {
  866. return type;
  867. }
  868. type = LLVMStructCreateNamed(ctx, name);
  869. LLVMTypeRef fields[4] = {
  870. lb_type(m, t_f32),
  871. lb_type(m, t_f32),
  872. lb_type(m, t_f32),
  873. lb_type(m, t_f32),
  874. };
  875. LLVMStructSetBody(type, fields, 4, false);
  876. return type;
  877. }
  878. case Basic_quaternion256:
  879. {
  880. char const *name = "..quaternion256";
  881. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  882. if (type != nullptr) {
  883. return type;
  884. }
  885. type = LLVMStructCreateNamed(ctx, name);
  886. LLVMTypeRef fields[4] = {
  887. lb_type(m, t_f64),
  888. lb_type(m, t_f64),
  889. lb_type(m, t_f64),
  890. lb_type(m, t_f64),
  891. };
  892. LLVMStructSetBody(type, fields, 4, false);
  893. return type;
  894. }
  895. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  896. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  897. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  898. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  899. case Basic_string:
  900. {
  901. char const *name = "..string";
  902. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  903. if (type != nullptr) {
  904. return type;
  905. }
  906. type = LLVMStructCreateNamed(ctx, name);
  907. LLVMTypeRef fields[2] = {
  908. LLVMPointerType(lb_type(m, t_u8), 0),
  909. lb_type(m, t_int),
  910. };
  911. LLVMStructSetBody(type, fields, 2, false);
  912. return type;
  913. }
  914. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  915. case Basic_any:
  916. {
  917. char const *name = "..any";
  918. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  919. if (type != nullptr) {
  920. return type;
  921. }
  922. type = LLVMStructCreateNamed(ctx, name);
  923. LLVMTypeRef fields[2] = {
  924. lb_type(m, t_rawptr),
  925. lb_type(m, t_typeid),
  926. };
  927. LLVMStructSetBody(type, fields, 2, false);
  928. return type;
  929. }
  930. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  931. // Endian Specific Types
  932. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  933. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  934. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  935. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  936. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  937. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  938. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  939. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  940. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  941. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  942. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  943. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  944. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  945. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  946. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  947. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  948. // Untyped types
  949. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  950. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  951. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  952. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  953. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  954. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  955. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  956. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  957. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  958. }
  959. break;
  960. case Type_Named:
  961. {
  962. Type *base = base_type(type->Named.base);
  963. switch (base->kind) {
  964. case Type_Basic:
  965. return lb_type_internal(m, base);
  966. case Type_Named:
  967. case Type_Generic:
  968. case Type_BitFieldValue:
  969. GB_PANIC("INVALID TYPE");
  970. break;
  971. case Type_Opaque:
  972. return lb_type_internal(m, base->Opaque.elem);
  973. case Type_Pointer:
  974. case Type_Array:
  975. case Type_EnumeratedArray:
  976. case Type_Slice:
  977. case Type_DynamicArray:
  978. case Type_Map:
  979. case Type_Enum:
  980. case Type_BitSet:
  981. case Type_SimdVector:
  982. return lb_type_internal(m, base);
  983. // TODO(bill): Deal with this correctly. Can this be named?
  984. case Type_Proc:
  985. return lb_type_internal(m, base);
  986. case Type_Tuple:
  987. return lb_type_internal(m, base);
  988. }
  989. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  990. if (found) {
  991. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  992. if (kind == LLVMStructTypeKind) {
  993. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  994. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  995. if (llvm_type != nullptr) {
  996. return llvm_type;
  997. }
  998. llvm_type = LLVMStructCreateNamed(ctx, name);
  999. map_set(&m->types, hash_type(type), llvm_type);
  1000. lb_clone_struct_type(llvm_type, *found);
  1001. return llvm_type;
  1002. }
  1003. }
  1004. switch (base->kind) {
  1005. case Type_Struct:
  1006. case Type_Union:
  1007. case Type_BitField:
  1008. {
  1009. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1010. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1011. if (llvm_type != nullptr) {
  1012. return llvm_type;
  1013. }
  1014. llvm_type = LLVMStructCreateNamed(ctx, name);
  1015. map_set(&m->types, hash_type(type), llvm_type);
  1016. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1017. return llvm_type;
  1018. }
  1019. }
  1020. return lb_type_internal(m, base);
  1021. }
  1022. case Type_Pointer:
  1023. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1024. case Type_Opaque:
  1025. return lb_type(m, base_type(type));
  1026. case Type_Array:
  1027. return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1028. case Type_EnumeratedArray:
  1029. return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1030. case Type_Slice:
  1031. {
  1032. LLVMTypeRef fields[2] = {
  1033. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1034. lb_type(m, t_int), // len
  1035. };
  1036. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1037. }
  1038. break;
  1039. case Type_DynamicArray:
  1040. {
  1041. LLVMTypeRef fields[4] = {
  1042. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1043. lb_type(m, t_int), // len
  1044. lb_type(m, t_int), // cap
  1045. lb_type(m, t_allocator), // allocator
  1046. };
  1047. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1048. }
  1049. break;
  1050. case Type_Map:
  1051. return lb_type(m, type->Map.internal_type);
  1052. case Type_Struct:
  1053. {
  1054. if (type->Struct.is_raw_union) {
  1055. unsigned field_count = 2;
  1056. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1057. i64 alignment = type_align_of(type);
  1058. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1059. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1060. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1061. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1062. }
  1063. isize offset = 0;
  1064. if (type->Struct.custom_align > 0) {
  1065. offset = 1;
  1066. }
  1067. m->internal_type_level += 1;
  1068. defer (m->internal_type_level -= 1);
  1069. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1070. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1071. for_array(i, type->Struct.fields) {
  1072. Entity *field = type->Struct.fields[i];
  1073. fields[i+offset] = lb_type(m, field->type);
  1074. }
  1075. if (type->Struct.custom_align > 0) {
  1076. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1077. }
  1078. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1079. }
  1080. break;
  1081. case Type_Union:
  1082. if (type->Union.variants.count == 0) {
  1083. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1084. } else {
  1085. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1086. // LLVM takes the first element's alignment as the entire alignment (like C)
  1087. i64 align = type_align_of(type);
  1088. i64 size = type_size_of(type);
  1089. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1090. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1091. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1092. }
  1093. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1094. LLVMTypeRef fields[3] = {};
  1095. unsigned field_count = 1;
  1096. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1097. if (is_type_union_maybe_pointer(type)) {
  1098. field_count += 1;
  1099. fields[1] = lb_type(m, type->Union.variants[0]);
  1100. } else {
  1101. field_count += 2;
  1102. if (block_size == align) {
  1103. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1104. } else {
  1105. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1106. }
  1107. fields[2] = lb_type(m, union_tag_type(type));
  1108. }
  1109. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1110. }
  1111. break;
  1112. case Type_Enum:
  1113. return lb_type(m, base_enum_type(type));
  1114. case Type_Tuple:
  1115. if (type->Tuple.variables.count == 1) {
  1116. return lb_type(m, type->Tuple.variables[0]->type);
  1117. } else {
  1118. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1119. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1120. for_array(i, type->Tuple.variables) {
  1121. Entity *field = type->Tuple.variables[i];
  1122. LLVMTypeRef param_type = nullptr;
  1123. param_type = lb_type(m, field->type);
  1124. fields[i] = param_type;
  1125. }
  1126. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1127. }
  1128. case Type_Proc:
  1129. {
  1130. if (USE_LLVM_ABI) {
  1131. if (m->internal_type_level > 5) { // TODO HACK(bill): is this really enough?
  1132. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1133. } else {
  1134. unsigned param_count = 0;
  1135. if (type->Proc.calling_convention == ProcCC_Odin) {
  1136. param_count += 1;
  1137. }
  1138. if (type->Proc.param_count != 0) {
  1139. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1140. for_array(i, type->Proc.params->Tuple.variables) {
  1141. Entity *e = type->Proc.params->Tuple.variables[i];
  1142. if (e->kind != Entity_Variable) {
  1143. continue;
  1144. }
  1145. param_count += 1;
  1146. }
  1147. }
  1148. m->internal_type_level += 1;
  1149. defer (m->internal_type_level -= 1);
  1150. LLVMTypeRef ret = nullptr;
  1151. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1152. if (type->Proc.result_count != 0) {
  1153. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1154. ret = lb_type(m, single_ret);
  1155. if (ret != nullptr) {
  1156. if (is_type_boolean(single_ret) &&
  1157. is_calling_convention_none(type->Proc.calling_convention) &&
  1158. type_size_of(single_ret) <= 1) {
  1159. ret = LLVMInt1TypeInContext(m->ctx);
  1160. }
  1161. }
  1162. }
  1163. isize param_index = 0;
  1164. if (type->Proc.param_count != 0) {
  1165. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1166. for_array(i, type->Proc.params->Tuple.variables) {
  1167. Entity *e = type->Proc.params->Tuple.variables[i];
  1168. if (e->kind != Entity_Variable) {
  1169. continue;
  1170. }
  1171. Type *e_type = reduce_tuple_to_single_type(e->type);
  1172. LLVMTypeRef param_type = nullptr;
  1173. if (is_type_boolean(e_type) &&
  1174. type_size_of(e_type) <= 1) {
  1175. param_type = LLVMInt1TypeInContext(m->ctx);
  1176. } else {
  1177. param_type = lb_type(m, e_type);
  1178. }
  1179. params[param_index++] = param_type;
  1180. }
  1181. }
  1182. if (param_index < param_count) {
  1183. params[param_index++] = lb_type(m, t_context_ptr);
  1184. }
  1185. GB_ASSERT(param_index == param_count);
  1186. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1187. map_set(&m->function_type_map, hash_type(type), ft);
  1188. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1189. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1190. // LLVMTypeRef new_ret = LLVMGetReturnType(new_abi_fn_type);
  1191. // LLVMTypeRef old_ret = LLVMGetReturnType(old_abi_fn_type);
  1192. // unsigned new_count = LLVMCountParamTypes(new_abi_fn_type);
  1193. // unsigned old_count = LLVMCountParamTypes(old_abi_fn_type);
  1194. // GB_ASSERT_MSG(new_count == old_count, "%u %u, %s %s", new_count, old_count, LLVMPrintTypeToString(new_abi_fn_type), LLVMPrintTypeToString(old_abi_fn_type));
  1195. return new_abi_fn_ptr_type;
  1196. }
  1197. } else {
  1198. LLVMTypeRef old_abi_fn_type = nullptr;
  1199. set_procedure_abi_types(type);
  1200. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1201. if (type->Proc.return_by_pointer) {
  1202. // Void
  1203. } else if (type->Proc.abi_compat_result_type != nullptr) {
  1204. return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1205. }
  1206. isize extra_param_count = 0;
  1207. if (type->Proc.return_by_pointer) {
  1208. extra_param_count += 1;
  1209. }
  1210. if (type->Proc.calling_convention == ProcCC_Odin) {
  1211. extra_param_count += 1;
  1212. }
  1213. isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1214. auto param_types = array_make<LLVMTypeRef>(temporary_allocator(), 0, param_count);
  1215. if (type->Proc.return_by_pointer) {
  1216. array_add(&param_types, LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0));
  1217. }
  1218. for_array(i, type->Proc.abi_compat_params) {
  1219. Type *param = type->Proc.abi_compat_params[i];
  1220. if (param == nullptr) {
  1221. continue;
  1222. }
  1223. if (type->Proc.params->Tuple.variables[i]->flags & EntityFlag_CVarArg) {
  1224. GB_ASSERT(i+1 == type->Proc.abi_compat_params.count);
  1225. break;
  1226. }
  1227. if (is_type_tuple(param)) {
  1228. param = base_type(param);
  1229. for_array(j, param->Tuple.variables) {
  1230. Entity *v = param->Tuple.variables[j];
  1231. if (v->kind != Entity_Variable) {
  1232. // Sanity check
  1233. continue;
  1234. }
  1235. LLVMTypeRef t = lb_type(m, v->type);
  1236. array_add(&param_types, t);
  1237. }
  1238. } else {
  1239. array_add(&param_types, lb_type(m, param));
  1240. }
  1241. }
  1242. if (type->Proc.calling_convention == ProcCC_Odin) {
  1243. array_add(&param_types, lb_type(m, t_context_ptr));
  1244. }
  1245. old_abi_fn_type = LLVMFunctionType(return_type, param_types.data, cast(unsigned)param_types.count, type->Proc.c_vararg);
  1246. return LLVMPointerType(old_abi_fn_type, 0);
  1247. }
  1248. }
  1249. break;
  1250. case Type_BitFieldValue:
  1251. return LLVMIntTypeInContext(m->ctx, type->BitFieldValue.bits);
  1252. case Type_BitField:
  1253. {
  1254. LLVMTypeRef internal_type = nullptr;
  1255. {
  1256. GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  1257. unsigned field_count = cast(unsigned)type->BitField.fields.count;
  1258. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1259. for_array(i, type->BitField.sizes) {
  1260. u32 size = type->BitField.sizes[i];
  1261. fields[i] = LLVMIntTypeInContext(m->ctx, size);
  1262. }
  1263. internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  1264. }
  1265. unsigned field_count = 2;
  1266. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1267. i64 alignment = 1;
  1268. if (type->BitField.custom_align > 0) {
  1269. alignment = type->BitField.custom_align;
  1270. }
  1271. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1272. fields[1] = internal_type;
  1273. return LLVMStructTypeInContext(ctx, fields, field_count, true);
  1274. }
  1275. break;
  1276. case Type_BitSet:
  1277. {
  1278. Type *ut = bit_set_to_int(type);
  1279. return lb_type(m, ut);
  1280. }
  1281. case Type_SimdVector:
  1282. if (type->SimdVector.is_x86_mmx) {
  1283. return LLVMX86MMXTypeInContext(ctx);
  1284. }
  1285. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1286. case Type_RelativePointer:
  1287. return lb_type_internal(m, type->RelativePointer.base_integer);
  1288. case Type_RelativeSlice:
  1289. {
  1290. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1291. unsigned field_count = 2;
  1292. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1293. fields[0] = base_integer;
  1294. fields[1] = base_integer;
  1295. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1296. }
  1297. }
  1298. GB_PANIC("Invalid type %s", type_to_string(type));
  1299. return LLVMInt32TypeInContext(ctx);
  1300. }
  1301. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1302. type = default_type(type);
  1303. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1304. if (found) {
  1305. return *found;
  1306. }
  1307. LLVMTypeRef llvm_type = nullptr;
  1308. m->internal_type_level += 1;
  1309. llvm_type = lb_type_internal(m, type);
  1310. m->internal_type_level -= 1;
  1311. if (USE_LLVM_ABI && m->internal_type_level == 0) {
  1312. map_set(&m->types, hash_type(type), llvm_type);
  1313. if (is_type_named(type)) {
  1314. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1315. }
  1316. }
  1317. return llvm_type;
  1318. }
  1319. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1320. Type *original_type = type;
  1321. LLVMContextRef ctx = m->ctx;
  1322. i64 size = type_size_of(type); // Check size
  1323. GB_ASSERT(type != t_invalid);
  1324. switch (type->kind) {
  1325. case Type_Basic:
  1326. switch (type->Basic.kind) {
  1327. case Basic_llvm_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "llvm bool", 9, 1, 0, LLVMDIFlagZero);
  1328. case Basic_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "bool", 4, 8, 0, LLVMDIFlagZero);
  1329. case Basic_b8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b8", 2, 8, 0, LLVMDIFlagZero);
  1330. case Basic_b16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b16", 3, 16, 0, LLVMDIFlagZero);
  1331. case Basic_b32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b32", 3, 32, 0, LLVMDIFlagZero);
  1332. case Basic_b64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b64", 3, 64, 0, LLVMDIFlagZero);
  1333. case Basic_i8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i8", 2, 8, 0, LLVMDIFlagZero);
  1334. case Basic_u8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u8", 2, 8, 0, LLVMDIFlagZero);
  1335. case Basic_i16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16", 3, 16, 0, LLVMDIFlagZero);
  1336. case Basic_u16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16", 3, 16, 0, LLVMDIFlagZero);
  1337. case Basic_i32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32", 3, 32, 0, LLVMDIFlagZero);
  1338. case Basic_u32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32", 3, 32, 0, LLVMDIFlagZero);
  1339. case Basic_i64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64", 3, 64, 0, LLVMDIFlagZero);
  1340. case Basic_u64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64", 3, 64, 0, LLVMDIFlagZero);
  1341. case Basic_i128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128", 4, 128, 0, LLVMDIFlagZero);
  1342. case Basic_u128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128", 4, 128, 0, LLVMDIFlagZero);
  1343. case Basic_rune: return LLVMDIBuilderCreateBasicType(m->debug_builder, "rune", 4, 32, 0, LLVMDIFlagZero);
  1344. // Basic_f16,
  1345. case Basic_f32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f32", 3, 32, 0, LLVMDIFlagZero);
  1346. case Basic_f64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f64", 3, 64, 0, LLVMDIFlagZero);
  1347. // Basic_complex32,
  1348. case Basic_complex64:
  1349. {
  1350. return nullptr;
  1351. // char const *name = "..complex64";
  1352. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1353. // if (type != nullptr) {
  1354. // return type;
  1355. // }
  1356. // type = LLVMStructCreateNamed(ctx, name);
  1357. // LLVMTypeRef fields[2] = {
  1358. // lb_type(m, t_f32),
  1359. // lb_type(m, t_f32),
  1360. // };
  1361. // LLVMStructSetBody(type, fields, 2, false);
  1362. // return type;
  1363. }
  1364. case Basic_complex128:
  1365. {
  1366. return nullptr;
  1367. // char const *name = "..complex128";
  1368. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1369. // if (type != nullptr) {
  1370. // return type;
  1371. // }
  1372. // type = LLVMStructCreateNamed(ctx, name);
  1373. // LLVMTypeRef fields[2] = {
  1374. // lb_type(m, t_f64),
  1375. // lb_type(m, t_f64),
  1376. // };
  1377. // LLVMStructSetBody(type, fields, 2, false);
  1378. // return type;
  1379. }
  1380. case Basic_quaternion128:
  1381. {
  1382. return nullptr;
  1383. // char const *name = "..quaternion128";
  1384. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1385. // if (type != nullptr) {
  1386. // return type;
  1387. // }
  1388. // type = LLVMStructCreateNamed(ctx, name);
  1389. // LLVMTypeRef fields[4] = {
  1390. // lb_type(m, t_f32),
  1391. // lb_type(m, t_f32),
  1392. // lb_type(m, t_f32),
  1393. // lb_type(m, t_f32),
  1394. // };
  1395. // LLVMStructSetBody(type, fields, 4, false);
  1396. // return type;
  1397. }
  1398. case Basic_quaternion256:
  1399. {
  1400. return nullptr;
  1401. // char const *name = "..quaternion256";
  1402. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1403. // if (type != nullptr) {
  1404. // return type;
  1405. // }
  1406. // type = LLVMStructCreateNamed(ctx, name);
  1407. // LLVMTypeRef fields[4] = {
  1408. // lb_type(m, t_f64),
  1409. // lb_type(m, t_f64),
  1410. // lb_type(m, t_f64),
  1411. // lb_type(m, t_f64),
  1412. // };
  1413. // LLVMStructSetBody(type, fields, 4, false);
  1414. // return type;
  1415. }
  1416. case Basic_int: return LLVMDIBuilderCreateBasicType(m->debug_builder, "int", 3, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1417. case Basic_uint: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uint", 4, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1418. case Basic_uintptr: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uintptr", 7, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1419. case Basic_rawptr:
  1420. return nullptr;
  1421. // return LLVMPointerType(LLVMInt8Type(), 0);
  1422. case Basic_string:
  1423. {
  1424. return nullptr;
  1425. // char const *name = "..string";
  1426. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1427. // if (type != nullptr) {
  1428. // return type;
  1429. // }
  1430. // type = LLVMStructCreateNamed(ctx, name);
  1431. // LLVMTypeRef fields[2] = {
  1432. // LLVMPointerType(lb_type(m, t_u8), 0),
  1433. // lb_type(m, t_int),
  1434. // };
  1435. // LLVMStructSetBody(type, fields, 2, false);
  1436. // return type;
  1437. }
  1438. case Basic_cstring:
  1439. return nullptr;
  1440. // return LLVMPointerType(LLVMInt8Type(), 0);
  1441. case Basic_any:
  1442. {
  1443. return nullptr;
  1444. // char const *name = "..any";
  1445. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1446. // if (type != nullptr) {
  1447. // return type;
  1448. // }
  1449. // type = LLVMStructCreateNamed(ctx, name);
  1450. // LLVMTypeRef fields[2] = {
  1451. // lb_type(m, t_rawptr),
  1452. // lb_type(m, t_typeid),
  1453. // };
  1454. // LLVMStructSetBody(type, fields, 2, false);
  1455. // return type;
  1456. }
  1457. case Basic_typeid: return LLVMDIBuilderCreateBasicType(m->debug_builder, "typeid", 6, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1458. // Endian Specific Types
  1459. case Basic_i16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1460. case Basic_u16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1461. case Basic_i32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1462. case Basic_u32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1463. case Basic_i64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1464. case Basic_u64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1465. case Basic_i128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1466. case Basic_u128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1467. case Basic_i16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1468. case Basic_u16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1469. case Basic_i32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1470. case Basic_u32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1471. case Basic_i64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1472. case Basic_u64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1473. case Basic_i128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1474. case Basic_u128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1475. // Untyped types
  1476. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1477. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1478. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1479. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1480. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1481. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1482. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1483. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1484. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1485. }
  1486. break;
  1487. case Type_Named:
  1488. {
  1489. return nullptr;
  1490. // Type *base = base_type(type->Named.base);
  1491. // switch (base->kind) {
  1492. // case Type_Basic:
  1493. // return lb_type(m, base);
  1494. // case Type_Named:
  1495. // case Type_Generic:
  1496. // case Type_BitFieldValue:
  1497. // GB_PANIC("INVALID TYPE");
  1498. // break;
  1499. // case Type_Opaque:
  1500. // return lb_type(m, base->Opaque.elem);
  1501. // case Type_Pointer:
  1502. // case Type_Array:
  1503. // case Type_EnumeratedArray:
  1504. // case Type_Slice:
  1505. // case Type_DynamicArray:
  1506. // case Type_Map:
  1507. // case Type_Enum:
  1508. // case Type_BitSet:
  1509. // case Type_SimdVector:
  1510. // return lb_type(m, base);
  1511. // // TODO(bill): Deal with this correctly. Can this be named?
  1512. // case Type_Proc:
  1513. // return lb_type(m, base);
  1514. // case Type_Tuple:
  1515. // return lb_type(m, base);
  1516. // }
  1517. // LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1518. // if (found) {
  1519. // LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1520. // if (kind == LLVMStructTypeKind) {
  1521. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1522. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1523. // if (llvm_type != nullptr) {
  1524. // return llvm_type;
  1525. // }
  1526. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1527. // map_set(&m->types, hash_type(type), llvm_type);
  1528. // lb_clone_struct_type(llvm_type, *found);
  1529. // return llvm_type;
  1530. // }
  1531. // }
  1532. // switch (base->kind) {
  1533. // case Type_Struct:
  1534. // case Type_Union:
  1535. // case Type_BitField:
  1536. // {
  1537. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1538. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1539. // if (llvm_type != nullptr) {
  1540. // return llvm_type;
  1541. // }
  1542. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1543. // map_set(&m->types, hash_type(type), llvm_type);
  1544. // lb_clone_struct_type(llvm_type, lb_type(m, base));
  1545. // return llvm_type;
  1546. // }
  1547. // }
  1548. // return lb_type(m, base);
  1549. }
  1550. case Type_Pointer:
  1551. return nullptr;
  1552. // return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1553. case Type_Opaque:
  1554. return nullptr;
  1555. // return lb_type(m, base_type(type));
  1556. case Type_Array:
  1557. return nullptr;
  1558. // return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1559. case Type_EnumeratedArray:
  1560. return nullptr;
  1561. // return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1562. case Type_Slice:
  1563. {
  1564. return nullptr;
  1565. // LLVMTypeRef fields[2] = {
  1566. // LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1567. // lb_type(m, t_int), // len
  1568. // };
  1569. // return LLVMStructTypeInContext(ctx, fields, 2, false);
  1570. }
  1571. break;
  1572. case Type_DynamicArray:
  1573. {
  1574. return nullptr;
  1575. // LLVMTypeRef fields[4] = {
  1576. // LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1577. // lb_type(m, t_int), // len
  1578. // lb_type(m, t_int), // cap
  1579. // lb_type(m, t_allocator), // allocator
  1580. // };
  1581. // return LLVMStructTypeInContext(ctx, fields, 4, false);
  1582. }
  1583. break;
  1584. case Type_Map:
  1585. return nullptr;
  1586. // return lb_type(m, type->Map.internal_type);
  1587. case Type_Struct:
  1588. {
  1589. return nullptr;
  1590. // if (type->Struct.is_raw_union) {
  1591. // unsigned field_count = 2;
  1592. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1593. // i64 alignment = type_align_of(type);
  1594. // unsigned size_of_union = cast(unsigned)type_size_of(type);
  1595. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1596. // fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1597. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1598. // }
  1599. // isize offset = 0;
  1600. // if (type->Struct.custom_align > 0) {
  1601. // offset = 1;
  1602. // }
  1603. // unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1604. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1605. // GB_ASSERT(fields != nullptr);
  1606. // defer (gb_free(heap_allocator(), fields));
  1607. // for_array(i, type->Struct.fields) {
  1608. // Entity *field = type->Struct.fields[i];
  1609. // fields[i+offset] = lb_type(m, field->type);
  1610. // }
  1611. // if (type->Struct.custom_align > 0) {
  1612. // fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1613. // }
  1614. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1615. }
  1616. break;
  1617. case Type_Union:
  1618. return nullptr;
  1619. // if (type->Union.variants.count == 0) {
  1620. // return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1621. // } else {
  1622. // // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1623. // // LLVM takes the first element's alignment as the entire alignment (like C)
  1624. // i64 align = type_align_of(type);
  1625. // i64 size = type_size_of(type);
  1626. // if (is_type_union_maybe_pointer_original_alignment(type)) {
  1627. // LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1628. // return LLVMStructTypeInContext(ctx, fields, 1, false);
  1629. // }
  1630. // unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1631. // LLVMTypeRef fields[3] = {};
  1632. // unsigned field_count = 1;
  1633. // fields[0] = lb_alignment_prefix_type_hack(m, align);
  1634. // if (is_type_union_maybe_pointer(type)) {
  1635. // field_count += 1;
  1636. // fields[1] = lb_type(m, type->Union.variants[0]);
  1637. // } else {
  1638. // field_count += 2;
  1639. // if (block_size == align) {
  1640. // fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1641. // } else {
  1642. // fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1643. // }
  1644. // fields[2] = lb_type(m, union_tag_type(type));
  1645. // }
  1646. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1647. // }
  1648. // break;
  1649. case Type_Enum:
  1650. return nullptr;
  1651. // return lb_type(m, base_enum_type(type));
  1652. case Type_Tuple:
  1653. return nullptr;
  1654. // if (type->Tuple.variables.count == 1) {
  1655. // return lb_type(m, type->Tuple.variables[0]->type);
  1656. // } else {
  1657. // unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1658. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1659. // defer (gb_free(heap_allocator(), fields));
  1660. // for_array(i, type->Tuple.variables) {
  1661. // Entity *field = type->Tuple.variables[i];
  1662. // fields[i] = lb_type(m, field->type);
  1663. // }
  1664. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1665. // }
  1666. case Type_Proc:
  1667. {
  1668. return nullptr;
  1669. // set_procedure_abi_types(type);
  1670. // LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1671. // isize offset = 0;
  1672. // if (type->Proc.return_by_pointer) {
  1673. // offset = 1;
  1674. // } else if (type->Proc.abi_compat_result_type != nullptr) {
  1675. // return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1676. // }
  1677. // isize extra_param_count = offset;
  1678. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1679. // extra_param_count += 1;
  1680. // }
  1681. // isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1682. // LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1683. // defer (gb_free(heap_allocator(), param_types));
  1684. // isize param_index = offset;
  1685. // for_array(i, type->Proc.abi_compat_params) {
  1686. // Type *param = type->Proc.abi_compat_params[i];
  1687. // if (param == nullptr) {
  1688. // continue;
  1689. // }
  1690. // param_types[param_index++] = lb_type(m, param);
  1691. // }
  1692. // if (type->Proc.return_by_pointer) {
  1693. // param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0);
  1694. // }
  1695. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1696. // param_types[param_index++] = lb_type(m, t_context_ptr);
  1697. // }
  1698. // LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg);
  1699. // return LLVMPointerType(t, 0);
  1700. }
  1701. break;
  1702. case Type_BitFieldValue:
  1703. return nullptr;
  1704. // return LLVMIntTypeInContext(m->ctx, type->BitFieldValue.bits);
  1705. case Type_BitField:
  1706. {
  1707. return nullptr;
  1708. // LLVMTypeRef internal_type = nullptr;
  1709. // {
  1710. // GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  1711. // unsigned field_count = cast(unsigned)type->BitField.fields.count;
  1712. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1713. // defer (gb_free(heap_allocator(), fields));
  1714. // for_array(i, type->BitField.sizes) {
  1715. // u32 size = type->BitField.sizes[i];
  1716. // fields[i] = LLVMIntTypeInContext(m->ctx, size);
  1717. // }
  1718. // internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  1719. // }
  1720. // unsigned field_count = 2;
  1721. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1722. // i64 alignment = 1;
  1723. // if (type->BitField.custom_align > 0) {
  1724. // alignment = type->BitField.custom_align;
  1725. // }
  1726. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1727. // fields[1] = internal_type;
  1728. // return LLVMStructTypeInContext(ctx, fields, field_count, true);
  1729. }
  1730. break;
  1731. case Type_BitSet:
  1732. return nullptr;
  1733. // return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)type_size_of(type));
  1734. case Type_SimdVector:
  1735. return nullptr;
  1736. // if (type->SimdVector.is_x86_mmx) {
  1737. // return LLVMX86MMXTypeInContext(ctx);
  1738. // }
  1739. // return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1740. }
  1741. GB_PANIC("Invalid type %s", type_to_string(type));
  1742. return nullptr;
  1743. }
  1744. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1745. LLVMTypeRef t = lb_type(m, type);
  1746. LLVMMetadataRef *found = map_get(&m->debug_values, hash_pointer(t));
  1747. if (found != nullptr) {
  1748. return *found;
  1749. }
  1750. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1751. map_set(&m->debug_values, hash_pointer(t), dt);
  1752. return dt;
  1753. }
  1754. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1755. if (e != nullptr) {
  1756. map_set(&m->values, hash_entity(e), val);
  1757. }
  1758. }
  1759. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1760. if (name.len > 0) {
  1761. string_map_set(&m->members, name, val);
  1762. }
  1763. }
  1764. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1765. string_map_set(&m->members, key, val);
  1766. }
  1767. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1768. if (p->entity != nullptr) {
  1769. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1770. }
  1771. string_map_set(&m->procedures, p->name, p);
  1772. }
  1773. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  1774. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  1775. LLVMValueRef values[2] = {
  1776. str_elem.value,
  1777. str_len.value,
  1778. };
  1779. lbValue res = {};
  1780. res.type = t_string;
  1781. res.value = LLVMConstNamedStruct(lb_type(p->module, t_string), values, gb_count_of(values));
  1782. return res;
  1783. } else {
  1784. lbAddr res = lb_add_local_generated(p, t_string, false);
  1785. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  1786. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  1787. return lb_addr_load(p, res);
  1788. }
  1789. }
  1790. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1791. unsigned kind = LLVMGetEnumAttributeKindForName(name, gb_strlen(name));
  1792. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1793. return LLVMCreateEnumAttribute(ctx, kind, value);
  1794. }
  1795. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1796. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1797. GB_ASSERT(attr != nullptr);
  1798. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1799. }
  1800. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1801. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  1802. }
  1803. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  1804. GB_ASSERT(entity != nullptr);
  1805. String link_name = lb_get_entity_name(m, entity);
  1806. {
  1807. StringHashKey key = string_hash_string(link_name);
  1808. lbValue *found = string_map_get(&m->members, key);
  1809. if (found) {
  1810. lb_add_entity(m, entity, *found);
  1811. lbProcedure **p_found = string_map_get(&m->procedures, key);
  1812. GB_ASSERT(p_found != nullptr);
  1813. return *p_found;
  1814. }
  1815. }
  1816. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  1817. p->module = m;
  1818. entity->code_gen_module = m;
  1819. entity->code_gen_procedure = p;
  1820. p->entity = entity;
  1821. p->name = link_name;
  1822. DeclInfo *decl = entity->decl_info;
  1823. ast_node(pl, ProcLit, decl->proc_lit);
  1824. Type *pt = base_type(entity->type);
  1825. GB_ASSERT(pt->kind == Type_Proc);
  1826. set_procedure_abi_types(entity->type);
  1827. p->type = entity->type;
  1828. p->type_expr = decl->type_expr;
  1829. p->body = pl->body;
  1830. p->tags = pt->Proc.tags;
  1831. p->inlining = ProcInlining_none;
  1832. p->is_foreign = entity->Procedure.is_foreign;
  1833. p->is_export = entity->Procedure.is_export;
  1834. p->is_entry_point = false;
  1835. gbAllocator a = heap_allocator();
  1836. p->children.allocator = a;
  1837. p->params.allocator = a;
  1838. p->defer_stmts.allocator = a;
  1839. p->blocks.allocator = a;
  1840. p->branch_blocks.allocator = a;
  1841. p->context_stack.allocator = a;
  1842. if (p->is_foreign) {
  1843. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  1844. }
  1845. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  1846. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1847. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1848. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1849. lbFunctionType **ft_found = map_get(&m->function_type_map, hash_type(p->type));
  1850. if (USE_LLVM_ABI && ft_found) {
  1851. lbFunctionType *abi_ft = *ft_found;
  1852. p->abi_function_type = abi_ft;
  1853. lb_add_function_type_attributes(p->value, abi_ft, abi_ft->calling_convention);
  1854. } else {
  1855. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1856. // TODO(bill): Clean up this logic
  1857. if (build_context.metrics.os != TargetOs_js) {
  1858. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1859. }
  1860. LLVMSetFunctionCallConv(p->value, cc_kind);
  1861. }
  1862. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1863. // // TODO(bill): Clean up this logic
  1864. // if (build_context.metrics.os != TargetOs_js) {
  1865. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1866. // }
  1867. // LLVMSetFunctionCallConv(p->value, cc_kind);
  1868. lbValue proc_value = {p->value, p->type};
  1869. lb_add_entity(m, entity, proc_value);
  1870. lb_add_member(m, p->name, proc_value);
  1871. lb_add_procedure_value(m, p);
  1872. if (p->is_export) {
  1873. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  1874. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  1875. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  1876. if (build_context.metrics.os == TargetOs_js) {
  1877. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  1878. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  1879. }
  1880. }
  1881. if (p->is_foreign) {
  1882. if (build_context.metrics.os == TargetOs_js) {
  1883. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  1884. char const *module_name = "env";
  1885. if (entity->Procedure.foreign_library != nullptr) {
  1886. Entity *foreign_library = entity->Procedure.foreign_library;
  1887. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  1888. if (foreign_library->LibraryName.paths.count > 0) {
  1889. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  1890. }
  1891. }
  1892. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  1893. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  1894. }
  1895. }
  1896. // NOTE(bill): offset==0 is the return value
  1897. isize offset = 1;
  1898. if (pt->Proc.return_by_pointer) {
  1899. if (!USE_LLVM_ABI) {
  1900. lb_add_proc_attribute_at_index(p, 1, "sret");
  1901. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1902. }
  1903. offset = 2;
  1904. }
  1905. isize parameter_index = 0;
  1906. if (pt->Proc.param_count) {
  1907. TypeTuple *params = &pt->Proc.params->Tuple;
  1908. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1909. Entity *e = params->variables[i];
  1910. Type *original_type = e->type;
  1911. Type *abi_type = pt->Proc.abi_compat_params[i];
  1912. if (e->kind != Entity_Variable) continue;
  1913. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1914. continue;
  1915. }
  1916. if (is_type_tuple(abi_type)) {
  1917. for_array(j, abi_type->Tuple.variables) {
  1918. Type *tft = abi_type->Tuple.variables[j]->type;
  1919. if (e->flags&EntityFlag_NoAlias) {
  1920. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1921. }
  1922. }
  1923. parameter_index += abi_type->Tuple.variables.count;
  1924. } else {
  1925. if (e->flags&EntityFlag_NoAlias) {
  1926. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1927. }
  1928. parameter_index += 1;
  1929. }
  1930. }
  1931. }
  1932. if (!USE_LLVM_ABI && pt->Proc.calling_convention == ProcCC_Odin) {
  1933. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1934. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1935. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1936. }
  1937. { // Debug Information
  1938. unsigned line = cast(unsigned)entity->token.pos.line;
  1939. LLVMMetadataRef file = nullptr;
  1940. if (entity->file != nullptr) {
  1941. cast(LLVMMetadataRef)entity->file->llvm_metadata;
  1942. }
  1943. LLVMMetadataRef scope = nullptr;
  1944. LLVMMetadataRef type = nullptr;
  1945. // type = LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, nullptr, 0, LLVMDIFlagZero);
  1946. LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  1947. cast(char const *)entity->token.string.text, entity->token.string.len,
  1948. cast(char const *)p->name.text, p->name.len,
  1949. file, line, type,
  1950. true, p->body == nullptr,
  1951. line, LLVMDIFlagZero, false
  1952. );
  1953. GB_ASSERT(res != nullptr);
  1954. map_set(&m->debug_values, hash_pointer(p), res);
  1955. }
  1956. return p;
  1957. }
  1958. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  1959. {
  1960. lbValue *found = string_map_get(&m->members, link_name);
  1961. GB_ASSERT(found == nullptr);
  1962. }
  1963. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  1964. p->module = m;
  1965. p->name = link_name;
  1966. p->type = type;
  1967. p->type_expr = nullptr;
  1968. p->body = nullptr;
  1969. p->tags = 0;
  1970. p->inlining = ProcInlining_none;
  1971. p->is_foreign = false;
  1972. p->is_export = false;
  1973. p->is_entry_point = false;
  1974. gbAllocator a = permanent_allocator();
  1975. p->children.allocator = a;
  1976. p->params.allocator = a;
  1977. p->defer_stmts.allocator = a;
  1978. p->blocks.allocator = a;
  1979. p->branch_blocks.allocator = a;
  1980. p->context_stack.allocator = a;
  1981. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  1982. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1983. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1984. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1985. Type *pt = p->type;
  1986. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1987. // TODO(bill): Clean up this logic
  1988. if (build_context.metrics.os != TargetOs_js) {
  1989. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1990. }
  1991. LLVMSetFunctionCallConv(p->value, cc_kind);
  1992. lbValue proc_value = {p->value, p->type};
  1993. lb_add_member(m, p->name, proc_value);
  1994. lb_add_procedure_value(m, p);
  1995. // NOTE(bill): offset==0 is the return value
  1996. isize offset = 1;
  1997. if (pt->Proc.return_by_pointer) {
  1998. lb_add_proc_attribute_at_index(p, 1, "sret");
  1999. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2000. offset = 2;
  2001. }
  2002. isize parameter_index = 0;
  2003. if (!USE_LLVM_ABI && pt->Proc.param_count) {
  2004. TypeTuple *params = &pt->Proc.params->Tuple;
  2005. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2006. Entity *e = params->variables[i];
  2007. Type *original_type = e->type;
  2008. Type *abi_type = pt->Proc.abi_compat_params[i];
  2009. if (e->kind != Entity_Variable) continue;
  2010. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2011. continue;
  2012. }
  2013. if (is_type_tuple(abi_type)) {
  2014. for_array(j, abi_type->Tuple.variables) {
  2015. Type *tft = abi_type->Tuple.variables[j]->type;
  2016. if (e->flags&EntityFlag_NoAlias) {
  2017. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  2018. }
  2019. }
  2020. parameter_index += abi_type->Tuple.variables.count;
  2021. } else {
  2022. if (e->flags&EntityFlag_NoAlias) {
  2023. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2024. }
  2025. parameter_index += 1;
  2026. }
  2027. }
  2028. }
  2029. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2030. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2031. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2032. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2033. }
  2034. return p;
  2035. }
  2036. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2037. lbParamPasskind kind = lbParamPass_Value;
  2038. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2039. if (is_type_pointer(abi_type)) {
  2040. GB_ASSERT(e->kind == Entity_Variable);
  2041. Type *av = core_type(type_deref(abi_type));
  2042. if (are_types_identical(av, core_type(e->type))) {
  2043. kind = lbParamPass_Pointer;
  2044. if (e->flags&EntityFlag_Value) {
  2045. kind = lbParamPass_ConstRef;
  2046. }
  2047. } else {
  2048. kind = lbParamPass_BitCast;
  2049. }
  2050. } else if (is_type_integer(abi_type)) {
  2051. kind = lbParamPass_Integer;
  2052. } else if (abi_type == t_llvm_bool) {
  2053. kind = lbParamPass_Value;
  2054. } else if (is_type_boolean(abi_type)) {
  2055. kind = lbParamPass_Integer;
  2056. } else if (is_type_simd_vector(abi_type)) {
  2057. kind = lbParamPass_BitCast;
  2058. } else if (is_type_float(abi_type)) {
  2059. kind = lbParamPass_BitCast;
  2060. } else if (is_type_tuple(abi_type)) {
  2061. kind = lbParamPass_Tuple;
  2062. } else if (is_type_proc(abi_type)) {
  2063. kind = lbParamPass_Value;
  2064. } else {
  2065. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2066. }
  2067. }
  2068. if (kind_) *kind_ = kind;
  2069. lbValue res = {};
  2070. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2071. res.type = abi_type;
  2072. return res;
  2073. }
  2074. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  2075. lbParamPasskind kind = lbParamPass_Value;
  2076. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  2077. array_add(&p->params, v);
  2078. lbValue res = {};
  2079. switch (kind) {
  2080. case lbParamPass_Value: {
  2081. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2082. lbValue x = v;
  2083. if (abi_type == t_llvm_bool) {
  2084. x = lb_emit_conv(p, x, t_bool);
  2085. }
  2086. lb_addr_store(p, l, x);
  2087. return x;
  2088. }
  2089. case lbParamPass_Pointer:
  2090. lb_add_entity(p->module, e, v);
  2091. return lb_emit_load(p, v);
  2092. case lbParamPass_Integer: {
  2093. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2094. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  2095. lb_emit_store(p, iptr, v);
  2096. return lb_addr_load(p, l);
  2097. }
  2098. case lbParamPass_ConstRef:
  2099. lb_add_entity(p->module, e, v);
  2100. return lb_emit_load(p, v);
  2101. case lbParamPass_BitCast: {
  2102. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2103. lbValue x = lb_emit_transmute(p, v, e->type);
  2104. lb_addr_store(p, l, x);
  2105. return x;
  2106. }
  2107. case lbParamPass_Tuple: {
  2108. lbAddr l = lb_add_local(p, e->type, e, true, index);
  2109. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2110. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  2111. if (abi_type->Tuple.variables.count > 0) {
  2112. array_pop(&p->params);
  2113. }
  2114. for_array(i, abi_type->Tuple.variables) {
  2115. Type *t = abi_type->Tuple.variables[i]->type;
  2116. GB_ASSERT(!is_type_tuple(t));
  2117. lbParamPasskind elem_kind = lbParamPass_Value;
  2118. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  2119. array_add(&p->params, elem);
  2120. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2121. lb_emit_store(p, dst, elem);
  2122. }
  2123. return lb_addr_load(p, l);
  2124. }
  2125. }
  2126. GB_PANIC("Unreachable");
  2127. return {};
  2128. }
  2129. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2130. GB_ASSERT(b != nullptr);
  2131. if (!b->appended) {
  2132. b->appended = true;
  2133. LLVMAppendExistingBasicBlock(p->value, b->block);
  2134. }
  2135. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2136. p->curr_block = b;
  2137. }
  2138. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2139. LLVMContextRef ctx = p->module->ctx;
  2140. LLVMTypeRef src_type = LLVMTypeOf(val);
  2141. if (src_type == dst_type) {
  2142. return val;
  2143. }
  2144. i64 src_size = lb_sizeof(src_type);
  2145. i64 dst_size = lb_sizeof(dst_type);
  2146. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2147. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2148. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2149. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2150. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2151. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2152. }
  2153. if (src_size != dst_size && (lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2154. // Okay
  2155. } else {
  2156. GB_ASSERT_MSG(src_size == dst_size, "%s == %s", LLVMPrintTypeToString(src_type), LLVMPrintTypeToString(dst_type));
  2157. }
  2158. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2159. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2160. if (src_kind == dst_kind) {
  2161. if (src_kind == LLVMPointerTypeKind) {
  2162. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2163. } else if (src_kind != LLVMStructTypeKind) {
  2164. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2165. }
  2166. } else {
  2167. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2168. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2169. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2170. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2171. }
  2172. }
  2173. if (LLVMIsALoadInst(val)) {
  2174. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2175. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2176. return LLVMBuildLoad(p->builder, val_ptr, "");
  2177. } else {
  2178. GB_ASSERT(p->decl_block != p->curr_block);
  2179. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2180. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2181. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2182. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2183. max_align = gb_max(max_align, 4);
  2184. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2185. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2186. LLVMBuildStore(p->builder, val, nptr);
  2187. return LLVMBuildLoad(p->builder, ptr, "");
  2188. }
  2189. }
  2190. void lb_begin_procedure_body(lbProcedure *p) {
  2191. DeclInfo *decl = decl_info_of_entity(p->entity);
  2192. if (decl != nullptr) {
  2193. for_array(i, decl->labels) {
  2194. BlockLabel bl = decl->labels[i];
  2195. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2196. array_add(&p->branch_blocks, bb);
  2197. }
  2198. }
  2199. if (p->tags != 0) {
  2200. u64 in = p->tags;
  2201. u64 out = p->module->state_flags;
  2202. if (in & ProcTag_bounds_check) {
  2203. out |= StateFlag_bounds_check;
  2204. out &= ~StateFlag_no_bounds_check;
  2205. } else if (in & ProcTag_no_bounds_check) {
  2206. out |= StateFlag_no_bounds_check;
  2207. out &= ~StateFlag_bounds_check;
  2208. }
  2209. p->module->state_flags = out;
  2210. }
  2211. p->builder = LLVMCreateBuilder();
  2212. p->decl_block = lb_create_block(p, "decls", true);
  2213. p->entry_block = lb_create_block(p, "entry", true);
  2214. lb_start_block(p, p->entry_block);
  2215. GB_ASSERT(p->type != nullptr);
  2216. if (p->abi_function_type) {
  2217. lbFunctionType *ft = p->abi_function_type;
  2218. unsigned param_offset = 0;
  2219. lbValue return_ptr_value = {};
  2220. if (ft->ret.kind == lbArg_Indirect) {
  2221. // NOTE(bill): this must be parameter 0
  2222. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2223. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2224. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2225. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2226. return_ptr_value.type = ptr_type;
  2227. p->return_ptr = lb_addr(return_ptr_value);
  2228. lb_add_entity(p->module, e, return_ptr_value);
  2229. param_offset += 1;
  2230. }
  2231. if (p->type->Proc.params != nullptr) {
  2232. TypeTuple *params = &p->type->Proc.params->Tuple;
  2233. unsigned param_index = 0;
  2234. for_array(i, params->variables) {
  2235. Entity *e = params->variables[i];
  2236. if (e->kind != Entity_Variable) {
  2237. continue;
  2238. }
  2239. lbArgType *arg_type = &ft->args[param_index];
  2240. if (arg_type->kind == lbArg_Ignore) {
  2241. continue;
  2242. } else if (arg_type->kind == lbArg_Direct) {
  2243. lbParamPasskind kind = lbParamPass_Value;
  2244. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2245. if (param_type != arg_type->type) {
  2246. kind = lbParamPass_BitCast;
  2247. }
  2248. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2249. value = OdinLLVMBuildTransmute(p, value, param_type);
  2250. lbValue param = {};
  2251. param.value = value;
  2252. param.type = e->type;
  2253. array_add(&p->params, param);
  2254. if (e->token.string.len != 0) {
  2255. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2256. lb_addr_store(p, l, param);
  2257. }
  2258. param_index += 1;
  2259. } else if (arg_type->kind == lbArg_Indirect) {
  2260. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2261. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2262. lbValue param = {};
  2263. param.value = value;
  2264. param.type = e->type;
  2265. array_add(&p->params, param);
  2266. lbValue ptr = {};
  2267. ptr.value = value_ptr;
  2268. ptr.type = alloc_type_pointer(e->type);
  2269. lb_add_entity(p->module, e, ptr);
  2270. param_index += 1;
  2271. }
  2272. }
  2273. }
  2274. if (p->type->Proc.has_named_results) {
  2275. GB_ASSERT(p->type->Proc.result_count > 0);
  2276. TypeTuple *results = &p->type->Proc.results->Tuple;
  2277. for_array(i, results->variables) {
  2278. Entity *e = results->variables[i];
  2279. GB_ASSERT(e->kind == Entity_Variable);
  2280. if (e->token.string != "") {
  2281. GB_ASSERT(!is_blank_ident(e->token));
  2282. lbAddr res = {};
  2283. if (return_ptr_value.value) {
  2284. lbValue ptr = return_ptr_value;
  2285. if (results->variables.count != 1) {
  2286. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2287. }
  2288. res = lb_addr(ptr);
  2289. lb_add_entity(p->module, e, ptr);
  2290. } else {
  2291. res = lb_add_local(p, e->type, e);
  2292. }
  2293. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2294. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2295. lb_addr_store(p, res, c);
  2296. }
  2297. }
  2298. }
  2299. }
  2300. } else {
  2301. i32 parameter_index = 0;
  2302. lbValue return_ptr_value = {};
  2303. if (p->type->Proc.return_by_pointer) {
  2304. // NOTE(bill): this must be parameter 0
  2305. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2306. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2307. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2308. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2309. return_ptr_value.type = ptr_type;
  2310. p->return_ptr = lb_addr(return_ptr_value);
  2311. lb_add_entity(p->module, e, return_ptr_value);
  2312. parameter_index += 1;
  2313. }
  2314. if (p->type->Proc.params != nullptr) {
  2315. TypeTuple *params = &p->type->Proc.params->Tuple;
  2316. auto abi_types = p->type->Proc.abi_compat_params;
  2317. for_array(i, params->variables) {
  2318. Entity *e = params->variables[i];
  2319. if (e->kind != Entity_Variable) {
  2320. continue;
  2321. }
  2322. Type *abi_type = e->type;
  2323. if (abi_types.count > 0) {
  2324. abi_type = abi_types[i];
  2325. }
  2326. if (e->token.string != "") {
  2327. lb_add_param(p, e, nullptr, abi_type, parameter_index);
  2328. }
  2329. if (is_type_tuple(abi_type)) {
  2330. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  2331. } else {
  2332. parameter_index += 1;
  2333. }
  2334. }
  2335. }
  2336. if (p->type->Proc.has_named_results) {
  2337. GB_ASSERT(p->type->Proc.result_count > 0);
  2338. TypeTuple *results = &p->type->Proc.results->Tuple;
  2339. for_array(i, results->variables) {
  2340. Entity *e = results->variables[i];
  2341. GB_ASSERT(e->kind == Entity_Variable);
  2342. if (e->token.string != "") {
  2343. GB_ASSERT(!is_blank_ident(e->token));
  2344. lbAddr res = {};
  2345. if (p->type->Proc.return_by_pointer) {
  2346. lbValue ptr = return_ptr_value;
  2347. if (results->variables.count != 1) {
  2348. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2349. }
  2350. res = lb_addr(ptr);
  2351. lb_add_entity(p->module, e, ptr);
  2352. } else {
  2353. res = lb_add_local(p, e->type, e);
  2354. }
  2355. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2356. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2357. lb_addr_store(p, res, c);
  2358. }
  2359. }
  2360. }
  2361. }
  2362. }
  2363. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2364. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  2365. e->flags |= EntityFlag_NoAlias;
  2366. lbValue param = {};
  2367. param.value = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  2368. param.type = e->type;
  2369. lb_add_entity(p->module, e, param);
  2370. lbAddr ctx_addr = {};
  2371. ctx_addr.kind = lbAddr_Context;
  2372. ctx_addr.addr = param;
  2373. lbContextData ctx = {ctx_addr, p->scope_index};
  2374. array_add(&p->context_stack, ctx);
  2375. }
  2376. lb_start_block(p, p->entry_block);
  2377. }
  2378. void lb_end_procedure_body(lbProcedure *p) {
  2379. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2380. LLVMBuildBr(p->builder, p->entry_block->block);
  2381. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2382. if (p->type->Proc.result_count == 0) {
  2383. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2384. if (!lb_is_instr_terminating(instr)) {
  2385. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2386. LLVMBuildRetVoid(p->builder);
  2387. }
  2388. } else {
  2389. if (p->curr_block->preds.count == 0) {
  2390. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2391. if (instr == nullptr) {
  2392. // NOTE(bill): Remove dead trailing block
  2393. LLVMDeleteBasicBlock(p->curr_block->block);
  2394. }
  2395. }
  2396. }
  2397. p->curr_block = nullptr;
  2398. p->module->state_flags = 0;
  2399. }
  2400. void lb_end_procedure(lbProcedure *p) {
  2401. LLVMDisposeBuilder(p->builder);
  2402. }
  2403. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2404. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2405. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2406. array_add(&from->succs, to);
  2407. array_add(&to->preds, from);
  2408. }
  2409. }
  2410. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2411. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2412. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2413. b->appended = false;
  2414. if (append) {
  2415. b->appended = true;
  2416. LLVMAppendExistingBasicBlock(p->value, b->block);
  2417. }
  2418. b->scope = p->curr_scope;
  2419. b->scope_index = p->scope_index;
  2420. b->preds.allocator = heap_allocator();
  2421. b->succs.allocator = heap_allocator();
  2422. array_add(&p->blocks, b);
  2423. return b;
  2424. }
  2425. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2426. if (p->curr_block == nullptr) {
  2427. return;
  2428. }
  2429. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2430. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2431. return;
  2432. }
  2433. lb_add_edge(p->curr_block, target_block);
  2434. LLVMBuildBr(p->builder, target_block->block);
  2435. p->curr_block = nullptr;
  2436. }
  2437. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2438. lbBlock *b = p->curr_block;
  2439. if (b == nullptr) {
  2440. return;
  2441. }
  2442. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2443. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2444. return;
  2445. }
  2446. lb_add_edge(b, true_block);
  2447. lb_add_edge(b, false_block);
  2448. LLVMValueRef cv = cond.value;
  2449. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2450. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2451. }
  2452. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2453. GB_ASSERT(cond != nullptr);
  2454. GB_ASSERT(true_block != nullptr);
  2455. GB_ASSERT(false_block != nullptr);
  2456. switch (cond->kind) {
  2457. case_ast_node(pe, ParenExpr, cond);
  2458. return lb_build_cond(p, pe->expr, true_block, false_block);
  2459. case_end;
  2460. case_ast_node(ue, UnaryExpr, cond);
  2461. if (ue->op.kind == Token_Not) {
  2462. return lb_build_cond(p, ue->expr, false_block, true_block);
  2463. }
  2464. case_end;
  2465. case_ast_node(be, BinaryExpr, cond);
  2466. if (be->op.kind == Token_CmpAnd) {
  2467. lbBlock *block = lb_create_block(p, "cmp.and");
  2468. lb_build_cond(p, be->left, block, false_block);
  2469. lb_start_block(p, block);
  2470. return lb_build_cond(p, be->right, true_block, false_block);
  2471. } else if (be->op.kind == Token_CmpOr) {
  2472. lbBlock *block = lb_create_block(p, "cmp.or");
  2473. lb_build_cond(p, be->left, true_block, block);
  2474. lb_start_block(p, block);
  2475. return lb_build_cond(p, be->right, true_block, false_block);
  2476. }
  2477. case_end;
  2478. }
  2479. lbValue v = lb_build_expr(p, cond);
  2480. // v = lb_emit_conv(p, v, t_bool);
  2481. v = lb_emit_conv(p, v, t_llvm_bool);
  2482. lb_emit_if(p, v, true_block, false_block);
  2483. return v;
  2484. }
  2485. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2486. GB_ASSERT(p->decl_block != p->curr_block);
  2487. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2488. char const *name = "";
  2489. if (e != nullptr) {
  2490. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2491. }
  2492. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2493. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2494. // unsigned alignment = 16; // TODO(bill): Make this configurable
  2495. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  2496. LLVMSetAlignment(ptr, alignment);
  2497. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2498. if (zero_init) {
  2499. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2500. switch (kind) {
  2501. case LLVMStructTypeKind:
  2502. case LLVMArrayTypeKind:
  2503. {
  2504. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  2505. LLVMTypeRef type_i8 = LLVMInt8TypeInContext(p->module->ctx);
  2506. LLVMTypeRef type_i32 = LLVMInt32TypeInContext(p->module->ctx);
  2507. i32 sz = cast(i32)type_size_of(type);
  2508. LLVMBuildMemSet(p->builder, ptr, LLVMConstNull(type_i8), LLVMConstInt(type_i32, sz, false), alignment);
  2509. }
  2510. break;
  2511. default:
  2512. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2513. }
  2514. }
  2515. lbValue val = {};
  2516. val.value = ptr;
  2517. val.type = alloc_type_pointer(type);
  2518. if (e != nullptr) {
  2519. lb_add_entity(p->module, e, val);
  2520. }
  2521. return lb_addr(val);
  2522. }
  2523. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2524. return lb_add_local(p, type, nullptr, zero_init);
  2525. }
  2526. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2527. GB_ASSERT(pd->body != nullptr);
  2528. lbModule *m = p->module;
  2529. auto *min_dep_set = &m->info->minimum_dependency_set;
  2530. if (ptr_set_exists(min_dep_set, e) == false) {
  2531. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2532. return;
  2533. }
  2534. // NOTE(bill): Generate a new name
  2535. // parent.name-guid
  2536. String original_name = e->token.string;
  2537. String pd_name = original_name;
  2538. if (e->Procedure.link_name.len > 0) {
  2539. pd_name = e->Procedure.link_name;
  2540. }
  2541. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2542. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2543. i32 guid = cast(i32)p->children.count;
  2544. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2545. String name = make_string(cast(u8 *)name_text, name_len-1);
  2546. set_procedure_abi_types(e->type);
  2547. e->Procedure.link_name = name;
  2548. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2549. e->code_gen_procedure = nested_proc;
  2550. lbValue value = {};
  2551. value.value = nested_proc->value;
  2552. value.type = nested_proc->type;
  2553. lb_add_entity(m, e, value);
  2554. array_add(&p->children, nested_proc);
  2555. array_add(&m->procedures_to_generate, nested_proc);
  2556. }
  2557. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2558. if (e == nullptr) {
  2559. return;
  2560. }
  2561. GB_ASSERT(e->kind == Entity_LibraryName);
  2562. GB_ASSERT(e->flags & EntityFlag_Used);
  2563. for_array(i, e->LibraryName.paths) {
  2564. String library_path = e->LibraryName.paths[i];
  2565. if (library_path.len == 0) {
  2566. continue;
  2567. }
  2568. bool ok = true;
  2569. for_array(path_index, m->foreign_library_paths) {
  2570. String path = m->foreign_library_paths[path_index];
  2571. #if defined(GB_SYSTEM_WINDOWS)
  2572. if (str_eq_ignore_case(path, library_path)) {
  2573. #else
  2574. if (str_eq(path, library_path)) {
  2575. #endif
  2576. ok = false;
  2577. break;
  2578. }
  2579. }
  2580. if (ok) {
  2581. array_add(&m->foreign_library_paths, library_path);
  2582. }
  2583. }
  2584. }
  2585. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2586. if (vd == nullptr || vd->is_mutable) {
  2587. return;
  2588. }
  2589. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2590. static i32 global_guid = 0;
  2591. for_array(i, vd->names) {
  2592. Ast *ident = vd->names[i];
  2593. GB_ASSERT(ident->kind == Ast_Ident);
  2594. Entity *e = entity_of_node(ident);
  2595. GB_ASSERT(e != nullptr);
  2596. if (e->kind != Entity_TypeName) {
  2597. continue;
  2598. }
  2599. bool polymorphic_struct = false;
  2600. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2601. Type *bt = base_type(e->type);
  2602. if (bt->kind == Type_Struct) {
  2603. polymorphic_struct = bt->Struct.is_polymorphic;
  2604. }
  2605. }
  2606. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2607. continue;
  2608. }
  2609. if (e->TypeName.ir_mangled_name.len != 0) {
  2610. // NOTE(bill): Already set
  2611. continue;
  2612. }
  2613. lb_set_nested_type_name_ir_mangled_name(e, p);
  2614. }
  2615. for_array(i, vd->names) {
  2616. Ast *ident = vd->names[i];
  2617. GB_ASSERT(ident->kind == Ast_Ident);
  2618. Entity *e = entity_of_node(ident);
  2619. GB_ASSERT(e != nullptr);
  2620. if (e->kind != Entity_Procedure) {
  2621. continue;
  2622. }
  2623. CheckerInfo *info = p->module->info;
  2624. DeclInfo *decl = decl_info_of_entity(e);
  2625. ast_node(pl, ProcLit, decl->proc_lit);
  2626. if (pl->body != nullptr) {
  2627. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2628. if (found) {
  2629. auto procs = *found;
  2630. for_array(i, procs) {
  2631. Entity *e = procs[i];
  2632. if (!ptr_set_exists(min_dep_set, e)) {
  2633. continue;
  2634. }
  2635. DeclInfo *d = decl_info_of_entity(e);
  2636. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2637. }
  2638. } else {
  2639. lb_build_nested_proc(p, pl, e);
  2640. }
  2641. } else {
  2642. // FFI - Foreign function interace
  2643. String original_name = e->token.string;
  2644. String name = original_name;
  2645. if (e->Procedure.is_foreign) {
  2646. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2647. }
  2648. if (e->Procedure.link_name.len > 0) {
  2649. name = e->Procedure.link_name;
  2650. }
  2651. lbValue *prev_value = string_map_get(&p->module->members, name);
  2652. if (prev_value != nullptr) {
  2653. // NOTE(bill): Don't do mutliple declarations in the IR
  2654. return;
  2655. }
  2656. set_procedure_abi_types(e->type);
  2657. e->Procedure.link_name = name;
  2658. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2659. lbValue value = {};
  2660. value.value = nested_proc->value;
  2661. value.type = nested_proc->type;
  2662. array_add(&p->module->procedures_to_generate, nested_proc);
  2663. if (p != nullptr) {
  2664. array_add(&p->children, nested_proc);
  2665. } else {
  2666. string_map_set(&p->module->members, name, value);
  2667. }
  2668. }
  2669. }
  2670. }
  2671. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  2672. for_array(i, stmts) {
  2673. Ast *stmt = stmts[i];
  2674. switch (stmt->kind) {
  2675. case_ast_node(vd, ValueDecl, stmt);
  2676. lb_build_constant_value_decl(p, vd);
  2677. case_end;
  2678. case_ast_node(fb, ForeignBlockDecl, stmt);
  2679. ast_node(block, BlockStmt, fb->body);
  2680. lb_build_stmt_list(p, block->stmts);
  2681. case_end;
  2682. }
  2683. }
  2684. for_array(i, stmts) {
  2685. lb_build_stmt(p, stmts[i]);
  2686. }
  2687. }
  2688. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  2689. GB_ASSERT(ident->kind == Ast_Ident);
  2690. Entity *e = entity_of_node(ident);
  2691. GB_ASSERT(e->kind == Entity_Label);
  2692. for_array(i, p->branch_blocks) {
  2693. lbBranchBlocks *b = &p->branch_blocks[i];
  2694. if (b->label == e->Label.node) {
  2695. return *b;
  2696. }
  2697. }
  2698. GB_PANIC("Unreachable");
  2699. lbBranchBlocks empty = {};
  2700. return empty;
  2701. }
  2702. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  2703. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  2704. tl->prev = p->target_list;
  2705. tl->break_ = break_;
  2706. tl->continue_ = continue_;
  2707. tl->fallthrough_ = fallthrough_;
  2708. p->target_list = tl;
  2709. if (label != nullptr) { // Set label blocks
  2710. GB_ASSERT(label->kind == Ast_Label);
  2711. for_array(i, p->branch_blocks) {
  2712. lbBranchBlocks *b = &p->branch_blocks[i];
  2713. GB_ASSERT(b->label != nullptr && label != nullptr);
  2714. GB_ASSERT(b->label->kind == Ast_Label);
  2715. if (b->label == label) {
  2716. b->break_ = break_;
  2717. b->continue_ = continue_;
  2718. return tl;
  2719. }
  2720. }
  2721. GB_PANIC("Unreachable");
  2722. }
  2723. return tl;
  2724. }
  2725. void lb_pop_target_list(lbProcedure *p) {
  2726. p->target_list = p->target_list->prev;
  2727. }
  2728. void lb_open_scope(lbProcedure *p) {
  2729. p->scope_index += 1;
  2730. }
  2731. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  2732. lb_emit_defer_stmts(p, kind, block);
  2733. GB_ASSERT(p->scope_index > 0);
  2734. // NOTE(bill): Remove `context`s made in that scope
  2735. while (p->context_stack.count > 0) {
  2736. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  2737. if (ctx->scope_index >= p->scope_index) {
  2738. array_pop(&p->context_stack);
  2739. } else {
  2740. break;
  2741. }
  2742. }
  2743. p->scope_index -= 1;
  2744. }
  2745. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  2746. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  2747. GB_ASSERT(is_type_boolean(tv.type));
  2748. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  2749. if (tv.value.value_bool) {
  2750. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  2751. } else if (ws->else_stmt) {
  2752. switch (ws->else_stmt->kind) {
  2753. case Ast_BlockStmt:
  2754. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  2755. break;
  2756. case Ast_WhenStmt:
  2757. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  2758. break;
  2759. default:
  2760. GB_PANIC("Invalid 'else' statement in 'when' statement");
  2761. break;
  2762. }
  2763. }
  2764. }
  2765. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  2766. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2767. lbModule *m = p->module;
  2768. lbValue count = {};
  2769. Type *expr_type = base_type(type_deref(expr.type));
  2770. switch (expr_type->kind) {
  2771. case Type_Array:
  2772. count = lb_const_int(m, t_int, expr_type->Array.count);
  2773. break;
  2774. }
  2775. lbValue val = {};
  2776. lbValue idx = {};
  2777. lbBlock *loop = nullptr;
  2778. lbBlock *done = nullptr;
  2779. lbBlock *body = nullptr;
  2780. lbAddr index = lb_add_local_generated(p, t_int, false);
  2781. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  2782. loop = lb_create_block(p, "for.index.loop");
  2783. lb_emit_jump(p, loop);
  2784. lb_start_block(p, loop);
  2785. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  2786. lb_addr_store(p, index, incr);
  2787. body = lb_create_block(p, "for.index.body");
  2788. done = lb_create_block(p, "for.index.done");
  2789. if (count.value == nullptr) {
  2790. GB_ASSERT(count_ptr.value != nullptr);
  2791. count = lb_emit_load(p, count_ptr);
  2792. }
  2793. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  2794. lb_emit_if(p, cond, body, done);
  2795. lb_start_block(p, body);
  2796. idx = lb_addr_load(p, index);
  2797. switch (expr_type->kind) {
  2798. case Type_Array: {
  2799. if (val_type != nullptr) {
  2800. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2801. }
  2802. break;
  2803. }
  2804. case Type_EnumeratedArray: {
  2805. if (val_type != nullptr) {
  2806. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2807. // NOTE(bill): Override the idx value for the enumeration
  2808. Type *index_type = expr_type->EnumeratedArray.index;
  2809. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  2810. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  2811. }
  2812. }
  2813. break;
  2814. }
  2815. case Type_Slice: {
  2816. if (val_type != nullptr) {
  2817. lbValue elem = lb_slice_elem(p, expr);
  2818. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2819. }
  2820. break;
  2821. }
  2822. case Type_DynamicArray: {
  2823. if (val_type != nullptr) {
  2824. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  2825. elem = lb_emit_load(p, elem);
  2826. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2827. }
  2828. break;
  2829. }
  2830. case Type_Map: {
  2831. lbValue entries = lb_map_entries_ptr(p, expr);
  2832. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  2833. elem = lb_emit_load(p, elem);
  2834. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  2835. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  2836. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  2837. break;
  2838. }
  2839. default:
  2840. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  2841. break;
  2842. }
  2843. if (val_) *val_ = val;
  2844. if (idx_) *idx_ = idx;
  2845. if (loop_) *loop_ = loop;
  2846. if (done_) *done_ = done;
  2847. }
  2848. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  2849. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2850. lbModule *m = p->module;
  2851. lbValue count = lb_const_int(m, t_int, 0);
  2852. Type *expr_type = base_type(expr.type);
  2853. switch (expr_type->kind) {
  2854. case Type_Basic:
  2855. count = lb_string_len(p, expr);
  2856. break;
  2857. default:
  2858. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  2859. break;
  2860. }
  2861. lbValue val = {};
  2862. lbValue idx = {};
  2863. lbBlock *loop = nullptr;
  2864. lbBlock *done = nullptr;
  2865. lbBlock *body = nullptr;
  2866. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2867. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2868. loop = lb_create_block(p, "for.string.loop");
  2869. lb_emit_jump(p, loop);
  2870. lb_start_block(p, loop);
  2871. body = lb_create_block(p, "for.string.body");
  2872. done = lb_create_block(p, "for.string.done");
  2873. lbValue offset = lb_addr_load(p, offset_);
  2874. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  2875. lb_emit_if(p, cond, body, done);
  2876. lb_start_block(p, body);
  2877. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  2878. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  2879. auto args = array_make<lbValue>(permanent_allocator(), 1);
  2880. args[0] = lb_emit_string(p, str_elem, str_len);
  2881. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  2882. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  2883. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  2884. idx = offset;
  2885. if (val_type != nullptr) {
  2886. val = lb_emit_struct_ev(p, rune_and_len, 0);
  2887. }
  2888. if (val_) *val_ = val;
  2889. if (idx_) *idx_ = idx;
  2890. if (loop_) *loop_ = loop;
  2891. if (done_) *done_ = done;
  2892. }
  2893. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  2894. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2895. lbModule *m = p->module;
  2896. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  2897. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  2898. lbValue lower = lb_build_expr(p, node->left);
  2899. lbValue upper = {};
  2900. lbValue val = {};
  2901. lbValue idx = {};
  2902. lbBlock *loop = nullptr;
  2903. lbBlock *done = nullptr;
  2904. lbBlock *body = nullptr;
  2905. if (val_type == nullptr) {
  2906. val_type = lower.type;
  2907. }
  2908. lbAddr value = lb_add_local_generated(p, val_type, false);
  2909. lb_addr_store(p, value, lower);
  2910. lbAddr index = lb_add_local_generated(p, t_int, false);
  2911. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  2912. loop = lb_create_block(p, "for.interval.loop");
  2913. lb_emit_jump(p, loop);
  2914. lb_start_block(p, loop);
  2915. body = lb_create_block(p, "for.interval.body");
  2916. done = lb_create_block(p, "for.interval.done");
  2917. TokenKind op = Token_Lt;
  2918. switch (node->op.kind) {
  2919. case Token_Ellipsis: op = Token_LtEq; break;
  2920. case Token_RangeHalf: op = Token_Lt; break;
  2921. default: GB_PANIC("Invalid interval operator"); break;
  2922. }
  2923. upper = lb_build_expr(p, node->right);
  2924. lbValue curr_value = lb_addr_load(p, value);
  2925. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  2926. lb_emit_if(p, cond, body, done);
  2927. lb_start_block(p, body);
  2928. val = lb_addr_load(p, value);
  2929. idx = lb_addr_load(p, index);
  2930. lb_emit_increment(p, value.addr);
  2931. lb_emit_increment(p, index.addr);
  2932. if (val_) *val_ = val;
  2933. if (idx_) *idx_ = idx;
  2934. if (loop_) *loop_ = loop;
  2935. if (done_) *done_ = done;
  2936. }
  2937. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2938. lbModule *m = p->module;
  2939. Type *t = enum_type;
  2940. GB_ASSERT(is_type_enum(t));
  2941. Type *enum_ptr = alloc_type_pointer(t);
  2942. t = base_type(t);
  2943. Type *core_elem = core_type(t);
  2944. GB_ASSERT(t->kind == Type_Enum);
  2945. i64 enum_count = t->Enum.fields.count;
  2946. lbValue max_count = lb_const_int(m, t_int, enum_count);
  2947. lbValue ti = lb_type_info(m, t);
  2948. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  2949. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  2950. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  2951. lbValue values_data = lb_slice_elem(p, values);
  2952. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2953. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2954. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  2955. lb_emit_jump(p, loop);
  2956. lb_start_block(p, loop);
  2957. lbBlock *body = lb_create_block(p, "for.enum.body");
  2958. lbBlock *done = lb_create_block(p, "for.enum.done");
  2959. lbValue offset = lb_addr_load(p, offset_);
  2960. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  2961. lb_emit_if(p, cond, body, done);
  2962. lb_start_block(p, body);
  2963. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  2964. lb_emit_increment(p, offset_.addr);
  2965. lbValue val = {};
  2966. if (val_type != nullptr) {
  2967. GB_ASSERT(are_types_identical(enum_type, val_type));
  2968. if (is_type_integer(core_elem)) {
  2969. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  2970. val = lb_emit_conv(p, i, t);
  2971. } else {
  2972. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  2973. }
  2974. }
  2975. if (val_) *val_ = val;
  2976. if (idx_) *idx_ = offset;
  2977. if (loop_) *loop_ = loop;
  2978. if (done_) *done_ = done;
  2979. }
  2980. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  2981. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  2982. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  2983. lb_emit_jump(p, loop);
  2984. lb_start_block(p, loop);
  2985. lbBlock *body = lb_create_block(p, "for.tuple.body");
  2986. lbBlock *done = lb_create_block(p, "for.tuple.done");
  2987. lbValue tuple_value = lb_build_expr(p, expr);
  2988. Type *tuple = tuple_value.type;
  2989. GB_ASSERT(tuple->kind == Type_Tuple);
  2990. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  2991. i32 cond_index = tuple_count-1;
  2992. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  2993. lb_emit_if(p, cond, body, done);
  2994. lb_start_block(p, body);
  2995. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  2996. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  2997. if (loop_) *loop_ = loop;
  2998. if (done_) *done_ = done;
  2999. }
  3000. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) {
  3001. lb_open_scope(p);
  3002. Type *val0_type = nullptr;
  3003. Type *val1_type = nullptr;
  3004. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3005. val0_type = type_of_expr(rs->val0);
  3006. }
  3007. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3008. val1_type = type_of_expr(rs->val1);
  3009. }
  3010. if (val0_type != nullptr) {
  3011. Entity *e = entity_of_node(rs->val0);
  3012. lb_add_local(p, e->type, e, true);
  3013. }
  3014. if (val1_type != nullptr) {
  3015. Entity *e = entity_of_node(rs->val1);
  3016. lb_add_local(p, e->type, e, true);
  3017. }
  3018. lbValue val = {};
  3019. lbValue key = {};
  3020. lbBlock *loop = nullptr;
  3021. lbBlock *done = nullptr;
  3022. Ast *expr = unparen_expr(rs->expr);
  3023. bool is_map = false;
  3024. TypeAndValue tav = type_and_value_of_expr(expr);
  3025. if (is_ast_range(expr)) {
  3026. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  3027. } else if (tav.mode == Addressing_Type) {
  3028. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3029. } else {
  3030. Type *expr_type = type_of_expr(expr);
  3031. Type *et = base_type(type_deref(expr_type));
  3032. switch (et->kind) {
  3033. case Type_Map: {
  3034. is_map = true;
  3035. lbValue map = lb_build_addr_ptr(p, expr);
  3036. if (is_type_pointer(type_deref(map.type))) {
  3037. map = lb_emit_load(p, map);
  3038. }
  3039. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3040. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3041. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3042. break;
  3043. }
  3044. case Type_Array: {
  3045. lbValue array = lb_build_addr_ptr(p, expr);
  3046. if (is_type_pointer(type_deref(array.type))) {
  3047. array = lb_emit_load(p, array);
  3048. }
  3049. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3050. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3051. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3052. break;
  3053. }
  3054. case Type_EnumeratedArray: {
  3055. lbValue array = lb_build_addr_ptr(p, expr);
  3056. if (is_type_pointer(type_deref(array.type))) {
  3057. array = lb_emit_load(p, array);
  3058. }
  3059. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3060. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3061. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3062. break;
  3063. }
  3064. case Type_DynamicArray: {
  3065. lbValue count_ptr = {};
  3066. lbValue array = lb_build_addr_ptr(p, expr);
  3067. if (is_type_pointer(type_deref(array.type))) {
  3068. array = lb_emit_load(p, array);
  3069. }
  3070. count_ptr = lb_emit_struct_ep(p, array, 1);
  3071. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3072. break;
  3073. }
  3074. case Type_Slice: {
  3075. lbValue count_ptr = {};
  3076. lbValue slice = lb_build_expr(p, expr);
  3077. if (is_type_pointer(slice.type)) {
  3078. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3079. slice = lb_emit_load(p, slice);
  3080. } else {
  3081. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3082. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3083. }
  3084. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3085. break;
  3086. }
  3087. case Type_Basic: {
  3088. lbValue string = lb_build_expr(p, expr);
  3089. if (is_type_pointer(string.type)) {
  3090. string = lb_emit_load(p, string);
  3091. }
  3092. if (is_type_untyped(expr_type)) {
  3093. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3094. lb_addr_store(p, s, string);
  3095. string = lb_addr_load(p, s);
  3096. }
  3097. Type *t = base_type(string.type);
  3098. GB_ASSERT(!is_type_cstring(t));
  3099. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3100. break;
  3101. }
  3102. case Type_Tuple:
  3103. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3104. break;
  3105. default:
  3106. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3107. break;
  3108. }
  3109. }
  3110. if (is_map) {
  3111. if (val0_type) lb_store_range_stmt_val(p, rs->val0, key);
  3112. if (val1_type) lb_store_range_stmt_val(p, rs->val1, val);
  3113. } else {
  3114. if (val0_type) lb_store_range_stmt_val(p, rs->val0, val);
  3115. if (val1_type) lb_store_range_stmt_val(p, rs->val1, key);
  3116. }
  3117. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3118. lb_build_stmt(p, rs->body);
  3119. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3120. lb_pop_target_list(p);
  3121. lb_emit_jump(p, loop);
  3122. lb_start_block(p, done);
  3123. }
  3124. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) {
  3125. lbModule *m = p->module;
  3126. lb_open_scope(p); // Open scope here
  3127. Type *val0_type = nullptr;
  3128. Type *val1_type = nullptr;
  3129. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3130. val0_type = type_of_expr(rs->val0);
  3131. }
  3132. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3133. val1_type = type_of_expr(rs->val1);
  3134. }
  3135. if (val0_type != nullptr) {
  3136. Entity *e = entity_of_node(rs->val0);
  3137. lb_add_local(p, e->type, e, true);
  3138. }
  3139. if (val1_type != nullptr) {
  3140. Entity *e = entity_of_node(rs->val1);
  3141. lb_add_local(p, e->type, e, true);
  3142. }
  3143. lbValue val = {};
  3144. lbValue key = {};
  3145. lbBlock *loop = nullptr;
  3146. lbBlock *done = nullptr;
  3147. Ast *expr = unparen_expr(rs->expr);
  3148. TypeAndValue tav = type_and_value_of_expr(expr);
  3149. if (is_ast_range(expr)) {
  3150. lbAddr val0_addr = {};
  3151. lbAddr val1_addr = {};
  3152. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3153. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3154. TokenKind op = expr->BinaryExpr.op.kind;
  3155. Ast *start_expr = expr->BinaryExpr.left;
  3156. Ast *end_expr = expr->BinaryExpr.right;
  3157. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3158. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3159. ExactValue start = start_expr->tav.value;
  3160. ExactValue end = end_expr->tav.value;
  3161. if (op == Token_Ellipsis) { // .. [start, end]
  3162. ExactValue index = exact_value_i64(0);
  3163. for (ExactValue val = start;
  3164. compare_exact_values(Token_LtEq, val, end);
  3165. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3166. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3167. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3168. lb_build_stmt(p, rs->body);
  3169. }
  3170. } else if (op == Token_RangeHalf) { // ..< [start, end)
  3171. ExactValue index = exact_value_i64(0);
  3172. for (ExactValue val = start;
  3173. compare_exact_values(Token_Lt, val, end);
  3174. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3175. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3176. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3177. lb_build_stmt(p, rs->body);
  3178. }
  3179. }
  3180. } else if (tav.mode == Addressing_Type) {
  3181. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3182. Type *et = type_deref(tav.type);
  3183. Type *bet = base_type(et);
  3184. lbAddr val0_addr = {};
  3185. lbAddr val1_addr = {};
  3186. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3187. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3188. for_array(i, bet->Enum.fields) {
  3189. Entity *field = bet->Enum.fields[i];
  3190. GB_ASSERT(field->kind == Entity_Constant);
  3191. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3192. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3193. lb_build_stmt(p, rs->body);
  3194. }
  3195. } else {
  3196. lbAddr val0_addr = {};
  3197. lbAddr val1_addr = {};
  3198. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3199. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3200. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3201. Type *t = base_type(expr->tav.type);
  3202. switch (t->kind) {
  3203. case Type_Basic:
  3204. GB_ASSERT(is_type_string(t));
  3205. {
  3206. ExactValue value = expr->tav.value;
  3207. GB_ASSERT(value.kind == ExactValue_String);
  3208. String str = value.value_string;
  3209. Rune codepoint = 0;
  3210. isize offset = 0;
  3211. do {
  3212. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3213. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3214. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3215. lb_build_stmt(p, rs->body);
  3216. offset += width;
  3217. } while (offset < str.len);
  3218. }
  3219. break;
  3220. case Type_Array:
  3221. if (t->Array.count > 0) {
  3222. lbValue val = lb_build_expr(p, expr);
  3223. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3224. for (i64 i = 0; i < t->Array.count; i++) {
  3225. if (val0_type) {
  3226. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3227. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3228. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3229. }
  3230. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3231. lb_build_stmt(p, rs->body);
  3232. }
  3233. }
  3234. break;
  3235. case Type_EnumeratedArray:
  3236. if (t->EnumeratedArray.count > 0) {
  3237. lbValue val = lb_build_expr(p, expr);
  3238. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3239. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3240. if (val0_type) {
  3241. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3242. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3243. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3244. }
  3245. if (val1_type) {
  3246. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3247. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3248. }
  3249. lb_build_stmt(p, rs->body);
  3250. }
  3251. }
  3252. break;
  3253. default:
  3254. GB_PANIC("Invalid inline for type");
  3255. break;
  3256. }
  3257. }
  3258. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3259. }
  3260. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) {
  3261. if (ss->init != nullptr) {
  3262. lb_build_stmt(p, ss->init);
  3263. }
  3264. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3265. if (ss->tag != nullptr) {
  3266. tag = lb_build_expr(p, ss->tag);
  3267. }
  3268. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3269. ast_node(body, BlockStmt, ss->body);
  3270. Slice<Ast *> default_stmts = {};
  3271. lbBlock *default_fall = nullptr;
  3272. lbBlock *default_block = nullptr;
  3273. lbBlock *fall = nullptr;
  3274. isize case_count = body->stmts.count;
  3275. for_array(i, body->stmts) {
  3276. Ast *clause = body->stmts[i];
  3277. ast_node(cc, CaseClause, clause);
  3278. lbBlock *body = fall;
  3279. if (body == nullptr) {
  3280. body = lb_create_block(p, "switch.case.body");
  3281. }
  3282. fall = done;
  3283. if (i+1 < case_count) {
  3284. fall = lb_create_block(p, "switch.fall.body");
  3285. }
  3286. if (cc->list.count == 0) {
  3287. // default case
  3288. default_stmts = cc->stmts;
  3289. default_fall = fall;
  3290. default_block = body;
  3291. continue;
  3292. }
  3293. lbBlock *next_cond = nullptr;
  3294. for_array(j, cc->list) {
  3295. Ast *expr = unparen_expr(cc->list[j]);
  3296. next_cond = lb_create_block(p, "switch.case.next");
  3297. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3298. if (is_ast_range(expr)) {
  3299. ast_node(ie, BinaryExpr, expr);
  3300. TokenKind op = Token_Invalid;
  3301. switch (ie->op.kind) {
  3302. case Token_Ellipsis: op = Token_LtEq; break;
  3303. case Token_RangeHalf: op = Token_Lt; break;
  3304. default: GB_PANIC("Invalid interval operator"); break;
  3305. }
  3306. lbValue lhs = lb_build_expr(p, ie->left);
  3307. lbValue rhs = lb_build_expr(p, ie->right);
  3308. // TODO(bill): do short circuit here
  3309. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3310. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3311. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3312. } else {
  3313. if (expr->tav.mode == Addressing_Type) {
  3314. GB_ASSERT(is_type_typeid(tag.type));
  3315. lbValue e = lb_typeid(p->module, expr->tav.type);
  3316. e = lb_emit_conv(p, e, tag.type);
  3317. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3318. } else {
  3319. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3320. }
  3321. }
  3322. lb_emit_if(p, cond, body, next_cond);
  3323. lb_start_block(p, next_cond);
  3324. }
  3325. lb_start_block(p, body);
  3326. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3327. lb_open_scope(p);
  3328. lb_build_stmt_list(p, cc->stmts);
  3329. lb_close_scope(p, lbDeferExit_Default, body);
  3330. lb_pop_target_list(p);
  3331. lb_emit_jump(p, done);
  3332. lb_start_block(p, next_cond);
  3333. }
  3334. if (default_block != nullptr) {
  3335. lb_emit_jump(p, default_block);
  3336. lb_start_block(p, default_block);
  3337. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3338. lb_open_scope(p);
  3339. lb_build_stmt_list(p, default_stmts);
  3340. lb_close_scope(p, lbDeferExit_Default, default_block);
  3341. lb_pop_target_list(p);
  3342. }
  3343. lb_emit_jump(p, done);
  3344. lb_start_block(p, done);
  3345. }
  3346. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3347. Entity *e = implicit_entity_of_node(clause);
  3348. GB_ASSERT(e != nullptr);
  3349. if (e->flags & EntityFlag_Value) {
  3350. // by value
  3351. GB_ASSERT(are_types_identical(e->type, value.type));
  3352. lbAddr x = lb_add_local(p, e->type, e, false);
  3353. lb_addr_store(p, x, value);
  3354. } else {
  3355. // by reference
  3356. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3357. lb_add_entity(p->module, e, value);
  3358. }
  3359. }
  3360. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3361. Entity *e = entity_of_node(stmt_val);
  3362. if (e == nullptr) {
  3363. return {};
  3364. }
  3365. if ((e->flags & EntityFlag_Value) == 0) {
  3366. if (LLVMIsALoadInst(value.value)) {
  3367. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3368. lb_add_entity(p->module, e, ptr);
  3369. return lb_addr(ptr);
  3370. }
  3371. }
  3372. // by value
  3373. lbAddr addr = lb_add_local(p, e->type, e, false);
  3374. lb_addr_store(p, addr, value);
  3375. return addr;
  3376. }
  3377. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3378. ast_node(cc, CaseClause, clause);
  3379. lb_push_target_list(p, label, done, nullptr, nullptr);
  3380. lb_open_scope(p);
  3381. lb_build_stmt_list(p, cc->stmts);
  3382. lb_close_scope(p, lbDeferExit_Default, body);
  3383. lb_pop_target_list(p);
  3384. lb_emit_jump(p, done);
  3385. }
  3386. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3387. lbModule *m = p->module;
  3388. ast_node(as, AssignStmt, ss->tag);
  3389. GB_ASSERT(as->lhs.count == 1);
  3390. GB_ASSERT(as->rhs.count == 1);
  3391. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3392. bool is_parent_ptr = is_type_pointer(parent.type);
  3393. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3394. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3395. lbValue parent_value = parent;
  3396. lbValue parent_ptr = parent;
  3397. if (!is_parent_ptr) {
  3398. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3399. }
  3400. lbValue tag_index = {};
  3401. lbValue union_data = {};
  3402. if (switch_kind == TypeSwitch_Union) {
  3403. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3404. tag_index = lb_emit_load(p, tag_ptr);
  3405. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3406. }
  3407. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3408. lb_emit_jump(p, start_block);
  3409. lb_start_block(p, start_block);
  3410. // NOTE(bill): Append this later
  3411. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3412. Ast *default_ = nullptr;
  3413. ast_node(body, BlockStmt, ss->body);
  3414. gb_local_persist i32 weird_count = 0;
  3415. for_array(i, body->stmts) {
  3416. Ast *clause = body->stmts[i];
  3417. ast_node(cc, CaseClause, clause);
  3418. if (cc->list.count == 0) {
  3419. default_ = clause;
  3420. continue;
  3421. }
  3422. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3423. lbBlock *next = nullptr;
  3424. Type *case_type = nullptr;
  3425. for_array(type_index, cc->list) {
  3426. next = lb_create_block(p, "typeswitch.next");
  3427. case_type = type_of_expr(cc->list[type_index]);
  3428. lbValue cond = {};
  3429. if (switch_kind == TypeSwitch_Union) {
  3430. Type *ut = base_type(type_deref(parent.type));
  3431. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3432. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3433. } else if (switch_kind == TypeSwitch_Any) {
  3434. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3435. lbValue case_typeid = lb_typeid(m, case_type);
  3436. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3437. }
  3438. GB_ASSERT(cond.value != nullptr);
  3439. lb_emit_if(p, cond, body, next);
  3440. lb_start_block(p, next);
  3441. }
  3442. Entity *case_entity = implicit_entity_of_node(clause);
  3443. lbValue value = parent_value;
  3444. lb_start_block(p, body);
  3445. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3446. if (cc->list.count == 1) {
  3447. lbValue data = {};
  3448. if (switch_kind == TypeSwitch_Union) {
  3449. data = union_data;
  3450. } else if (switch_kind == TypeSwitch_Any) {
  3451. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3452. data = any_data;
  3453. }
  3454. Type *ct = case_entity->type;
  3455. Type *ct_ptr = alloc_type_pointer(ct);
  3456. value = lb_emit_conv(p, data, ct_ptr);
  3457. if (!by_reference) {
  3458. value = lb_emit_load(p, value);
  3459. }
  3460. }
  3461. lb_store_type_case_implicit(p, clause, value);
  3462. lb_type_case_body(p, ss->label, clause, body, done);
  3463. lb_start_block(p, next);
  3464. }
  3465. if (default_ != nullptr) {
  3466. lb_store_type_case_implicit(p, default_, parent_value);
  3467. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3468. } else {
  3469. lb_emit_jump(p, done);
  3470. }
  3471. lb_start_block(p, done);
  3472. }
  3473. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3474. lbModule *m = p->module;
  3475. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3476. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3477. type = default_type(type);
  3478. lbValue short_circuit = {};
  3479. if (op == Token_CmpAnd) {
  3480. lb_build_cond(p, left, rhs, done);
  3481. short_circuit = lb_const_bool(m, type, false);
  3482. } else if (op == Token_CmpOr) {
  3483. lb_build_cond(p, left, done, rhs);
  3484. short_circuit = lb_const_bool(m, type, true);
  3485. }
  3486. if (rhs->preds.count == 0) {
  3487. lb_start_block(p, done);
  3488. return short_circuit;
  3489. }
  3490. if (done->preds.count == 0) {
  3491. lb_start_block(p, rhs);
  3492. return lb_build_expr(p, right);
  3493. }
  3494. Array<LLVMValueRef> incoming_values = {};
  3495. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3496. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3497. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3498. for_array(i, done->preds) {
  3499. incoming_values[i] = short_circuit.value;
  3500. incoming_blocks[i] = done->preds[i]->block;
  3501. }
  3502. lb_start_block(p, rhs);
  3503. lbValue edge = lb_build_expr(p, right);
  3504. incoming_values[done->preds.count] = edge.value;
  3505. incoming_blocks[done->preds.count] = p->curr_block->block;
  3506. lb_emit_jump(p, done);
  3507. lb_start_block(p, done);
  3508. lbValue res = {};
  3509. res.type = type;
  3510. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3511. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3512. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3513. return res;
  3514. }
  3515. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3516. Ast *prev_stmt = p->curr_stmt;
  3517. defer (p->curr_stmt = prev_stmt);
  3518. p->curr_stmt = node;
  3519. if (p->curr_block != nullptr) {
  3520. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  3521. if (lb_is_instr_terminating(last_instr)) {
  3522. return;
  3523. }
  3524. }
  3525. u64 prev_state_flags = p->module->state_flags;
  3526. defer (p->module->state_flags = prev_state_flags);
  3527. if (node->state_flags != 0) {
  3528. u64 in = node->state_flags;
  3529. u64 out = p->module->state_flags;
  3530. if (in & StateFlag_bounds_check) {
  3531. out |= StateFlag_bounds_check;
  3532. out &= ~StateFlag_no_bounds_check;
  3533. } else if (in & StateFlag_no_bounds_check) {
  3534. out |= StateFlag_no_bounds_check;
  3535. out &= ~StateFlag_bounds_check;
  3536. }
  3537. p->module->state_flags = out;
  3538. }
  3539. switch (node->kind) {
  3540. case_ast_node(bs, EmptyStmt, node);
  3541. case_end;
  3542. case_ast_node(us, UsingStmt, node);
  3543. case_end;
  3544. case_ast_node(ws, WhenStmt, node);
  3545. lb_build_when_stmt(p, ws);
  3546. case_end;
  3547. case_ast_node(bs, BlockStmt, node);
  3548. if (bs->label != nullptr) {
  3549. lbBlock *done = lb_create_block(p, "block.done");
  3550. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3551. tl->is_block = true;
  3552. lb_open_scope(p);
  3553. lb_build_stmt_list(p, bs->stmts);
  3554. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3555. lb_emit_jump(p, done);
  3556. lb_start_block(p, done);
  3557. } else {
  3558. lb_open_scope(p);
  3559. lb_build_stmt_list(p, bs->stmts);
  3560. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3561. }
  3562. case_end;
  3563. case_ast_node(vd, ValueDecl, node);
  3564. if (!vd->is_mutable) {
  3565. return;
  3566. }
  3567. bool is_static = false;
  3568. if (vd->names.count > 0) {
  3569. Entity *e = entity_of_node(vd->names[0]);
  3570. if (e->flags & EntityFlag_Static) {
  3571. // NOTE(bill): If one of the entities is static, they all are
  3572. is_static = true;
  3573. }
  3574. }
  3575. if (is_static) {
  3576. for_array(i, vd->names) {
  3577. lbValue value = {};
  3578. if (vd->values.count > 0) {
  3579. GB_ASSERT(vd->names.count == vd->values.count);
  3580. Ast *ast_value = vd->values[i];
  3581. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  3582. ast_value->tav.mode == Addressing_Invalid);
  3583. bool allow_local = false;
  3584. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  3585. }
  3586. Ast *ident = vd->names[i];
  3587. GB_ASSERT(!is_blank_ident(ident));
  3588. Entity *e = entity_of_node(ident);
  3589. GB_ASSERT(e->flags & EntityFlag_Static);
  3590. String name = e->token.string;
  3591. String mangled_name = {};
  3592. {
  3593. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  3594. str = gb_string_appendc(str, "-");
  3595. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  3596. mangled_name.text = cast(u8 *)str;
  3597. mangled_name.len = gb_string_length(str);
  3598. }
  3599. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  3600. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  3601. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  3602. if (value.value != nullptr) {
  3603. LLVMSetInitializer(global, value.value);
  3604. } else {
  3605. }
  3606. if (e->Variable.thread_local_model != "") {
  3607. LLVMSetThreadLocal(global, true);
  3608. String m = e->Variable.thread_local_model;
  3609. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  3610. if (m == "default") {
  3611. mode = LLVMGeneralDynamicTLSModel;
  3612. } else if (m == "localdynamic") {
  3613. mode = LLVMLocalDynamicTLSModel;
  3614. } else if (m == "initialexec") {
  3615. mode = LLVMInitialExecTLSModel;
  3616. } else if (m == "localexec") {
  3617. mode = LLVMLocalExecTLSModel;
  3618. } else {
  3619. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  3620. }
  3621. LLVMSetThreadLocalMode(global, mode);
  3622. } else {
  3623. LLVMSetLinkage(global, LLVMInternalLinkage);
  3624. }
  3625. lbValue global_val = {global, alloc_type_pointer(e->type)};
  3626. lb_add_entity(p->module, e, global_val);
  3627. lb_add_member(p->module, mangled_name, global_val);
  3628. }
  3629. return;
  3630. }
  3631. if (vd->values.count == 0) { // declared and zero-initialized
  3632. for_array(i, vd->names) {
  3633. Ast *name = vd->names[i];
  3634. if (!is_blank_ident(name)) {
  3635. Entity *e = entity_of_node(name);
  3636. lb_add_local(p, e->type, e, true);
  3637. }
  3638. }
  3639. } else { // Tuple(s)
  3640. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  3641. auto inits = array_make<lbValue>(permanent_allocator(), 0, vd->names.count);
  3642. for_array(i, vd->names) {
  3643. Ast *name = vd->names[i];
  3644. lbAddr lval = {};
  3645. if (!is_blank_ident(name)) {
  3646. Entity *e = entity_of_node(name);
  3647. lval = lb_add_local(p, e->type, e, false);
  3648. }
  3649. array_add(&lvals, lval);
  3650. }
  3651. for_array(i, vd->values) {
  3652. lbValue init = lb_build_expr(p, vd->values[i]);
  3653. Type *t = init.type;
  3654. if (t->kind == Type_Tuple) {
  3655. for_array(i, t->Tuple.variables) {
  3656. Entity *e = t->Tuple.variables[i];
  3657. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3658. array_add(&inits, v);
  3659. }
  3660. } else {
  3661. array_add(&inits, init);
  3662. }
  3663. }
  3664. for_array(i, inits) {
  3665. lbAddr lval = lvals[i];
  3666. lbValue init = inits[i];
  3667. lb_addr_store(p, lval, init);
  3668. }
  3669. }
  3670. case_end;
  3671. case_ast_node(as, AssignStmt, node);
  3672. if (as->op.kind == Token_Eq) {
  3673. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  3674. for_array(i, as->lhs) {
  3675. Ast *lhs = as->lhs[i];
  3676. lbAddr lval = {};
  3677. if (!is_blank_ident(lhs)) {
  3678. lval = lb_build_addr(p, lhs);
  3679. }
  3680. array_add(&lvals, lval);
  3681. }
  3682. if (as->lhs.count == as->rhs.count) {
  3683. if (as->lhs.count == 1) {
  3684. lbAddr lval = lvals[0];
  3685. Ast *rhs = as->rhs[0];
  3686. lbValue init = lb_build_expr(p, rhs);
  3687. lb_addr_store(p, lvals[0], init);
  3688. } else {
  3689. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  3690. for_array(i, as->rhs) {
  3691. lbValue init = lb_build_expr(p, as->rhs[i]);
  3692. array_add(&inits, init);
  3693. }
  3694. for_array(i, inits) {
  3695. lbAddr lval = lvals[i];
  3696. lbValue init = inits[i];
  3697. lb_addr_store(p, lval, init);
  3698. }
  3699. }
  3700. } else {
  3701. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  3702. for_array(i, as->rhs) {
  3703. lbValue init = lb_build_expr(p, as->rhs[i]);
  3704. Type *t = init.type;
  3705. // TODO(bill): refactor for code reuse as this is repeated a bit
  3706. if (t->kind == Type_Tuple) {
  3707. for_array(i, t->Tuple.variables) {
  3708. Entity *e = t->Tuple.variables[i];
  3709. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3710. array_add(&inits, v);
  3711. }
  3712. } else {
  3713. array_add(&inits, init);
  3714. }
  3715. }
  3716. for_array(i, inits) {
  3717. lbAddr lval = lvals[i];
  3718. lbValue init = inits[i];
  3719. lb_addr_store(p, lval, init);
  3720. }
  3721. }
  3722. } else {
  3723. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  3724. // +=, -=, etc
  3725. i32 op = cast(i32)as->op.kind;
  3726. op += Token_Add - Token_AddEq; // Convert += to +
  3727. if (op == Token_CmpAnd || op == Token_CmpOr) {
  3728. Type *type = as->lhs[0]->tav.type;
  3729. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  3730. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3731. lb_addr_store(p, lhs, new_value);
  3732. } else {
  3733. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3734. lbValue value = lb_build_expr(p, as->rhs[0]);
  3735. lbValue old_value = lb_addr_load(p, lhs);
  3736. Type *type = old_value.type;
  3737. lbValue change = lb_emit_conv(p, value, type);
  3738. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  3739. lb_addr_store(p, lhs, new_value);
  3740. }
  3741. return;
  3742. }
  3743. case_end;
  3744. case_ast_node(es, ExprStmt, node);
  3745. lb_build_expr(p, es->expr);
  3746. case_end;
  3747. case_ast_node(ds, DeferStmt, node);
  3748. isize scope_index = p->scope_index;
  3749. lb_add_defer_node(p, scope_index, ds->stmt);
  3750. case_end;
  3751. case_ast_node(rs, ReturnStmt, node);
  3752. lbValue res = {};
  3753. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  3754. isize return_count = p->type->Proc.result_count;
  3755. isize res_count = rs->results.count;
  3756. if (return_count == 0) {
  3757. // No return values
  3758. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3759. LLVMBuildRetVoid(p->builder);
  3760. return;
  3761. } else if (return_count == 1) {
  3762. Entity *e = tuple->variables[0];
  3763. if (res_count == 0) {
  3764. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3765. GB_ASSERT(found);
  3766. res = lb_emit_load(p, *found);
  3767. } else {
  3768. res = lb_build_expr(p, rs->results[0]);
  3769. res = lb_emit_conv(p, res, e->type);
  3770. }
  3771. if (p->type->Proc.has_named_results) {
  3772. // NOTE(bill): store the named values before returning
  3773. if (e->token.string != "") {
  3774. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3775. GB_ASSERT(found != nullptr);
  3776. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  3777. }
  3778. }
  3779. } else {
  3780. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  3781. if (res_count != 0) {
  3782. for (isize res_index = 0; res_index < res_count; res_index++) {
  3783. lbValue res = lb_build_expr(p, rs->results[res_index]);
  3784. Type *t = res.type;
  3785. if (t->kind == Type_Tuple) {
  3786. for_array(i, t->Tuple.variables) {
  3787. Entity *e = t->Tuple.variables[i];
  3788. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  3789. array_add(&results, v);
  3790. }
  3791. } else {
  3792. array_add(&results, res);
  3793. }
  3794. }
  3795. } else {
  3796. for (isize res_index = 0; res_index < return_count; res_index++) {
  3797. Entity *e = tuple->variables[res_index];
  3798. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3799. GB_ASSERT(found);
  3800. lbValue res = lb_emit_load(p, *found);
  3801. array_add(&results, res);
  3802. }
  3803. }
  3804. GB_ASSERT(results.count == return_count);
  3805. if (p->type->Proc.has_named_results) {
  3806. // NOTE(bill): store the named values before returning
  3807. for_array(i, p->type->Proc.results->Tuple.variables) {
  3808. Entity *e = p->type->Proc.results->Tuple.variables[i];
  3809. if (e->kind != Entity_Variable) {
  3810. continue;
  3811. }
  3812. if (e->token.string == "") {
  3813. continue;
  3814. }
  3815. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3816. GB_ASSERT(found != nullptr);
  3817. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  3818. }
  3819. }
  3820. Type *ret_type = p->type->Proc.results;
  3821. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3822. res = lb_add_local_generated(p, ret_type, false).addr;
  3823. for_array(i, results) {
  3824. Entity *e = tuple->variables[i];
  3825. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  3826. lbValue val = lb_emit_conv(p, results[i], e->type);
  3827. lb_emit_store(p, field, val);
  3828. }
  3829. res = lb_emit_load(p, res);
  3830. }
  3831. if (p->abi_function_type) {
  3832. if (p->abi_function_type->ret.kind == lbArg_Indirect) {
  3833. if (res.value != nullptr) {
  3834. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  3835. } else {
  3836. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  3837. }
  3838. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3839. LLVMBuildRetVoid(p->builder);
  3840. } else {
  3841. LLVMValueRef ret_val = res.value;
  3842. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  3843. if (p->abi_function_type->ret.cast_type != nullptr) {
  3844. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  3845. }
  3846. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3847. LLVMBuildRet(p->builder, ret_val);
  3848. }
  3849. } else {
  3850. GB_ASSERT(!USE_LLVM_ABI);
  3851. if (p->type->Proc.return_by_pointer) {
  3852. if (res.value != nullptr) {
  3853. lb_addr_store(p, p->return_ptr, res);
  3854. } else {
  3855. lb_addr_store(p, p->return_ptr, lb_const_nil(p->module, p->type->Proc.abi_compat_result_type));
  3856. }
  3857. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3858. LLVMBuildRetVoid(p->builder);
  3859. } else {
  3860. GB_ASSERT_MSG(res.value != nullptr, "%.*s", LIT(p->name));
  3861. Type *abi_rt = p->type->Proc.abi_compat_result_type;
  3862. if (!are_types_identical(res.type, abi_rt)) {
  3863. res = lb_emit_transmute(p, res, abi_rt);
  3864. }
  3865. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3866. LLVMBuildRet(p->builder, res.value);
  3867. }
  3868. }
  3869. case_end;
  3870. case_ast_node(is, IfStmt, node);
  3871. lb_open_scope(p); // Scope #1
  3872. if (is->init != nullptr) {
  3873. // TODO(bill): Should this have a separate block to begin with?
  3874. #if 1
  3875. lbBlock *init = lb_create_block(p, "if.init");
  3876. lb_emit_jump(p, init);
  3877. lb_start_block(p, init);
  3878. #endif
  3879. lb_build_stmt(p, is->init);
  3880. }
  3881. lbBlock *then = lb_create_block(p, "if.then");
  3882. lbBlock *done = lb_create_block(p, "if.done");
  3883. lbBlock *else_ = done;
  3884. if (is->else_stmt != nullptr) {
  3885. else_ = lb_create_block(p, "if.else");
  3886. }
  3887. lb_build_cond(p, is->cond, then, else_);
  3888. lb_start_block(p, then);
  3889. if (is->label != nullptr) {
  3890. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  3891. tl->is_block = true;
  3892. }
  3893. lb_build_stmt(p, is->body);
  3894. lb_emit_jump(p, done);
  3895. if (is->else_stmt != nullptr) {
  3896. lb_start_block(p, else_);
  3897. lb_open_scope(p);
  3898. lb_build_stmt(p, is->else_stmt);
  3899. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3900. lb_emit_jump(p, done);
  3901. }
  3902. lb_start_block(p, done);
  3903. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3904. case_end;
  3905. case_ast_node(fs, ForStmt, node);
  3906. lb_open_scope(p); // Open Scope here
  3907. if (fs->init != nullptr) {
  3908. #if 1
  3909. lbBlock *init = lb_create_block(p, "for.init");
  3910. lb_emit_jump(p, init);
  3911. lb_start_block(p, init);
  3912. #endif
  3913. lb_build_stmt(p, fs->init);
  3914. }
  3915. lbBlock *body = lb_create_block(p, "for.body");
  3916. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  3917. lbBlock *loop = body;
  3918. if (fs->cond != nullptr) {
  3919. loop = lb_create_block(p, "for.loop");
  3920. }
  3921. lbBlock *post = loop;
  3922. if (fs->post != nullptr) {
  3923. post = lb_create_block(p, "for.post");
  3924. }
  3925. lb_emit_jump(p, loop);
  3926. lb_start_block(p, loop);
  3927. if (loop != body) {
  3928. lb_build_cond(p, fs->cond, body, done);
  3929. lb_start_block(p, body);
  3930. }
  3931. lb_push_target_list(p, fs->label, done, post, nullptr);
  3932. lb_build_stmt(p, fs->body);
  3933. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3934. lb_pop_target_list(p);
  3935. lb_emit_jump(p, post);
  3936. if (fs->post != nullptr) {
  3937. lb_start_block(p, post);
  3938. lb_build_stmt(p, fs->post);
  3939. lb_emit_jump(p, loop);
  3940. }
  3941. lb_start_block(p, done);
  3942. case_end;
  3943. case_ast_node(rs, RangeStmt, node);
  3944. lb_build_range_stmt(p, rs);
  3945. case_end;
  3946. case_ast_node(rs, InlineRangeStmt, node);
  3947. lb_build_inline_range_stmt(p, rs);
  3948. case_end;
  3949. case_ast_node(ss, SwitchStmt, node);
  3950. lb_build_switch_stmt(p, ss);
  3951. case_end;
  3952. case_ast_node(ss, TypeSwitchStmt, node);
  3953. lb_build_type_switch_stmt(p, ss);
  3954. case_end;
  3955. case_ast_node(bs, BranchStmt, node);
  3956. lbBlock *block = nullptr;
  3957. if (bs->label != nullptr) {
  3958. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  3959. switch (bs->token.kind) {
  3960. case Token_break: block = bb.break_; break;
  3961. case Token_continue: block = bb.continue_; break;
  3962. case Token_fallthrough:
  3963. GB_PANIC("fallthrough cannot have a label");
  3964. break;
  3965. }
  3966. } else {
  3967. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  3968. if (t->is_block) {
  3969. continue;
  3970. }
  3971. switch (bs->token.kind) {
  3972. case Token_break: block = t->break_; break;
  3973. case Token_continue: block = t->continue_; break;
  3974. case Token_fallthrough: block = t->fallthrough_; break;
  3975. }
  3976. }
  3977. }
  3978. if (block != nullptr) {
  3979. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  3980. }
  3981. lb_emit_jump(p, block);
  3982. case_end;
  3983. }
  3984. }
  3985. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  3986. cond = lb_emit_conv(p, cond, t_llvm_bool);
  3987. lbValue res = {};
  3988. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  3989. res.type = x.type;
  3990. return res;
  3991. }
  3992. lbValue lb_const_nil(lbModule *m, Type *type) {
  3993. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  3994. return lbValue{v, type};
  3995. }
  3996. lbValue lb_const_undef(lbModule *m, Type *type) {
  3997. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  3998. return lbValue{v, type};
  3999. }
  4000. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  4001. lbValue res = {};
  4002. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  4003. res.type = type;
  4004. return res;
  4005. }
  4006. lbValue lb_const_string(lbModule *m, String const &value) {
  4007. return lb_const_value(m, t_string, exact_value_string(value));
  4008. }
  4009. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  4010. lbValue res = {};
  4011. res.value = LLVMConstInt(lb_type(m, type), value, false);
  4012. res.type = type;
  4013. return res;
  4014. }
  4015. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  4016. GB_ASSERT(type_size_of(type) == 4);
  4017. u32 u = bit_cast<u32>(f);
  4018. if (is_type_different_to_arch_endianness(type)) {
  4019. u = gb_endian_swap32(u);
  4020. }
  4021. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  4022. return LLVMConstBitCast(i, lb_type(m, type));
  4023. }
  4024. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4025. x = lb_emit_conv(p, x, t);
  4026. y = lb_emit_conv(p, y, t);
  4027. if (is_type_float(t)) {
  4028. i64 sz = 8*type_size_of(t);
  4029. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4030. args[0] = x;
  4031. args[1] = y;
  4032. switch (sz) {
  4033. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  4034. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  4035. }
  4036. GB_PANIC("Unknown float type");
  4037. }
  4038. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  4039. }
  4040. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4041. x = lb_emit_conv(p, x, t);
  4042. y = lb_emit_conv(p, y, t);
  4043. if (is_type_float(t)) {
  4044. i64 sz = 8*type_size_of(t);
  4045. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4046. args[0] = x;
  4047. args[1] = y;
  4048. switch (sz) {
  4049. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  4050. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  4051. }
  4052. GB_PANIC("Unknown float type");
  4053. }
  4054. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  4055. }
  4056. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  4057. lbValue z = {};
  4058. z = lb_emit_max(p, t, x, min);
  4059. z = lb_emit_min(p, t, z, max);
  4060. return z;
  4061. }
  4062. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  4063. StringHashKey key = string_hash_string(str);
  4064. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  4065. if (found != nullptr) {
  4066. return *found;
  4067. } else {
  4068. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4069. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4070. cast(char const *)str.text,
  4071. cast(unsigned)str.len,
  4072. false);
  4073. isize max_len = 7+8+1;
  4074. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  4075. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4076. len -= 1;
  4077. m->global_array_index++;
  4078. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4079. LLVMSetInitializer(global_data, data);
  4080. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4081. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4082. string_map_set(&m->const_strings, key, ptr);
  4083. return ptr;
  4084. }
  4085. }
  4086. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  4087. LLVMValueRef ptr = nullptr;
  4088. if (str.len != 0) {
  4089. ptr = lb_find_or_add_entity_string_ptr(m, str);
  4090. } else {
  4091. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4092. }
  4093. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4094. LLVMValueRef values[2] = {ptr, str_len};
  4095. lbValue res = {};
  4096. res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2);
  4097. res.type = t_string;
  4098. return res;
  4099. }
  4100. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  4101. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4102. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4103. cast(char const *)str.text,
  4104. cast(unsigned)str.len,
  4105. false);
  4106. char *name = nullptr;
  4107. {
  4108. isize max_len = 7+8+1;
  4109. name = gb_alloc_array(permanent_allocator(), char, max_len);
  4110. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4111. len -= 1;
  4112. m->global_array_index++;
  4113. }
  4114. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4115. LLVMSetInitializer(global_data, data);
  4116. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4117. LLVMValueRef ptr = nullptr;
  4118. if (str.len != 0) {
  4119. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4120. } else {
  4121. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4122. }
  4123. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4124. LLVMValueRef values[2] = {ptr, len};
  4125. lbValue res = {};
  4126. res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2);
  4127. res.type = t_u8_slice;
  4128. return res;
  4129. }
  4130. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4131. isize index = type_info_index(info, type, false);
  4132. if (index >= 0) {
  4133. auto *set = &info->minimum_dependency_type_info_set;
  4134. for_array(i, set->entries) {
  4135. if (set->entries[i].ptr == index) {
  4136. return i+1;
  4137. }
  4138. }
  4139. }
  4140. if (err_on_not_found) {
  4141. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  4142. }
  4143. return -1;
  4144. }
  4145. lbValue lb_typeid(lbModule *m, Type *type) {
  4146. type = default_type(type);
  4147. u64 id = cast(u64)lb_type_info_index(m->info, type);
  4148. GB_ASSERT(id >= 0);
  4149. u64 kind = Typeid_Invalid;
  4150. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4151. u64 special = 0;
  4152. u64 reserved = 0;
  4153. Type *bt = base_type(type);
  4154. TypeKind tk = bt->kind;
  4155. switch (tk) {
  4156. case Type_Basic: {
  4157. u32 flags = bt->Basic.flags;
  4158. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4159. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4160. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4161. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4162. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4163. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4164. if (flags & BasicFlag_String) kind = Typeid_String;
  4165. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4166. } break;
  4167. case Type_Pointer: kind = Typeid_Pointer; break;
  4168. case Type_Array: kind = Typeid_Array; break;
  4169. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  4170. case Type_Slice: kind = Typeid_Slice; break;
  4171. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4172. case Type_Map: kind = Typeid_Map; break;
  4173. case Type_Struct: kind = Typeid_Struct; break;
  4174. case Type_Enum: kind = Typeid_Enum; break;
  4175. case Type_Union: kind = Typeid_Union; break;
  4176. case Type_Tuple: kind = Typeid_Tuple; break;
  4177. case Type_Proc: kind = Typeid_Procedure; break;
  4178. case Type_BitField: kind = Typeid_Bit_Field; break;
  4179. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4180. case Type_Opaque: kind = Typeid_Opaque; break;
  4181. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  4182. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  4183. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  4184. }
  4185. if (is_type_cstring(type)) {
  4186. special = 1;
  4187. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4188. special = 1;
  4189. }
  4190. u64 data = 0;
  4191. if (build_context.word_size == 4) {
  4192. GB_ASSERT(id <= (1u<<24u));
  4193. data |= (id &~ (1u<<24)) << 0u; // index
  4194. data |= (kind &~ (1u<<5)) << 24u; // kind
  4195. data |= (named &~ (1u<<1)) << 29u; // kind
  4196. data |= (special &~ (1u<<1)) << 30u; // kind
  4197. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4198. } else {
  4199. GB_ASSERT(build_context.word_size == 8);
  4200. GB_ASSERT(id <= (1ull<<56u));
  4201. data |= (id &~ (1ull<<56)) << 0ul; // index
  4202. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4203. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4204. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4205. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4206. }
  4207. lbValue res = {};
  4208. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  4209. res.type = t_typeid;
  4210. return res;
  4211. }
  4212. lbValue lb_type_info(lbModule *m, Type *type) {
  4213. type = default_type(type);
  4214. isize index = lb_type_info_index(m->info, type);
  4215. GB_ASSERT(index >= 0);
  4216. LLVMTypeRef it = lb_type(m, t_int);
  4217. LLVMValueRef indices[2] = {
  4218. LLVMConstInt(it, 0, false),
  4219. LLVMConstInt(it, index, true),
  4220. };
  4221. lbValue value = {};
  4222. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  4223. value.type = t_type_info_ptr;
  4224. return value;
  4225. }
  4226. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  4227. LLVMContextRef ctx = m->ctx;
  4228. type = default_type(type);
  4229. Type *original_type = type;
  4230. lbValue res = {};
  4231. res.type = original_type;
  4232. type = core_type(type);
  4233. value = convert_exact_value_for_type(value, type);
  4234. if (value.kind == ExactValue_Typeid) {
  4235. return lb_typeid(m, value.value_typeid);
  4236. }
  4237. if (value.kind == ExactValue_Invalid) {
  4238. return lb_const_nil(m, type);
  4239. }
  4240. if (value.kind == ExactValue_Procedure) {
  4241. Ast *expr = unparen_expr(value.value_procedure);
  4242. if (expr->kind == Ast_ProcLit) {
  4243. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4244. }
  4245. Entity *e = entity_from_expr(expr);
  4246. e = strip_entity_wrapping(e);
  4247. GB_ASSERT(e != nullptr);
  4248. auto *found = map_get(&m->values, hash_entity(e));
  4249. if (found) {
  4250. return *found;
  4251. }
  4252. 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));
  4253. }
  4254. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  4255. if (is_type_slice(type)) {
  4256. if (value.kind == ExactValue_String) {
  4257. GB_ASSERT(is_type_u8_slice(type));
  4258. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  4259. return res;
  4260. } else {
  4261. ast_node(cl, CompoundLit, value.value_compound);
  4262. isize count = cl->elems.count;
  4263. if (count == 0) {
  4264. return lb_const_nil(m, type);
  4265. }
  4266. count = gb_max(cl->max_count, count);
  4267. Type *elem = base_type(type)->Slice.elem;
  4268. Type *t = alloc_type_array(elem, count);
  4269. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4270. LLVMValueRef array_data = nullptr;
  4271. if (allow_local && m->curr_procedure != nullptr) {
  4272. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4273. // its backing data on the stack
  4274. lbProcedure *p = m->curr_procedure;
  4275. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4276. LLVMTypeRef llvm_type = lb_type(m, t);
  4277. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4278. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4279. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4280. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4281. {
  4282. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4283. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4284. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4285. lbAddr slice = lb_add_local_generated(p, type, false);
  4286. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4287. return lb_addr_load(p, slice);
  4288. }
  4289. } else {
  4290. isize max_len = 7+8+1;
  4291. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  4292. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4293. m->global_array_index++;
  4294. String name = make_string(cast(u8 *)str, len-1);
  4295. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4296. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4297. LLVMSetInitializer(array_data, backing_array.value);
  4298. lbValue g = {};
  4299. g.value = array_data;
  4300. g.type = t;
  4301. lb_add_entity(m, e, g);
  4302. lb_add_member(m, name, g);
  4303. {
  4304. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4305. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4306. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4307. LLVMValueRef values[2] = {ptr, len};
  4308. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4309. return res;
  4310. }
  4311. }
  4312. }
  4313. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4314. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  4315. i64 count = type->Array.count;
  4316. Type *elem = type->Array.elem;
  4317. LLVMTypeRef et = lb_type(m, elem);
  4318. Rune rune;
  4319. isize offset = 0;
  4320. isize width = 1;
  4321. String s = value.value_string;
  4322. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4323. for (i64 i = 0; i < count && offset < s.len; i++) {
  4324. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  4325. offset += width;
  4326. elems[i] = LLVMConstInt(et, rune, true);
  4327. }
  4328. GB_ASSERT(offset == s.len);
  4329. res.value = LLVMConstArray(et, elems, cast(unsigned)count);
  4330. return res;
  4331. }
  4332. GB_PANIC("HERE!\n");
  4333. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4334. cast(char const *)value.value_string.text,
  4335. cast(unsigned)value.value_string.len,
  4336. false /*DontNullTerminate*/);
  4337. res.value = data;
  4338. return res;
  4339. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  4340. GB_ASSERT(type->Array.count == value.value_string.len);
  4341. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4342. cast(char const *)value.value_string.text,
  4343. cast(unsigned)value.value_string.len,
  4344. true /*DontNullTerminate*/);
  4345. res.value = data;
  4346. return res;
  4347. } else if (is_type_array(type) &&
  4348. value.kind != ExactValue_Invalid &&
  4349. value.kind != ExactValue_String &&
  4350. value.kind != ExactValue_Compound) {
  4351. i64 count = type->Array.count;
  4352. Type *elem = type->Array.elem;
  4353. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4354. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4355. for (i64 i = 0; i < count; i++) {
  4356. elems[i] = single_elem.value;
  4357. }
  4358. res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)count);
  4359. return res;
  4360. }
  4361. switch (value.kind) {
  4362. case ExactValue_Invalid:
  4363. res.value = LLVMConstNull(lb_type(m, original_type));
  4364. return res;
  4365. case ExactValue_Bool:
  4366. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4367. return res;
  4368. case ExactValue_String:
  4369. {
  4370. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4371. lbValue res = {};
  4372. res.type = default_type(original_type);
  4373. if (is_type_cstring(res.type)) {
  4374. res.value = ptr;
  4375. } else {
  4376. if (value.value_string.len == 0) {
  4377. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4378. }
  4379. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4380. LLVMValueRef values[2] = {ptr, str_len};
  4381. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4382. }
  4383. return res;
  4384. }
  4385. case ExactValue_Integer:
  4386. if (is_type_pointer(type)) {
  4387. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  4388. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  4389. } else {
  4390. unsigned len = cast(unsigned)value.value_integer.len;
  4391. if (len == 0) {
  4392. u64 word = 0;
  4393. res.value = LLVMConstNull(lb_type(m, original_type));
  4394. } else {
  4395. u64 *words = big_int_ptr(&value.value_integer);
  4396. if (is_type_different_to_arch_endianness(type)) {
  4397. // NOTE(bill): Swap byte order for different endianness
  4398. i64 sz = type_size_of(type);
  4399. isize byte_len = gb_size_of(u64)*len;
  4400. u8 *old_bytes = cast(u8 *)words;
  4401. // TODO(bill): Use a different allocator here for a temporary allocation
  4402. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  4403. for (i64 i = 0; i < sz; i++) {
  4404. new_bytes[i] = old_bytes[sz-1-i];
  4405. }
  4406. words = cast(u64 *)new_bytes;
  4407. }
  4408. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4409. if (value.value_integer.neg) {
  4410. res.value = LLVMConstNeg(res.value);
  4411. }
  4412. }
  4413. }
  4414. return res;
  4415. case ExactValue_Float:
  4416. if (type_size_of(type) == 4) {
  4417. f32 f = cast(f32)value.value_float;
  4418. res.value = lb_const_f32(m, f, type);
  4419. return res;
  4420. }
  4421. if (is_type_different_to_arch_endianness(type)) {
  4422. u64 u = bit_cast<u64>(value.value_float);
  4423. u = gb_endian_swap64(u);
  4424. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4425. } else {
  4426. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4427. }
  4428. return res;
  4429. case ExactValue_Complex:
  4430. {
  4431. LLVMValueRef values[2] = {};
  4432. switch (8*type_size_of(type)) {
  4433. case 64:
  4434. values[0] = lb_const_f32(m, cast(f32)value.value_complex.real);
  4435. values[1] = lb_const_f32(m, cast(f32)value.value_complex.imag);
  4436. break;
  4437. case 128:
  4438. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.real);
  4439. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.imag);
  4440. break;
  4441. }
  4442. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4443. return res;
  4444. }
  4445. break;
  4446. case ExactValue_Quaternion:
  4447. {
  4448. LLVMValueRef values[4] = {};
  4449. switch (8*type_size_of(type)) {
  4450. case 128:
  4451. // @QuaternionLayout
  4452. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion.real);
  4453. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion.imag);
  4454. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion.jmag);
  4455. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion.kmag);
  4456. break;
  4457. case 256:
  4458. // @QuaternionLayout
  4459. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.real);
  4460. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.imag);
  4461. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.jmag);
  4462. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.kmag);
  4463. break;
  4464. }
  4465. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 4);
  4466. return res;
  4467. }
  4468. break;
  4469. case ExactValue_Pointer:
  4470. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4471. return res;
  4472. case ExactValue_Compound:
  4473. if (is_type_slice(type)) {
  4474. return lb_const_value(m, type, value, allow_local);
  4475. } else if (is_type_array(type)) {
  4476. ast_node(cl, CompoundLit, value.value_compound);
  4477. Type *elem_type = type->Array.elem;
  4478. isize elem_count = cl->elems.count;
  4479. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4480. return lb_const_nil(m, original_type);
  4481. }
  4482. if (cl->elems[0]->kind == Ast_FieldValue) {
  4483. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4484. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4485. isize value_index = 0;
  4486. for (i64 i = 0; i < type->Array.count; i++) {
  4487. bool found = false;
  4488. for (isize j = 0; j < elem_count; j++) {
  4489. Ast *elem = cl->elems[j];
  4490. ast_node(fv, FieldValue, elem);
  4491. if (is_ast_range(fv->field)) {
  4492. ast_node(ie, BinaryExpr, fv->field);
  4493. TypeAndValue lo_tav = ie->left->tav;
  4494. TypeAndValue hi_tav = ie->right->tav;
  4495. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4496. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4497. TokenKind op = ie->op.kind;
  4498. i64 lo = exact_value_to_i64(lo_tav.value);
  4499. i64 hi = exact_value_to_i64(hi_tav.value);
  4500. if (op == Token_Ellipsis) {
  4501. hi += 1;
  4502. }
  4503. if (lo == i) {
  4504. TypeAndValue tav = fv->value->tav;
  4505. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4506. for (i64 k = lo; k < hi; k++) {
  4507. values[value_index++] = val;
  4508. }
  4509. found = true;
  4510. i += (hi-lo-1);
  4511. break;
  4512. }
  4513. } else {
  4514. TypeAndValue index_tav = fv->field->tav;
  4515. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4516. i64 index = exact_value_to_i64(index_tav.value);
  4517. if (index == i) {
  4518. TypeAndValue tav = fv->value->tav;
  4519. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4520. values[value_index++] = val;
  4521. found = true;
  4522. break;
  4523. }
  4524. }
  4525. }
  4526. if (!found) {
  4527. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4528. }
  4529. }
  4530. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  4531. return res;
  4532. } else {
  4533. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  4534. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4535. for (isize i = 0; i < elem_count; i++) {
  4536. TypeAndValue tav = cl->elems[i]->tav;
  4537. GB_ASSERT(tav.mode != Addressing_Invalid);
  4538. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4539. }
  4540. for (isize i = elem_count; i < type->Array.count; i++) {
  4541. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4542. }
  4543. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  4544. return res;
  4545. }
  4546. } else if (is_type_enumerated_array(type)) {
  4547. ast_node(cl, CompoundLit, value.value_compound);
  4548. Type *elem_type = type->EnumeratedArray.elem;
  4549. isize elem_count = cl->elems.count;
  4550. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4551. return lb_const_nil(m, original_type);
  4552. }
  4553. if (cl->elems[0]->kind == Ast_FieldValue) {
  4554. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4555. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4556. isize value_index = 0;
  4557. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  4558. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  4559. for (i64 i = total_lo; i <= total_hi; i++) {
  4560. bool found = false;
  4561. for (isize j = 0; j < elem_count; j++) {
  4562. Ast *elem = cl->elems[j];
  4563. ast_node(fv, FieldValue, elem);
  4564. if (is_ast_range(fv->field)) {
  4565. ast_node(ie, BinaryExpr, fv->field);
  4566. TypeAndValue lo_tav = ie->left->tav;
  4567. TypeAndValue hi_tav = ie->right->tav;
  4568. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4569. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4570. TokenKind op = ie->op.kind;
  4571. i64 lo = exact_value_to_i64(lo_tav.value);
  4572. i64 hi = exact_value_to_i64(hi_tav.value);
  4573. if (op == Token_Ellipsis) {
  4574. hi += 1;
  4575. }
  4576. if (lo == i) {
  4577. TypeAndValue tav = fv->value->tav;
  4578. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4579. for (i64 k = lo; k < hi; k++) {
  4580. values[value_index++] = val;
  4581. }
  4582. found = true;
  4583. i += (hi-lo-1);
  4584. break;
  4585. }
  4586. } else {
  4587. TypeAndValue index_tav = fv->field->tav;
  4588. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4589. i64 index = exact_value_to_i64(index_tav.value);
  4590. if (index == i) {
  4591. TypeAndValue tav = fv->value->tav;
  4592. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4593. values[value_index++] = val;
  4594. found = true;
  4595. break;
  4596. }
  4597. }
  4598. }
  4599. if (!found) {
  4600. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4601. }
  4602. }
  4603. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  4604. return res;
  4605. } else {
  4606. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  4607. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4608. for (isize i = 0; i < elem_count; i++) {
  4609. TypeAndValue tav = cl->elems[i]->tav;
  4610. GB_ASSERT(tav.mode != Addressing_Invalid);
  4611. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4612. }
  4613. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  4614. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4615. }
  4616. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  4617. return res;
  4618. }
  4619. } else if (is_type_simd_vector(type)) {
  4620. ast_node(cl, CompoundLit, value.value_compound);
  4621. Type *elem_type = type->SimdVector.elem;
  4622. isize elem_count = cl->elems.count;
  4623. if (elem_count == 0) {
  4624. return lb_const_nil(m, original_type);
  4625. }
  4626. GB_ASSERT(elem_type_can_be_constant(elem_type));
  4627. isize total_elem_count = type->SimdVector.count;
  4628. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  4629. for (isize i = 0; i < elem_count; i++) {
  4630. TypeAndValue tav = cl->elems[i]->tav;
  4631. GB_ASSERT(tav.mode != Addressing_Invalid);
  4632. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4633. }
  4634. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  4635. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4636. }
  4637. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  4638. return res;
  4639. } else if (is_type_struct(type)) {
  4640. ast_node(cl, CompoundLit, value.value_compound);
  4641. if (cl->elems.count == 0) {
  4642. return lb_const_nil(m, original_type);
  4643. }
  4644. isize offset = 0;
  4645. if (type->Struct.custom_align > 0) {
  4646. offset = 1;
  4647. }
  4648. isize value_count = type->Struct.fields.count + offset;
  4649. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  4650. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  4651. if (cl->elems.count > 0) {
  4652. if (cl->elems[0]->kind == Ast_FieldValue) {
  4653. isize elem_count = cl->elems.count;
  4654. for (isize i = 0; i < elem_count; i++) {
  4655. ast_node(fv, FieldValue, cl->elems[i]);
  4656. String name = fv->field->Ident.token.string;
  4657. TypeAndValue tav = fv->value->tav;
  4658. GB_ASSERT(tav.mode != Addressing_Invalid);
  4659. Selection sel = lookup_field(type, name, false);
  4660. Entity *f = type->Struct.fields[sel.index[0]];
  4661. if (elem_type_can_be_constant(f->type)) {
  4662. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  4663. visited[offset+f->Variable.field_index] = true;
  4664. }
  4665. }
  4666. } else {
  4667. for_array(i, cl->elems) {
  4668. Entity *f = type->Struct.fields[i];
  4669. TypeAndValue tav = cl->elems[i]->tav;
  4670. ExactValue val = {};
  4671. if (tav.mode != Addressing_Invalid) {
  4672. val = tav.value;
  4673. }
  4674. if (elem_type_can_be_constant(f->type)) {
  4675. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  4676. visited[offset+f->Variable.field_index] = true;
  4677. }
  4678. }
  4679. }
  4680. }
  4681. for (isize i = 0; i < type->Struct.fields.count; i++) {
  4682. if (!visited[offset+i]) {
  4683. GB_ASSERT(values[offset+i] == nullptr);
  4684. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  4685. }
  4686. }
  4687. if (type->Struct.custom_align > 0) {
  4688. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  4689. }
  4690. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, cast(unsigned)value_count);
  4691. return res;
  4692. } else if (is_type_bit_set(type)) {
  4693. ast_node(cl, CompoundLit, value.value_compound);
  4694. if (cl->elems.count == 0) {
  4695. return lb_const_nil(m, original_type);
  4696. }
  4697. i64 sz = type_size_of(type);
  4698. if (sz == 0) {
  4699. return lb_const_nil(m, original_type);
  4700. }
  4701. u64 bits = 0;
  4702. for_array(i, cl->elems) {
  4703. Ast *e = cl->elems[i];
  4704. GB_ASSERT(e->kind != Ast_FieldValue);
  4705. TypeAndValue tav = e->tav;
  4706. if (tav.mode != Addressing_Constant) {
  4707. continue;
  4708. }
  4709. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  4710. i64 v = big_int_to_i64(&tav.value.value_integer);
  4711. i64 lower = type->BitSet.lower;
  4712. bits |= 1ull<<cast(u64)(v-lower);
  4713. }
  4714. if (is_type_different_to_arch_endianness(type)) {
  4715. i64 size = type_size_of(type);
  4716. switch (size) {
  4717. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  4718. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  4719. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  4720. }
  4721. }
  4722. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  4723. return res;
  4724. } else {
  4725. return lb_const_nil(m, original_type);
  4726. }
  4727. break;
  4728. case ExactValue_Procedure:
  4729. {
  4730. Ast *expr = value.value_procedure;
  4731. GB_ASSERT(expr != nullptr);
  4732. if (expr->kind == Ast_ProcLit) {
  4733. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4734. }
  4735. }
  4736. break;
  4737. case ExactValue_Typeid:
  4738. return lb_typeid(m, value.value_typeid);
  4739. }
  4740. return lb_const_nil(m, original_type);
  4741. }
  4742. u64 lb_generate_source_code_location_hash(TokenPos const &pos) {
  4743. u64 h = 0xcbf29ce484222325;
  4744. for (isize i = 0; i < pos.file.len; i++) {
  4745. h = (h ^ u64(pos.file[i])) * 0x100000001b3;
  4746. }
  4747. h = h ^ (u64(pos.line) * 0x100000001b3);
  4748. h = h ^ (u64(pos.column) * 0x100000001b3);
  4749. return h;
  4750. }
  4751. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  4752. lbModule *m = p->module;
  4753. LLVMValueRef fields[5] = {};
  4754. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value;
  4755. fields[1]/*line*/ = lb_const_int(m, t_int, pos.line).value;
  4756. fields[2]/*column*/ = lb_const_int(m, t_int, pos.column).value;
  4757. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  4758. fields[4]/*hash*/ = lb_const_int(m, t_u64, lb_generate_source_code_location_hash(pos)).value;
  4759. lbValue res = {};
  4760. res.value = LLVMConstNamedStruct(lb_type(m, t_source_code_location), fields, 5);
  4761. res.type = t_source_code_location;
  4762. return res;
  4763. }
  4764. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  4765. String proc_name = {};
  4766. if (p->entity) {
  4767. proc_name = p->entity->token.string;
  4768. }
  4769. TokenPos pos = {};
  4770. if (node) {
  4771. pos = ast_token(node).pos;
  4772. }
  4773. return lb_emit_source_code_location(p, proc_name, pos);
  4774. }
  4775. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  4776. switch (op) {
  4777. case Token_Add:
  4778. return x;
  4779. case Token_Not: // Boolean not
  4780. case Token_Xor: // Bitwise not
  4781. case Token_Sub: // Number negation
  4782. break;
  4783. case Token_Pointer:
  4784. GB_PANIC("This should be handled elsewhere");
  4785. break;
  4786. }
  4787. if (is_type_array(x.type)) {
  4788. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  4789. Type *tl = base_type(x.type);
  4790. lbValue val = lb_address_from_load_or_generate_local(p, x);
  4791. GB_ASSERT(is_type_array(type));
  4792. Type *elem_type = base_array_type(type);
  4793. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4794. lbAddr res_addr = lb_add_local_generated(p, type, false);
  4795. lbValue res = lb_addr_get_ptr(p, res_addr);
  4796. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4797. i32 count = cast(i32)tl->Array.count;
  4798. if (inline_array_arith) {
  4799. // inline
  4800. for (i32 i = 0; i < count; i++) {
  4801. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  4802. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4803. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  4804. }
  4805. } else {
  4806. auto loop_data = lb_loop_start(p, count, t_i32);
  4807. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  4808. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4809. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  4810. lb_loop_end(p, loop_data);
  4811. }
  4812. return lb_emit_load(p, res);
  4813. }
  4814. if (op == Token_Xor) {
  4815. lbValue cmp = {};
  4816. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  4817. cmp.type = x.type;
  4818. return lb_emit_conv(p, cmp, type);
  4819. }
  4820. if (op == Token_Not) {
  4821. lbValue cmp = {};
  4822. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  4823. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  4824. cmp.type = t_llvm_bool;
  4825. return lb_emit_conv(p, cmp, type);
  4826. }
  4827. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4828. Type *platform_type = integer_endian_type_to_platform_type(type);
  4829. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4830. lbValue res = {};
  4831. res.value = LLVMBuildNeg(p->builder, v.value, "");
  4832. res.type = platform_type;
  4833. return lb_emit_byte_swap(p, res, type);
  4834. }
  4835. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4836. Type *platform_type = integer_endian_type_to_platform_type(type);
  4837. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4838. lbValue res = {};
  4839. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  4840. res.type = platform_type;
  4841. return lb_emit_byte_swap(p, res, type);
  4842. }
  4843. lbValue res = {};
  4844. switch (op) {
  4845. case Token_Not: // Boolean not
  4846. case Token_Xor: // Bitwise not
  4847. res.value = LLVMBuildNot(p->builder, x.value, "");
  4848. res.type = x.type;
  4849. return res;
  4850. case Token_Sub: // Number negation
  4851. if (is_type_integer(x.type)) {
  4852. res.value = LLVMBuildNeg(p->builder, x.value, "");
  4853. } else if (is_type_float(x.type)) {
  4854. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  4855. } else if (is_type_complex(x.type)) {
  4856. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4857. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4858. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4859. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4860. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4861. return lb_addr_load(p, addr);
  4862. } else if (is_type_quaternion(x.type)) {
  4863. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4864. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4865. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  4866. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  4867. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4868. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4869. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4870. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  4871. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  4872. return lb_addr_load(p, addr);
  4873. } else {
  4874. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  4875. }
  4876. res.type = x.type;
  4877. return res;
  4878. }
  4879. return res;
  4880. }
  4881. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  4882. lbModule *m = p->module;
  4883. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  4884. lhs = lb_emit_conv(p, lhs, type);
  4885. rhs = lb_emit_conv(p, rhs, type);
  4886. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  4887. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4888. GB_ASSERT(is_type_array(type));
  4889. Type *elem_type = base_array_type(type);
  4890. lbAddr res = lb_add_local_generated(p, type, false);
  4891. i64 count = base_type(type)->Array.count;
  4892. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4893. if (inline_array_arith) {
  4894. for (i64 i = 0; i < count; i++) {
  4895. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  4896. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  4897. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  4898. lbValue a = lb_emit_load(p, a_ptr);
  4899. lbValue b = lb_emit_load(p, b_ptr);
  4900. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4901. lb_emit_store(p, dst_ptr, c);
  4902. }
  4903. } else {
  4904. auto loop_data = lb_loop_start(p, count, t_i32);
  4905. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  4906. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  4907. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  4908. lbValue a = lb_emit_load(p, a_ptr);
  4909. lbValue b = lb_emit_load(p, b_ptr);
  4910. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4911. lb_emit_store(p, dst_ptr, c);
  4912. lb_loop_end(p, loop_data);
  4913. }
  4914. return lb_addr_load(p, res);
  4915. } else if (is_type_complex(type)) {
  4916. lhs = lb_emit_conv(p, lhs, type);
  4917. rhs = lb_emit_conv(p, rhs, type);
  4918. Type *ft = base_complex_elem_type(type);
  4919. if (op == Token_Quo) {
  4920. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4921. args[0] = lhs;
  4922. args[1] = rhs;
  4923. switch (type_size_of(ft)) {
  4924. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  4925. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  4926. default: GB_PANIC("Unknown float type"); break;
  4927. }
  4928. }
  4929. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4930. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  4931. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  4932. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  4933. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  4934. lbValue real = {};
  4935. lbValue imag = {};
  4936. switch (op) {
  4937. case Token_Add:
  4938. real = lb_emit_arith(p, Token_Add, a, c, ft);
  4939. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  4940. break;
  4941. case Token_Sub:
  4942. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  4943. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  4944. break;
  4945. case Token_Mul: {
  4946. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  4947. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  4948. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  4949. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  4950. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  4951. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  4952. break;
  4953. }
  4954. }
  4955. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  4956. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  4957. return lb_addr_load(p, res);
  4958. } else if (is_type_quaternion(type)) {
  4959. lhs = lb_emit_conv(p, lhs, type);
  4960. rhs = lb_emit_conv(p, rhs, type);
  4961. Type *ft = base_complex_elem_type(type);
  4962. if (op == Token_Add || op == Token_Sub) {
  4963. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4964. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  4965. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  4966. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  4967. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  4968. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  4969. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  4970. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  4971. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  4972. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  4973. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  4974. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  4975. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  4976. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  4977. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  4978. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  4979. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  4980. return lb_addr_load(p, res);
  4981. } else if (op == Token_Mul) {
  4982. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4983. args[0] = lhs;
  4984. args[1] = rhs;
  4985. switch (8*type_size_of(ft)) {
  4986. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  4987. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  4988. default: GB_PANIC("Unknown float type"); break;
  4989. }
  4990. } else if (op == Token_Quo) {
  4991. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4992. args[0] = lhs;
  4993. args[1] = rhs;
  4994. switch (8*type_size_of(ft)) {
  4995. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  4996. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  4997. default: GB_PANIC("Unknown float type"); break;
  4998. }
  4999. }
  5000. }
  5001. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5002. switch (op) {
  5003. case Token_AndNot:
  5004. case Token_And:
  5005. case Token_Or:
  5006. case Token_Xor:
  5007. goto handle_op;
  5008. }
  5009. Type *platform_type = integer_endian_type_to_platform_type(type);
  5010. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5011. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5012. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5013. return lb_emit_byte_swap(p, res, type);
  5014. }
  5015. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5016. Type *platform_type = integer_endian_type_to_platform_type(type);
  5017. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5018. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5019. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5020. return lb_emit_byte_swap(p, res, type);
  5021. }
  5022. handle_op:
  5023. lhs = lb_emit_conv(p, lhs, type);
  5024. rhs = lb_emit_conv(p, rhs, type);
  5025. lbValue res = {};
  5026. res.type = type;
  5027. switch (op) {
  5028. case Token_Add:
  5029. if (is_type_float(type)) {
  5030. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  5031. return res;
  5032. }
  5033. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  5034. return res;
  5035. case Token_Sub:
  5036. if (is_type_float(type)) {
  5037. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  5038. return res;
  5039. }
  5040. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  5041. return res;
  5042. case Token_Mul:
  5043. if (is_type_float(type)) {
  5044. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  5045. return res;
  5046. }
  5047. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  5048. return res;
  5049. case Token_Quo:
  5050. if (is_type_float(type)) {
  5051. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  5052. return res;
  5053. } else if (is_type_unsigned(type)) {
  5054. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  5055. return res;
  5056. }
  5057. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  5058. return res;
  5059. case Token_Mod:
  5060. if (is_type_float(type)) {
  5061. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  5062. return res;
  5063. } else if (is_type_unsigned(type)) {
  5064. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5065. return res;
  5066. }
  5067. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5068. return res;
  5069. case Token_ModMod:
  5070. if (is_type_unsigned(type)) {
  5071. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5072. return res;
  5073. } else {
  5074. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5075. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  5076. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  5077. res.value = c;
  5078. return res;
  5079. }
  5080. case Token_And:
  5081. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  5082. return res;
  5083. case Token_Or:
  5084. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  5085. return res;
  5086. case Token_Xor:
  5087. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  5088. return res;
  5089. case Token_Shl:
  5090. {
  5091. rhs = lb_emit_conv(p, rhs, lhs.type);
  5092. LLVMValueRef lhsval = lhs.value;
  5093. LLVMValueRef bits = rhs.value;
  5094. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  5095. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  5096. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  5097. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5098. res.value = LLVMBuildSelect(p->builder, less_equal_width, res.value, zero, "");
  5099. return res;
  5100. }
  5101. case Token_Shr:
  5102. {
  5103. rhs = lb_emit_conv(p, rhs, lhs.type);
  5104. LLVMValueRef lhsval = lhs.value;
  5105. LLVMValueRef bits = rhs.value;
  5106. bool is_unsigned = is_type_unsigned(type);
  5107. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  5108. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  5109. bits = LLVMBuildSelect(p->builder, less_equal_width, bits, max, "");
  5110. if (is_unsigned) {
  5111. res.value = LLVMBuildLShr(p->builder, lhs.value, bits, "");
  5112. } else {
  5113. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  5114. }
  5115. return res;
  5116. }
  5117. case Token_AndNot:
  5118. {
  5119. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  5120. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  5121. return res;
  5122. }
  5123. break;
  5124. }
  5125. GB_PANIC("unhandled operator of lb_emit_arith");
  5126. return {};
  5127. }
  5128. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  5129. ast_node(be, BinaryExpr, expr);
  5130. TypeAndValue tv = type_and_value_of_expr(expr);
  5131. switch (be->op.kind) {
  5132. case Token_Add:
  5133. case Token_Sub:
  5134. case Token_Mul:
  5135. case Token_Quo:
  5136. case Token_Mod:
  5137. case Token_ModMod:
  5138. case Token_And:
  5139. case Token_Or:
  5140. case Token_Xor:
  5141. case Token_AndNot:
  5142. case Token_Shl:
  5143. case Token_Shr: {
  5144. Type *type = default_type(tv.type);
  5145. lbValue left = lb_build_expr(p, be->left);
  5146. lbValue right = lb_build_expr(p, be->right);
  5147. return lb_emit_arith(p, be->op.kind, left, right, type);
  5148. }
  5149. case Token_CmpEq:
  5150. case Token_NotEq:
  5151. case Token_Lt:
  5152. case Token_LtEq:
  5153. case Token_Gt:
  5154. case Token_GtEq:
  5155. {
  5156. lbValue left = {};
  5157. lbValue right = {};
  5158. if (be->left->tav.mode == Addressing_Type) {
  5159. left = lb_typeid(p->module, be->left->tav.type);
  5160. }
  5161. if (be->right->tav.mode == Addressing_Type) {
  5162. right = lb_typeid(p->module, be->right->tav.type);
  5163. }
  5164. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  5165. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  5166. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  5167. Type *type = default_type(tv.type);
  5168. return lb_emit_conv(p, cmp, type);
  5169. }
  5170. case Token_CmpAnd:
  5171. case Token_CmpOr:
  5172. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  5173. case Token_in:
  5174. case Token_not_in:
  5175. {
  5176. lbValue left = lb_build_expr(p, be->left);
  5177. Type *type = default_type(tv.type);
  5178. lbValue right = lb_build_expr(p, be->right);
  5179. Type *rt = base_type(right.type);
  5180. switch (rt->kind) {
  5181. case Type_Map:
  5182. {
  5183. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  5184. lbValue h = lb_gen_map_header(p, addr, rt);
  5185. lbValue key = lb_gen_map_key(p, left, rt->Map.key);
  5186. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5187. args[0] = h;
  5188. args[1] = key;
  5189. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  5190. if (be->op.kind == Token_in) {
  5191. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  5192. } else {
  5193. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  5194. }
  5195. }
  5196. break;
  5197. case Type_BitSet:
  5198. {
  5199. Type *key_type = rt->BitSet.elem;
  5200. GB_ASSERT(are_types_identical(left.type, key_type));
  5201. Type *it = bit_set_to_int(rt);
  5202. left = lb_emit_conv(p, left, it);
  5203. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  5204. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  5205. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  5206. bit = lb_emit_conv(p, bit, it);
  5207. lbValue old_value = lb_emit_transmute(p, right, it);
  5208. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  5209. if (be->op.kind == Token_in) {
  5210. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5211. } else {
  5212. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5213. }
  5214. }
  5215. break;
  5216. default:
  5217. GB_PANIC("Invalid 'in' type");
  5218. }
  5219. break;
  5220. }
  5221. break;
  5222. default:
  5223. GB_PANIC("Invalid binary expression");
  5224. break;
  5225. }
  5226. return {};
  5227. }
  5228. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  5229. Type *prev_src = src;
  5230. // Type *prev_dst = dst;
  5231. src = base_type(type_deref(src));
  5232. // dst = base_type(type_deref(dst));
  5233. bool src_is_ptr = src != prev_src;
  5234. // bool dst_is_ptr = dst != prev_dst;
  5235. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  5236. for_array(i, src->Struct.fields) {
  5237. Entity *f = src->Struct.fields[i];
  5238. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  5239. if (are_types_identical(dst, f->type)) {
  5240. return f->token.string;
  5241. }
  5242. if (src_is_ptr && is_type_pointer(dst)) {
  5243. if (are_types_identical(type_deref(dst), f->type)) {
  5244. return f->token.string;
  5245. }
  5246. }
  5247. if (is_type_struct(f->type)) {
  5248. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  5249. if (name.len > 0) {
  5250. return name;
  5251. }
  5252. }
  5253. }
  5254. }
  5255. return str_lit("");
  5256. }
  5257. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  5258. GB_ASSERT(is_type_pointer(value.type));
  5259. GB_ASSERT(is_type_pointer(t));
  5260. GB_ASSERT(lb_is_const(value));
  5261. lbValue res = {};
  5262. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  5263. res.type = t;
  5264. return res;
  5265. }
  5266. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  5267. lbModule *m = p->module;
  5268. t = reduce_tuple_to_single_type(t);
  5269. Type *src_type = value.type;
  5270. if (are_types_identical(t, src_type)) {
  5271. return value;
  5272. }
  5273. Type *src = core_type(src_type);
  5274. Type *dst = core_type(t);
  5275. GB_ASSERT(src != nullptr);
  5276. GB_ASSERT(dst != nullptr);
  5277. if (is_type_untyped_nil(src)) {
  5278. return lb_const_nil(m, t);
  5279. }
  5280. if (is_type_untyped_undef(src)) {
  5281. return lb_const_undef(m, t);
  5282. }
  5283. if (LLVMIsConstant(value.value)) {
  5284. if (is_type_any(dst)) {
  5285. Type *st = default_type(src_type);
  5286. lbAddr default_value = lb_add_local_generated(p, st, false);
  5287. lb_addr_store(p, default_value, value);
  5288. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  5289. lbValue id = lb_typeid(m, st);
  5290. lbAddr res = lb_add_local_generated(p, t, false);
  5291. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  5292. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  5293. lb_emit_store(p, a0, data);
  5294. lb_emit_store(p, a1, id);
  5295. return lb_addr_load(p, res);
  5296. } else if (dst->kind == Type_Basic) {
  5297. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5298. String str = lb_get_const_string(m, value);
  5299. lbValue res = {};
  5300. res.type = t;
  5301. res.value = llvm_cstring(m, str);
  5302. return res;
  5303. }
  5304. // if (is_type_float(dst)) {
  5305. // return value;
  5306. // } else if (is_type_integer(dst)) {
  5307. // return value;
  5308. // }
  5309. // ExactValue ev = value->Constant.value;
  5310. // if (is_type_float(dst)) {
  5311. // ev = exact_value_to_float(ev);
  5312. // } else if (is_type_complex(dst)) {
  5313. // ev = exact_value_to_complex(ev);
  5314. // } else if (is_type_quaternion(dst)) {
  5315. // ev = exact_value_to_quaternion(ev);
  5316. // } else if (is_type_string(dst)) {
  5317. // // Handled elsewhere
  5318. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5319. // } else if (is_type_integer(dst)) {
  5320. // ev = exact_value_to_integer(ev);
  5321. // } else if (is_type_pointer(dst)) {
  5322. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5323. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5324. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5325. // }
  5326. // return lb_const_value(p->module, t, ev);
  5327. }
  5328. }
  5329. if (are_types_identical(src, dst)) {
  5330. if (!are_types_identical(src_type, t)) {
  5331. return lb_emit_transmute(p, value, t);
  5332. }
  5333. return value;
  5334. }
  5335. // bool <-> llvm bool
  5336. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5337. lbValue res = {};
  5338. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5339. res.type = dst;
  5340. return res;
  5341. }
  5342. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5343. lbValue res = {};
  5344. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5345. res.type = dst;
  5346. return res;
  5347. }
  5348. // integer -> integer
  5349. if (is_type_integer(src) && is_type_integer(dst)) {
  5350. GB_ASSERT(src->kind == Type_Basic &&
  5351. dst->kind == Type_Basic);
  5352. i64 sz = type_size_of(default_type(src));
  5353. i64 dz = type_size_of(default_type(dst));
  5354. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5355. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5356. value = lb_emit_byte_swap(p, value, platform_src_type);
  5357. }
  5358. LLVMOpcode op = LLVMTrunc;
  5359. if (dz < sz) {
  5360. op = LLVMTrunc;
  5361. } else if (dz == sz) {
  5362. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5363. // NOTE(bill): Copy the value just for type correctness
  5364. op = LLVMBitCast;
  5365. } else if (dz > sz) {
  5366. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5367. }
  5368. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5369. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5370. lbValue res = {};
  5371. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5372. res.type = t;
  5373. return lb_emit_byte_swap(p, res, t);
  5374. } else {
  5375. lbValue res = {};
  5376. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5377. res.type = t;
  5378. return res;
  5379. }
  5380. }
  5381. // boolean -> boolean/integer
  5382. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5383. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5384. lbValue res = {};
  5385. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5386. res.type = t;
  5387. return res;
  5388. }
  5389. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5390. return lb_emit_transmute(p, value, dst);
  5391. }
  5392. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5393. return lb_emit_transmute(p, value, dst);
  5394. }
  5395. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5396. return lb_emit_transmute(p, value, dst);
  5397. }
  5398. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5399. return lb_emit_transmute(p, value, dst);
  5400. }
  5401. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5402. lbValue c = lb_emit_conv(p, value, t_cstring);
  5403. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5404. args[0] = c;
  5405. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5406. return lb_emit_conv(p, s, dst);
  5407. }
  5408. // integer -> boolean
  5409. if (is_type_integer(src) && is_type_boolean(dst)) {
  5410. lbValue res = {};
  5411. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5412. res.type = t_llvm_bool;
  5413. return lb_emit_conv(p, res, t);
  5414. }
  5415. // float -> float
  5416. if (is_type_float(src) && is_type_float(dst)) {
  5417. i64 sz = type_size_of(src);
  5418. i64 dz = type_size_of(dst);
  5419. if (dz == sz) {
  5420. if (types_have_same_internal_endian(src, dst)) {
  5421. lbValue res = {};
  5422. res.type = t;
  5423. res.value = value.value;
  5424. return res;
  5425. } else {
  5426. return lb_emit_byte_swap(p, value, t);
  5427. }
  5428. }
  5429. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5430. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5431. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5432. lbValue res = {};
  5433. res = lb_emit_conv(p, value, platform_src_type);
  5434. res = lb_emit_conv(p, res, platform_dst_type);
  5435. if (is_type_different_to_arch_endianness(dst)) {
  5436. res = lb_emit_byte_swap(p, res, t);
  5437. }
  5438. return lb_emit_conv(p, res, t);
  5439. }
  5440. lbValue res = {};
  5441. res.type = t;
  5442. if (dz >= sz) {
  5443. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  5444. } else {
  5445. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  5446. }
  5447. return res;
  5448. }
  5449. if (is_type_complex(src) && is_type_complex(dst)) {
  5450. Type *ft = base_complex_elem_type(dst);
  5451. lbAddr gen = lb_add_local_generated(p, dst, false);
  5452. lbValue gp = lb_addr_get_ptr(p, gen);
  5453. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5454. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5455. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5456. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  5457. return lb_addr_load(p, gen);
  5458. }
  5459. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5460. // @QuaternionLayout
  5461. Type *ft = base_complex_elem_type(dst);
  5462. lbAddr gen = lb_add_local_generated(p, dst, false);
  5463. lbValue gp = lb_addr_get_ptr(p, gen);
  5464. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5465. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5466. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  5467. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  5468. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  5469. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  5470. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  5471. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  5472. return lb_addr_load(p, gen);
  5473. }
  5474. if (is_type_float(src) && is_type_complex(dst)) {
  5475. Type *ft = base_complex_elem_type(dst);
  5476. lbAddr gen = lb_add_local_generated(p, dst, true);
  5477. lbValue gp = lb_addr_get_ptr(p, gen);
  5478. lbValue real = lb_emit_conv(p, value, ft);
  5479. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5480. return lb_addr_load(p, gen);
  5481. }
  5482. if (is_type_float(src) && is_type_quaternion(dst)) {
  5483. Type *ft = base_complex_elem_type(dst);
  5484. lbAddr gen = lb_add_local_generated(p, dst, true);
  5485. lbValue gp = lb_addr_get_ptr(p, gen);
  5486. lbValue real = lb_emit_conv(p, value, ft);
  5487. // @QuaternionLayout
  5488. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5489. return lb_addr_load(p, gen);
  5490. }
  5491. if (is_type_complex(src) && is_type_quaternion(dst)) {
  5492. Type *ft = base_complex_elem_type(dst);
  5493. lbAddr gen = lb_add_local_generated(p, dst, true);
  5494. lbValue gp = lb_addr_get_ptr(p, gen);
  5495. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5496. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5497. // @QuaternionLayout
  5498. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5499. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  5500. return lb_addr_load(p, gen);
  5501. }
  5502. // float <-> integer
  5503. if (is_type_float(src) && is_type_integer(dst)) {
  5504. lbValue res = {};
  5505. res.type = t;
  5506. if (is_type_unsigned(dst)) {
  5507. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  5508. } else {
  5509. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  5510. }
  5511. return res;
  5512. }
  5513. if (is_type_integer(src) && is_type_float(dst)) {
  5514. lbValue res = {};
  5515. res.type = t;
  5516. if (is_type_unsigned(src)) {
  5517. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  5518. } else {
  5519. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  5520. }
  5521. return res;
  5522. }
  5523. // Pointer <-> uintptr
  5524. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5525. lbValue res = {};
  5526. res.type = t;
  5527. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5528. return res;
  5529. }
  5530. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5531. lbValue res = {};
  5532. res.type = t;
  5533. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5534. return res;
  5535. }
  5536. #if 1
  5537. if (is_type_union(dst)) {
  5538. for_array(i, dst->Union.variants) {
  5539. Type *vt = dst->Union.variants[i];
  5540. if (are_types_identical(vt, src_type)) {
  5541. lbAddr parent = lb_add_local_generated(p, t, true);
  5542. lb_emit_store_union_variant(p, parent.addr, value, vt);
  5543. return lb_addr_load(p, parent);
  5544. }
  5545. }
  5546. }
  5547. #endif
  5548. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  5549. // subtype polymorphism casting
  5550. if (check_is_assignable_to_using_subtype(src_type, t)) {
  5551. Type *st = type_deref(src_type);
  5552. Type *pst = st;
  5553. st = type_deref(st);
  5554. bool st_is_ptr = is_type_pointer(src_type);
  5555. st = base_type(st);
  5556. Type *dt = t;
  5557. bool dt_is_ptr = type_deref(dt) != dt;
  5558. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  5559. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  5560. if (field_name.len > 0) {
  5561. // NOTE(bill): It can be casted
  5562. Selection sel = lookup_field(st, field_name, false, true);
  5563. if (sel.entity != nullptr) {
  5564. if (st_is_ptr) {
  5565. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  5566. Type *rt = res.type;
  5567. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5568. res = lb_emit_load(p, res);
  5569. }
  5570. return res;
  5571. } else {
  5572. if (is_type_pointer(value.type)) {
  5573. Type *rt = value.type;
  5574. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5575. value = lb_emit_load(p, value);
  5576. } else {
  5577. value = lb_emit_deep_field_gep(p, value, sel);
  5578. return lb_emit_load(p, value);
  5579. }
  5580. }
  5581. return lb_emit_deep_field_ev(p, value, sel);
  5582. }
  5583. } else {
  5584. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  5585. }
  5586. }
  5587. }
  5588. // Pointer <-> Pointer
  5589. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5590. lbValue res = {};
  5591. res.type = t;
  5592. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5593. return res;
  5594. }
  5595. // proc <-> proc
  5596. if (is_type_proc(src) && is_type_proc(dst)) {
  5597. lbValue res = {};
  5598. res.type = t;
  5599. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5600. return res;
  5601. }
  5602. // pointer -> proc
  5603. if (is_type_pointer(src) && is_type_proc(dst)) {
  5604. lbValue res = {};
  5605. res.type = t;
  5606. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5607. return res;
  5608. }
  5609. // proc -> pointer
  5610. if (is_type_proc(src) && is_type_pointer(dst)) {
  5611. lbValue res = {};
  5612. res.type = t;
  5613. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5614. return res;
  5615. }
  5616. // []byte/[]u8 <-> string
  5617. if (is_type_u8_slice(src) && is_type_string(dst)) {
  5618. return lb_emit_transmute(p, value, t);
  5619. }
  5620. if (is_type_string(src) && is_type_u8_slice(dst)) {
  5621. return lb_emit_transmute(p, value, t);
  5622. }
  5623. if (is_type_array(dst)) {
  5624. Type *elem = dst->Array.elem;
  5625. lbValue e = lb_emit_conv(p, value, elem);
  5626. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5627. lbAddr v = lb_add_local_generated(p, t, false);
  5628. isize index_count = cast(isize)dst->Array.count;
  5629. for (isize i = 0; i < index_count; i++) {
  5630. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  5631. lb_emit_store(p, elem, e);
  5632. }
  5633. return lb_addr_load(p, v);
  5634. }
  5635. if (is_type_any(dst)) {
  5636. if (is_type_untyped_nil(src)) {
  5637. return lb_const_nil(p->module, t);
  5638. }
  5639. if (is_type_untyped_undef(src)) {
  5640. return lb_const_undef(p->module, t);
  5641. }
  5642. lbAddr result = lb_add_local_generated(p, t, true);
  5643. Type *st = default_type(src_type);
  5644. lbValue data = lb_address_from_load_or_generate_local(p, value);
  5645. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  5646. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  5647. data = lb_emit_conv(p, data, t_rawptr);
  5648. lbValue id = lb_typeid(p->module, st);
  5649. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  5650. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  5651. lb_emit_store(p, any_data, data);
  5652. lb_emit_store(p, any_id, id);
  5653. return lb_addr_load(p, result);
  5654. }
  5655. i64 src_sz = type_size_of(src);
  5656. i64 dst_sz = type_size_of(dst);
  5657. if (src_sz == dst_sz) {
  5658. // bit_set <-> integer
  5659. if (is_type_integer(src) && is_type_bit_set(dst)) {
  5660. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  5661. res.type = dst;
  5662. return res;
  5663. }
  5664. if (is_type_bit_set(src) && is_type_integer(dst)) {
  5665. lbValue bs = value;
  5666. bs.type = bit_set_to_int(src);
  5667. return lb_emit_conv(p, bs, dst);
  5668. }
  5669. // typeid <-> integer
  5670. if (is_type_integer(src) && is_type_typeid(dst)) {
  5671. return lb_emit_transmute(p, value, dst);
  5672. }
  5673. if (is_type_typeid(src) && is_type_integer(dst)) {
  5674. return lb_emit_transmute(p, value, dst);
  5675. }
  5676. }
  5677. if (is_type_untyped(src)) {
  5678. if (is_type_string(src) && is_type_string(dst)) {
  5679. lbAddr result = lb_add_local_generated(p, t, false);
  5680. lb_addr_store(p, result, value);
  5681. return lb_addr_load(p, result);
  5682. }
  5683. }
  5684. gb_printf_err("%.*s\n", LIT(p->name));
  5685. gb_printf_err("lb_emit_conv: src -> dst\n");
  5686. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  5687. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  5688. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  5689. gb_printf_err("Not Identical %p != %p\n", src, dst);
  5690. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  5691. type_to_string(src_type), type_to_string(t),
  5692. LIT(p->name));
  5693. return {};
  5694. }
  5695. bool lb_is_type_aggregate(Type *t) {
  5696. t = base_type(t);
  5697. switch (t->kind) {
  5698. case Type_Basic:
  5699. switch (t->Basic.kind) {
  5700. case Basic_string:
  5701. case Basic_any:
  5702. return true;
  5703. // case Basic_complex32:
  5704. case Basic_complex64:
  5705. case Basic_complex128:
  5706. case Basic_quaternion128:
  5707. case Basic_quaternion256:
  5708. return true;
  5709. }
  5710. break;
  5711. case Type_Pointer:
  5712. return false;
  5713. case Type_Array:
  5714. case Type_Slice:
  5715. case Type_Struct:
  5716. case Type_Union:
  5717. case Type_Tuple:
  5718. case Type_DynamicArray:
  5719. case Type_Map:
  5720. case Type_BitField:
  5721. case Type_SimdVector:
  5722. return true;
  5723. case Type_Named:
  5724. return lb_is_type_aggregate(t->Named.base);
  5725. }
  5726. return false;
  5727. }
  5728. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  5729. Type *src_type = value.type;
  5730. if (are_types_identical(t, src_type)) {
  5731. return value;
  5732. }
  5733. lbValue res = {};
  5734. res.type = t;
  5735. Type *src = base_type(src_type);
  5736. Type *dst = base_type(t);
  5737. lbModule *m = p->module;
  5738. i64 sz = type_size_of(src);
  5739. i64 dz = type_size_of(dst);
  5740. if (sz != dz) {
  5741. LLVMTypeRef s = lb_type(m, src);
  5742. LLVMTypeRef d = lb_type(m, dst);
  5743. i64 llvm_sz = lb_sizeof(s);
  5744. i64 llvm_dz = lb_sizeof(d);
  5745. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  5746. }
  5747. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  5748. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  5749. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5750. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5751. return res;
  5752. }
  5753. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5754. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5755. return res;
  5756. }
  5757. if (is_type_uintptr(src) && is_type_proc(dst)) {
  5758. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5759. return res;
  5760. }
  5761. if (is_type_proc(src) && is_type_uintptr(dst)) {
  5762. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5763. return res;
  5764. }
  5765. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  5766. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5767. return res;
  5768. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  5769. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5770. return res;
  5771. }
  5772. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5773. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  5774. return res;
  5775. }
  5776. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  5777. lbValue s = lb_address_from_load_or_generate_local(p, value);
  5778. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  5779. return lb_emit_load(p, d);
  5780. }
  5781. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  5782. // GB_PANIC("lb_emit_transmute");
  5783. return res;
  5784. }
  5785. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  5786. GB_ASSERT(addr.kind == lbAddr_Context);
  5787. GB_ASSERT(addr.ctx.sel.index.count == 0);
  5788. lbModule *m = p->module;
  5789. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5790. args[0] = addr.addr;
  5791. lb_emit_runtime_call(p, "__init_context", args);
  5792. }
  5793. void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  5794. ctx.kind = lbAddr_Context;
  5795. lbContextData cd = {ctx, p->scope_index};
  5796. array_add(&p->context_stack, cd);
  5797. }
  5798. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  5799. if (p->context_stack.count > 0) {
  5800. return p->context_stack[p->context_stack.count-1].ctx;
  5801. }
  5802. Type *pt = base_type(p->type);
  5803. GB_ASSERT(pt->kind == Type_Proc);
  5804. {
  5805. lbAddr c = lb_add_local_generated(p, t_context, false);
  5806. c.kind = lbAddr_Context;
  5807. lb_emit_init_context(p, c);
  5808. lb_push_context_onto_stack(p, c);
  5809. return c;
  5810. }
  5811. }
  5812. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  5813. if (LLVMIsALoadInst(value.value)) {
  5814. lbValue res = {};
  5815. res.value = LLVMGetOperand(value.value, 0);
  5816. res.type = alloc_type_pointer(value.type);
  5817. return res;
  5818. }
  5819. GB_ASSERT(is_type_typed(value.type));
  5820. lbAddr res = lb_add_local_generated(p, value.type, false);
  5821. lb_addr_store(p, res, value);
  5822. return res.addr;
  5823. }
  5824. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  5825. if (LLVMIsALoadInst(value.value)) {
  5826. lbValue res = {};
  5827. res.value = LLVMGetOperand(value.value, 0);
  5828. res.type = alloc_type_pointer(value.type);
  5829. return res;
  5830. }
  5831. GB_PANIC("lb_address_from_load");
  5832. return {};
  5833. }
  5834. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  5835. i64 type_alignment = type_align_of(new_type);
  5836. if (alignment < type_alignment) {
  5837. alignment = type_alignment;
  5838. }
  5839. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  5840. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  5841. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  5842. lb_addr_store(p, ptr, val);
  5843. ptr.kind = lbAddr_Context;
  5844. return ptr.addr;
  5845. }
  5846. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  5847. GB_ASSERT(is_type_pointer(s.type));
  5848. Type *t = base_type(type_deref(s.type));
  5849. Type *result_type = nullptr;
  5850. if (t->kind == Type_Opaque) {
  5851. t = t->Opaque.elem;
  5852. }
  5853. if (is_type_relative_pointer(t)) {
  5854. s = lb_addr_get_ptr(p, lb_addr(s));
  5855. }
  5856. if (is_type_struct(t)) {
  5857. result_type = get_struct_field_type(t, index);
  5858. } else if (is_type_union(t)) {
  5859. GB_ASSERT(index == -1);
  5860. return lb_emit_union_tag_ptr(p, s);
  5861. } else if (is_type_tuple(t)) {
  5862. GB_ASSERT(t->Tuple.variables.count > 0);
  5863. result_type = t->Tuple.variables[index]->type;
  5864. } else if (is_type_complex(t)) {
  5865. Type *ft = base_complex_elem_type(t);
  5866. switch (index) {
  5867. case 0: result_type = ft; break;
  5868. case 1: result_type = ft; break;
  5869. }
  5870. } else if (is_type_quaternion(t)) {
  5871. Type *ft = base_complex_elem_type(t);
  5872. switch (index) {
  5873. case 0: result_type = ft; break;
  5874. case 1: result_type = ft; break;
  5875. case 2: result_type = ft; break;
  5876. case 3: result_type = ft; break;
  5877. }
  5878. } else if (is_type_slice(t)) {
  5879. switch (index) {
  5880. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5881. case 1: result_type = t_int; break;
  5882. }
  5883. } else if (is_type_string(t)) {
  5884. switch (index) {
  5885. case 0: result_type = t_u8_ptr; break;
  5886. case 1: result_type = t_int; break;
  5887. }
  5888. } else if (is_type_any(t)) {
  5889. switch (index) {
  5890. case 0: result_type = t_rawptr; break;
  5891. case 1: result_type = t_typeid; break;
  5892. }
  5893. } else if (is_type_dynamic_array(t)) {
  5894. switch (index) {
  5895. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5896. case 1: result_type = t_int; break;
  5897. case 2: result_type = t_int; break;
  5898. case 3: result_type = t_allocator; break;
  5899. }
  5900. } else if (is_type_map(t)) {
  5901. init_map_internal_types(t);
  5902. Type *itp = alloc_type_pointer(t->Map.internal_type);
  5903. s = lb_emit_transmute(p, s, itp);
  5904. Type *gst = t->Map.internal_type;
  5905. GB_ASSERT(gst->kind == Type_Struct);
  5906. switch (index) {
  5907. case 0: result_type = get_struct_field_type(gst, 0); break;
  5908. case 1: result_type = get_struct_field_type(gst, 1); break;
  5909. }
  5910. } else if (is_type_array(t)) {
  5911. return lb_emit_array_epi(p, s, index);
  5912. } else if (is_type_relative_slice(t)) {
  5913. switch (index) {
  5914. case 0: result_type = t->RelativeSlice.base_integer; break;
  5915. case 1: result_type = t->RelativeSlice.base_integer; break;
  5916. }
  5917. } else {
  5918. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  5919. }
  5920. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  5921. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5922. index += 1;
  5923. }
  5924. if (lb_is_const(s)) {
  5925. lbModule *m = p->module;
  5926. lbValue res = {};
  5927. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  5928. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  5929. res.type = alloc_type_pointer(result_type);
  5930. return res;
  5931. } else {
  5932. lbValue res = {};
  5933. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  5934. res.type = alloc_type_pointer(result_type);
  5935. return res;
  5936. }
  5937. }
  5938. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  5939. if (LLVMIsALoadInst(s.value)) {
  5940. lbValue res = {};
  5941. res.value = LLVMGetOperand(s.value, 0);
  5942. res.type = alloc_type_pointer(s.type);
  5943. lbValue ptr = lb_emit_struct_ep(p, res, index);
  5944. return lb_emit_load(p, ptr);
  5945. }
  5946. Type *t = base_type(s.type);
  5947. Type *result_type = nullptr;
  5948. switch (t->kind) {
  5949. case Type_Basic:
  5950. switch (t->Basic.kind) {
  5951. case Basic_string:
  5952. switch (index) {
  5953. case 0: result_type = t_u8_ptr; break;
  5954. case 1: result_type = t_int; break;
  5955. }
  5956. break;
  5957. case Basic_any:
  5958. switch (index) {
  5959. case 0: result_type = t_rawptr; break;
  5960. case 1: result_type = t_typeid; break;
  5961. }
  5962. break;
  5963. case Basic_complex64: case Basic_complex128:
  5964. {
  5965. Type *ft = base_complex_elem_type(t);
  5966. switch (index) {
  5967. case 0: result_type = ft; break;
  5968. case 1: result_type = ft; break;
  5969. }
  5970. break;
  5971. }
  5972. case Basic_quaternion128: case Basic_quaternion256:
  5973. {
  5974. Type *ft = base_complex_elem_type(t);
  5975. switch (index) {
  5976. case 0: result_type = ft; break;
  5977. case 1: result_type = ft; break;
  5978. case 2: result_type = ft; break;
  5979. case 3: result_type = ft; break;
  5980. }
  5981. break;
  5982. }
  5983. }
  5984. break;
  5985. case Type_Struct:
  5986. result_type = get_struct_field_type(t, index);
  5987. break;
  5988. case Type_Union:
  5989. GB_ASSERT(index == -1);
  5990. // return lb_emit_union_tag_value(p, s);
  5991. GB_PANIC("lb_emit_union_tag_value");
  5992. case Type_Tuple:
  5993. GB_ASSERT(t->Tuple.variables.count > 0);
  5994. result_type = t->Tuple.variables[index]->type;
  5995. if (t->Tuple.variables.count == 1) {
  5996. return s;
  5997. }
  5998. break;
  5999. case Type_Slice:
  6000. switch (index) {
  6001. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6002. case 1: result_type = t_int; break;
  6003. }
  6004. break;
  6005. case Type_DynamicArray:
  6006. switch (index) {
  6007. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6008. case 1: result_type = t_int; break;
  6009. case 2: result_type = t_int; break;
  6010. case 3: result_type = t_allocator; break;
  6011. }
  6012. break;
  6013. case Type_Map:
  6014. {
  6015. init_map_internal_types(t);
  6016. Type *gst = t->Map.generated_struct_type;
  6017. switch (index) {
  6018. case 0: result_type = get_struct_field_type(gst, 0); break;
  6019. case 1: result_type = get_struct_field_type(gst, 1); break;
  6020. }
  6021. }
  6022. break;
  6023. case Type_Array:
  6024. result_type = t->Array.elem;
  6025. break;
  6026. default:
  6027. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  6028. break;
  6029. }
  6030. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  6031. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6032. index += 1;
  6033. }
  6034. lbValue res = {};
  6035. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  6036. res.type = result_type;
  6037. return res;
  6038. }
  6039. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  6040. GB_ASSERT(sel.index.count > 0);
  6041. Type *type = type_deref(e.type);
  6042. for_array(i, sel.index) {
  6043. i32 index = cast(i32)sel.index[i];
  6044. if (is_type_pointer(type)) {
  6045. type = type_deref(type);
  6046. e = lb_emit_load(p, e);
  6047. }
  6048. type = core_type(type);
  6049. if (type->kind == Type_Opaque) {
  6050. type = type->Opaque.elem;
  6051. }
  6052. if (is_type_quaternion(type)) {
  6053. e = lb_emit_struct_ep(p, e, index);
  6054. } else if (is_type_raw_union(type)) {
  6055. type = get_struct_field_type(type, index);
  6056. GB_ASSERT(is_type_pointer(e.type));
  6057. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  6058. } else if (is_type_struct(type)) {
  6059. type = get_struct_field_type(type, index);
  6060. e = lb_emit_struct_ep(p, e, index);
  6061. } else if (type->kind == Type_Union) {
  6062. GB_ASSERT(index == -1);
  6063. type = t_type_info_ptr;
  6064. e = lb_emit_struct_ep(p, e, index);
  6065. } else if (type->kind == Type_Tuple) {
  6066. type = type->Tuple.variables[index]->type;
  6067. e = lb_emit_struct_ep(p, e, index);
  6068. } else if (type->kind == Type_Basic) {
  6069. switch (type->Basic.kind) {
  6070. case Basic_any: {
  6071. if (index == 0) {
  6072. type = t_rawptr;
  6073. } else if (index == 1) {
  6074. type = t_type_info_ptr;
  6075. }
  6076. e = lb_emit_struct_ep(p, e, index);
  6077. break;
  6078. }
  6079. case Basic_string:
  6080. e = lb_emit_struct_ep(p, e, index);
  6081. break;
  6082. default:
  6083. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6084. break;
  6085. }
  6086. } else if (type->kind == Type_Slice) {
  6087. e = lb_emit_struct_ep(p, e, index);
  6088. } else if (type->kind == Type_DynamicArray) {
  6089. e = lb_emit_struct_ep(p, e, index);
  6090. } else if (type->kind == Type_Array) {
  6091. e = lb_emit_array_epi(p, e, index);
  6092. } else if (type->kind == Type_Map) {
  6093. e = lb_emit_struct_ep(p, e, index);
  6094. } else if (type->kind == Type_RelativePointer) {
  6095. e = lb_emit_struct_ep(p, e, index);
  6096. } else {
  6097. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6098. }
  6099. }
  6100. return e;
  6101. }
  6102. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  6103. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  6104. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  6105. return lb_emit_load(p, res);
  6106. }
  6107. void lb_build_defer_stmt(lbProcedure *p, lbDefer d) {
  6108. // NOTE(bill): The prev block may defer injection before it's terminator
  6109. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  6110. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  6111. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  6112. return;
  6113. }
  6114. isize prev_context_stack_count = p->context_stack.count;
  6115. defer (p->context_stack.count = prev_context_stack_count);
  6116. p->context_stack.count = d.context_stack_count;
  6117. lbBlock *b = lb_create_block(p, "defer");
  6118. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6119. lb_emit_jump(p, b);
  6120. }
  6121. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6122. lb_emit_jump(p, b);
  6123. }
  6124. lb_start_block(p, b);
  6125. if (d.kind == lbDefer_Node) {
  6126. lb_build_stmt(p, d.stmt);
  6127. } else if (d.kind == lbDefer_Instr) {
  6128. // NOTE(bill): Need to make a new copy
  6129. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  6130. LLVMInsertIntoBuilder(p->builder, instr);
  6131. } else if (d.kind == lbDefer_Proc) {
  6132. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  6133. }
  6134. }
  6135. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  6136. isize count = p->defer_stmts.count;
  6137. isize i = count;
  6138. while (i --> 0) {
  6139. lbDefer d = p->defer_stmts[i];
  6140. isize prev_context_stack_count = p->context_stack.count;
  6141. defer (p->context_stack.count = prev_context_stack_count);
  6142. p->context_stack.count = d.context_stack_count;
  6143. if (kind == lbDeferExit_Default) {
  6144. if (p->scope_index == d.scope_index &&
  6145. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  6146. lb_build_defer_stmt(p, d);
  6147. array_pop(&p->defer_stmts);
  6148. continue;
  6149. } else {
  6150. break;
  6151. }
  6152. } else if (kind == lbDeferExit_Return) {
  6153. lb_build_defer_stmt(p, d);
  6154. } else if (kind == lbDeferExit_Branch) {
  6155. GB_ASSERT(block != nullptr);
  6156. isize lower_limit = block->scope_index;
  6157. if (lower_limit < d.scope_index) {
  6158. lb_build_defer_stmt(p, d);
  6159. }
  6160. }
  6161. }
  6162. }
  6163. lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  6164. lbDefer d = {lbDefer_Node};
  6165. d.scope_index = scope_index;
  6166. d.context_stack_count = p->context_stack.count;
  6167. d.block = p->curr_block;
  6168. d.stmt = stmt;
  6169. array_add(&p->defer_stmts, d);
  6170. return d;
  6171. }
  6172. lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  6173. lbDefer d = {lbDefer_Proc};
  6174. d.scope_index = p->scope_index;
  6175. d.block = p->curr_block;
  6176. d.proc.deferred = deferred;
  6177. d.proc.result_as_args = result_as_args;
  6178. array_add(&p->defer_stmts, d);
  6179. return d;
  6180. }
  6181. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  6182. Array<lbValue> array = {};
  6183. Type *t = base_type(value.type);
  6184. if (t == nullptr) {
  6185. // Do nothing
  6186. } else if (is_type_tuple(t)) {
  6187. GB_ASSERT(t->kind == Type_Tuple);
  6188. auto *rt = &t->Tuple;
  6189. if (rt->variables.count > 0) {
  6190. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  6191. for_array(i, rt->variables) {
  6192. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  6193. array[i] = elem;
  6194. }
  6195. }
  6196. } else {
  6197. array = array_make<lbValue>(permanent_allocator(), 1);
  6198. array[0] = value;
  6199. }
  6200. return array;
  6201. }
  6202. 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) {
  6203. unsigned arg_count = cast(unsigned)processed_args.count;
  6204. if (return_ptr.value != nullptr) {
  6205. arg_count += 1;
  6206. }
  6207. if (context_ptr.addr.value != nullptr) {
  6208. arg_count += 1;
  6209. }
  6210. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  6211. isize arg_index = 0;
  6212. if (return_ptr.value != nullptr) {
  6213. args[arg_index++] = return_ptr.value;
  6214. }
  6215. for_array(i, processed_args) {
  6216. lbValue arg = processed_args[i];
  6217. args[arg_index++] = arg.value;
  6218. }
  6219. if (context_ptr.addr.value != nullptr) {
  6220. args[arg_index++] = context_ptr.addr.value;
  6221. }
  6222. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  6223. GB_ASSERT(curr_block != p->decl_block->block);
  6224. if (USE_LLVM_ABI) {
  6225. LLVMTypeRef ftp = lb_type(p->module, value.type);
  6226. LLVMTypeRef ft = LLVMGetElementType(ftp);
  6227. LLVMValueRef fn = value.value;
  6228. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  6229. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  6230. }
  6231. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  6232. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  6233. LLVMValueRef ret = LLVMBuildCall2(p->builder, ft, fn, args, arg_count, "");;
  6234. lbValue res = {};
  6235. res.value = ret;
  6236. res.type = abi_rt;
  6237. return res;
  6238. } else {
  6239. LLVMValueRef ret = LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(p->module, value.type)), value.value, args, arg_count, "");;
  6240. lbValue res = {};
  6241. res.value = ret;
  6242. res.type = abi_rt;
  6243. return res;
  6244. }
  6245. }
  6246. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  6247. String name = make_string_c(c_name);
  6248. AstPackage *pkg = p->module->info->runtime_package;
  6249. Entity *e = scope_lookup_current(pkg->scope, name);
  6250. lbValue *found = nullptr;
  6251. if (p->module != e->code_gen_module) {
  6252. gb_mutex_lock(&p->module->mutex);
  6253. }
  6254. found = map_get(&e->code_gen_module->values, hash_entity(e));
  6255. if (p->module != e->code_gen_module) {
  6256. gb_mutex_unlock(&p->module->mutex);
  6257. }
  6258. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  6259. return lb_emit_call(p, *found, args);
  6260. }
  6261. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  6262. lbModule *m = p->module;
  6263. Type *pt = base_type(value.type);
  6264. GB_ASSERT(pt->kind == Type_Proc);
  6265. Type *results = pt->Proc.results;
  6266. if (p->entity != nullptr) {
  6267. if (p->entity->flags & EntityFlag_Disabled) {
  6268. return {};
  6269. }
  6270. }
  6271. lbAddr context_ptr = {};
  6272. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6273. context_ptr = lb_find_or_generate_context_ptr(p);
  6274. }
  6275. defer (if (pt->Proc.diverging) {
  6276. LLVMBuildUnreachable(p->builder);
  6277. });
  6278. set_procedure_abi_types(pt);
  6279. bool is_c_vararg = pt->Proc.c_vararg;
  6280. isize param_count = pt->Proc.param_count;
  6281. if (is_c_vararg) {
  6282. GB_ASSERT(param_count-1 <= args.count);
  6283. param_count -= 1;
  6284. } else {
  6285. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  6286. }
  6287. lbValue result = {};
  6288. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  6289. if (USE_LLVM_ABI) {
  6290. lbFunctionType **ft_found = nullptr;
  6291. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6292. if (!ft_found) {
  6293. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  6294. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6295. }
  6296. GB_ASSERT(ft_found != nullptr);
  6297. lbFunctionType *ft = *ft_found;
  6298. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  6299. unsigned param_index = 0;
  6300. for (isize i = 0; i < param_count; i++) {
  6301. Entity *e = pt->Proc.params->Tuple.variables[i];
  6302. if (e->kind != Entity_Variable) {
  6303. continue;
  6304. }
  6305. GB_ASSERT(e->flags & EntityFlag_Param);
  6306. Type *original_type = e->type;
  6307. lbArgType *arg = &ft->args[param_index];
  6308. if (arg->kind == lbArg_Ignore) {
  6309. continue;
  6310. }
  6311. lbValue x = lb_emit_conv(p, args[i], original_type);
  6312. LLVMTypeRef xt = lb_type(p->module, x.type);
  6313. if (arg->kind == lbArg_Direct) {
  6314. LLVMTypeRef abi_type = arg->cast_type;
  6315. if (!abi_type) {
  6316. abi_type = arg->type;
  6317. }
  6318. if (xt == abi_type) {
  6319. array_add(&processed_args, x);
  6320. } else {
  6321. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  6322. array_add(&processed_args, x);
  6323. }
  6324. } else if (arg->kind == lbArg_Indirect) {
  6325. lbValue ptr = {};
  6326. if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  6327. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  6328. // i.e. `T const &` in C++
  6329. ptr = lb_address_from_load_or_generate_local(p, x);
  6330. } else {
  6331. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  6332. }
  6333. array_add(&processed_args, ptr);
  6334. }
  6335. param_index += 1;
  6336. }
  6337. if (inlining == ProcInlining_none) {
  6338. inlining = p->inlining;
  6339. }
  6340. Type *rt = reduce_tuple_to_single_type(results);
  6341. if (return_by_pointer) {
  6342. lbValue return_ptr = {};
  6343. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6344. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6345. return_ptr = p->return_ptr_hint_value;
  6346. p->return_ptr_hint_used = true;
  6347. }
  6348. }
  6349. if (return_ptr.value == nullptr) {
  6350. lbAddr r = lb_add_local_generated(p, rt, true);
  6351. return_ptr = r.addr;
  6352. }
  6353. GB_ASSERT(is_type_pointer(return_ptr.type));
  6354. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6355. result = lb_emit_load(p, return_ptr);
  6356. } else if (rt != nullptr) {
  6357. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  6358. if (ft->ret.cast_type) {
  6359. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  6360. }
  6361. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  6362. result.type = rt;
  6363. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  6364. result.type = t_llvm_bool;
  6365. }
  6366. if (!is_type_tuple(rt)) {
  6367. result = lb_emit_conv(p, result, rt);
  6368. }
  6369. } else {
  6370. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  6371. }
  6372. } else {
  6373. for (isize i = 0; i < param_count; i++) {
  6374. Entity *e = pt->Proc.params->Tuple.variables[i];
  6375. if (e->kind != Entity_Variable) {
  6376. // array_add(&processed_args, args[i]);
  6377. continue;
  6378. }
  6379. GB_ASSERT(e->flags & EntityFlag_Param);
  6380. Type *original_type = e->type;
  6381. Type *new_type = pt->Proc.abi_compat_params[i];
  6382. Type *arg_type = args[i].type;
  6383. if (are_types_identical(arg_type, new_type)) {
  6384. // NOTE(bill): Done
  6385. array_add(&processed_args, args[i]);
  6386. } else if (!are_types_identical(original_type, new_type)) {
  6387. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  6388. Type *av = core_type(type_deref(new_type));
  6389. if (are_types_identical(av, core_type(original_type))) {
  6390. if (e->flags&EntityFlag_ImplicitReference) {
  6391. array_add(&processed_args, lb_address_from_load_or_generate_local(p, args[i]));
  6392. } else if (!is_type_pointer(arg_type)) {
  6393. array_add(&processed_args, lb_copy_value_to_ptr(p, args[i], original_type, 16));
  6394. }
  6395. } else {
  6396. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  6397. }
  6398. } else if (new_type == t_llvm_bool) {
  6399. array_add(&processed_args, lb_emit_conv(p, args[i], new_type));
  6400. } else if (is_type_integer(new_type) || is_type_float(new_type) || is_type_boolean(new_type)) {
  6401. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  6402. } else if (is_type_simd_vector(new_type)) {
  6403. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  6404. } else if (is_type_tuple(new_type)) {
  6405. Type *abi_type = pt->Proc.abi_compat_params[i];
  6406. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  6407. lbValue x = {};
  6408. i64 st_sz = type_size_of(st);
  6409. i64 arg_sz = type_size_of(args[i].type);
  6410. if (st_sz == arg_sz) {
  6411. x = lb_emit_transmute(p, args[i], st);
  6412. } else {
  6413. // NOTE(bill): struct{f32, f32, f32} != struct{#simd[2]f32, f32}
  6414. GB_ASSERT(st_sz > arg_sz);
  6415. lbAddr xx = lb_add_local_generated(p, st, false);
  6416. lbValue pp = lb_emit_conv(p, xx.addr, alloc_type_pointer(args[i].type));
  6417. lb_emit_store(p, pp, args[i]);
  6418. x = lb_addr_load(p, xx);
  6419. }
  6420. for (isize j = 0; j < new_type->Tuple.variables.count; j++) {
  6421. lbValue xx = lb_emit_struct_ev(p, x, cast(i32)j);
  6422. array_add(&processed_args, xx);
  6423. }
  6424. }
  6425. } else {
  6426. lbValue x = lb_emit_conv(p, args[i], new_type);
  6427. array_add(&processed_args, x);
  6428. }
  6429. }
  6430. if (inlining == ProcInlining_none) {
  6431. inlining = p->inlining;
  6432. }
  6433. Type *abi_rt = reduce_tuple_to_single_type(pt->Proc.abi_compat_result_type);
  6434. Type *rt = reduce_tuple_to_single_type(results);
  6435. if (pt->Proc.return_by_pointer) {
  6436. lbValue return_ptr = {};
  6437. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6438. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6439. return_ptr = p->return_ptr_hint_value;
  6440. p->return_ptr_hint_used = true;
  6441. }
  6442. }
  6443. if (return_ptr.value == nullptr) {
  6444. lbAddr r = lb_add_local_generated(p, rt, true);
  6445. return_ptr = r.addr;
  6446. }
  6447. GB_ASSERT(is_type_pointer(return_ptr.type));
  6448. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6449. result = lb_emit_load(p, return_ptr);
  6450. } else {
  6451. result = lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining);
  6452. if (abi_rt != rt) {
  6453. result = lb_emit_transmute(p, result, rt);
  6454. }
  6455. }
  6456. }
  6457. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  6458. if (found != nullptr) {
  6459. Entity *e = *found;
  6460. if (e != nullptr && entity_has_deferred_procedure(e)) {
  6461. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  6462. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  6463. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  6464. GB_ASSERT(deferred_found != nullptr);
  6465. lbValue deferred = *deferred_found;
  6466. auto in_args = args;
  6467. Array<lbValue> result_as_args = {};
  6468. switch (kind) {
  6469. case DeferredProcedure_none:
  6470. break;
  6471. case DeferredProcedure_in:
  6472. result_as_args = in_args;
  6473. break;
  6474. case DeferredProcedure_out:
  6475. result_as_args = lb_value_to_array(p, result);
  6476. break;
  6477. case DeferredProcedure_in_out:
  6478. {
  6479. auto out_args = lb_value_to_array(p, result);
  6480. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  6481. array_copy(&result_as_args, in_args, 0);
  6482. array_copy(&result_as_args, out_args, in_args.count);
  6483. }
  6484. break;
  6485. }
  6486. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  6487. }
  6488. }
  6489. return result;
  6490. }
  6491. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  6492. Type *t = s.type;
  6493. GB_ASSERT(is_type_pointer(t));
  6494. Type *st = base_type(type_deref(t));
  6495. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6496. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  6497. LLVMValueRef indices[2] = {};
  6498. indices[0] = llvm_zero(p->module);
  6499. indices[1] = lb_emit_conv(p, index, t_int).value;
  6500. Type *ptr = base_array_type(st);
  6501. lbValue res = {};
  6502. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  6503. res.type = alloc_type_pointer(ptr);
  6504. return res;
  6505. }
  6506. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  6507. Type *t = s.type;
  6508. GB_ASSERT(is_type_pointer(t));
  6509. Type *st = base_type(type_deref(t));
  6510. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6511. GB_ASSERT(0 <= index);
  6512. Type *ptr = base_array_type(st);
  6513. LLVMValueRef indices[2] = {
  6514. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  6515. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  6516. };
  6517. lbValue res = {};
  6518. if (lb_is_const(s)) {
  6519. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6520. } else {
  6521. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  6522. }
  6523. res.type = alloc_type_pointer(ptr);
  6524. return res;
  6525. }
  6526. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  6527. LLVMValueRef indices[1] = {index.value};
  6528. lbValue res = {};
  6529. res.type = ptr.type;
  6530. if (lb_is_const(ptr) && lb_is_const(index)) {
  6531. res.value = LLVMConstGEP(ptr.value, indices, 1);
  6532. } else {
  6533. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  6534. }
  6535. return res;
  6536. }
  6537. LLVMValueRef llvm_const_slice(lbValue data, lbValue len) {
  6538. GB_ASSERT(is_type_pointer(data.type));
  6539. GB_ASSERT(are_types_identical(len.type, t_int));
  6540. LLVMValueRef vals[2] = {
  6541. data.value,
  6542. len.value,
  6543. };
  6544. return LLVMConstStruct(vals, gb_count_of(vals), false);
  6545. }
  6546. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  6547. Type *t = lb_addr_type(slice);
  6548. GB_ASSERT(is_type_slice(t));
  6549. lbValue ptr = lb_addr_get_ptr(p, slice);
  6550. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6551. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6552. }
  6553. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  6554. Type *t = lb_addr_type(string);
  6555. GB_ASSERT(is_type_string(t));
  6556. lbValue ptr = lb_addr_get_ptr(p, string);
  6557. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6558. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6559. }
  6560. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  6561. Type *t = base_type(string.type);
  6562. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  6563. return lb_emit_struct_ev(p, string, 0);
  6564. }
  6565. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  6566. Type *t = base_type(string.type);
  6567. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  6568. return lb_emit_struct_ev(p, string, 1);
  6569. }
  6570. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  6571. GB_ASSERT(is_type_cstring(value.type));
  6572. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6573. args[0] = lb_emit_conv(p, value, t_cstring);
  6574. return lb_emit_runtime_call(p, "cstring_len", args);
  6575. }
  6576. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  6577. Type *t = type_deref(array_ptr.type);
  6578. GB_ASSERT(is_type_array(t));
  6579. return lb_emit_struct_ep(p, array_ptr, 0);
  6580. }
  6581. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  6582. GB_ASSERT(is_type_slice(slice.type));
  6583. return lb_emit_struct_ev(p, slice, 0);
  6584. }
  6585. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  6586. GB_ASSERT(is_type_slice(slice.type));
  6587. return lb_emit_struct_ev(p, slice, 1);
  6588. }
  6589. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  6590. GB_ASSERT(is_type_dynamic_array(da.type));
  6591. return lb_emit_struct_ev(p, da, 0);
  6592. }
  6593. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  6594. GB_ASSERT(is_type_dynamic_array(da.type));
  6595. return lb_emit_struct_ev(p, da, 1);
  6596. }
  6597. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  6598. GB_ASSERT(is_type_dynamic_array(da.type));
  6599. return lb_emit_struct_ev(p, da, 2);
  6600. }
  6601. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  6602. GB_ASSERT(is_type_dynamic_array(da.type));
  6603. return lb_emit_struct_ev(p, da, 3);
  6604. }
  6605. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  6606. Type *t = base_type(value.type);
  6607. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6608. init_map_internal_types(t);
  6609. Type *gst = t->Map.generated_struct_type;
  6610. i32 index = 1;
  6611. lbValue entries = lb_emit_struct_ev(p, value, index);
  6612. return entries;
  6613. }
  6614. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  6615. Type *t = base_type(type_deref(value.type));
  6616. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6617. init_map_internal_types(t);
  6618. Type *gst = t->Map.generated_struct_type;
  6619. i32 index = 1;
  6620. lbValue entries = lb_emit_struct_ep(p, value, index);
  6621. return entries;
  6622. }
  6623. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  6624. lbValue entries = lb_map_entries(p, value);
  6625. return lb_dynamic_array_len(p, entries);
  6626. }
  6627. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  6628. lbValue entries = lb_map_entries(p, value);
  6629. return lb_dynamic_array_cap(p, entries);
  6630. }
  6631. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  6632. Type *t = base_type(value.type);
  6633. bool is_ptr = false;
  6634. if (is_type_pointer(t)) {
  6635. is_ptr = true;
  6636. t = base_type(type_deref(t));
  6637. }
  6638. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6639. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6640. }
  6641. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  6642. t->Struct.soa_kind == StructSoa_Dynamic);
  6643. isize n = 0;
  6644. Type *elem = base_type(t->Struct.soa_elem);
  6645. if (elem->kind == Type_Struct) {
  6646. n = elem->Struct.fields.count;
  6647. } else if (elem->kind == Type_Array) {
  6648. n = elem->Array.count;
  6649. } else {
  6650. GB_PANIC("Unreachable");
  6651. }
  6652. if (is_ptr) {
  6653. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6654. return lb_emit_load(p, v);
  6655. }
  6656. return lb_emit_struct_ev(p, value, cast(i32)n);
  6657. }
  6658. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  6659. Type *t = base_type(value.type);
  6660. bool is_ptr = false;
  6661. if (is_type_pointer(t)) {
  6662. is_ptr = true;
  6663. t = base_type(type_deref(t));
  6664. }
  6665. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6666. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6667. }
  6668. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  6669. isize n = 0;
  6670. Type *elem = base_type(t->Struct.soa_elem);
  6671. if (elem->kind == Type_Struct) {
  6672. n = elem->Struct.fields.count+1;
  6673. } else if (elem->kind == Type_Array) {
  6674. n = elem->Array.count+1;
  6675. } else {
  6676. GB_PANIC("Unreachable");
  6677. }
  6678. if (is_ptr) {
  6679. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6680. return lb_emit_load(p, v);
  6681. }
  6682. return lb_emit_struct_ev(p, value, cast(i32)n);
  6683. }
  6684. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  6685. ast_node(ce, CallExpr, expr);
  6686. switch (id) {
  6687. case BuiltinProc_DIRECTIVE: {
  6688. ast_node(bd, BasicDirective, ce->proc);
  6689. String name = bd->name;
  6690. GB_ASSERT(name == "location");
  6691. String procedure = p->entity->token.string;
  6692. TokenPos pos = ast_token(ce->proc).pos;
  6693. if (ce->args.count > 0) {
  6694. Ast *ident = unselector_expr(ce->args[0]);
  6695. GB_ASSERT(ident->kind == Ast_Ident);
  6696. Entity *e = entity_of_node(ident);
  6697. GB_ASSERT(e != nullptr);
  6698. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  6699. procedure = e->parent_proc_decl->entity->token.string;
  6700. } else {
  6701. procedure = str_lit("");
  6702. }
  6703. pos = e->token.pos;
  6704. }
  6705. return lb_emit_source_code_location(p, procedure, pos);
  6706. }
  6707. case BuiltinProc_type_info_of: {
  6708. Ast *arg = ce->args[0];
  6709. TypeAndValue tav = type_and_value_of_expr(arg);
  6710. if (tav.mode == Addressing_Type) {
  6711. Type *t = default_type(type_of_expr(arg));
  6712. return lb_type_info(p->module, t);
  6713. }
  6714. GB_ASSERT(is_type_typeid(tav.type));
  6715. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6716. args[0] = lb_build_expr(p, arg);
  6717. return lb_emit_runtime_call(p, "__type_info_of", args);
  6718. }
  6719. case BuiltinProc_typeid_of: {
  6720. Ast *arg = ce->args[0];
  6721. TypeAndValue tav = type_and_value_of_expr(arg);
  6722. GB_ASSERT(tav.mode == Addressing_Type);
  6723. Type *t = default_type(type_of_expr(arg));
  6724. return lb_typeid(p->module, t);
  6725. }
  6726. case BuiltinProc_len: {
  6727. lbValue v = lb_build_expr(p, ce->args[0]);
  6728. Type *t = base_type(v.type);
  6729. if (is_type_pointer(t)) {
  6730. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6731. v = lb_emit_load(p, v);
  6732. t = type_deref(t);
  6733. }
  6734. if (is_type_cstring(t)) {
  6735. return lb_cstring_len(p, v);
  6736. } else if (is_type_string(t)) {
  6737. return lb_string_len(p, v);
  6738. } else if (is_type_array(t)) {
  6739. GB_PANIC("Array lengths are constant");
  6740. } else if (is_type_slice(t)) {
  6741. return lb_slice_len(p, v);
  6742. } else if (is_type_dynamic_array(t)) {
  6743. return lb_dynamic_array_len(p, v);
  6744. } else if (is_type_map(t)) {
  6745. return lb_map_len(p, v);
  6746. } else if (is_type_soa_struct(t)) {
  6747. return lb_soa_struct_len(p, v);
  6748. }
  6749. GB_PANIC("Unreachable");
  6750. break;
  6751. }
  6752. case BuiltinProc_cap: {
  6753. lbValue v = lb_build_expr(p, ce->args[0]);
  6754. Type *t = base_type(v.type);
  6755. if (is_type_pointer(t)) {
  6756. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6757. v = lb_emit_load(p, v);
  6758. t = type_deref(t);
  6759. }
  6760. if (is_type_string(t)) {
  6761. GB_PANIC("Unreachable");
  6762. } else if (is_type_array(t)) {
  6763. GB_PANIC("Array lengths are constant");
  6764. } else if (is_type_slice(t)) {
  6765. return lb_slice_len(p, v);
  6766. } else if (is_type_dynamic_array(t)) {
  6767. return lb_dynamic_array_cap(p, v);
  6768. } else if (is_type_map(t)) {
  6769. return lb_map_cap(p, v);
  6770. } else if (is_type_soa_struct(t)) {
  6771. return lb_soa_struct_cap(p, v);
  6772. }
  6773. GB_PANIC("Unreachable");
  6774. break;
  6775. }
  6776. case BuiltinProc_swizzle: {
  6777. isize index_count = ce->args.count-1;
  6778. if (is_type_simd_vector(tv.type)) {
  6779. lbValue vec = lb_build_expr(p, ce->args[0]);
  6780. if (index_count == 0) {
  6781. return vec;
  6782. }
  6783. unsigned mask_len = cast(unsigned)index_count;
  6784. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  6785. for (isize i = 1; i < ce->args.count; i++) {
  6786. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6787. GB_ASSERT(is_type_integer(tv.type));
  6788. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6789. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  6790. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  6791. }
  6792. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  6793. LLVMValueRef v1 = vec.value;
  6794. LLVMValueRef v2 = vec.value;
  6795. lbValue res = {};
  6796. res.type = tv.type;
  6797. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  6798. return res;
  6799. }
  6800. lbAddr addr = lb_build_addr(p, ce->args[0]);
  6801. if (index_count == 0) {
  6802. return lb_addr_load(p, addr);
  6803. }
  6804. lbValue src = lb_addr_get_ptr(p, addr);
  6805. // TODO(bill): Should this be zeroed or not?
  6806. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  6807. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  6808. for (i32 i = 1; i < ce->args.count; i++) {
  6809. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6810. GB_ASSERT(is_type_integer(tv.type));
  6811. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6812. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  6813. i32 dst_index = i-1;
  6814. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  6815. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  6816. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  6817. }
  6818. return lb_addr_load(p, dst);
  6819. }
  6820. case BuiltinProc_complex: {
  6821. lbValue real = lb_build_expr(p, ce->args[0]);
  6822. lbValue imag = lb_build_expr(p, ce->args[1]);
  6823. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6824. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6825. Type *ft = base_complex_elem_type(tv.type);
  6826. real = lb_emit_conv(p, real, ft);
  6827. imag = lb_emit_conv(p, imag, ft);
  6828. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  6829. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  6830. return lb_emit_load(p, dst);
  6831. }
  6832. case BuiltinProc_quaternion: {
  6833. lbValue real = lb_build_expr(p, ce->args[0]);
  6834. lbValue imag = lb_build_expr(p, ce->args[1]);
  6835. lbValue jmag = lb_build_expr(p, ce->args[2]);
  6836. lbValue kmag = lb_build_expr(p, ce->args[3]);
  6837. // @QuaternionLayout
  6838. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6839. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6840. Type *ft = base_complex_elem_type(tv.type);
  6841. real = lb_emit_conv(p, real, ft);
  6842. imag = lb_emit_conv(p, imag, ft);
  6843. jmag = lb_emit_conv(p, jmag, ft);
  6844. kmag = lb_emit_conv(p, kmag, ft);
  6845. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  6846. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  6847. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  6848. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  6849. return lb_emit_load(p, dst);
  6850. }
  6851. case BuiltinProc_real: {
  6852. lbValue val = lb_build_expr(p, ce->args[0]);
  6853. if (is_type_complex(val.type)) {
  6854. lbValue real = lb_emit_struct_ev(p, val, 0);
  6855. return lb_emit_conv(p, real, tv.type);
  6856. } else if (is_type_quaternion(val.type)) {
  6857. // @QuaternionLayout
  6858. lbValue real = lb_emit_struct_ev(p, val, 3);
  6859. return lb_emit_conv(p, real, tv.type);
  6860. }
  6861. GB_PANIC("invalid type for real");
  6862. return {};
  6863. }
  6864. case BuiltinProc_imag: {
  6865. lbValue val = lb_build_expr(p, ce->args[0]);
  6866. if (is_type_complex(val.type)) {
  6867. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6868. return lb_emit_conv(p, imag, tv.type);
  6869. } else if (is_type_quaternion(val.type)) {
  6870. // @QuaternionLayout
  6871. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6872. return lb_emit_conv(p, imag, tv.type);
  6873. }
  6874. GB_PANIC("invalid type for imag");
  6875. return {};
  6876. }
  6877. case BuiltinProc_jmag: {
  6878. lbValue val = lb_build_expr(p, ce->args[0]);
  6879. if (is_type_quaternion(val.type)) {
  6880. // @QuaternionLayout
  6881. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6882. return lb_emit_conv(p, imag, tv.type);
  6883. }
  6884. GB_PANIC("invalid type for jmag");
  6885. return {};
  6886. }
  6887. case BuiltinProc_kmag: {
  6888. lbValue val = lb_build_expr(p, ce->args[0]);
  6889. if (is_type_quaternion(val.type)) {
  6890. // @QuaternionLayout
  6891. lbValue imag = lb_emit_struct_ev(p, val, 2);
  6892. return lb_emit_conv(p, imag, tv.type);
  6893. }
  6894. GB_PANIC("invalid type for kmag");
  6895. return {};
  6896. }
  6897. case BuiltinProc_conj: {
  6898. lbValue val = lb_build_expr(p, ce->args[0]);
  6899. lbValue res = {};
  6900. Type *t = val.type;
  6901. if (is_type_complex(t)) {
  6902. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6903. lbValue real = lb_emit_struct_ev(p, val, 0);
  6904. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6905. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6906. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  6907. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  6908. } else if (is_type_quaternion(t)) {
  6909. // @QuaternionLayout
  6910. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6911. lbValue real = lb_emit_struct_ev(p, val, 3);
  6912. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6913. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  6914. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  6915. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6916. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  6917. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  6918. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  6919. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  6920. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  6921. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  6922. }
  6923. return lb_emit_load(p, res);
  6924. }
  6925. case BuiltinProc_expand_to_tuple: {
  6926. lbValue val = lb_build_expr(p, ce->args[0]);
  6927. Type *t = base_type(val.type);
  6928. if (!is_type_tuple(tv.type)) {
  6929. if (t->kind == Type_Struct) {
  6930. GB_ASSERT(t->Struct.fields.count == 1);
  6931. return lb_emit_struct_ev(p, val, 0);
  6932. } else if (t->kind == Type_Array) {
  6933. GB_ASSERT(t->Array.count == 1);
  6934. return lb_emit_array_epi(p, val, 0);
  6935. } else {
  6936. GB_PANIC("Unknown type of expand_to_tuple");
  6937. }
  6938. }
  6939. GB_ASSERT(is_type_tuple(tv.type));
  6940. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6941. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6942. if (t->kind == Type_Struct) {
  6943. for_array(src_index, t->Struct.fields) {
  6944. Entity *field = t->Struct.fields[src_index];
  6945. i32 field_index = field->Variable.field_index;
  6946. lbValue f = lb_emit_struct_ev(p, val, field_index);
  6947. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  6948. lb_emit_store(p, ep, f);
  6949. }
  6950. } else if (t->kind == Type_Array) {
  6951. // TODO(bill): Clean-up this code
  6952. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  6953. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  6954. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  6955. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  6956. lb_emit_store(p, ep, f);
  6957. }
  6958. } else {
  6959. GB_PANIC("Unknown type of expand_to_tuple");
  6960. }
  6961. return lb_emit_load(p, tuple);
  6962. }
  6963. case BuiltinProc_min: {
  6964. Type *t = type_of_expr(expr);
  6965. if (ce->args.count == 2) {
  6966. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6967. } else {
  6968. lbValue x = lb_build_expr(p, ce->args[0]);
  6969. for (isize i = 1; i < ce->args.count; i++) {
  6970. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  6971. }
  6972. return x;
  6973. }
  6974. }
  6975. case BuiltinProc_max: {
  6976. Type *t = type_of_expr(expr);
  6977. if (ce->args.count == 2) {
  6978. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6979. } else {
  6980. lbValue x = lb_build_expr(p, ce->args[0]);
  6981. for (isize i = 1; i < ce->args.count; i++) {
  6982. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  6983. }
  6984. return x;
  6985. }
  6986. }
  6987. case BuiltinProc_abs: {
  6988. lbValue x = lb_build_expr(p, ce->args[0]);
  6989. Type *t = x.type;
  6990. if (is_type_unsigned(t)) {
  6991. return x;
  6992. }
  6993. if (is_type_quaternion(t)) {
  6994. i64 sz = 8*type_size_of(t);
  6995. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6996. args[0] = x;
  6997. switch (sz) {
  6998. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  6999. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  7000. }
  7001. GB_PANIC("Unknown complex type");
  7002. } else if (is_type_complex(t)) {
  7003. i64 sz = 8*type_size_of(t);
  7004. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7005. args[0] = x;
  7006. switch (sz) {
  7007. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  7008. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  7009. }
  7010. GB_PANIC("Unknown complex type");
  7011. } else if (is_type_float(t)) {
  7012. i64 sz = 8*type_size_of(t);
  7013. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7014. args[0] = x;
  7015. switch (sz) {
  7016. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  7017. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  7018. }
  7019. GB_PANIC("Unknown float type");
  7020. }
  7021. lbValue zero = lb_const_nil(p->module, t);
  7022. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  7023. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  7024. return lb_emit_select(p, cond, neg, x);
  7025. }
  7026. case BuiltinProc_clamp:
  7027. return lb_emit_clamp(p, type_of_expr(expr),
  7028. lb_build_expr(p, ce->args[0]),
  7029. lb_build_expr(p, ce->args[1]),
  7030. lb_build_expr(p, ce->args[2]));
  7031. // "Intrinsics"
  7032. case BuiltinProc_alloca:
  7033. {
  7034. lbValue sz = lb_build_expr(p, ce->args[0]);
  7035. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  7036. lbValue res = {};
  7037. res.type = t_u8_ptr;
  7038. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  7039. LLVMSetAlignment(res.value, cast(unsigned)al);
  7040. return res;
  7041. }
  7042. case BuiltinProc_cpu_relax:
  7043. {
  7044. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7045. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7046. cast(char *)"pause", 5,
  7047. cast(char *)"", 0,
  7048. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7049. LLVMInlineAsmDialectATT
  7050. );
  7051. GB_ASSERT(the_asm != nullptr);
  7052. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7053. }
  7054. return {};
  7055. case BuiltinProc_atomic_fence:
  7056. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  7057. return {};
  7058. case BuiltinProc_atomic_fence_acq:
  7059. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  7060. return {};
  7061. case BuiltinProc_atomic_fence_rel:
  7062. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  7063. return {};
  7064. case BuiltinProc_atomic_fence_acqrel:
  7065. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  7066. return {};
  7067. case BuiltinProc_atomic_store:
  7068. case BuiltinProc_atomic_store_rel:
  7069. case BuiltinProc_atomic_store_relaxed:
  7070. case BuiltinProc_atomic_store_unordered: {
  7071. lbValue dst = lb_build_expr(p, ce->args[0]);
  7072. lbValue val = lb_build_expr(p, ce->args[1]);
  7073. val = lb_emit_conv(p, val, type_deref(dst.type));
  7074. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  7075. switch (id) {
  7076. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7077. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  7078. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7079. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7080. }
  7081. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7082. return {};
  7083. }
  7084. case BuiltinProc_atomic_load:
  7085. case BuiltinProc_atomic_load_acq:
  7086. case BuiltinProc_atomic_load_relaxed:
  7087. case BuiltinProc_atomic_load_unordered: {
  7088. lbValue dst = lb_build_expr(p, ce->args[0]);
  7089. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  7090. switch (id) {
  7091. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7092. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  7093. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7094. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7095. }
  7096. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7097. lbValue res = {};
  7098. res.value = instr;
  7099. res.type = type_deref(dst.type);
  7100. return res;
  7101. }
  7102. case BuiltinProc_atomic_add:
  7103. case BuiltinProc_atomic_add_acq:
  7104. case BuiltinProc_atomic_add_rel:
  7105. case BuiltinProc_atomic_add_acqrel:
  7106. case BuiltinProc_atomic_add_relaxed:
  7107. case BuiltinProc_atomic_sub:
  7108. case BuiltinProc_atomic_sub_acq:
  7109. case BuiltinProc_atomic_sub_rel:
  7110. case BuiltinProc_atomic_sub_acqrel:
  7111. case BuiltinProc_atomic_sub_relaxed:
  7112. case BuiltinProc_atomic_and:
  7113. case BuiltinProc_atomic_and_acq:
  7114. case BuiltinProc_atomic_and_rel:
  7115. case BuiltinProc_atomic_and_acqrel:
  7116. case BuiltinProc_atomic_and_relaxed:
  7117. case BuiltinProc_atomic_nand:
  7118. case BuiltinProc_atomic_nand_acq:
  7119. case BuiltinProc_atomic_nand_rel:
  7120. case BuiltinProc_atomic_nand_acqrel:
  7121. case BuiltinProc_atomic_nand_relaxed:
  7122. case BuiltinProc_atomic_or:
  7123. case BuiltinProc_atomic_or_acq:
  7124. case BuiltinProc_atomic_or_rel:
  7125. case BuiltinProc_atomic_or_acqrel:
  7126. case BuiltinProc_atomic_or_relaxed:
  7127. case BuiltinProc_atomic_xor:
  7128. case BuiltinProc_atomic_xor_acq:
  7129. case BuiltinProc_atomic_xor_rel:
  7130. case BuiltinProc_atomic_xor_acqrel:
  7131. case BuiltinProc_atomic_xor_relaxed:
  7132. case BuiltinProc_atomic_xchg:
  7133. case BuiltinProc_atomic_xchg_acq:
  7134. case BuiltinProc_atomic_xchg_rel:
  7135. case BuiltinProc_atomic_xchg_acqrel:
  7136. case BuiltinProc_atomic_xchg_relaxed: {
  7137. lbValue dst = lb_build_expr(p, ce->args[0]);
  7138. lbValue val = lb_build_expr(p, ce->args[1]);
  7139. val = lb_emit_conv(p, val, type_deref(dst.type));
  7140. LLVMAtomicRMWBinOp op = {};
  7141. LLVMAtomicOrdering ordering = {};
  7142. switch (id) {
  7143. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7144. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  7145. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  7146. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7147. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  7148. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7149. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  7150. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  7151. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7152. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  7153. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7154. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  7155. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  7156. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7157. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  7158. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7159. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  7160. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  7161. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7162. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  7163. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7164. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  7165. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  7166. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7167. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  7168. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7169. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  7170. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  7171. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7172. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  7173. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7174. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  7175. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  7176. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7177. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  7178. }
  7179. lbValue res = {};
  7180. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  7181. res.type = tv.type;
  7182. return res;
  7183. }
  7184. case BuiltinProc_atomic_cxchg:
  7185. case BuiltinProc_atomic_cxchg_acq:
  7186. case BuiltinProc_atomic_cxchg_rel:
  7187. case BuiltinProc_atomic_cxchg_acqrel:
  7188. case BuiltinProc_atomic_cxchg_relaxed:
  7189. case BuiltinProc_atomic_cxchg_failrelaxed:
  7190. case BuiltinProc_atomic_cxchg_failacq:
  7191. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  7192. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  7193. case BuiltinProc_atomic_cxchgweak:
  7194. case BuiltinProc_atomic_cxchgweak_acq:
  7195. case BuiltinProc_atomic_cxchgweak_rel:
  7196. case BuiltinProc_atomic_cxchgweak_acqrel:
  7197. case BuiltinProc_atomic_cxchgweak_relaxed:
  7198. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  7199. case BuiltinProc_atomic_cxchgweak_failacq:
  7200. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  7201. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  7202. Type *type = expr->tav.type;
  7203. lbValue address = lb_build_expr(p, ce->args[0]);
  7204. Type *elem = type_deref(address.type);
  7205. lbValue old_value = lb_build_expr(p, ce->args[1]);
  7206. lbValue new_value = lb_build_expr(p, ce->args[2]);
  7207. old_value = lb_emit_conv(p, old_value, elem);
  7208. new_value = lb_emit_conv(p, new_value, elem);
  7209. LLVMAtomicOrdering success_ordering = {};
  7210. LLVMAtomicOrdering failure_ordering = {};
  7211. LLVMBool weak = false;
  7212. switch (id) {
  7213. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7214. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7215. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7216. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7217. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7218. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7219. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  7220. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7221. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7222. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7223. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7224. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7225. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7226. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7227. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7228. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  7229. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7230. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7231. }
  7232. // TODO(bill): Figure out how to make it weak
  7233. LLVMBool single_threaded = weak;
  7234. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  7235. p->builder, address.value,
  7236. old_value.value, new_value.value,
  7237. success_ordering,
  7238. failure_ordering,
  7239. single_threaded
  7240. );
  7241. GB_ASSERT(tv.type->kind == Type_Tuple);
  7242. Type *fix_typed = alloc_type_tuple();
  7243. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  7244. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  7245. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  7246. lbValue res = {};
  7247. res.value = value;
  7248. res.type = fix_typed;
  7249. return res;
  7250. }
  7251. case BuiltinProc_type_equal_proc:
  7252. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  7253. case BuiltinProc_type_hasher_proc:
  7254. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  7255. }
  7256. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  7257. return {};
  7258. }
  7259. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  7260. switch (param_value.kind) {
  7261. case ParameterValue_Constant:
  7262. if (is_type_constant_type(parameter_type)) {
  7263. return lb_const_value(p->module, parameter_type, param_value.value);
  7264. } else {
  7265. ExactValue ev = param_value.value;
  7266. lbValue arg = {};
  7267. Type *type = type_of_expr(param_value.original_ast_expr);
  7268. if (type != nullptr) {
  7269. arg = lb_const_value(p->module, type, ev);
  7270. } else {
  7271. arg = lb_const_value(p->module, parameter_type, param_value.value);
  7272. }
  7273. return lb_emit_conv(p, arg, parameter_type);
  7274. }
  7275. case ParameterValue_Nil:
  7276. return lb_const_nil(p->module, parameter_type);
  7277. case ParameterValue_Location:
  7278. {
  7279. String proc_name = {};
  7280. if (p->entity != nullptr) {
  7281. proc_name = p->entity->token.string;
  7282. }
  7283. return lb_emit_source_code_location(p, proc_name, pos);
  7284. }
  7285. case ParameterValue_Value:
  7286. return lb_build_expr(p, param_value.ast_value);
  7287. }
  7288. return lb_const_nil(p->module, parameter_type);
  7289. }
  7290. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  7291. lbModule *m = p->module;
  7292. TypeAndValue tv = type_and_value_of_expr(expr);
  7293. ast_node(ce, CallExpr, expr);
  7294. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  7295. AddressingMode proc_mode = proc_tv.mode;
  7296. if (proc_mode == Addressing_Type) {
  7297. GB_ASSERT(ce->args.count == 1);
  7298. lbValue x = lb_build_expr(p, ce->args[0]);
  7299. lbValue y = lb_emit_conv(p, x, tv.type);
  7300. return y;
  7301. }
  7302. Ast *pexpr = unparen_expr(ce->proc);
  7303. if (proc_mode == Addressing_Builtin) {
  7304. Entity *e = entity_of_node(pexpr);
  7305. BuiltinProcId id = BuiltinProc_Invalid;
  7306. if (e != nullptr) {
  7307. id = cast(BuiltinProcId)e->Builtin.id;
  7308. } else {
  7309. id = BuiltinProc_DIRECTIVE;
  7310. }
  7311. return lb_build_builtin_proc(p, expr, tv, id);
  7312. }
  7313. // NOTE(bill): Regular call
  7314. lbValue value = {};
  7315. Ast *proc_expr = unparen_expr(ce->proc);
  7316. if (proc_expr->tav.mode == Addressing_Constant) {
  7317. ExactValue v = proc_expr->tav.value;
  7318. switch (v.kind) {
  7319. case ExactValue_Integer:
  7320. {
  7321. u64 u = big_int_to_u64(&v.value_integer);
  7322. lbValue x = {};
  7323. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7324. x.type = t_uintptr;
  7325. x = lb_emit_conv(p, x, t_rawptr);
  7326. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7327. break;
  7328. }
  7329. case ExactValue_Pointer:
  7330. {
  7331. u64 u = cast(u64)v.value_pointer;
  7332. lbValue x = {};
  7333. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7334. x.type = t_uintptr;
  7335. x = lb_emit_conv(p, x, t_rawptr);
  7336. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7337. break;
  7338. }
  7339. }
  7340. }
  7341. if (value.value == nullptr) {
  7342. value = lb_build_expr(p, proc_expr);
  7343. }
  7344. GB_ASSERT(value.value != nullptr);
  7345. Type *proc_type_ = base_type(value.type);
  7346. GB_ASSERT(proc_type_->kind == Type_Proc);
  7347. TypeProc *pt = &proc_type_->Proc;
  7348. set_procedure_abi_types(proc_type_);
  7349. if (is_call_expr_field_value(ce)) {
  7350. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  7351. for_array(arg_index, ce->args) {
  7352. Ast *arg = ce->args[arg_index];
  7353. ast_node(fv, FieldValue, arg);
  7354. GB_ASSERT(fv->field->kind == Ast_Ident);
  7355. String name = fv->field->Ident.token.string;
  7356. isize index = lookup_procedure_parameter(pt, name);
  7357. GB_ASSERT(index >= 0);
  7358. TypeAndValue tav = type_and_value_of_expr(fv->value);
  7359. if (tav.mode == Addressing_Type) {
  7360. args[index] = lb_const_nil(m, tav.type);
  7361. } else {
  7362. args[index] = lb_build_expr(p, fv->value);
  7363. }
  7364. }
  7365. TypeTuple *params = &pt->params->Tuple;
  7366. for (isize i = 0; i < args.count; i++) {
  7367. Entity *e = params->variables[i];
  7368. if (e->kind == Entity_TypeName) {
  7369. args[i] = lb_const_nil(m, e->type);
  7370. } else if (e->kind == Entity_Constant) {
  7371. continue;
  7372. } else {
  7373. GB_ASSERT(e->kind == Entity_Variable);
  7374. if (args[i].value == nullptr) {
  7375. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7376. } else {
  7377. args[i] = lb_emit_conv(p, args[i], e->type);
  7378. }
  7379. }
  7380. }
  7381. for (isize i = 0; i < args.count; i++) {
  7382. Entity *e = params->variables[i];
  7383. if (args[i].type == nullptr) {
  7384. continue;
  7385. } else if (is_type_untyped_nil(args[i].type)) {
  7386. args[i] = lb_const_nil(m, e->type);
  7387. } else if (is_type_untyped_undef(args[i].type)) {
  7388. args[i] = lb_const_undef(m, e->type);
  7389. }
  7390. }
  7391. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  7392. }
  7393. isize arg_index = 0;
  7394. isize arg_count = 0;
  7395. for_array(i, ce->args) {
  7396. Ast *arg = ce->args[i];
  7397. TypeAndValue tav = type_and_value_of_expr(arg);
  7398. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  7399. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  7400. Type *at = tav.type;
  7401. if (at->kind == Type_Tuple) {
  7402. arg_count += at->Tuple.variables.count;
  7403. } else {
  7404. arg_count++;
  7405. }
  7406. }
  7407. isize param_count = 0;
  7408. if (pt->params) {
  7409. GB_ASSERT(pt->params->kind == Type_Tuple);
  7410. param_count = pt->params->Tuple.variables.count;
  7411. }
  7412. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  7413. isize variadic_index = pt->variadic_index;
  7414. bool variadic = pt->variadic && variadic_index >= 0;
  7415. bool vari_expand = ce->ellipsis.pos.line != 0;
  7416. bool is_c_vararg = pt->c_vararg;
  7417. String proc_name = {};
  7418. if (p->entity != nullptr) {
  7419. proc_name = p->entity->token.string;
  7420. }
  7421. TokenPos pos = ast_token(ce->proc).pos;
  7422. TypeTuple *param_tuple = nullptr;
  7423. if (pt->params) {
  7424. GB_ASSERT(pt->params->kind == Type_Tuple);
  7425. param_tuple = &pt->params->Tuple;
  7426. }
  7427. for_array(i, ce->args) {
  7428. Ast *arg = ce->args[i];
  7429. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  7430. if (arg_tv.mode == Addressing_Type) {
  7431. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  7432. } else {
  7433. lbValue a = lb_build_expr(p, arg);
  7434. Type *at = a.type;
  7435. if (at->kind == Type_Tuple) {
  7436. for_array(i, at->Tuple.variables) {
  7437. Entity *e = at->Tuple.variables[i];
  7438. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  7439. args[arg_index++] = v;
  7440. }
  7441. } else {
  7442. args[arg_index++] = a;
  7443. }
  7444. }
  7445. }
  7446. if (param_count > 0) {
  7447. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  7448. GB_ASSERT(param_count < 1000000);
  7449. if (arg_count < param_count) {
  7450. isize end = cast(isize)param_count;
  7451. if (variadic) {
  7452. end = variadic_index;
  7453. }
  7454. while (arg_index < end) {
  7455. Entity *e = param_tuple->variables[arg_index];
  7456. GB_ASSERT(e->kind == Entity_Variable);
  7457. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7458. }
  7459. }
  7460. if (is_c_vararg) {
  7461. GB_ASSERT(variadic);
  7462. GB_ASSERT(!vari_expand);
  7463. isize i = 0;
  7464. for (; i < variadic_index; i++) {
  7465. Entity *e = param_tuple->variables[i];
  7466. if (e->kind == Entity_Variable) {
  7467. args[i] = lb_emit_conv(p, args[i], e->type);
  7468. }
  7469. }
  7470. Type *variadic_type = param_tuple->variables[i]->type;
  7471. GB_ASSERT(is_type_slice(variadic_type));
  7472. variadic_type = base_type(variadic_type)->Slice.elem;
  7473. if (!is_type_any(variadic_type)) {
  7474. for (; i < arg_count; i++) {
  7475. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7476. }
  7477. } else {
  7478. for (; i < arg_count; i++) {
  7479. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  7480. }
  7481. }
  7482. } else if (variadic) {
  7483. isize i = 0;
  7484. for (; i < variadic_index; i++) {
  7485. Entity *e = param_tuple->variables[i];
  7486. if (e->kind == Entity_Variable) {
  7487. args[i] = lb_emit_conv(p, args[i], e->type);
  7488. }
  7489. }
  7490. if (!vari_expand) {
  7491. Type *variadic_type = param_tuple->variables[i]->type;
  7492. GB_ASSERT(is_type_slice(variadic_type));
  7493. variadic_type = base_type(variadic_type)->Slice.elem;
  7494. for (; i < arg_count; i++) {
  7495. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7496. }
  7497. }
  7498. } else {
  7499. for (isize i = 0; i < param_count; i++) {
  7500. Entity *e = param_tuple->variables[i];
  7501. if (e->kind == Entity_Variable) {
  7502. if (args[i].value == nullptr) {
  7503. continue;
  7504. }
  7505. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  7506. args[i] = lb_emit_conv(p, args[i], e->type);
  7507. }
  7508. }
  7509. }
  7510. if (variadic && !vari_expand && !is_c_vararg) {
  7511. // variadic call argument generation
  7512. Type *slice_type = param_tuple->variables[variadic_index]->type;
  7513. Type *elem_type = base_type(slice_type)->Slice.elem;
  7514. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  7515. isize slice_len = arg_count+1 - (variadic_index+1);
  7516. if (slice_len > 0) {
  7517. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  7518. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  7519. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  7520. lb_emit_store(p, addr, args[i]);
  7521. }
  7522. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  7523. lbValue len = lb_const_int(m, t_int, slice_len);
  7524. lb_fill_slice(p, slice, base_elem, len);
  7525. }
  7526. arg_count = param_count;
  7527. args[variadic_index] = lb_addr_load(p, slice);
  7528. }
  7529. }
  7530. if (variadic && variadic_index+1 < param_count) {
  7531. for (isize i = variadic_index+1; i < param_count; i++) {
  7532. Entity *e = param_tuple->variables[i];
  7533. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7534. }
  7535. }
  7536. isize final_count = param_count;
  7537. if (is_c_vararg) {
  7538. final_count = arg_count;
  7539. }
  7540. if (param_tuple != nullptr) {
  7541. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  7542. Entity *e = param_tuple->variables[i];
  7543. if (args[i].type == nullptr) {
  7544. continue;
  7545. } else if (is_type_untyped_nil(args[i].type)) {
  7546. args[i] = lb_const_nil(m, e->type);
  7547. } else if (is_type_untyped_undef(args[i].type)) {
  7548. args[i] = lb_const_undef(m, e->type);
  7549. }
  7550. }
  7551. }
  7552. auto call_args = array_slice(args, 0, final_count);
  7553. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  7554. }
  7555. bool lb_is_const(lbValue value) {
  7556. LLVMValueRef v = value.value;
  7557. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  7558. // TODO(bill): Is this correct behaviour?
  7559. return true;
  7560. }
  7561. if (LLVMIsConstant(v)) {
  7562. return true;
  7563. }
  7564. return false;
  7565. }
  7566. bool lb_is_const_nil(lbValue value) {
  7567. LLVMValueRef v = value.value;
  7568. if (LLVMIsConstant(v)) {
  7569. if (LLVMIsAConstantAggregateZero(v)) {
  7570. return true;
  7571. } else if (LLVMIsAConstantPointerNull(v)) {
  7572. return true;
  7573. }
  7574. }
  7575. return false;
  7576. }
  7577. String lb_get_const_string(lbModule *m, lbValue value) {
  7578. GB_ASSERT(lb_is_const(value));
  7579. Type *t = base_type(value.type);
  7580. GB_ASSERT(are_types_identical(t, t_string));
  7581. unsigned ptr_indices[1] = {0};
  7582. unsigned len_indices[1] = {1};
  7583. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  7584. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  7585. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  7586. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  7587. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  7588. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  7589. size_t length = 0;
  7590. char const *text = LLVMGetAsString(underlying_ptr, &length);
  7591. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  7592. return make_string(cast(u8 const *)text, real_length);
  7593. }
  7594. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  7595. GB_ASSERT(is_type_pointer(addr.type));
  7596. Type *type = type_deref(addr.type);
  7597. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  7598. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  7599. }
  7600. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7601. AstPackage *pkg = m->info->runtime_package;
  7602. Entity *e = scope_lookup_current(pkg->scope, name);
  7603. lbValue *found = nullptr;
  7604. if (m != e->code_gen_module) {
  7605. gb_mutex_lock(&m->mutex);
  7606. }
  7607. found = map_get(&e->code_gen_module->values, hash_entity(e));
  7608. if (m != e->code_gen_module) {
  7609. gb_mutex_unlock(&m->mutex);
  7610. }
  7611. GB_ASSERT(found != nullptr);
  7612. return found->value;
  7613. }
  7614. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  7615. Type *vt = core_type(value.type);
  7616. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  7617. // TODO(bill): lb_emit_byte_swap
  7618. lbValue res = {};
  7619. res.type = platform_type;
  7620. res.value = value.value;
  7621. int sz = cast(int)type_size_of(vt);
  7622. if (sz > 1) {
  7623. if (is_type_float(platform_type)) {
  7624. String name = {};
  7625. switch (sz) {
  7626. case 4: name = str_lit("bswap_f32"); break;
  7627. case 8: name = str_lit("bswap_f64"); break;
  7628. default: GB_PANIC("unhandled byteswap size"); break;
  7629. }
  7630. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7631. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7632. } else {
  7633. GB_ASSERT(is_type_integer(platform_type));
  7634. String name = {};
  7635. switch (sz) {
  7636. case 2: name = str_lit("bswap_16"); break;
  7637. case 4: name = str_lit("bswap_32"); break;
  7638. case 8: name = str_lit("bswap_64"); break;
  7639. case 16: name = str_lit("bswap_128"); break;
  7640. default: GB_PANIC("unhandled byteswap size"); break;
  7641. }
  7642. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7643. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7644. }
  7645. }
  7646. return res;
  7647. }
  7648. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  7649. lbLoopData data = {};
  7650. lbValue max = lb_const_int(p->module, t_int, count);
  7651. data.idx_addr = lb_add_local_generated(p, index_type, true);
  7652. data.body = lb_create_block(p, "loop.body");
  7653. data.done = lb_create_block(p, "loop.done");
  7654. data.loop = lb_create_block(p, "loop.loop");
  7655. lb_emit_jump(p, data.loop);
  7656. lb_start_block(p, data.loop);
  7657. data.idx = lb_addr_load(p, data.idx_addr);
  7658. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  7659. lb_emit_if(p, cond, data.body, data.done);
  7660. lb_start_block(p, data.body);
  7661. return data;
  7662. }
  7663. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  7664. if (data.idx_addr.addr.value != nullptr) {
  7665. lb_emit_increment(p, data.idx_addr.addr);
  7666. lb_emit_jump(p, data.loop);
  7667. lb_start_block(p, data.done);
  7668. }
  7669. }
  7670. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  7671. lbValue res = {};
  7672. res.type = t_llvm_bool;
  7673. Type *t = x.type;
  7674. if (is_type_pointer(t)) {
  7675. if (op_kind == Token_CmpEq) {
  7676. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7677. } else if (op_kind == Token_NotEq) {
  7678. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7679. }
  7680. return res;
  7681. } else if (is_type_cstring(t)) {
  7682. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  7683. if (op_kind == Token_CmpEq) {
  7684. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  7685. } else if (op_kind == Token_NotEq) {
  7686. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  7687. }
  7688. return res;
  7689. } else if (is_type_proc(t)) {
  7690. if (op_kind == Token_CmpEq) {
  7691. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7692. } else if (op_kind == Token_NotEq) {
  7693. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7694. }
  7695. return res;
  7696. } else if (is_type_any(t)) {
  7697. // TODO(bill): is this correct behaviour for nil comparison for any?
  7698. lbValue data = lb_emit_struct_ev(p, x, 0);
  7699. lbValue ti = lb_emit_struct_ev(p, x, 1);
  7700. if (op_kind == Token_CmpEq) {
  7701. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  7702. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  7703. res.value = LLVMBuildOr(p->builder, a, b, "");
  7704. return res;
  7705. } else if (op_kind == Token_NotEq) {
  7706. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  7707. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  7708. res.value = LLVMBuildAnd(p->builder, a, b, "");
  7709. return res;
  7710. }
  7711. } else if (is_type_slice(t)) {
  7712. lbValue len = lb_emit_struct_ev(p, x, 1);
  7713. if (op_kind == Token_CmpEq) {
  7714. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7715. return res;
  7716. } else if (op_kind == Token_NotEq) {
  7717. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7718. return res;
  7719. }
  7720. } else if (is_type_dynamic_array(t)) {
  7721. lbValue cap = lb_emit_struct_ev(p, x, 2);
  7722. if (op_kind == Token_CmpEq) {
  7723. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7724. return res;
  7725. } else if (op_kind == Token_NotEq) {
  7726. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7727. return res;
  7728. }
  7729. } else if (is_type_map(t)) {
  7730. lbValue cap = lb_map_cap(p, x);
  7731. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  7732. } else if (is_type_union(t)) {
  7733. if (type_size_of(t) == 0) {
  7734. if (op_kind == Token_CmpEq) {
  7735. return lb_const_bool(p->module, t_llvm_bool, true);
  7736. } else if (op_kind == Token_NotEq) {
  7737. return lb_const_bool(p->module, t_llvm_bool, false);
  7738. }
  7739. } else {
  7740. lbValue tag = lb_emit_union_tag_value(p, x);
  7741. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  7742. }
  7743. } else if (is_type_typeid(t)) {
  7744. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  7745. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  7746. } else if (is_type_bit_field(t)) {
  7747. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7748. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7749. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7750. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7751. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7752. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7753. return res;
  7754. } else if (is_type_soa_struct(t)) {
  7755. Type *bt = base_type(t);
  7756. if (bt->Struct.soa_kind == StructSoa_Slice) {
  7757. lbValue len = lb_soa_struct_len(p, x);
  7758. if (op_kind == Token_CmpEq) {
  7759. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7760. return res;
  7761. } else if (op_kind == Token_NotEq) {
  7762. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7763. return res;
  7764. }
  7765. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  7766. lbValue cap = lb_soa_struct_cap(p, x);
  7767. if (op_kind == Token_CmpEq) {
  7768. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7769. return res;
  7770. } else if (op_kind == Token_NotEq) {
  7771. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7772. return res;
  7773. }
  7774. }
  7775. } else if (is_type_struct(t) && type_has_nil(t)) {
  7776. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7777. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7778. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7779. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7780. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7781. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7782. return res;
  7783. }
  7784. return {};
  7785. }
  7786. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  7787. Type *original_type = type;
  7788. type = base_type(type);
  7789. GB_ASSERT(is_type_comparable(type));
  7790. Type *pt = alloc_type_pointer(type);
  7791. LLVMTypeRef ptr_type = lb_type(m, pt);
  7792. auto key = hash_type(type);
  7793. lbProcedure **found = map_get(&m->equal_procs, key);
  7794. lbProcedure *compare_proc = nullptr;
  7795. if (found) {
  7796. compare_proc = *found;
  7797. GB_ASSERT(compare_proc != nullptr);
  7798. return {compare_proc->value, compare_proc->type};
  7799. }
  7800. static u32 proc_index = 0;
  7801. char buf[16] = {};
  7802. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  7803. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  7804. String proc_name = make_string_c(str);
  7805. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  7806. map_set(&m->equal_procs, key, p);
  7807. lb_begin_procedure_body(p);
  7808. LLVMValueRef x = LLVMGetParam(p->value, 0);
  7809. LLVMValueRef y = LLVMGetParam(p->value, 1);
  7810. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  7811. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  7812. lbValue lhs = {x, pt};
  7813. lbValue rhs = {y, pt};
  7814. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  7815. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  7816. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  7817. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  7818. lb_start_block(p, block_same_ptr);
  7819. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  7820. lb_start_block(p, block_diff_ptr);
  7821. if (type->kind == Type_Struct) {
  7822. type_set_offsets(type);
  7823. lbBlock *block_false = lb_create_block(p, "bfalse");
  7824. lbValue res = lb_const_bool(m, t_bool, true);
  7825. for_array(i, type->Struct.fields) {
  7826. lbBlock *next_block = lb_create_block(p, "btrue");
  7827. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  7828. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  7829. lbValue left = lb_emit_load(p, pleft);
  7830. lbValue right = lb_emit_load(p, pright);
  7831. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  7832. lb_emit_if(p, ok, next_block, block_false);
  7833. lb_emit_jump(p, next_block);
  7834. lb_start_block(p, next_block);
  7835. }
  7836. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  7837. lb_start_block(p, block_false);
  7838. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  7839. } else {
  7840. lbValue left = lb_emit_load(p, lhs);
  7841. lbValue right = lb_emit_load(p, rhs);
  7842. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  7843. ok = lb_emit_conv(p, ok, t_bool);
  7844. LLVMBuildRet(p->builder, ok.value);
  7845. }
  7846. lb_end_procedure_body(p);
  7847. compare_proc = p;
  7848. return {compare_proc->value, compare_proc->type};
  7849. }
  7850. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  7851. Type *original_type = type;
  7852. type = base_type(type);
  7853. GB_ASSERT(is_type_valid_for_keys(type));
  7854. Type *pt = alloc_type_pointer(type);
  7855. LLVMTypeRef ptr_type = lb_type(m, pt);
  7856. auto key = hash_type(type);
  7857. lbProcedure **found = map_get(&m->hasher_procs, key);
  7858. lbProcedure *hasher_proc = nullptr;
  7859. if (found) {
  7860. hasher_proc = *found;
  7861. GB_ASSERT(hasher_proc != nullptr);
  7862. return {hasher_proc->value, hasher_proc->type};
  7863. }
  7864. static u32 proc_index = 0;
  7865. char buf[16] = {};
  7866. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  7867. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  7868. String proc_name = make_string_c(str);
  7869. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  7870. map_set(&m->hasher_procs, key, p);
  7871. lb_begin_procedure_body(p);
  7872. LLVMValueRef x = LLVMGetParam(p->value, 0);
  7873. LLVMValueRef y = LLVMGetParam(p->value, 1);
  7874. lbValue data = {x, t_rawptr};
  7875. lbValue seed = {y, t_uintptr};
  7876. if (type->kind == Type_Struct) {
  7877. type_set_offsets(type);
  7878. GB_PANIC("Type_Struct");
  7879. } else if (is_type_string(type)) {
  7880. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7881. args[0] = data;
  7882. args[1] = seed;
  7883. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  7884. LLVMBuildRet(p->builder, res.value);
  7885. } else {
  7886. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  7887. i64 sz = type_size_of(type);
  7888. char const *name = nullptr;
  7889. switch (sz) {
  7890. case 1: name = "default_hasher1"; break;
  7891. case 2: name = "default_hasher2"; break;
  7892. case 4: name = "default_hasher4"; break;
  7893. case 8: name = "default_hasher8"; break;
  7894. case 16: name = "default_hasher16"; break;
  7895. default: GB_PANIC("unhandled hasher for key type: %s", type_to_string(type));
  7896. }
  7897. GB_ASSERT(name != nullptr);
  7898. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7899. args[0] = data;
  7900. args[1] = seed;
  7901. lbValue res = lb_emit_runtime_call(p, name, args);
  7902. LLVMBuildRet(p->builder, res.value);
  7903. }
  7904. lb_end_procedure_body(p);
  7905. hasher_proc = p;
  7906. return {hasher_proc->value, hasher_proc->type};
  7907. }
  7908. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  7909. Type *a = core_type(left.type);
  7910. Type *b = core_type(right.type);
  7911. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  7912. lbValue nil_check = {};
  7913. if (is_type_untyped_nil(left.type)) {
  7914. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  7915. } else if (is_type_untyped_nil(right.type)) {
  7916. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  7917. }
  7918. if (nil_check.value != nullptr) {
  7919. return nil_check;
  7920. }
  7921. if (are_types_identical(a, b)) {
  7922. // NOTE(bill): No need for a conversion
  7923. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  7924. left = lb_emit_conv(p, left, right.type);
  7925. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  7926. right = lb_emit_conv(p, right, left.type);
  7927. } else {
  7928. Type *lt = left.type;
  7929. Type *rt = right.type;
  7930. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  7931. Type *blt = base_type(lt);
  7932. Type *brt = base_type(rt);
  7933. GB_ASSERT(is_type_bit_field_value(blt));
  7934. GB_ASSERT(is_type_bit_field_value(brt));
  7935. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  7936. i64 bytes = bits / 8;
  7937. switch (bytes) {
  7938. case 1:
  7939. left = lb_emit_conv(p, left, t_u8);
  7940. right = lb_emit_conv(p, right, t_u8);
  7941. break;
  7942. case 2:
  7943. left = lb_emit_conv(p, left, t_u16);
  7944. right = lb_emit_conv(p, right, t_u16);
  7945. break;
  7946. case 4:
  7947. left = lb_emit_conv(p, left, t_u32);
  7948. right = lb_emit_conv(p, right, t_u32);
  7949. break;
  7950. case 8:
  7951. left = lb_emit_conv(p, left, t_u64);
  7952. right = lb_emit_conv(p, right, t_u64);
  7953. break;
  7954. default: GB_PANIC("Unknown integer size"); break;
  7955. }
  7956. }
  7957. lt = left.type;
  7958. rt = right.type;
  7959. i64 ls = type_size_of(lt);
  7960. i64 rs = type_size_of(rt);
  7961. if (ls < rs) {
  7962. left = lb_emit_conv(p, left, rt);
  7963. } else if (ls > rs) {
  7964. right = lb_emit_conv(p, right, lt);
  7965. } else {
  7966. right = lb_emit_conv(p, right, lt);
  7967. }
  7968. }
  7969. if (is_type_array(a)) {
  7970. Type *tl = base_type(a);
  7971. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  7972. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  7973. TokenKind cmp_op = Token_And;
  7974. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  7975. if (op_kind == Token_NotEq) {
  7976. res = lb_const_bool(p->module, t_llvm_bool, false);
  7977. cmp_op = Token_Or;
  7978. } else if (op_kind == Token_CmpEq) {
  7979. res = lb_const_bool(p->module, t_llvm_bool, true);
  7980. cmp_op = Token_And;
  7981. }
  7982. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  7983. i32 count = cast(i32)tl->Array.count;
  7984. if (inline_array_arith) {
  7985. // inline
  7986. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7987. lb_addr_store(p, val, res);
  7988. for (i32 i = 0; i < count; i++) {
  7989. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  7990. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  7991. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7992. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7993. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7994. }
  7995. return lb_addr_load(p, val);
  7996. } else {
  7997. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  7998. // TODO(bill): Test to see if this is actually faster!!!!
  7999. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8000. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8001. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  8002. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  8003. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  8004. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  8005. return lb_emit_conv(p, res, t_bool);
  8006. } else {
  8007. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8008. lb_addr_store(p, val, res);
  8009. auto loop_data = lb_loop_start(p, count, t_i32);
  8010. {
  8011. lbValue i = loop_data.idx;
  8012. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  8013. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  8014. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8015. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8016. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8017. }
  8018. lb_loop_end(p, loop_data);
  8019. return lb_addr_load(p, val);
  8020. }
  8021. }
  8022. }
  8023. if (is_type_struct(a) && is_type_comparable(a)) {
  8024. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  8025. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  8026. lbValue res = {};
  8027. if (is_type_simple_compare(a)) {
  8028. // TODO(bill): Test to see if this is actually faster!!!!
  8029. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8030. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8031. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8032. args[2] = lb_const_int(p->module, t_int, type_size_of(a));
  8033. res = lb_emit_runtime_call(p, "memory_equal", args);
  8034. } else {
  8035. lbValue value = lb_get_equal_proc_for_type(p->module, a);
  8036. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8037. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8038. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8039. res = lb_emit_call(p, value, args);
  8040. }
  8041. if (op_kind == Token_NotEq) {
  8042. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  8043. }
  8044. return res;
  8045. }
  8046. if (is_type_string(a)) {
  8047. if (is_type_cstring(a)) {
  8048. left = lb_emit_conv(p, left, t_string);
  8049. right = lb_emit_conv(p, right, t_string);
  8050. }
  8051. char const *runtime_procedure = nullptr;
  8052. switch (op_kind) {
  8053. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  8054. case Token_NotEq: runtime_procedure = "string_ne"; break;
  8055. case Token_Lt: runtime_procedure = "string_lt"; break;
  8056. case Token_Gt: runtime_procedure = "string_gt"; break;
  8057. case Token_LtEq: runtime_procedure = "string_le"; break;
  8058. case Token_GtEq: runtime_procedure = "string_gt"; break;
  8059. }
  8060. GB_ASSERT(runtime_procedure != nullptr);
  8061. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8062. args[0] = left;
  8063. args[1] = right;
  8064. return lb_emit_runtime_call(p, runtime_procedure, args);
  8065. }
  8066. if (is_type_complex(a)) {
  8067. char const *runtime_procedure = "";
  8068. i64 sz = 8*type_size_of(a);
  8069. switch (sz) {
  8070. case 64:
  8071. switch (op_kind) {
  8072. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  8073. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  8074. }
  8075. break;
  8076. case 128:
  8077. switch (op_kind) {
  8078. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  8079. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  8080. }
  8081. break;
  8082. }
  8083. GB_ASSERT(runtime_procedure != nullptr);
  8084. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8085. args[0] = left;
  8086. args[1] = right;
  8087. return lb_emit_runtime_call(p, runtime_procedure, args);
  8088. }
  8089. if (is_type_quaternion(a)) {
  8090. char const *runtime_procedure = "";
  8091. i64 sz = 8*type_size_of(a);
  8092. switch (sz) {
  8093. case 128:
  8094. switch (op_kind) {
  8095. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  8096. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  8097. }
  8098. break;
  8099. case 256:
  8100. switch (op_kind) {
  8101. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  8102. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  8103. }
  8104. break;
  8105. }
  8106. GB_ASSERT(runtime_procedure != nullptr);
  8107. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8108. args[0] = left;
  8109. args[1] = right;
  8110. return lb_emit_runtime_call(p, runtime_procedure, args);
  8111. }
  8112. if (is_type_bit_set(a)) {
  8113. switch (op_kind) {
  8114. case Token_Lt:
  8115. case Token_LtEq:
  8116. case Token_Gt:
  8117. case Token_GtEq:
  8118. {
  8119. Type *it = bit_set_to_int(a);
  8120. lbValue lhs = lb_emit_transmute(p, left, it);
  8121. lbValue rhs = lb_emit_transmute(p, right, it);
  8122. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  8123. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  8124. // (lhs & rhs) == lhs
  8125. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  8126. res.type = t_llvm_bool;
  8127. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  8128. // (lhs & rhs) == rhs
  8129. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  8130. res.type = t_llvm_bool;
  8131. }
  8132. // NOTE(bill): Strict subsets
  8133. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  8134. // res &~ (lhs == rhs)
  8135. lbValue eq = {};
  8136. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  8137. eq.type = t_llvm_bool;
  8138. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  8139. }
  8140. return res;
  8141. }
  8142. case Token_CmpEq:
  8143. case Token_NotEq:
  8144. {
  8145. LLVMIntPredicate pred = {};
  8146. switch (op_kind) {
  8147. case Token_CmpEq: pred = LLVMIntEQ; break;
  8148. case Token_NotEq: pred = LLVMIntNE; break;
  8149. }
  8150. lbValue res = {};
  8151. res.type = t_llvm_bool;
  8152. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8153. return res;
  8154. }
  8155. }
  8156. }
  8157. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  8158. Type *t = left.type;
  8159. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  8160. Type *platform_type = integer_endian_type_to_platform_type(t);
  8161. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  8162. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  8163. left = x;
  8164. right = y;
  8165. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  8166. Type *platform_type = integer_endian_type_to_platform_type(t);
  8167. lbValue x = lb_emit_conv(p, left, platform_type);
  8168. lbValue y = lb_emit_conv(p, right, platform_type);
  8169. left = x;
  8170. right = y;
  8171. }
  8172. }
  8173. a = core_type(left.type);
  8174. b = core_type(right.type);
  8175. lbValue res = {};
  8176. res.type = t_llvm_bool;
  8177. if (is_type_integer(a) ||
  8178. is_type_boolean(a) ||
  8179. is_type_pointer(a) ||
  8180. is_type_proc(a) ||
  8181. is_type_enum(a)) {
  8182. LLVMIntPredicate pred = {};
  8183. if (is_type_unsigned(left.type)) {
  8184. switch (op_kind) {
  8185. case Token_Gt: pred = LLVMIntUGT; break;
  8186. case Token_GtEq: pred = LLVMIntUGE; break;
  8187. case Token_Lt: pred = LLVMIntULT; break;
  8188. case Token_LtEq: pred = LLVMIntULE; break;
  8189. }
  8190. } else {
  8191. switch (op_kind) {
  8192. case Token_Gt: pred = LLVMIntSGT; break;
  8193. case Token_GtEq: pred = LLVMIntSGE; break;
  8194. case Token_Lt: pred = LLVMIntSLT; break;
  8195. case Token_LtEq: pred = LLVMIntSLE; break;
  8196. }
  8197. }
  8198. switch (op_kind) {
  8199. case Token_CmpEq: pred = LLVMIntEQ; break;
  8200. case Token_NotEq: pred = LLVMIntNE; break;
  8201. }
  8202. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8203. } else if (is_type_float(a)) {
  8204. LLVMRealPredicate pred = {};
  8205. switch (op_kind) {
  8206. case Token_CmpEq: pred = LLVMRealOEQ; break;
  8207. case Token_Gt: pred = LLVMRealOGT; break;
  8208. case Token_GtEq: pred = LLVMRealOGE; break;
  8209. case Token_Lt: pred = LLVMRealOLT; break;
  8210. case Token_LtEq: pred = LLVMRealOLE; break;
  8211. case Token_NotEq: pred = LLVMRealONE; break;
  8212. }
  8213. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  8214. } else if (is_type_typeid(a)) {
  8215. LLVMIntPredicate pred = {};
  8216. switch (op_kind) {
  8217. case Token_Gt: pred = LLVMIntUGT; break;
  8218. case Token_GtEq: pred = LLVMIntUGE; break;
  8219. case Token_Lt: pred = LLVMIntULT; break;
  8220. case Token_LtEq: pred = LLVMIntULE; break;
  8221. case Token_CmpEq: pred = LLVMIntEQ; break;
  8222. case Token_NotEq: pred = LLVMIntNE; break;
  8223. }
  8224. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8225. } else {
  8226. 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)));
  8227. }
  8228. return res;
  8229. }
  8230. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  8231. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  8232. if (found != nullptr) {
  8233. lbValue value = {};
  8234. value.value = (*found)->value;
  8235. value.type = (*found)->type;
  8236. return value;
  8237. }
  8238. ast_node(pl, ProcLit, expr);
  8239. // NOTE(bill): Generate a new name
  8240. // parent$count
  8241. isize name_len = prefix_name.len + 1 + 8 + 1;
  8242. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  8243. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  8244. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  8245. String name = make_string((u8 *)name_text, name_len-1);
  8246. Type *type = type_of_expr(expr);
  8247. set_procedure_abi_types(type);
  8248. Token token = {};
  8249. token.pos = ast_token(expr).pos;
  8250. token.kind = Token_Ident;
  8251. token.string = name;
  8252. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  8253. e->decl_info = pl->decl;
  8254. lbProcedure *p = lb_create_procedure(m, e);
  8255. lbValue value = {};
  8256. value.value = p->value;
  8257. value.type = p->type;
  8258. array_add(&m->procedures_to_generate, p);
  8259. if (parent != nullptr) {
  8260. array_add(&parent->children, p);
  8261. } else {
  8262. string_map_set(&m->members, name, value);
  8263. }
  8264. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  8265. return value;
  8266. }
  8267. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  8268. lbModule *m = p->module;
  8269. Type *src_type = value.type;
  8270. bool is_ptr = is_type_pointer(src_type);
  8271. bool is_tuple = true;
  8272. Type *tuple = type;
  8273. if (type->kind != Type_Tuple) {
  8274. is_tuple = false;
  8275. tuple = make_optional_ok_type(type);
  8276. }
  8277. lbAddr v = lb_add_local_generated(p, tuple, true);
  8278. if (is_ptr) {
  8279. value = lb_emit_load(p, value);
  8280. }
  8281. Type *src = base_type(type_deref(src_type));
  8282. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  8283. Type *dst = tuple->Tuple.variables[0]->type;
  8284. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  8285. lbValue tag = {};
  8286. lbValue dst_tag = {};
  8287. lbValue cond = {};
  8288. lbValue data = {};
  8289. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8290. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8291. if (is_type_union_maybe_pointer(src)) {
  8292. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8293. } else {
  8294. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  8295. dst_tag = lb_const_union_tag(m, src, dst);
  8296. }
  8297. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  8298. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  8299. if (data.value != nullptr) {
  8300. GB_ASSERT(is_type_union_maybe_pointer(src));
  8301. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  8302. } else {
  8303. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  8304. }
  8305. lb_emit_if(p, cond, ok_block, end_block);
  8306. lb_start_block(p, ok_block);
  8307. if (data.value == nullptr) {
  8308. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8309. }
  8310. lb_emit_store(p, gep0, data);
  8311. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8312. lb_emit_jump(p, end_block);
  8313. lb_start_block(p, end_block);
  8314. if (!is_tuple) {
  8315. if (do_conversion_check) {
  8316. // NOTE(bill): Panic on invalid conversion
  8317. Type *dst_type = tuple->Tuple.variables[0]->type;
  8318. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8319. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8320. args[0] = ok;
  8321. args[1] = lb_const_string(m, pos.file);
  8322. args[2] = lb_const_int(m, t_int, pos.line);
  8323. args[3] = lb_const_int(m, t_int, pos.column);
  8324. args[4] = lb_typeid(m, src_type);
  8325. args[5] = lb_typeid(m, dst_type);
  8326. lb_emit_runtime_call(p, "type_assertion_check", args);
  8327. }
  8328. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  8329. }
  8330. return lb_addr_load(p, v);
  8331. }
  8332. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8333. lbModule *m = p->module;
  8334. Type *src_type = value.type;
  8335. if (is_type_pointer(src_type)) {
  8336. value = lb_emit_load(p, value);
  8337. }
  8338. bool is_tuple = true;
  8339. Type *tuple = type;
  8340. if (type->kind != Type_Tuple) {
  8341. is_tuple = false;
  8342. tuple = make_optional_ok_type(type);
  8343. }
  8344. Type *dst_type = tuple->Tuple.variables[0]->type;
  8345. lbAddr v = lb_add_local_generated(p, tuple, true);
  8346. lbValue dst_typeid = lb_typeid(m, dst_type);
  8347. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  8348. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  8349. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  8350. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  8351. lb_emit_if(p, cond, ok_block, end_block);
  8352. lb_start_block(p, ok_block);
  8353. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8354. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8355. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  8356. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  8357. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  8358. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8359. lb_emit_jump(p, end_block);
  8360. lb_start_block(p, end_block);
  8361. if (!is_tuple) {
  8362. // NOTE(bill): Panic on invalid conversion
  8363. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8364. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8365. args[0] = ok;
  8366. args[1] = lb_const_string(m, pos.file);
  8367. args[2] = lb_const_int(m, t_int, pos.line);
  8368. args[3] = lb_const_int(m, t_int, pos.column);
  8369. args[4] = any_typeid;
  8370. args[5] = dst_typeid;
  8371. lb_emit_runtime_call(p, "type_assertion_check", args);
  8372. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  8373. }
  8374. return v;
  8375. }
  8376. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8377. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  8378. }
  8379. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  8380. lbModule *m = p->module;
  8381. u64 prev_state_flags = p->module->state_flags;
  8382. defer (p->module->state_flags = prev_state_flags);
  8383. if (expr->state_flags != 0) {
  8384. u64 in = expr->state_flags;
  8385. u64 out = p->module->state_flags;
  8386. if (in & StateFlag_bounds_check) {
  8387. out |= StateFlag_bounds_check;
  8388. out &= ~StateFlag_no_bounds_check;
  8389. } else if (in & StateFlag_no_bounds_check) {
  8390. out |= StateFlag_no_bounds_check;
  8391. out &= ~StateFlag_bounds_check;
  8392. }
  8393. p->module->state_flags = out;
  8394. }
  8395. expr = unparen_expr(expr);
  8396. TypeAndValue tv = type_and_value_of_expr(expr);
  8397. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "%s", expr_to_string(expr));
  8398. GB_ASSERT(tv.mode != Addressing_Type);
  8399. if (tv.value.kind != ExactValue_Invalid) {
  8400. // NOTE(bill): Short on constant values
  8401. return lb_const_value(p->module, tv.type, tv.value);
  8402. }
  8403. switch (expr->kind) {
  8404. case_ast_node(bl, BasicLit, expr);
  8405. TokenPos pos = bl->token.pos;
  8406. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  8407. case_end;
  8408. case_ast_node(bd, BasicDirective, expr);
  8409. TokenPos pos = bd->token.pos;
  8410. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  8411. case_end;
  8412. case_ast_node(i, Implicit, expr);
  8413. return lb_addr_load(p, lb_build_addr(p, expr));
  8414. case_end;
  8415. case_ast_node(u, Undef, expr)
  8416. lbValue res = {};
  8417. if (is_type_untyped(tv.type)) {
  8418. res.value = nullptr;
  8419. res.type = t_untyped_undef;
  8420. } else {
  8421. res.value = LLVMGetUndef(lb_type(m, tv.type));
  8422. res.type = tv.type;
  8423. }
  8424. return res;
  8425. case_end;
  8426. case_ast_node(i, Ident, expr);
  8427. Entity *e = entity_from_expr(expr);
  8428. e = strip_entity_wrapping(e);
  8429. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  8430. if (e->kind == Entity_Builtin) {
  8431. Token token = ast_token(expr);
  8432. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  8433. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  8434. LIT(token.pos.file), token.pos.line, token.pos.column);
  8435. return {};
  8436. } else if (e->kind == Entity_Nil) {
  8437. lbValue res = {};
  8438. res.value = nullptr;
  8439. res.type = e->type;
  8440. return res;
  8441. }
  8442. GB_ASSERT(e->kind != Entity_ProcGroup);
  8443. auto *found = map_get(&p->module->values, hash_entity(e));
  8444. if (found) {
  8445. auto v = *found;
  8446. // NOTE(bill): This is because pointers are already pointers in LLVM
  8447. if (is_type_proc(v.type)) {
  8448. return v;
  8449. }
  8450. return lb_emit_load(p, v);
  8451. } else if (e != nullptr && e->kind == Entity_Variable) {
  8452. return lb_addr_load(p, lb_build_addr(p, expr));
  8453. }
  8454. gb_printf_err("Error in: %.*s(%td:%td)\n", LIT(p->name), i->token.pos.line, i->token.pos.column);
  8455. String pkg = {};
  8456. if (e->pkg) {
  8457. pkg = e->pkg->name;
  8458. }
  8459. 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);
  8460. return {};
  8461. case_end;
  8462. case_ast_node(de, DerefExpr, expr);
  8463. return lb_addr_load(p, lb_build_addr(p, expr));
  8464. case_end;
  8465. case_ast_node(se, SelectorExpr, expr);
  8466. TypeAndValue tav = type_and_value_of_expr(expr);
  8467. GB_ASSERT(tav.mode != Addressing_Invalid);
  8468. return lb_addr_load(p, lb_build_addr(p, expr));
  8469. case_end;
  8470. case_ast_node(ise, ImplicitSelectorExpr, expr);
  8471. TypeAndValue tav = type_and_value_of_expr(expr);
  8472. GB_ASSERT(tav.mode == Addressing_Constant);
  8473. return lb_const_value(p->module, tv.type, tv.value);
  8474. case_end;
  8475. case_ast_node(se, SelectorCallExpr, expr);
  8476. GB_ASSERT(se->modified_call);
  8477. TypeAndValue tav = type_and_value_of_expr(expr);
  8478. GB_ASSERT(tav.mode != Addressing_Invalid);
  8479. return lb_build_expr(p, se->call);
  8480. case_end;
  8481. case_ast_node(te, TernaryExpr, expr);
  8482. LLVMValueRef incoming_values[2] = {};
  8483. LLVMBasicBlockRef incoming_blocks[2] = {};
  8484. GB_ASSERT(te->y != nullptr);
  8485. lbBlock *then = lb_create_block(p, "if.then");
  8486. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8487. lbBlock *else_ = lb_create_block(p, "if.else");
  8488. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8489. lb_start_block(p, then);
  8490. Type *type = default_type(type_of_expr(expr));
  8491. lb_open_scope(p);
  8492. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8493. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8494. lb_emit_jump(p, done);
  8495. lb_start_block(p, else_);
  8496. lb_open_scope(p);
  8497. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8498. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8499. lb_emit_jump(p, done);
  8500. lb_start_block(p, done);
  8501. lbValue res = {};
  8502. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8503. res.type = type;
  8504. GB_ASSERT(p->curr_block->preds.count >= 2);
  8505. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8506. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8507. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8508. return res;
  8509. case_end;
  8510. case_ast_node(te, TernaryIfExpr, expr);
  8511. LLVMValueRef incoming_values[2] = {};
  8512. LLVMBasicBlockRef incoming_blocks[2] = {};
  8513. GB_ASSERT(te->y != nullptr);
  8514. lbBlock *then = lb_create_block(p, "if.then");
  8515. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8516. lbBlock *else_ = lb_create_block(p, "if.else");
  8517. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8518. lb_start_block(p, then);
  8519. Type *type = default_type(type_of_expr(expr));
  8520. lb_open_scope(p);
  8521. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8522. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8523. lb_emit_jump(p, done);
  8524. lb_start_block(p, else_);
  8525. lb_open_scope(p);
  8526. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8527. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8528. lb_emit_jump(p, done);
  8529. lb_start_block(p, done);
  8530. lbValue res = {};
  8531. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8532. res.type = type;
  8533. GB_ASSERT(p->curr_block->preds.count >= 2);
  8534. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8535. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8536. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8537. return res;
  8538. case_end;
  8539. case_ast_node(te, TernaryWhenExpr, expr);
  8540. TypeAndValue tav = type_and_value_of_expr(te->cond);
  8541. GB_ASSERT(tav.mode == Addressing_Constant);
  8542. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  8543. if (tav.value.value_bool) {
  8544. return lb_build_expr(p, te->x);
  8545. } else {
  8546. return lb_build_expr(p, te->y);
  8547. }
  8548. case_end;
  8549. case_ast_node(ta, TypeAssertion, expr);
  8550. TokenPos pos = ast_token(expr).pos;
  8551. Type *type = tv.type;
  8552. lbValue e = lb_build_expr(p, ta->expr);
  8553. Type *t = type_deref(e.type);
  8554. if (is_type_union(t)) {
  8555. return lb_emit_union_cast(p, e, type, pos);
  8556. } else if (is_type_any(t)) {
  8557. return lb_emit_any_cast(p, e, type, pos);
  8558. } else {
  8559. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8560. }
  8561. case_end;
  8562. case_ast_node(tc, TypeCast, expr);
  8563. lbValue e = lb_build_expr(p, tc->expr);
  8564. switch (tc->token.kind) {
  8565. case Token_cast:
  8566. return lb_emit_conv(p, e, tv.type);
  8567. case Token_transmute:
  8568. return lb_emit_transmute(p, e, tv.type);
  8569. }
  8570. GB_PANIC("Invalid AST TypeCast");
  8571. case_end;
  8572. case_ast_node(ac, AutoCast, expr);
  8573. return lb_build_expr(p, ac->expr);
  8574. case_end;
  8575. case_ast_node(ue, UnaryExpr, expr);
  8576. switch (ue->op.kind) {
  8577. case Token_And: {
  8578. Ast *ue_expr = unparen_expr(ue->expr);
  8579. if (ue_expr->kind == Ast_CompoundLit) {
  8580. lbValue v = lb_build_expr(p, ue->expr);
  8581. Type *type = v.type;
  8582. lbAddr addr = {};
  8583. if (p->is_startup) {
  8584. addr = lb_add_global_generated(p->module, type, v);
  8585. } else {
  8586. addr = lb_add_local_generated(p, type, false);
  8587. }
  8588. lb_addr_store(p, addr, v);
  8589. return addr.addr;
  8590. } else if (ue_expr->kind == Ast_TypeAssertion) {
  8591. GB_ASSERT(is_type_pointer(tv.type));
  8592. ast_node(ta, TypeAssertion, ue_expr);
  8593. TokenPos pos = ast_token(expr).pos;
  8594. Type *type = type_of_expr(ue_expr);
  8595. GB_ASSERT(!is_type_tuple(type));
  8596. lbValue e = lb_build_expr(p, ta->expr);
  8597. Type *t = type_deref(e.type);
  8598. if (is_type_union(t)) {
  8599. lbValue v = e;
  8600. if (!is_type_pointer(v.type)) {
  8601. v = lb_address_from_load_or_generate_local(p, v);
  8602. }
  8603. Type *src_type = type_deref(v.type);
  8604. Type *dst_type = type;
  8605. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  8606. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  8607. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  8608. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8609. args[0] = ok;
  8610. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8611. args[2] = lb_const_int(p->module, t_int, pos.line);
  8612. args[3] = lb_const_int(p->module, t_int, pos.column);
  8613. args[4] = lb_typeid(p->module, src_type);
  8614. args[5] = lb_typeid(p->module, dst_type);
  8615. lb_emit_runtime_call(p, "type_assertion_check", args);
  8616. lbValue data_ptr = v;
  8617. return lb_emit_conv(p, data_ptr, tv.type);
  8618. } else if (is_type_any(t)) {
  8619. lbValue v = e;
  8620. if (is_type_pointer(v.type)) {
  8621. v = lb_emit_load(p, v);
  8622. }
  8623. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  8624. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  8625. lbValue id = lb_typeid(p->module, type);
  8626. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  8627. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8628. args[0] = ok;
  8629. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8630. args[2] = lb_const_int(p->module, t_int, pos.line);
  8631. args[3] = lb_const_int(p->module, t_int, pos.column);
  8632. args[4] = any_id;
  8633. args[5] = id;
  8634. lb_emit_runtime_call(p, "type_assertion_check", args);
  8635. return lb_emit_conv(p, data_ptr, tv.type);
  8636. } else {
  8637. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  8638. }
  8639. }
  8640. return lb_build_addr_ptr(p, ue->expr);
  8641. }
  8642. default:
  8643. {
  8644. lbValue v = lb_build_expr(p, ue->expr);
  8645. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  8646. }
  8647. }
  8648. case_end;
  8649. case_ast_node(be, BinaryExpr, expr);
  8650. return lb_build_binary_expr(p, expr);
  8651. case_end;
  8652. case_ast_node(pl, ProcLit, expr);
  8653. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  8654. case_end;
  8655. case_ast_node(cl, CompoundLit, expr);
  8656. return lb_addr_load(p, lb_build_addr(p, expr));
  8657. case_end;
  8658. case_ast_node(ce, CallExpr, expr);
  8659. lbValue res = lb_build_call_expr(p, expr);
  8660. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  8661. GB_ASSERT(is_type_tuple(res.type));
  8662. GB_ASSERT(res.type->Tuple.variables.count == 2);
  8663. return lb_emit_struct_ev(p, res, 0);
  8664. }
  8665. return res;
  8666. case_end;
  8667. case_ast_node(se, SliceExpr, expr);
  8668. return lb_addr_load(p, lb_build_addr(p, expr));
  8669. case_end;
  8670. case_ast_node(ie, IndexExpr, expr);
  8671. return lb_addr_load(p, lb_build_addr(p, expr));
  8672. case_end;
  8673. case_ast_node(ia, InlineAsmExpr, expr);
  8674. Type *t = type_of_expr(expr);
  8675. GB_ASSERT(is_type_asm_proc(t));
  8676. String asm_string = {};
  8677. String constraints_string = {};
  8678. TypeAndValue tav;
  8679. tav = type_and_value_of_expr(ia->asm_string);
  8680. GB_ASSERT(is_type_string(tav.type));
  8681. GB_ASSERT(tav.value.kind == ExactValue_String);
  8682. asm_string = tav.value.value_string;
  8683. tav = type_and_value_of_expr(ia->constraints_string);
  8684. GB_ASSERT(is_type_string(tav.type));
  8685. GB_ASSERT(tav.value.kind == ExactValue_String);
  8686. constraints_string = tav.value.value_string;
  8687. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  8688. switch (ia->dialect) {
  8689. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  8690. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  8691. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  8692. default: GB_PANIC("Unhandled inline asm dialect"); break;
  8693. }
  8694. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  8695. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  8696. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  8697. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  8698. ia->has_side_effects, ia->is_align_stack, dialect
  8699. );
  8700. GB_ASSERT(the_asm != nullptr);
  8701. return {the_asm, t};
  8702. case_end;
  8703. }
  8704. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  8705. return {};
  8706. }
  8707. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  8708. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  8709. String name = e->token.string;
  8710. Entity *parent = e->using_parent;
  8711. Selection sel = lookup_field(parent->type, name, false);
  8712. GB_ASSERT(sel.entity != nullptr);
  8713. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  8714. lbValue v = {};
  8715. if (pv != nullptr) {
  8716. v = *pv;
  8717. } else {
  8718. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  8719. v = lb_build_addr_ptr(p, e->using_expr);
  8720. }
  8721. GB_ASSERT(v.value != nullptr);
  8722. GB_ASSERT(parent->type == type_deref(v.type));
  8723. return lb_emit_deep_field_gep(p, v, sel);
  8724. }
  8725. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  8726. GB_ASSERT(e != nullptr);
  8727. if (e->kind == Entity_Constant) {
  8728. Type *t = default_type(type_of_expr(expr));
  8729. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  8730. lbAddr g = lb_add_global_generated(p->module, t, v);
  8731. return g;
  8732. }
  8733. lbValue v = {};
  8734. lbValue *found = map_get(&p->module->values, hash_entity(e));
  8735. if (found) {
  8736. v = *found;
  8737. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  8738. // NOTE(bill): Calculate the using variable every time
  8739. v = lb_get_using_variable(p, e);
  8740. }
  8741. if (v.value == nullptr) {
  8742. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  8743. LIT(p->name),
  8744. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  8745. GB_PANIC("Unknown value");
  8746. }
  8747. return lb_addr(v);
  8748. }
  8749. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  8750. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  8751. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  8752. map_type = base_type(map_type);
  8753. GB_ASSERT(map_type->kind == Type_Map);
  8754. Type *key_type = map_type->Map.key;
  8755. Type *val_type = map_type->Map.value;
  8756. // NOTE(bill): Removes unnecessary allocation if split gep
  8757. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  8758. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  8759. lb_emit_store(p, gep0, m);
  8760. i64 entry_size = type_size_of (map_type->Map.entry_type);
  8761. i64 entry_align = type_align_of (map_type->Map.entry_type);
  8762. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  8763. i64 key_size = type_size_of (map_type->Map.key);
  8764. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  8765. i64 value_size = type_size_of (map_type->Map.value);
  8766. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  8767. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  8768. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  8769. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  8770. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  8771. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  8772. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  8773. return lb_addr_load(p, h);
  8774. }
  8775. lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type) {
  8776. Type *hash_type = t_u64;
  8777. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  8778. lbValue vp = lb_addr_get_ptr(p, v);
  8779. Type *t = base_type(key.type);
  8780. key = lb_emit_conv(p, key, key_type);
  8781. if (is_type_string(t)) {
  8782. lbValue str = lb_emit_conv(p, key, t_string);
  8783. lbValue hashed_str = {};
  8784. if (lb_is_const(str)) {
  8785. String v = lb_get_const_string(p->module, str);
  8786. u64 hs = fnv64a(v.text, v.len);
  8787. if (build_context.word_size == 4) {
  8788. hs &= 0xffffffff;
  8789. }
  8790. hashed_str = lb_const_int(p->module, t_uintptr, hs);
  8791. } else {
  8792. auto args = array_make<lbValue>(permanent_allocator(), 1);
  8793. args[0] = str;
  8794. hashed_str = lb_emit_runtime_call(p, "default_hash_string", args);
  8795. }
  8796. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_str);
  8797. } else {
  8798. i64 sz = type_size_of(t);
  8799. GB_ASSERT(sz <= 8);
  8800. if (sz != 0) {
  8801. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8802. args[0] = lb_address_from_load_or_generate_local(p, key);
  8803. args[1] = lb_const_int(p->module, t_int, sz);
  8804. lbValue hash = lb_emit_runtime_call(p, "default_hash_ptr", args);
  8805. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hash);
  8806. }
  8807. }
  8808. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  8809. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  8810. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  8811. return lb_addr_load(p, v);
  8812. }
  8813. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  8814. lbValue map_key, lbValue map_value, Ast *node) {
  8815. map_type = base_type(map_type);
  8816. GB_ASSERT(map_type->kind == Type_Map);
  8817. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  8818. lbValue key = lb_gen_map_key(p, map_key, map_type->Map.key);
  8819. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  8820. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  8821. lb_addr_store(p, value_addr, v);
  8822. auto args = array_make<lbValue>(permanent_allocator(), 4);
  8823. args[0] = h;
  8824. args[1] = key;
  8825. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  8826. args[3] = lb_emit_source_code_location(p, node);
  8827. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  8828. }
  8829. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  8830. expr = unparen_expr(expr);
  8831. switch (expr->kind) {
  8832. case_ast_node(i, Implicit, expr);
  8833. lbAddr v = {};
  8834. switch (i->kind) {
  8835. case Token_context:
  8836. v = lb_find_or_generate_context_ptr(p);
  8837. break;
  8838. }
  8839. GB_ASSERT(v.addr.value != nullptr);
  8840. return v;
  8841. case_end;
  8842. case_ast_node(i, Ident, expr);
  8843. if (is_blank_ident(expr)) {
  8844. lbAddr val = {};
  8845. return val;
  8846. }
  8847. String name = i->token.string;
  8848. Entity *e = entity_of_node(expr);
  8849. return lb_build_addr_from_entity(p, e, expr);
  8850. case_end;
  8851. case_ast_node(se, SelectorExpr, expr);
  8852. Ast *sel = unparen_expr(se->selector);
  8853. if (sel->kind == Ast_Ident) {
  8854. String selector = sel->Ident.token.string;
  8855. TypeAndValue tav = type_and_value_of_expr(se->expr);
  8856. if (tav.mode == Addressing_Invalid) {
  8857. // NOTE(bill): Imports
  8858. Entity *imp = entity_of_node(se->expr);
  8859. if (imp != nullptr) {
  8860. GB_ASSERT(imp->kind == Entity_ImportName);
  8861. }
  8862. return lb_build_addr(p, unparen_expr(se->selector));
  8863. }
  8864. Type *type = base_type(tav.type);
  8865. if (tav.mode == Addressing_Type) { // Addressing_Type
  8866. Selection sel = lookup_field(type, selector, true);
  8867. Entity *e = sel.entity;
  8868. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  8869. GB_ASSERT(e->flags & EntityFlag_TypeField);
  8870. String name = e->token.string;
  8871. /*if (name == "names") {
  8872. lbValue ti_ptr = lb_type_info(m, type);
  8873. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  8874. lbValue names_ptr = nullptr;
  8875. if (is_type_enum(type)) {
  8876. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  8877. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  8878. } else if (type->kind == Type_Struct) {
  8879. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  8880. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  8881. }
  8882. return ir_addr(names_ptr);
  8883. } else */{
  8884. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  8885. }
  8886. GB_PANIC("Unreachable");
  8887. }
  8888. Selection sel = lookup_field(type, selector, false);
  8889. GB_ASSERT(sel.entity != nullptr);
  8890. if (sel.entity->type->kind == Type_BitFieldValue) {
  8891. lbAddr addr = lb_build_addr(p, se->expr);
  8892. Type *bft = type_deref(lb_addr_type(addr));
  8893. if (sel.index.count == 1) {
  8894. GB_ASSERT(is_type_bit_field(bft));
  8895. i32 index = sel.index[0];
  8896. return lb_addr_bit_field(lb_addr_get_ptr(p, addr), index);
  8897. } else {
  8898. Selection s = sel;
  8899. s.index.count--;
  8900. i32 index = s.index[s.index.count-1];
  8901. lbValue a = lb_addr_get_ptr(p, addr);
  8902. a = lb_emit_deep_field_gep(p, a, s);
  8903. return lb_addr_bit_field(a, index);
  8904. }
  8905. } else {
  8906. lbAddr addr = lb_build_addr(p, se->expr);
  8907. if (addr.kind == lbAddr_Map) {
  8908. lbValue v = lb_addr_load(p, addr);
  8909. lbValue a = lb_address_from_load_or_generate_local(p, v);
  8910. a = lb_emit_deep_field_gep(p, a, sel);
  8911. return lb_addr(a);
  8912. } else if (addr.kind == lbAddr_Context) {
  8913. GB_ASSERT(sel.index.count > 0);
  8914. if (addr.ctx.sel.index.count >= 0) {
  8915. sel = selection_combine(addr.ctx.sel, sel);
  8916. }
  8917. addr.ctx.sel = sel;
  8918. addr.kind = lbAddr_Context;
  8919. return addr;
  8920. } else if (addr.kind == lbAddr_SoaVariable) {
  8921. lbValue index = addr.soa.index;
  8922. i32 first_index = sel.index[0];
  8923. Selection sub_sel = sel;
  8924. sub_sel.index.data += 1;
  8925. sub_sel.index.count -= 1;
  8926. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  8927. Type *t = base_type(type_deref(addr.addr.type));
  8928. GB_ASSERT(is_type_soa_struct(t));
  8929. // TODO(bill): Bounds check
  8930. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  8931. lbValue len = lb_soa_struct_len(p, addr.addr);
  8932. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  8933. }
  8934. lbValue item = {};
  8935. if (t->Struct.soa_kind == StructSoa_Fixed) {
  8936. item = lb_emit_array_ep(p, arr, index);
  8937. } else {
  8938. item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index));
  8939. }
  8940. if (sub_sel.index.count > 0) {
  8941. item = lb_emit_deep_field_gep(p, item, sub_sel);
  8942. }
  8943. return lb_addr(item);
  8944. }
  8945. lbValue a = lb_addr_get_ptr(p, addr);
  8946. a = lb_emit_deep_field_gep(p, a, sel);
  8947. return lb_addr(a);
  8948. }
  8949. } else {
  8950. GB_PANIC("Unsupported selector expression");
  8951. }
  8952. case_end;
  8953. case_ast_node(se, SelectorCallExpr, expr);
  8954. GB_ASSERT(se->modified_call);
  8955. TypeAndValue tav = type_and_value_of_expr(expr);
  8956. GB_ASSERT(tav.mode != Addressing_Invalid);
  8957. return lb_build_addr(p, se->call);
  8958. case_end;
  8959. case_ast_node(ta, TypeAssertion, expr);
  8960. TokenPos pos = ast_token(expr).pos;
  8961. lbValue e = lb_build_expr(p, ta->expr);
  8962. Type *t = type_deref(e.type);
  8963. if (is_type_union(t)) {
  8964. Type *type = type_of_expr(expr);
  8965. lbAddr v = lb_add_local_generated(p, type, false);
  8966. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  8967. return v;
  8968. } else if (is_type_any(t)) {
  8969. Type *type = type_of_expr(expr);
  8970. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  8971. } else {
  8972. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8973. }
  8974. case_end;
  8975. case_ast_node(ue, UnaryExpr, expr);
  8976. switch (ue->op.kind) {
  8977. case Token_And: {
  8978. return lb_build_addr(p, ue->expr);
  8979. }
  8980. default:
  8981. GB_PANIC("Invalid unary expression for lb_build_addr");
  8982. }
  8983. case_end;
  8984. case_ast_node(be, BinaryExpr, expr);
  8985. lbValue v = lb_build_expr(p, expr);
  8986. Type *t = v.type;
  8987. if (is_type_pointer(t)) {
  8988. return lb_addr(v);
  8989. }
  8990. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  8991. case_end;
  8992. case_ast_node(ie, IndexExpr, expr);
  8993. Type *t = base_type(type_of_expr(ie->expr));
  8994. bool deref = is_type_pointer(t);
  8995. t = base_type(type_deref(t));
  8996. if (is_type_soa_struct(t)) {
  8997. // SOA STRUCTURES!!!!
  8998. lbValue val = lb_build_addr_ptr(p, ie->expr);
  8999. if (deref) {
  9000. val = lb_emit_load(p, val);
  9001. }
  9002. lbValue index = lb_build_expr(p, ie->index);
  9003. return lb_addr_soa_variable(val, index, ie->index);
  9004. }
  9005. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  9006. // SOA Structures for slices/dynamic arrays
  9007. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  9008. lbValue field = lb_build_expr(p, ie->expr);
  9009. lbValue index = lb_build_expr(p, ie->index);
  9010. if (!build_context.no_bounds_check) {
  9011. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  9012. // GB_ASSERT(LLVMIsALoadInst(field.value));
  9013. // lbValue a = {};
  9014. // a.value = LLVMGetOperand(field.value, 0);
  9015. // a.type = alloc_type_pointer(field.type);
  9016. // irInstr *b = &a->Instr;
  9017. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  9018. // lbValue base_struct = b->StructElementPtr.address;
  9019. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  9020. // lbValue len = ir_soa_struct_len(p, base_struct);
  9021. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9022. }
  9023. lbValue val = lb_emit_ptr_offset(p, field, index);
  9024. return lb_addr(val);
  9025. }
  9026. if (!is_type_indexable(t)) {
  9027. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9028. if (found != nullptr) {
  9029. if (found->kind == TypeAtomOp_index_get) {
  9030. return lb_build_addr(p, found->node);
  9031. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  9032. return lb_addr(lb_build_expr(p, found->node));
  9033. } else if (found->kind == TypeAtomOp_index_set) {
  9034. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  9035. if (deref) {
  9036. ptr = lb_emit_load(p, ptr);
  9037. }
  9038. lbAddr addr = {lbAddr_AtomOp_index_set};
  9039. addr.addr = ptr;
  9040. addr.index_set.index = lb_build_expr(p, ie->index);
  9041. addr.index_set.node = found->node;
  9042. return addr;
  9043. }
  9044. }
  9045. }
  9046. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  9047. if (is_type_map(t)) {
  9048. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  9049. if (deref) {
  9050. map_val = lb_emit_load(p, map_val);
  9051. }
  9052. lbValue key = lb_build_expr(p, ie->index);
  9053. key = lb_emit_conv(p, key, t->Map.key);
  9054. Type *result_type = type_of_expr(expr);
  9055. return lb_addr_map(map_val, key, t, result_type);
  9056. }
  9057. switch (t->kind) {
  9058. case Type_Array: {
  9059. lbValue array = {};
  9060. array = lb_build_addr_ptr(p, ie->expr);
  9061. if (deref) {
  9062. array = lb_emit_load(p, array);
  9063. }
  9064. lbValue index = lb_build_expr(p, ie->index);
  9065. index = lb_emit_conv(p, index, t_int);
  9066. lbValue elem = lb_emit_array_ep(p, array, index);
  9067. auto index_tv = type_and_value_of_expr(ie->index);
  9068. if (index_tv.mode != Addressing_Constant) {
  9069. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  9070. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9071. }
  9072. return lb_addr(elem);
  9073. }
  9074. case Type_EnumeratedArray: {
  9075. lbValue array = {};
  9076. array = lb_build_addr_ptr(p, ie->expr);
  9077. if (deref) {
  9078. array = lb_emit_load(p, array);
  9079. }
  9080. Type *index_type = t->EnumeratedArray.index;
  9081. auto index_tv = type_and_value_of_expr(ie->index);
  9082. lbValue index = {};
  9083. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  9084. if (index_tv.mode == Addressing_Constant) {
  9085. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  9086. index = lb_const_value(p->module, index_type, idx);
  9087. } else {
  9088. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9089. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  9090. }
  9091. } else {
  9092. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9093. }
  9094. lbValue elem = lb_emit_array_ep(p, array, index);
  9095. if (index_tv.mode != Addressing_Constant) {
  9096. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  9097. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9098. }
  9099. return lb_addr(elem);
  9100. }
  9101. case Type_Slice: {
  9102. lbValue slice = {};
  9103. slice = lb_build_expr(p, ie->expr);
  9104. if (deref) {
  9105. slice = lb_emit_load(p, slice);
  9106. }
  9107. lbValue elem = lb_slice_elem(p, slice);
  9108. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9109. lbValue len = lb_slice_len(p, slice);
  9110. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9111. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9112. return lb_addr(v);
  9113. }
  9114. case Type_RelativeSlice: {
  9115. lbAddr slice_addr = {};
  9116. if (deref) {
  9117. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  9118. } else {
  9119. slice_addr = lb_build_addr(p, ie->expr);
  9120. }
  9121. lbValue slice = lb_addr_load(p, slice_addr);
  9122. lbValue elem = lb_slice_elem(p, slice);
  9123. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9124. lbValue len = lb_slice_len(p, slice);
  9125. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9126. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9127. return lb_addr(v);
  9128. }
  9129. case Type_DynamicArray: {
  9130. lbValue dynamic_array = {};
  9131. dynamic_array = lb_build_expr(p, ie->expr);
  9132. if (deref) {
  9133. dynamic_array = lb_emit_load(p, dynamic_array);
  9134. }
  9135. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  9136. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  9137. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9138. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9139. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9140. return lb_addr(v);
  9141. }
  9142. case Type_Basic: { // Basic_string
  9143. lbValue str;
  9144. lbValue elem;
  9145. lbValue len;
  9146. lbValue index;
  9147. str = lb_build_expr(p, ie->expr);
  9148. if (deref) {
  9149. str = lb_emit_load(p, str);
  9150. }
  9151. elem = lb_string_elem(p, str);
  9152. len = lb_string_len(p, str);
  9153. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9154. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9155. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  9156. }
  9157. }
  9158. case_end;
  9159. case_ast_node(se, SliceExpr, expr);
  9160. lbValue low = lb_const_int(p->module, t_int, 0);
  9161. lbValue high = {};
  9162. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  9163. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  9164. bool no_indices = se->low == nullptr && se->high == nullptr;
  9165. {
  9166. Type *type = base_type(type_of_expr(se->expr));
  9167. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  9168. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  9169. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  9170. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9171. if (found) {
  9172. lbValue base = lb_build_expr(p, found->node);
  9173. Type *slice_type = base.type;
  9174. lbValue len = lb_slice_len(p, base);
  9175. if (high.value == nullptr) high = len;
  9176. if (!no_indices) {
  9177. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9178. }
  9179. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9180. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9181. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9182. lb_fill_slice(p, slice, elem, new_len);
  9183. return slice;
  9184. }
  9185. }
  9186. }
  9187. }
  9188. lbAddr addr = lb_build_addr(p, se->expr);
  9189. lbValue base = lb_addr_load(p, addr);
  9190. Type *type = base_type(base.type);
  9191. if (is_type_pointer(type)) {
  9192. type = base_type(type_deref(type));
  9193. addr = lb_addr(base);
  9194. base = lb_addr_load(p, addr);
  9195. }
  9196. switch (type->kind) {
  9197. case Type_Slice: {
  9198. Type *slice_type = type;
  9199. lbValue len = lb_slice_len(p, base);
  9200. if (high.value == nullptr) high = len;
  9201. if (!no_indices) {
  9202. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9203. }
  9204. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9205. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9206. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9207. lb_fill_slice(p, slice, elem, new_len);
  9208. return slice;
  9209. }
  9210. case Type_RelativeSlice:
  9211. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  9212. break;
  9213. case Type_DynamicArray: {
  9214. Type *elem_type = type->DynamicArray.elem;
  9215. Type *slice_type = alloc_type_slice(elem_type);
  9216. lbValue len = lb_dynamic_array_len(p, base);
  9217. if (high.value == nullptr) high = len;
  9218. if (!no_indices) {
  9219. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9220. }
  9221. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  9222. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9223. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9224. lb_fill_slice(p, slice, elem, new_len);
  9225. return slice;
  9226. }
  9227. case Type_Array: {
  9228. Type *slice_type = alloc_type_slice(type->Array.elem);
  9229. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  9230. if (high.value == nullptr) high = len;
  9231. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  9232. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  9233. if (!low_const || !high_const) {
  9234. if (!no_indices) {
  9235. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9236. }
  9237. }
  9238. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  9239. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9240. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9241. lb_fill_slice(p, slice, elem, new_len);
  9242. return slice;
  9243. }
  9244. case Type_Basic: {
  9245. GB_ASSERT(type == t_string);
  9246. lbValue len = lb_string_len(p, base);
  9247. if (high.value == nullptr) high = len;
  9248. if (!no_indices) {
  9249. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9250. }
  9251. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  9252. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9253. lbAddr str = lb_add_local_generated(p, t_string, false);
  9254. lb_fill_string(p, str, elem, new_len);
  9255. return str;
  9256. }
  9257. case Type_Struct:
  9258. if (is_type_soa_struct(type)) {
  9259. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  9260. if (high.value == nullptr) high = len;
  9261. if (!no_indices) {
  9262. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9263. }
  9264. #if 1
  9265. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  9266. if (type->Struct.soa_kind == StructSoa_Fixed) {
  9267. i32 field_count = cast(i32)type->Struct.fields.count;
  9268. for (i32 i = 0; i < field_count; i++) {
  9269. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9270. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  9271. field_src = lb_emit_array_ep(p, field_src, low);
  9272. lb_emit_store(p, field_dst, field_src);
  9273. }
  9274. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9275. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9276. lb_emit_store(p, len_dst, new_len);
  9277. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  9278. if (no_indices) {
  9279. lb_addr_store(p, dst, base);
  9280. } else {
  9281. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  9282. for (i32 i = 0; i < field_count; i++) {
  9283. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9284. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9285. field_src = lb_emit_ptr_offset(p, field_src, low);
  9286. lb_emit_store(p, field_dst, field_src);
  9287. }
  9288. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9289. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9290. lb_emit_store(p, len_dst, new_len);
  9291. }
  9292. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  9293. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  9294. for (i32 i = 0; i < field_count; i++) {
  9295. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9296. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9297. field_src = lb_emit_ptr_offset(p, field_src, low);
  9298. lb_emit_store(p, field_dst, field_src);
  9299. }
  9300. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9301. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9302. lb_emit_store(p, len_dst, new_len);
  9303. }
  9304. return dst;
  9305. #endif
  9306. }
  9307. break;
  9308. }
  9309. GB_PANIC("Unknown slicable type");
  9310. case_end;
  9311. case_ast_node(de, DerefExpr, expr);
  9312. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  9313. lbAddr addr = lb_build_addr(p, de->expr);
  9314. addr.relative.deref = true;
  9315. return addr;
  9316. }
  9317. lbValue addr = lb_build_expr(p, de->expr);
  9318. return lb_addr(addr);
  9319. case_end;
  9320. case_ast_node(ce, CallExpr, expr);
  9321. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  9322. lbValue e = lb_build_expr(p, expr);
  9323. lbAddr v = lb_add_local_generated(p, e.type, false);
  9324. lb_addr_store(p, v, e);
  9325. return v;
  9326. case_end;
  9327. case_ast_node(cl, CompoundLit, expr);
  9328. Type *type = type_of_expr(expr);
  9329. Type *bt = base_type(type);
  9330. lbAddr v = lb_add_local_generated(p, type, true);
  9331. Type *et = nullptr;
  9332. switch (bt->kind) {
  9333. case Type_Array: et = bt->Array.elem; break;
  9334. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  9335. case Type_Slice: et = bt->Slice.elem; break;
  9336. case Type_BitSet: et = bt->BitSet.elem; break;
  9337. case Type_SimdVector: et = bt->SimdVector.elem; break;
  9338. }
  9339. String proc_name = {};
  9340. if (p->entity) {
  9341. proc_name = p->entity->token.string;
  9342. }
  9343. TokenPos pos = ast_token(expr).pos;
  9344. switch (bt->kind) {
  9345. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  9346. case Type_Struct: {
  9347. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  9348. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  9349. bool is_raw_union = is_type_raw_union(bt);
  9350. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  9351. TypeStruct *st = &bt->Struct;
  9352. if (cl->elems.count > 0) {
  9353. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9354. for_array(field_index, cl->elems) {
  9355. Ast *elem = cl->elems[field_index];
  9356. lbValue field_expr = {};
  9357. Entity *field = nullptr;
  9358. isize index = field_index;
  9359. if (elem->kind == Ast_FieldValue) {
  9360. ast_node(fv, FieldValue, elem);
  9361. String name = fv->field->Ident.token.string;
  9362. Selection sel = lookup_field(bt, name, false);
  9363. index = sel.index[0];
  9364. elem = fv->value;
  9365. TypeAndValue tav = type_and_value_of_expr(elem);
  9366. } else {
  9367. TypeAndValue tav = type_and_value_of_expr(elem);
  9368. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  9369. index = sel.index[0];
  9370. }
  9371. field = st->fields[index];
  9372. Type *ft = field->type;
  9373. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  9374. continue;
  9375. }
  9376. field_expr = lb_build_expr(p, elem);
  9377. Type *fet = field_expr.type;
  9378. GB_ASSERT(fet->kind != Type_Tuple);
  9379. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  9380. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  9381. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  9382. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9383. lb_emit_store_union_variant(p, gep, field_expr, fet);
  9384. } else {
  9385. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9386. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9387. lb_emit_store(p, gep, fv);
  9388. }
  9389. }
  9390. }
  9391. break;
  9392. }
  9393. case Type_Map: {
  9394. if (cl->elems.count == 0) {
  9395. break;
  9396. }
  9397. {
  9398. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9399. args[0] = lb_gen_map_header(p, v.addr, type);
  9400. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  9401. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  9402. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  9403. }
  9404. for_array(field_index, cl->elems) {
  9405. Ast *elem = cl->elems[field_index];
  9406. ast_node(fv, FieldValue, elem);
  9407. lbValue key = lb_build_expr(p, fv->field);
  9408. lbValue value = lb_build_expr(p, fv->value);
  9409. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  9410. }
  9411. break;
  9412. }
  9413. case Type_Array: {
  9414. if (cl->elems.count > 0) {
  9415. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9416. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9417. // NOTE(bill): Separate value, gep, store into their own chunks
  9418. for_array(i, cl->elems) {
  9419. Ast *elem = cl->elems[i];
  9420. if (elem->kind == Ast_FieldValue) {
  9421. ast_node(fv, FieldValue, elem);
  9422. if (lb_is_elem_const(fv->value, et)) {
  9423. continue;
  9424. }
  9425. if (is_ast_range(fv->field)) {
  9426. ast_node(ie, BinaryExpr, fv->field);
  9427. TypeAndValue lo_tav = ie->left->tav;
  9428. TypeAndValue hi_tav = ie->right->tav;
  9429. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9430. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9431. TokenKind op = ie->op.kind;
  9432. i64 lo = exact_value_to_i64(lo_tav.value);
  9433. i64 hi = exact_value_to_i64(hi_tav.value);
  9434. if (op == Token_Ellipsis) {
  9435. hi += 1;
  9436. }
  9437. lbValue value = lb_build_expr(p, fv->value);
  9438. for (i64 k = lo; k < hi; k++) {
  9439. lbCompoundLitElemTempData data = {};
  9440. data.value = value;
  9441. data.elem_index = cast(i32)k;
  9442. array_add(&temp_data, data);
  9443. }
  9444. } else {
  9445. auto tav = fv->field->tav;
  9446. GB_ASSERT(tav.mode == Addressing_Constant);
  9447. i64 index = exact_value_to_i64(tav.value);
  9448. lbValue value = lb_build_expr(p, fv->value);
  9449. lbCompoundLitElemTempData data = {};
  9450. data.value = lb_emit_conv(p, value, et);
  9451. data.expr = fv->value;
  9452. data.elem_index = cast(i32)index;
  9453. array_add(&temp_data, data);
  9454. }
  9455. } else {
  9456. if (lb_is_elem_const(elem, et)) {
  9457. continue;
  9458. }
  9459. lbCompoundLitElemTempData data = {};
  9460. data.expr = elem;
  9461. data.elem_index = cast(i32)i;
  9462. array_add(&temp_data, data);
  9463. }
  9464. }
  9465. for_array(i, temp_data) {
  9466. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  9467. }
  9468. for_array(i, temp_data) {
  9469. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9470. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9471. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9472. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9473. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9474. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9475. lbValue field_expr = temp_data[i].value;
  9476. Ast *expr = temp_data[i].expr;
  9477. p->return_ptr_hint_value = temp_data[i].gep;
  9478. p->return_ptr_hint_ast = unparen_expr(expr);
  9479. if (field_expr.value == nullptr) {
  9480. field_expr = lb_build_expr(p, expr);
  9481. }
  9482. Type *t = field_expr.type;
  9483. GB_ASSERT(t->kind != Type_Tuple);
  9484. lbValue ev = lb_emit_conv(p, field_expr, et);
  9485. if (!p->return_ptr_hint_used) {
  9486. temp_data[i].value = ev;
  9487. }
  9488. }
  9489. for_array(i, temp_data) {
  9490. if (temp_data[i].value.value != nullptr) {
  9491. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9492. }
  9493. }
  9494. }
  9495. break;
  9496. }
  9497. case Type_EnumeratedArray: {
  9498. if (cl->elems.count > 0) {
  9499. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9500. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9501. // NOTE(bill): Separate value, gep, store into their own chunks
  9502. for_array(i, cl->elems) {
  9503. Ast *elem = cl->elems[i];
  9504. if (elem->kind == Ast_FieldValue) {
  9505. ast_node(fv, FieldValue, elem);
  9506. if (lb_is_elem_const(fv->value, et)) {
  9507. continue;
  9508. }
  9509. if (is_ast_range(fv->field)) {
  9510. ast_node(ie, BinaryExpr, fv->field);
  9511. TypeAndValue lo_tav = ie->left->tav;
  9512. TypeAndValue hi_tav = ie->right->tav;
  9513. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9514. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9515. TokenKind op = ie->op.kind;
  9516. i64 lo = exact_value_to_i64(lo_tav.value);
  9517. i64 hi = exact_value_to_i64(hi_tav.value);
  9518. if (op == Token_Ellipsis) {
  9519. hi += 1;
  9520. }
  9521. lbValue value = lb_build_expr(p, fv->value);
  9522. for (i64 k = lo; k < hi; k++) {
  9523. lbCompoundLitElemTempData data = {};
  9524. data.value = value;
  9525. data.elem_index = cast(i32)k;
  9526. array_add(&temp_data, data);
  9527. }
  9528. } else {
  9529. auto tav = fv->field->tav;
  9530. GB_ASSERT(tav.mode == Addressing_Constant);
  9531. i64 index = exact_value_to_i64(tav.value);
  9532. lbValue value = lb_build_expr(p, fv->value);
  9533. lbCompoundLitElemTempData data = {};
  9534. data.value = lb_emit_conv(p, value, et);
  9535. data.expr = fv->value;
  9536. data.elem_index = cast(i32)index;
  9537. array_add(&temp_data, data);
  9538. }
  9539. } else {
  9540. if (lb_is_elem_const(elem, et)) {
  9541. continue;
  9542. }
  9543. lbCompoundLitElemTempData data = {};
  9544. data.expr = elem;
  9545. data.elem_index = cast(i32)i;
  9546. array_add(&temp_data, data);
  9547. }
  9548. }
  9549. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  9550. for_array(i, temp_data) {
  9551. i32 index = temp_data[i].elem_index - index_offset;
  9552. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  9553. }
  9554. for_array(i, temp_data) {
  9555. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9556. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9557. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9558. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9559. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9560. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9561. lbValue field_expr = temp_data[i].value;
  9562. Ast *expr = temp_data[i].expr;
  9563. p->return_ptr_hint_value = temp_data[i].gep;
  9564. p->return_ptr_hint_ast = unparen_expr(expr);
  9565. if (field_expr.value == nullptr) {
  9566. field_expr = lb_build_expr(p, expr);
  9567. }
  9568. Type *t = field_expr.type;
  9569. GB_ASSERT(t->kind != Type_Tuple);
  9570. lbValue ev = lb_emit_conv(p, field_expr, et);
  9571. if (!p->return_ptr_hint_used) {
  9572. temp_data[i].value = ev;
  9573. }
  9574. }
  9575. for_array(i, temp_data) {
  9576. if (temp_data[i].value.value != nullptr) {
  9577. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9578. }
  9579. }
  9580. }
  9581. break;
  9582. }
  9583. case Type_Slice: {
  9584. if (cl->elems.count > 0) {
  9585. Type *elem_type = bt->Slice.elem;
  9586. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  9587. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  9588. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  9589. lbValue data = lb_slice_elem(p, slice);
  9590. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9591. for_array(i, cl->elems) {
  9592. Ast *elem = cl->elems[i];
  9593. if (elem->kind == Ast_FieldValue) {
  9594. ast_node(fv, FieldValue, elem);
  9595. if (lb_is_elem_const(fv->value, et)) {
  9596. continue;
  9597. }
  9598. if (is_ast_range(fv->field)) {
  9599. ast_node(ie, BinaryExpr, fv->field);
  9600. TypeAndValue lo_tav = ie->left->tav;
  9601. TypeAndValue hi_tav = ie->right->tav;
  9602. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9603. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9604. TokenKind op = ie->op.kind;
  9605. i64 lo = exact_value_to_i64(lo_tav.value);
  9606. i64 hi = exact_value_to_i64(hi_tav.value);
  9607. if (op == Token_Ellipsis) {
  9608. hi += 1;
  9609. }
  9610. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9611. for (i64 k = lo; k < hi; k++) {
  9612. lbCompoundLitElemTempData data = {};
  9613. data.value = value;
  9614. data.elem_index = cast(i32)k;
  9615. array_add(&temp_data, data);
  9616. }
  9617. } else {
  9618. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9619. i64 index = exact_value_to_i64(fv->field->tav.value);
  9620. lbValue field_expr = lb_build_expr(p, fv->value);
  9621. GB_ASSERT(!is_type_tuple(field_expr.type));
  9622. lbValue ev = lb_emit_conv(p, field_expr, et);
  9623. lbCompoundLitElemTempData data = {};
  9624. data.value = ev;
  9625. data.elem_index = cast(i32)index;
  9626. array_add(&temp_data, data);
  9627. }
  9628. } else {
  9629. if (lb_is_elem_const(elem, et)) {
  9630. continue;
  9631. }
  9632. lbValue field_expr = lb_build_expr(p, elem);
  9633. GB_ASSERT(!is_type_tuple(field_expr.type));
  9634. lbValue ev = lb_emit_conv(p, field_expr, et);
  9635. lbCompoundLitElemTempData data = {};
  9636. data.value = ev;
  9637. data.elem_index = cast(i32)i;
  9638. array_add(&temp_data, data);
  9639. }
  9640. }
  9641. for_array(i, temp_data) {
  9642. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  9643. }
  9644. for_array(i, temp_data) {
  9645. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9646. }
  9647. {
  9648. lbValue count = {};
  9649. count.type = t_int;
  9650. if (lb_is_const(slice)) {
  9651. unsigned indices[1] = {1};
  9652. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  9653. } else {
  9654. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  9655. }
  9656. lb_fill_slice(p, v, data, count);
  9657. }
  9658. }
  9659. break;
  9660. }
  9661. case Type_DynamicArray: {
  9662. if (cl->elems.count == 0) {
  9663. break;
  9664. }
  9665. Type *et = bt->DynamicArray.elem;
  9666. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  9667. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  9668. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  9669. {
  9670. auto args = array_make<lbValue>(permanent_allocator(), 5);
  9671. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  9672. args[1] = size;
  9673. args[2] = align;
  9674. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  9675. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  9676. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  9677. }
  9678. lbValue items = lb_generate_local_array(p, et, item_count);
  9679. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  9680. for_array(i, cl->elems) {
  9681. Ast *elem = cl->elems[i];
  9682. if (elem->kind == Ast_FieldValue) {
  9683. ast_node(fv, FieldValue, elem);
  9684. if (is_ast_range(fv->field)) {
  9685. ast_node(ie, BinaryExpr, fv->field);
  9686. TypeAndValue lo_tav = ie->left->tav;
  9687. TypeAndValue hi_tav = ie->right->tav;
  9688. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9689. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9690. TokenKind op = ie->op.kind;
  9691. i64 lo = exact_value_to_i64(lo_tav.value);
  9692. i64 hi = exact_value_to_i64(hi_tav.value);
  9693. if (op == Token_Ellipsis) {
  9694. hi += 1;
  9695. }
  9696. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9697. for (i64 k = lo; k < hi; k++) {
  9698. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  9699. lb_emit_store(p, ep, value);
  9700. }
  9701. } else {
  9702. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9703. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  9704. lbValue ev = lb_build_expr(p, fv->value);
  9705. lbValue value = lb_emit_conv(p, ev, et);
  9706. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  9707. lb_emit_store(p, ep, value);
  9708. }
  9709. } else {
  9710. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  9711. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  9712. lb_emit_store(p, ep, value);
  9713. }
  9714. }
  9715. {
  9716. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9717. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  9718. args[1] = size;
  9719. args[2] = align;
  9720. args[3] = lb_emit_conv(p, items, t_rawptr);
  9721. args[4] = lb_const_int(p->module, t_int, item_count);
  9722. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  9723. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  9724. }
  9725. break;
  9726. }
  9727. case Type_Basic: {
  9728. GB_ASSERT(is_type_any(bt));
  9729. if (cl->elems.count > 0) {
  9730. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9731. String field_names[2] = {
  9732. str_lit("data"),
  9733. str_lit("id"),
  9734. };
  9735. Type *field_types[2] = {
  9736. t_rawptr,
  9737. t_typeid,
  9738. };
  9739. for_array(field_index, cl->elems) {
  9740. Ast *elem = cl->elems[field_index];
  9741. lbValue field_expr = {};
  9742. isize index = field_index;
  9743. if (elem->kind == Ast_FieldValue) {
  9744. ast_node(fv, FieldValue, elem);
  9745. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  9746. index = sel.index[0];
  9747. elem = fv->value;
  9748. } else {
  9749. TypeAndValue tav = type_and_value_of_expr(elem);
  9750. Selection sel = lookup_field(bt, field_names[field_index], false);
  9751. index = sel.index[0];
  9752. }
  9753. field_expr = lb_build_expr(p, elem);
  9754. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  9755. Type *ft = field_types[index];
  9756. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9757. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9758. lb_emit_store(p, gep, fv);
  9759. }
  9760. }
  9761. break;
  9762. }
  9763. case Type_BitSet: {
  9764. i64 sz = type_size_of(type);
  9765. if (cl->elems.count > 0 && sz > 0) {
  9766. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9767. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  9768. for_array(i, cl->elems) {
  9769. Ast *elem = cl->elems[i];
  9770. GB_ASSERT(elem->kind != Ast_FieldValue);
  9771. if (lb_is_elem_const(elem, et)) {
  9772. continue;
  9773. }
  9774. lbValue expr = lb_build_expr(p, elem);
  9775. GB_ASSERT(expr.type->kind != Type_Tuple);
  9776. Type *it = bit_set_to_int(bt);
  9777. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  9778. lbValue e = lb_emit_conv(p, expr, it);
  9779. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  9780. e = lb_emit_arith(p, Token_Shl, one, e, it);
  9781. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  9782. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  9783. new_value = lb_emit_transmute(p, new_value, type);
  9784. lb_addr_store(p, v, new_value);
  9785. }
  9786. }
  9787. break;
  9788. }
  9789. }
  9790. return v;
  9791. case_end;
  9792. case_ast_node(tc, TypeCast, expr);
  9793. Type *type = type_of_expr(expr);
  9794. lbValue x = lb_build_expr(p, tc->expr);
  9795. lbValue e = {};
  9796. switch (tc->token.kind) {
  9797. case Token_cast:
  9798. e = lb_emit_conv(p, x, type);
  9799. break;
  9800. case Token_transmute:
  9801. e = lb_emit_transmute(p, x, type);
  9802. break;
  9803. default:
  9804. GB_PANIC("Invalid AST TypeCast");
  9805. }
  9806. lbAddr v = lb_add_local_generated(p, type, false);
  9807. lb_addr_store(p, v, e);
  9808. return v;
  9809. case_end;
  9810. case_ast_node(ac, AutoCast, expr);
  9811. return lb_build_addr(p, ac->expr);
  9812. case_end;
  9813. }
  9814. TokenPos token_pos = ast_token(expr).pos;
  9815. GB_PANIC("Unexpected address expression\n"
  9816. "\tAst: %.*s @ "
  9817. "%.*s(%td:%td)\n",
  9818. LIT(ast_strings[expr->kind]),
  9819. LIT(token_pos.file), token_pos.line, token_pos.column);
  9820. return {};
  9821. }
  9822. void lb_init_module(lbModule *m, Checker *c) {
  9823. m->info = &c->info;
  9824. m->ctx = LLVMGetGlobalContext();
  9825. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  9826. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  9827. m->state_flags = 0;
  9828. m->state_flags |= StateFlag_bounds_check;
  9829. gb_mutex_init(&m->mutex);
  9830. gbAllocator a = heap_allocator();
  9831. map_init(&m->types, a);
  9832. map_init(&m->llvm_types, a);
  9833. map_init(&m->values, a);
  9834. string_map_init(&m->members, a);
  9835. map_init(&m->procedure_values, a);
  9836. string_map_init(&m->procedures, a);
  9837. string_map_init(&m->const_strings, a);
  9838. map_init(&m->anonymous_proc_lits, a);
  9839. map_init(&m->function_type_map, a);
  9840. map_init(&m->equal_procs, a);
  9841. map_init(&m->hasher_procs, a);
  9842. array_init(&m->procedures_to_generate, a);
  9843. array_init(&m->foreign_library_paths, a);
  9844. map_init(&m->debug_values, a);
  9845. }
  9846. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  9847. if (global_error_collector.count != 0) {
  9848. return false;
  9849. }
  9850. isize tc = c->parser->total_token_count;
  9851. if (tc < 2) {
  9852. return false;
  9853. }
  9854. String init_fullpath = c->parser->init_fullpath;
  9855. if (build_context.out_filepath.len == 0) {
  9856. gen->output_name = remove_directory_from_path(init_fullpath);
  9857. gen->output_name = remove_extension_from_path(gen->output_name);
  9858. gen->output_name = string_trim_whitespace(gen->output_name);
  9859. if (gen->output_name.len == 0) {
  9860. gen->output_name = c->info.init_scope->pkg->name;
  9861. }
  9862. gen->output_base = gen->output_name;
  9863. } else {
  9864. gen->output_name = build_context.out_filepath;
  9865. gen->output_name = string_trim_whitespace(gen->output_name);
  9866. if (gen->output_name.len == 0) {
  9867. gen->output_name = c->info.init_scope->pkg->name;
  9868. }
  9869. isize pos = string_extension_position(gen->output_name);
  9870. if (pos < 0) {
  9871. gen->output_base = gen->output_name;
  9872. } else {
  9873. gen->output_base = substring(gen->output_name, 0, pos);
  9874. }
  9875. }
  9876. gbAllocator ha = heap_allocator();
  9877. array_init(&gen->output_object_paths, ha);
  9878. gen->output_base = path_to_full_path(ha, gen->output_base);
  9879. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  9880. output_file_path = gb_string_appendc(output_file_path, ".obj");
  9881. defer (gb_string_free(output_file_path));
  9882. gen->info = &c->info;
  9883. lb_init_module(&gen->module, c);
  9884. return true;
  9885. }
  9886. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  9887. GB_ASSERT(type != nullptr);
  9888. type = default_type(type);
  9889. isize max_len = 7+8+1;
  9890. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  9891. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  9892. m->global_generated_index++;
  9893. String name = make_string(str, len-1);
  9894. Scope *scope = nullptr;
  9895. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  9896. lbValue g = {};
  9897. g.type = alloc_type_pointer(type);
  9898. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  9899. if (value.value != nullptr) {
  9900. GB_ASSERT(LLVMIsConstant(value.value));
  9901. LLVMSetInitializer(g.value, value.value);
  9902. } else {
  9903. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  9904. }
  9905. lb_add_entity(m, e, g);
  9906. lb_add_member(m, name, g);
  9907. return lb_addr(g);
  9908. }
  9909. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  9910. AstPackage *p = m->info->runtime_package;
  9911. Entity *e = scope_lookup_current(p->scope, name);
  9912. lbValue *found = map_get(&m->values, hash_entity(e));
  9913. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  9914. lbValue value = *found;
  9915. return value;
  9916. }
  9917. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  9918. i32 index = cast(i32)lb_type_info_index(m->info, type);
  9919. GB_ASSERT(index >= 0);
  9920. // gb_printf_err("%d %s\n", index, type_to_string(type));
  9921. LLVMValueRef indices[2] = {
  9922. LLVMConstInt(lb_type(m, t_int), 0, false),
  9923. LLVMConstInt(lb_type(m, t_int), index, false),
  9924. };
  9925. lbValue res = {};
  9926. res.type = t_type_info_ptr;
  9927. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  9928. return res;
  9929. }
  9930. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  9931. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  9932. lb_global_type_info_member_types_index += cast(i32)count;
  9933. return offset;
  9934. }
  9935. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  9936. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  9937. lb_global_type_info_member_names_index += cast(i32)count;
  9938. return offset;
  9939. }
  9940. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  9941. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  9942. lb_global_type_info_member_offsets_index += cast(i32)count;
  9943. return offset;
  9944. }
  9945. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  9946. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  9947. lb_global_type_info_member_usings_index += cast(i32)count;
  9948. return offset;
  9949. }
  9950. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  9951. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  9952. lb_global_type_info_member_tags_index += cast(i32)count;
  9953. return offset;
  9954. }
  9955. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  9956. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  9957. return lb_addr_get_ptr(p, addr);
  9958. }
  9959. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  9960. Token token = {Token_Ident};
  9961. isize name_len = prefix.len + 1 + 20;
  9962. auto suffix_id = cast(unsigned long long)id;
  9963. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  9964. gb_snprintf(text, name_len,
  9965. "%.*s-%llu", LIT(prefix), suffix_id);
  9966. text[name_len] = 0;
  9967. String s = make_string_c(text);
  9968. Type *t = alloc_type_array(elem_type, count);
  9969. lbValue g = {};
  9970. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  9971. g.type = alloc_type_pointer(t);
  9972. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  9973. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  9974. string_map_set(&m->members, s, g);
  9975. return g;
  9976. }
  9977. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  9978. lbModule *m = p->module;
  9979. LLVMContextRef ctx = m->ctx;
  9980. CheckerInfo *info = m->info;
  9981. {
  9982. // NOTE(bill): Set the type_table slice with the global backing array
  9983. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  9984. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  9985. GB_ASSERT(is_type_array(type));
  9986. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  9987. LLVMValueRef values[2] = {
  9988. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  9989. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  9990. };
  9991. LLVMValueRef slice = LLVMConstStructInContext(ctx, values, gb_count_of(values), false);
  9992. LLVMSetInitializer(global_type_table.value, slice);
  9993. }
  9994. // Useful types
  9995. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  9996. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  9997. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  9998. Type *t_type_info_flags = type_info_flags_entity->type;
  9999. i32 type_info_member_types_index = 0;
  10000. i32 type_info_member_names_index = 0;
  10001. i32 type_info_member_offsets_index = 0;
  10002. for_array(type_info_type_index, info->type_info_types) {
  10003. Type *t = info->type_info_types[type_info_type_index];
  10004. t = default_type(t);
  10005. if (t == t_invalid) {
  10006. continue;
  10007. }
  10008. isize entry_index = lb_type_info_index(info, t, false);
  10009. if (entry_index <= 0) {
  10010. continue;
  10011. }
  10012. lbValue tag = {};
  10013. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  10014. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  10015. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  10016. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  10017. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  10018. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  10019. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  10020. switch (t->kind) {
  10021. case Type_Named: {
  10022. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  10023. LLVMValueRef vals[2] = {
  10024. lb_const_string(p->module, t->Named.type_name->token.string).value,
  10025. lb_get_type_info_ptr(m, t->Named.base).value,
  10026. };
  10027. lbValue res = {};
  10028. res.type = type_deref(tag.type);
  10029. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10030. lb_emit_store(p, tag, res);
  10031. break;
  10032. }
  10033. case Type_Basic:
  10034. switch (t->Basic.kind) {
  10035. case Basic_bool:
  10036. case Basic_b8:
  10037. case Basic_b16:
  10038. case Basic_b32:
  10039. case Basic_b64:
  10040. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  10041. break;
  10042. case Basic_i8:
  10043. case Basic_u8:
  10044. case Basic_i16:
  10045. case Basic_u16:
  10046. case Basic_i32:
  10047. case Basic_u32:
  10048. case Basic_i64:
  10049. case Basic_u64:
  10050. case Basic_i128:
  10051. case Basic_u128:
  10052. case Basic_i16le:
  10053. case Basic_u16le:
  10054. case Basic_i32le:
  10055. case Basic_u32le:
  10056. case Basic_i64le:
  10057. case Basic_u64le:
  10058. case Basic_i128le:
  10059. case Basic_u128le:
  10060. case Basic_i16be:
  10061. case Basic_u16be:
  10062. case Basic_i32be:
  10063. case Basic_u32be:
  10064. case Basic_i64be:
  10065. case Basic_u64be:
  10066. case Basic_i128be:
  10067. case Basic_u128be:
  10068. case Basic_int:
  10069. case Basic_uint:
  10070. case Basic_uintptr: {
  10071. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  10072. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  10073. // NOTE(bill): This is matches the runtime layout
  10074. u8 endianness_value = 0;
  10075. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10076. endianness_value = 1;
  10077. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10078. endianness_value = 2;
  10079. }
  10080. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10081. LLVMValueRef vals[2] = {
  10082. is_signed.value,
  10083. endianness.value,
  10084. };
  10085. lbValue res = {};
  10086. res.type = type_deref(tag.type);
  10087. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10088. lb_emit_store(p, tag, res);
  10089. break;
  10090. }
  10091. case Basic_rune:
  10092. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  10093. break;
  10094. // case Basic_f16:
  10095. case Basic_f32:
  10096. case Basic_f64:
  10097. case Basic_f32le:
  10098. case Basic_f64le:
  10099. case Basic_f32be:
  10100. case Basic_f64be:
  10101. {
  10102. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  10103. // NOTE(bill): This is matches the runtime layout
  10104. u8 endianness_value = 0;
  10105. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10106. endianness_value = 1;
  10107. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10108. endianness_value = 2;
  10109. }
  10110. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10111. LLVMValueRef vals[1] = {
  10112. endianness.value,
  10113. };
  10114. lbValue res = {};
  10115. res.type = type_deref(tag.type);
  10116. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10117. lb_emit_store(p, tag, res);
  10118. }
  10119. break;
  10120. // case Basic_complex32:
  10121. case Basic_complex64:
  10122. case Basic_complex128:
  10123. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  10124. break;
  10125. case Basic_quaternion128:
  10126. case Basic_quaternion256:
  10127. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  10128. break;
  10129. case Basic_rawptr:
  10130. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10131. break;
  10132. case Basic_string:
  10133. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10134. break;
  10135. case Basic_cstring:
  10136. {
  10137. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10138. LLVMValueRef vals[1] = {
  10139. lb_const_bool(m, t_bool, true).value,
  10140. };
  10141. lbValue res = {};
  10142. res.type = type_deref(tag.type);
  10143. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10144. lb_emit_store(p, tag, res);
  10145. }
  10146. break;
  10147. case Basic_any:
  10148. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  10149. break;
  10150. case Basic_typeid:
  10151. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  10152. break;
  10153. }
  10154. break;
  10155. case Type_Pointer: {
  10156. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10157. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  10158. LLVMValueRef vals[1] = {
  10159. gep.value,
  10160. };
  10161. lbValue res = {};
  10162. res.type = type_deref(tag.type);
  10163. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10164. lb_emit_store(p, tag, res);
  10165. break;
  10166. }
  10167. case Type_Array: {
  10168. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  10169. i64 ez = type_size_of(t->Array.elem);
  10170. LLVMValueRef vals[3] = {
  10171. lb_get_type_info_ptr(m, t->Array.elem).value,
  10172. lb_const_int(m, t_int, ez).value,
  10173. lb_const_int(m, t_int, t->Array.count).value,
  10174. };
  10175. lbValue res = {};
  10176. res.type = type_deref(tag.type);
  10177. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10178. lb_emit_store(p, tag, res);
  10179. break;
  10180. }
  10181. case Type_EnumeratedArray: {
  10182. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  10183. LLVMValueRef vals[6] = {
  10184. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  10185. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  10186. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  10187. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  10188. // Unions
  10189. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10190. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10191. };
  10192. lbValue res = {};
  10193. res.type = type_deref(tag.type);
  10194. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10195. lb_emit_store(p, tag, res);
  10196. // NOTE(bill): Union assignment
  10197. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  10198. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  10199. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  10200. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  10201. lb_emit_store(p, min_value, min_v);
  10202. lb_emit_store(p, max_value, max_v);
  10203. break;
  10204. }
  10205. case Type_DynamicArray: {
  10206. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  10207. LLVMValueRef vals[2] = {
  10208. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  10209. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  10210. };
  10211. lbValue res = {};
  10212. res.type = type_deref(tag.type);
  10213. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10214. lb_emit_store(p, tag, res);
  10215. break;
  10216. }
  10217. case Type_Slice: {
  10218. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  10219. LLVMValueRef vals[2] = {
  10220. lb_get_type_info_ptr(m, t->Slice.elem).value,
  10221. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  10222. };
  10223. lbValue res = {};
  10224. res.type = type_deref(tag.type);
  10225. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10226. lb_emit_store(p, tag, res);
  10227. break;
  10228. }
  10229. case Type_Proc: {
  10230. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  10231. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10232. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10233. if (t->Proc.params != nullptr) {
  10234. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  10235. }
  10236. if (t->Proc.results != nullptr) {
  10237. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  10238. }
  10239. LLVMValueRef vals[4] = {
  10240. params,
  10241. results,
  10242. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  10243. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  10244. };
  10245. lbValue res = {};
  10246. res.type = type_deref(tag.type);
  10247. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10248. lb_emit_store(p, tag, res);
  10249. break;
  10250. }
  10251. case Type_Tuple: {
  10252. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  10253. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  10254. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  10255. for_array(i, t->Tuple.variables) {
  10256. // NOTE(bill): offset is not used for tuples
  10257. Entity *f = t->Tuple.variables[i];
  10258. lbValue index = lb_const_int(m, t_int, i);
  10259. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10260. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  10261. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10262. if (f->token.string.len > 0) {
  10263. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10264. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10265. }
  10266. }
  10267. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  10268. LLVMValueRef types_slice = llvm_const_slice(memory_types, count);
  10269. LLVMValueRef names_slice = llvm_const_slice(memory_names, count);
  10270. LLVMValueRef vals[2] = {
  10271. types_slice,
  10272. names_slice,
  10273. };
  10274. lbValue res = {};
  10275. res.type = type_deref(tag.type);
  10276. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10277. lb_emit_store(p, tag, res);
  10278. break;
  10279. }
  10280. case Type_Enum:
  10281. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  10282. {
  10283. GB_ASSERT(t->Enum.base_type != nullptr);
  10284. // 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));
  10285. LLVMValueRef vals[3] = {};
  10286. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  10287. if (t->Enum.fields.count > 0) {
  10288. auto fields = t->Enum.fields;
  10289. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  10290. str_lit("$enum_names"), cast(i64)entry_index);
  10291. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  10292. str_lit("$enum_values"), cast(i64)entry_index);
  10293. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10294. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10295. GB_ASSERT(is_type_integer(t->Enum.base_type));
  10296. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  10297. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  10298. for_array(i, fields) {
  10299. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  10300. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  10301. }
  10302. LLVMValueRef name_init = LLVMConstArray(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  10303. LLVMValueRef value_init = LLVMConstArray(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  10304. LLVMSetInitializer(name_array.value, name_init);
  10305. LLVMSetInitializer(value_array.value, value_init);
  10306. lbValue v_count = lb_const_int(m, t_int, fields.count);
  10307. vals[1] = llvm_const_slice(lb_array_elem(p, name_array), v_count);
  10308. vals[2] = llvm_const_slice(lb_array_elem(p, value_array), v_count);
  10309. } else {
  10310. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  10311. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  10312. }
  10313. lbValue res = {};
  10314. res.type = type_deref(tag.type);
  10315. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10316. lb_emit_store(p, tag, res);
  10317. }
  10318. break;
  10319. case Type_Union: {
  10320. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  10321. {
  10322. LLVMValueRef vals[6] = {};
  10323. isize variant_count = gb_max(0, t->Union.variants.count);
  10324. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  10325. // NOTE(bill): Zeroth is nil so ignore it
  10326. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  10327. Type *vt = t->Union.variants[variant_index];
  10328. lbValue tip = lb_get_type_info_ptr(m, vt);
  10329. lbValue index = lb_const_int(m, t_int, variant_index);
  10330. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10331. lb_emit_store(p, type_info, lb_type_info(m, vt));
  10332. }
  10333. lbValue count = lb_const_int(m, t_int, variant_count);
  10334. vals[0] = llvm_const_slice(memory_types, count);
  10335. i64 tag_size = union_tag_size(t);
  10336. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  10337. if (tag_size > 0) {
  10338. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  10339. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  10340. } else {
  10341. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  10342. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10343. }
  10344. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  10345. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  10346. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  10347. lbValue res = {};
  10348. res.type = type_deref(tag.type);
  10349. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10350. lb_emit_store(p, tag, res);
  10351. }
  10352. break;
  10353. }
  10354. case Type_Struct: {
  10355. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  10356. LLVMValueRef vals[12] = {};
  10357. {
  10358. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  10359. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  10360. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  10361. vals[5] = is_packed.value;
  10362. vals[6] = is_raw_union.value;
  10363. vals[7] = is_custom_align.value;
  10364. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  10365. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  10366. }
  10367. if (t->Struct.soa_kind != StructSoa_None) {
  10368. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  10369. Type *kind_type = type_deref(kind.type);
  10370. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  10371. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  10372. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  10373. vals[9] = soa_kind.value;
  10374. vals[10] = soa_type.value;
  10375. vals[11] = soa_len.value;
  10376. }
  10377. }
  10378. isize count = t->Struct.fields.count;
  10379. if (count > 0) {
  10380. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  10381. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  10382. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  10383. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  10384. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  10385. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  10386. for (isize source_index = 0; source_index < count; source_index++) {
  10387. // TODO(bill): Order fields in source order not layout order
  10388. Entity *f = t->Struct.fields[source_index];
  10389. lbValue tip = lb_get_type_info_ptr(m, f->type);
  10390. i64 foffset = 0;
  10391. if (!t->Struct.is_raw_union) {
  10392. foffset = t->Struct.offsets[f->Variable.field_index];
  10393. }
  10394. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  10395. lbValue index = lb_const_int(m, t_int, source_index);
  10396. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10397. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  10398. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  10399. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10400. if (f->token.string.len > 0) {
  10401. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10402. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10403. }
  10404. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  10405. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  10406. if (t->Struct.tags.count > 0) {
  10407. String tag_string = t->Struct.tags[source_index];
  10408. if (tag_string.len > 0) {
  10409. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  10410. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  10411. }
  10412. }
  10413. }
  10414. lbValue cv = lb_const_int(m, t_int, count);
  10415. vals[0] = llvm_const_slice(memory_types, cv);
  10416. vals[1] = llvm_const_slice(memory_names, cv);
  10417. vals[2] = llvm_const_slice(memory_offsets, cv);
  10418. vals[3] = llvm_const_slice(memory_usings, cv);
  10419. vals[4] = llvm_const_slice(memory_tags, cv);
  10420. }
  10421. for (isize i = 0; i < gb_count_of(vals); i++) {
  10422. if (vals[i] == nullptr) {
  10423. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  10424. }
  10425. }
  10426. lbValue res = {};
  10427. res.type = type_deref(tag.type);
  10428. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10429. lb_emit_store(p, tag, res);
  10430. break;
  10431. }
  10432. case Type_Map: {
  10433. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  10434. init_map_internal_types(t);
  10435. LLVMValueRef vals[5] = {
  10436. lb_get_type_info_ptr(m, t->Map.key).value,
  10437. lb_get_type_info_ptr(m, t->Map.value).value,
  10438. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  10439. lb_get_equal_proc_for_type(m, t->Map.key).value,
  10440. lb_get_hasher_proc_for_type(m, t->Map.key).value
  10441. };
  10442. lbValue res = {};
  10443. res.type = type_deref(tag.type);
  10444. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10445. lb_emit_store(p, tag, res);
  10446. break;
  10447. }
  10448. case Type_BitField: {
  10449. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_field_ptr);
  10450. // names: []string;
  10451. // bits: []u32;
  10452. // offsets: []u32;
  10453. isize count = t->BitField.fields.count;
  10454. if (count > 0) {
  10455. auto fields = t->BitField.fields;
  10456. lbValue name_array = lb_generate_global_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  10457. lbValue bit_array = lb_generate_global_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  10458. lbValue offset_array = lb_generate_global_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  10459. for (isize i = 0; i < count; i++) {
  10460. Entity *f = fields[i];
  10461. GB_ASSERT(f->type != nullptr);
  10462. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  10463. lbValue name_ep = lb_emit_array_epi(p, name_array, cast(i32)i);
  10464. lbValue bit_ep = lb_emit_array_epi(p, bit_array, cast(i32)i);
  10465. lbValue offset_ep = lb_emit_array_epi(p, offset_array, cast(i32)i);
  10466. lb_emit_store(p, name_ep, lb_const_string(m, f->token.string));
  10467. lb_emit_store(p, bit_ep, lb_const_int(m, t_i32, f->type->BitFieldValue.bits));
  10468. lb_emit_store(p, offset_ep, lb_const_int(m, t_i32, t->BitField.offsets[i]));
  10469. }
  10470. lbValue v_count = lb_const_int(m, t_int, count);
  10471. lbValue name_array_elem = lb_array_elem(p, name_array);
  10472. lbValue bit_array_elem = lb_array_elem(p, bit_array);
  10473. lbValue offset_array_elem = lb_array_elem(p, offset_array);
  10474. LLVMValueRef vals[3] = {
  10475. llvm_const_slice(name_array_elem, v_count),
  10476. llvm_const_slice(bit_array_elem, v_count),
  10477. llvm_const_slice(offset_array_elem, v_count),
  10478. };
  10479. lbValue res = {};
  10480. res.type = type_deref(tag.type);
  10481. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10482. lb_emit_store(p, tag, res);
  10483. }
  10484. break;
  10485. }
  10486. case Type_BitSet:
  10487. {
  10488. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  10489. GB_ASSERT(is_type_typed(t->BitSet.elem));
  10490. LLVMValueRef vals[4] = {
  10491. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  10492. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  10493. lb_const_int(m, t_i64, t->BitSet.lower).value,
  10494. lb_const_int(m, t_i64, t->BitSet.upper).value,
  10495. };
  10496. if (t->BitSet.underlying != nullptr) {
  10497. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  10498. }
  10499. lbValue res = {};
  10500. res.type = type_deref(tag.type);
  10501. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10502. lb_emit_store(p, tag, res);
  10503. }
  10504. break;
  10505. case Type_Opaque:
  10506. {
  10507. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_opaque_ptr);
  10508. LLVMValueRef vals[1] = {
  10509. lb_get_type_info_ptr(m, t->Opaque.elem).value,
  10510. };
  10511. lbValue res = {};
  10512. res.type = type_deref(tag.type);
  10513. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10514. lb_emit_store(p, tag, res);
  10515. }
  10516. break;
  10517. case Type_SimdVector:
  10518. {
  10519. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  10520. LLVMValueRef vals[4] = {};
  10521. if (t->SimdVector.is_x86_mmx) {
  10522. vals[3] = lb_const_bool(m, t_bool, true).value;
  10523. } else {
  10524. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  10525. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  10526. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  10527. }
  10528. lbValue res = {};
  10529. res.type = type_deref(tag.type);
  10530. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10531. lb_emit_store(p, tag, res);
  10532. }
  10533. break;
  10534. case Type_RelativePointer:
  10535. {
  10536. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  10537. LLVMValueRef vals[2] = {
  10538. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  10539. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  10540. };
  10541. lbValue res = {};
  10542. res.type = type_deref(tag.type);
  10543. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10544. lb_emit_store(p, tag, res);
  10545. }
  10546. break;
  10547. case Type_RelativeSlice:
  10548. {
  10549. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  10550. LLVMValueRef vals[2] = {
  10551. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  10552. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  10553. };
  10554. lbValue res = {};
  10555. res.type = type_deref(tag.type);
  10556. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10557. lb_emit_store(p, tag, res);
  10558. }
  10559. break;
  10560. }
  10561. if (tag.value != nullptr) {
  10562. Type *tag_type = type_deref(tag.type);
  10563. GB_ASSERT(is_type_named(tag_type));
  10564. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  10565. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  10566. } else {
  10567. if (t != t_llvm_bool) {
  10568. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  10569. }
  10570. }
  10571. }
  10572. }
  10573. void lb_generate_code(lbGenerator *gen) {
  10574. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  10575. TIME_SECTION("LLVM Initializtion");
  10576. lbModule *m = &gen->module;
  10577. LLVMModuleRef mod = gen->module.mod;
  10578. CheckerInfo *info = gen->info;
  10579. auto *min_dep_set = &info->minimum_dependency_set;
  10580. LLVMInitializeAllTargetInfos();
  10581. LLVMInitializeAllTargets();
  10582. LLVMInitializeAllTargetMCs();
  10583. LLVMInitializeAllAsmPrinters();
  10584. LLVMInitializeAllAsmParsers();
  10585. LLVMInitializeAllDisassemblers();
  10586. LLVMInitializeNativeTarget();
  10587. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  10588. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  10589. LLVMSetTarget(mod, target_triple);
  10590. LLVMTargetRef target = {};
  10591. char *llvm_error = nullptr;
  10592. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  10593. GB_ASSERT(target != nullptr);
  10594. TIME_SECTION("LLVM Create Target Machine");
  10595. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  10596. if (build_context.metrics.arch == TargetArch_wasm32) {
  10597. code_mode = LLVMCodeModelJITDefault;
  10598. }
  10599. char const *host_cpu_name = LLVMGetHostCPUName();
  10600. char const *llvm_cpu = "generic";
  10601. char const *llvm_features = "";
  10602. if (build_context.microarch.len != 0) {
  10603. if (build_context.microarch == "native") {
  10604. llvm_cpu = host_cpu_name;
  10605. } else {
  10606. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  10607. }
  10608. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  10609. llvm_features = LLVMGetHostCPUFeatures();
  10610. }
  10611. }
  10612. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  10613. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  10614. switch (build_context.optimization_level) {
  10615. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  10616. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  10617. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  10618. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  10619. }
  10620. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, llvm_cpu, llvm_features, code_gen_level, LLVMRelocDefault, code_mode);
  10621. defer (LLVMDisposeTargetMachine(target_machine));
  10622. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  10623. { // Debug Info
  10624. for_array(i, info->files.entries) {
  10625. AstFile *f = info->files.entries[i].value;
  10626. String fullpath = f->fullpath;
  10627. String filename = filename_from_path(fullpath);
  10628. String directory = directory_from_path(fullpath);
  10629. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  10630. cast(char const *)filename.text, filename.len,
  10631. cast(char const *)directory.text, directory.len);
  10632. map_set(&m->debug_values, hash_pointer(f), res);
  10633. f->llvm_metadata = res;
  10634. }
  10635. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC,
  10636. cast(LLVMMetadataRef)m->info->files.entries[0].value->llvm_metadata,
  10637. "odin", 4,
  10638. false, "", 0,
  10639. 1, "", 0,
  10640. LLVMDWARFEmissionFull, 0, true,
  10641. true
  10642. #if LLVM_VERSION_MAJOR > 10
  10643. , "", 0,
  10644. "", 0
  10645. #endif
  10646. );
  10647. }
  10648. TIME_SECTION("LLVM Global Variables");
  10649. {
  10650. { // Add type info data
  10651. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  10652. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  10653. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  10654. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  10655. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10656. LLVMSetLinkage(g, LLVMInternalLinkage);
  10657. lbValue value = {};
  10658. value.value = g;
  10659. value.type = alloc_type_pointer(t);
  10660. lb_global_type_info_data = lb_addr(value);
  10661. }
  10662. { // Type info member buffer
  10663. // NOTE(bill): Removes need for heap allocation by making it global memory
  10664. isize count = 0;
  10665. for_array(entry_index, m->info->type_info_types) {
  10666. Type *t = m->info->type_info_types[entry_index];
  10667. isize index = lb_type_info_index(m->info, t, false);
  10668. if (index < 0) {
  10669. continue;
  10670. }
  10671. switch (t->kind) {
  10672. case Type_Union:
  10673. count += t->Union.variants.count;
  10674. break;
  10675. case Type_Struct:
  10676. count += t->Struct.fields.count;
  10677. break;
  10678. case Type_Tuple:
  10679. count += t->Tuple.variables.count;
  10680. break;
  10681. }
  10682. }
  10683. if (count > 0) {
  10684. {
  10685. char const *name = LB_TYPE_INFO_TYPES_NAME;
  10686. Type *t = alloc_type_array(t_type_info_ptr, count);
  10687. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10688. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10689. LLVMSetLinkage(g, LLVMInternalLinkage);
  10690. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  10691. }
  10692. {
  10693. char const *name = LB_TYPE_INFO_NAMES_NAME;
  10694. Type *t = alloc_type_array(t_string, count);
  10695. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10696. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10697. LLVMSetLinkage(g, LLVMInternalLinkage);
  10698. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  10699. }
  10700. {
  10701. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  10702. Type *t = alloc_type_array(t_uintptr, count);
  10703. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10704. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10705. LLVMSetLinkage(g, LLVMInternalLinkage);
  10706. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  10707. }
  10708. {
  10709. char const *name = LB_TYPE_INFO_USINGS_NAME;
  10710. Type *t = alloc_type_array(t_bool, count);
  10711. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10712. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10713. LLVMSetLinkage(g, LLVMInternalLinkage);
  10714. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  10715. }
  10716. {
  10717. char const *name = LB_TYPE_INFO_TAGS_NAME;
  10718. Type *t = alloc_type_array(t_string, count);
  10719. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10720. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10721. LLVMSetLinkage(g, LLVMInternalLinkage);
  10722. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  10723. }
  10724. }
  10725. }
  10726. }
  10727. isize global_variable_max_count = 0;
  10728. Entity *entry_point = info->entry_point;
  10729. bool has_dll_main = false;
  10730. bool has_win_main = false;
  10731. for_array(i, info->entities) {
  10732. Entity *e = info->entities[i];
  10733. String name = e->token.string;
  10734. bool is_global = e->pkg != nullptr;
  10735. if (e->kind == Entity_Variable) {
  10736. global_variable_max_count++;
  10737. } else if (e->kind == Entity_Procedure && !is_global) {
  10738. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  10739. GB_ASSERT(e == entry_point);
  10740. // entry_point = e;
  10741. }
  10742. if (e->Procedure.is_export ||
  10743. (e->Procedure.link_name.len > 0) ||
  10744. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  10745. if (!has_dll_main && name == "DllMain") {
  10746. has_dll_main = true;
  10747. } else if (!has_win_main && name == "WinMain") {
  10748. has_win_main = true;
  10749. }
  10750. }
  10751. }
  10752. }
  10753. struct GlobalVariable {
  10754. lbValue var;
  10755. lbValue init;
  10756. DeclInfo *decl;
  10757. };
  10758. auto global_variables = array_make<GlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  10759. for_array(i, info->variable_init_order) {
  10760. DeclInfo *d = info->variable_init_order[i];
  10761. Entity *e = d->entity;
  10762. if ((e->scope->flags & ScopeFlag_File) == 0) {
  10763. continue;
  10764. }
  10765. if (!ptr_set_exists(min_dep_set, e)) {
  10766. continue;
  10767. }
  10768. DeclInfo *decl = decl_info_of_entity(e);
  10769. if (decl == nullptr) {
  10770. continue;
  10771. }
  10772. GB_ASSERT(e->kind == Entity_Variable);
  10773. bool is_foreign = e->Variable.is_foreign;
  10774. bool is_export = e->Variable.is_export;
  10775. String name = lb_get_entity_name(m, e);
  10776. lbValue g = {};
  10777. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  10778. g.type = alloc_type_pointer(e->type);
  10779. if (e->Variable.thread_local_model != "") {
  10780. LLVMSetThreadLocal(g.value, true);
  10781. String m = e->Variable.thread_local_model;
  10782. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  10783. if (m == "default") {
  10784. mode = LLVMGeneralDynamicTLSModel;
  10785. } else if (m == "localdynamic") {
  10786. mode = LLVMLocalDynamicTLSModel;
  10787. } else if (m == "initialexec") {
  10788. mode = LLVMInitialExecTLSModel;
  10789. } else if (m == "localexec") {
  10790. mode = LLVMLocalExecTLSModel;
  10791. } else {
  10792. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  10793. }
  10794. LLVMSetThreadLocalMode(g.value, mode);
  10795. }
  10796. if (is_foreign) {
  10797. LLVMSetExternallyInitialized(g.value, true);
  10798. } else {
  10799. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  10800. }
  10801. if (is_export) {
  10802. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  10803. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  10804. }
  10805. GlobalVariable var = {};
  10806. var.var = g;
  10807. var.decl = decl;
  10808. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  10809. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  10810. if (tav.mode != Addressing_Invalid) {
  10811. if (tav.value.kind != ExactValue_Invalid) {
  10812. ExactValue v = tav.value;
  10813. lbValue init = lb_const_value(m, tav.type, v);
  10814. LLVMSetInitializer(g.value, init.value);
  10815. }
  10816. }
  10817. }
  10818. array_add(&global_variables, var);
  10819. lb_add_entity(m, e, g);
  10820. lb_add_member(m, name, g);
  10821. }
  10822. TIME_SECTION("LLVM Global Procedures and Types");
  10823. for_array(i, info->entities) {
  10824. Entity *e = info->entities[i];
  10825. String name = e->token.string;
  10826. DeclInfo *decl = e->decl_info;
  10827. Scope * scope = e->scope;
  10828. if ((scope->flags & ScopeFlag_File) == 0) {
  10829. continue;
  10830. }
  10831. Scope *package_scope = scope->parent;
  10832. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  10833. switch (e->kind) {
  10834. case Entity_Variable:
  10835. // NOTE(bill): Handled above as it requires a specific load order
  10836. continue;
  10837. case Entity_ProcGroup:
  10838. continue;
  10839. case Entity_TypeName:
  10840. case Entity_Procedure:
  10841. break;
  10842. }
  10843. bool polymorphic_struct = false;
  10844. if (e->type != nullptr && e->kind == Entity_TypeName) {
  10845. Type *bt = base_type(e->type);
  10846. if (bt->kind == Type_Struct) {
  10847. polymorphic_struct = is_type_polymorphic(bt);
  10848. }
  10849. }
  10850. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  10851. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  10852. continue;
  10853. }
  10854. String mangled_name = lb_get_entity_name(m, e);
  10855. switch (e->kind) {
  10856. case Entity_TypeName:
  10857. lb_type(m, e->type);
  10858. break;
  10859. case Entity_Procedure:
  10860. {
  10861. lbProcedure *p = lb_create_procedure(m, e);
  10862. array_add(&m->procedures_to_generate, p);
  10863. }
  10864. break;
  10865. }
  10866. }
  10867. TIME_SECTION("LLVM Registry Initializtion");
  10868. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  10869. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  10870. defer (LLVMDisposePassManager(default_function_pass_manager));
  10871. /*{
  10872. LLVMAddMemCpyOptPass(default_function_pass_manager);
  10873. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10874. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  10875. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager);
  10876. LLVMAddConstantPropagationPass(default_function_pass_manager);
  10877. LLVMAddAggressiveDCEPass(default_function_pass_manager);
  10878. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  10879. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10880. LLVMAddCFGSimplificationPass(default_function_pass_manager);
  10881. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager);
  10882. if (build_context.optimization_level >= 2) {
  10883. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager);
  10884. LLVMAddEarlyCSEPass(default_function_pass_manager);
  10885. LLVMAddEarlyCSEMemSSAPass(default_function_pass_manager);
  10886. LLVMAddLowerExpectIntrinsicPass(default_function_pass_manager);
  10887. LLVMAddAlignmentFromAssumptionsPass(default_function_pass_manager);
  10888. LLVMAddLoopRotatePass(default_function_pass_manager);
  10889. LLVMAddDeadStoreEliminationPass(default_function_pass_manager);
  10890. LLVMAddScalarizerPass(default_function_pass_manager);
  10891. LLVMAddReassociatePass(default_function_pass_manager);
  10892. LLVMAddAddDiscriminatorsPass(default_function_pass_manager);
  10893. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10894. LLVMAddCorrelatedValuePropagationPass(default_function_pass_manager);
  10895. LLVMAddSLPVectorizePass(default_function_pass_manager);
  10896. LLVMAddLoopVectorizePass(default_function_pass_manager);
  10897. }
  10898. }*/
  10899. if (build_context.optimization_level == 0 && false) {
  10900. auto dfpm = default_function_pass_manager;
  10901. LLVMAddMemCpyOptPass(dfpm);
  10902. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10903. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10904. LLVMAddAggressiveInstCombinerPass(dfpm);
  10905. LLVMAddConstantPropagationPass(dfpm);
  10906. LLVMAddAggressiveDCEPass(dfpm);
  10907. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10908. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10909. LLVMAddCFGSimplificationPass(dfpm);
  10910. LLVMAddScalarizerPass(dfpm);
  10911. } else {
  10912. auto dfpm = default_function_pass_manager;
  10913. LLVMAddMemCpyOptPass(dfpm);
  10914. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10915. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10916. LLVMAddAggressiveInstCombinerPass(dfpm);
  10917. LLVMAddConstantPropagationPass(dfpm);
  10918. LLVMAddAggressiveDCEPass(dfpm);
  10919. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10920. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10921. LLVMAddCFGSimplificationPass(dfpm);
  10922. // LLVMAddInstructionCombiningPass(dfpm);
  10923. LLVMAddSLPVectorizePass(dfpm);
  10924. LLVMAddLoopVectorizePass(dfpm);
  10925. LLVMAddEarlyCSEPass(dfpm);
  10926. LLVMAddEarlyCSEMemSSAPass(dfpm);
  10927. LLVMAddScalarizerPass(dfpm);
  10928. LLVMAddLoopIdiomPass(dfpm);
  10929. // LLVMAddAggressiveInstCombinerPass(dfpm);
  10930. // LLVMAddLowerExpectIntrinsicPass(dfpm);
  10931. // LLVMAddPartiallyInlineLibCallsPass(dfpm);
  10932. // LLVMAddAlignmentFromAssumptionsPass(dfpm);
  10933. // LLVMAddDeadStoreEliminationPass(dfpm);
  10934. // LLVMAddReassociatePass(dfpm);
  10935. // LLVMAddAddDiscriminatorsPass(dfpm);
  10936. // LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10937. // LLVMAddCorrelatedValuePropagationPass(dfpm);
  10938. // LLVMAddMemCpyOptPass(dfpm);
  10939. }
  10940. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  10941. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  10942. {
  10943. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  10944. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  10945. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager_without_memcpy);
  10946. LLVMAddConstantPropagationPass(default_function_pass_manager_without_memcpy);
  10947. LLVMAddAggressiveDCEPass(default_function_pass_manager_without_memcpy);
  10948. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  10949. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  10950. LLVMAddCFGSimplificationPass(default_function_pass_manager_without_memcpy);
  10951. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager_without_memcpy);
  10952. }
  10953. TIME_SECTION("LLVM Runtime Creation");
  10954. lbProcedure *startup_type_info = nullptr;
  10955. lbProcedure *startup_runtime = nullptr;
  10956. { // Startup Type Info
  10957. Type *params = alloc_type_tuple();
  10958. Type *results = alloc_type_tuple();
  10959. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10960. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  10961. p->is_startup = true;
  10962. startup_type_info = p;
  10963. lb_begin_procedure_body(p);
  10964. lb_setup_type_info_data(p);
  10965. lb_end_procedure_body(p);
  10966. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10967. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10968. LLVMDumpValue(p->value);
  10969. gb_printf_err("\n\n\n\n");
  10970. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10971. }
  10972. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10973. }
  10974. { // Startup Runtime
  10975. Type *params = alloc_type_tuple();
  10976. Type *results = alloc_type_tuple();
  10977. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10978. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  10979. p->is_startup = true;
  10980. startup_runtime = p;
  10981. lb_begin_procedure_body(p);
  10982. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  10983. for_array(i, global_variables) {
  10984. auto *var = &global_variables[i];
  10985. if (var->decl->init_expr != nullptr) {
  10986. lbValue init = lb_build_expr(p, var->decl->init_expr);
  10987. if (!lb_is_const(init)) {
  10988. var->init = init;
  10989. }
  10990. }
  10991. Entity *e = var->decl->entity;
  10992. GB_ASSERT(e->kind == Entity_Variable);
  10993. if (e->Variable.is_foreign) {
  10994. Entity *fl = e->Procedure.foreign_library;
  10995. lb_add_foreign_library_path(m, fl);
  10996. }
  10997. if (e->flags & EntityFlag_Static) {
  10998. LLVMSetLinkage(var->var.value, LLVMInternalLinkage);
  10999. }
  11000. if (var->init.value != nullptr) {
  11001. Type *t = type_deref(var->var.type);
  11002. if (is_type_any(t)) {
  11003. // NOTE(bill): Edge case for 'any' type
  11004. Type *var_type = default_type(var->init.type);
  11005. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  11006. lb_addr_store(p, g, var->init);
  11007. lbValue gp = lb_addr_get_ptr(p, g);
  11008. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  11009. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  11010. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  11011. lb_emit_store(p, ti, lb_type_info(m, var_type));
  11012. } else {
  11013. lb_emit_store(p, var->var, lb_emit_conv(p, var->init, t));
  11014. }
  11015. }
  11016. }
  11017. lb_end_procedure_body(p);
  11018. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11019. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11020. LLVMDumpValue(p->value);
  11021. gb_printf_err("\n\n\n\n");
  11022. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11023. }
  11024. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11025. /*{
  11026. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  11027. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  11028. instr != last_instr;
  11029. instr = LLVMGetNextInstruction(instr)) {
  11030. if (LLVMIsAAllocaInst(instr)) {
  11031. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  11032. LLVMValueRef sz_val = LLVMSizeOf(type);
  11033. GB_ASSERT(LLVMIsConstant(sz_val));
  11034. gb_printf_err(">> 0x%p\n", sz_val);
  11035. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  11036. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  11037. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  11038. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  11039. gb_printf_err(">> %ll\n", sz);
  11040. }
  11041. }
  11042. }*/
  11043. }
  11044. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  11045. Type *params = alloc_type_tuple();
  11046. Type *results = alloc_type_tuple();
  11047. String name = str_lit("main");
  11048. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  11049. name = str_lit("mainCRTStartup");
  11050. } else {
  11051. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  11052. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  11053. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  11054. }
  11055. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  11056. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  11057. Type *proc_type = alloc_type_proc(nullptr,
  11058. params, params->Tuple.variables.count,
  11059. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  11060. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  11061. p->is_startup = true;
  11062. lb_begin_procedure_body(p);
  11063. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  11064. if (build_context.command_kind == Command_test) {
  11065. for_array(i, m->info->testing_procedures) {
  11066. Entity *e = m->info->testing_procedures[i];
  11067. lbValue *found = map_get(&m->values, hash_entity(e));
  11068. GB_ASSERT(found != nullptr);
  11069. lb_emit_call(p, *found, {});
  11070. }
  11071. } else {
  11072. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  11073. GB_ASSERT(found != nullptr);
  11074. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  11075. }
  11076. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  11077. lb_end_procedure_body(p);
  11078. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11079. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11080. LLVMDumpValue(p->value);
  11081. gb_printf_err("\n\n\n\n");
  11082. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11083. }
  11084. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11085. }
  11086. String filepath_ll = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".ll"));
  11087. TIME_SECTION("LLVM Procedure Generation");
  11088. for_array(i, m->procedures_to_generate) {
  11089. lbProcedure *p = m->procedures_to_generate[i];
  11090. if (p->is_done) {
  11091. continue;
  11092. }
  11093. if (p->body != nullptr) { // Build Procedure
  11094. m->curr_procedure = p;
  11095. lb_begin_procedure_body(p);
  11096. lb_build_stmt(p, p->body);
  11097. lb_end_procedure_body(p);
  11098. p->is_done = true;
  11099. m->curr_procedure = nullptr;
  11100. }
  11101. lb_end_procedure(p);
  11102. // Add Flags
  11103. if (p->body != nullptr) {
  11104. if (p->name == "memcpy" || p->name == "memmove" ||
  11105. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  11106. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  11107. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  11108. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  11109. }
  11110. }
  11111. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11112. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  11113. LLVMDumpValue(p->value);
  11114. gb_printf_err("\n\n\n\n");
  11115. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11116. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11117. }
  11118. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  11119. gb_exit(1);
  11120. }
  11121. }
  11122. TIME_SECTION("LLVM Function Pass");
  11123. for_array(i, m->procedures_to_generate) {
  11124. lbProcedure *p = m->procedures_to_generate[i];
  11125. if (p->body != nullptr) { // Build Procedure
  11126. for (i32 i = 0; i <= build_context.optimization_level; i++) {
  11127. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  11128. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  11129. } else {
  11130. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11131. }
  11132. }
  11133. }
  11134. }
  11135. TIME_SECTION("LLVM Module Pass");
  11136. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  11137. defer (LLVMDisposePassManager(module_pass_manager));
  11138. LLVMAddAlwaysInlinerPass(module_pass_manager);
  11139. LLVMAddStripDeadPrototypesPass(module_pass_manager);
  11140. LLVMAddAnalysisPasses(target_machine, module_pass_manager);
  11141. // if (build_context.optimization_level >= 2) {
  11142. // LLVMAddArgumentPromotionPass(module_pass_manager);
  11143. // LLVMAddConstantMergePass(module_pass_manager);
  11144. // LLVMAddGlobalDCEPass(module_pass_manager);
  11145. // LLVMAddDeadArgEliminationPass(module_pass_manager);
  11146. // }
  11147. LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate();
  11148. defer (LLVMPassManagerBuilderDispose(pass_manager_builder));
  11149. LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, build_context.optimization_level);
  11150. LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, build_context.optimization_level);
  11151. LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false);
  11152. LLVMRunPassManager(module_pass_manager, mod);
  11153. llvm_error = nullptr;
  11154. defer (LLVMDisposeMessage(llvm_error));
  11155. String filepath_obj = {};
  11156. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  11157. if (build_context.build_mode == BuildMode_Assembly) {
  11158. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".S"));
  11159. code_gen_file_type = LLVMAssemblyFile;
  11160. } else {
  11161. switch (build_context.metrics.os) {
  11162. case TargetOs_windows:
  11163. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".obj"));
  11164. break;
  11165. case TargetOs_darwin:
  11166. case TargetOs_linux:
  11167. case TargetOs_essence:
  11168. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".o"));
  11169. break;
  11170. case TargetOs_js:
  11171. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  11172. break;
  11173. }
  11174. }
  11175. LLVMDIBuilderFinalize(m->debug_builder);
  11176. if (LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error)) {
  11177. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11178. gb_exit(1);
  11179. return;
  11180. }
  11181. llvm_error = nullptr;
  11182. if (build_context.keep_temp_files) {
  11183. TIME_SECTION("LLVM Print Module to File");
  11184. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11185. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11186. gb_exit(1);
  11187. return;
  11188. }
  11189. }
  11190. TIME_SECTION("LLVM Object Generation");
  11191. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  11192. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11193. gb_exit(1);
  11194. return;
  11195. }
  11196. array_add(&gen->output_object_paths, filepath_obj);
  11197. for_array(i, m->info->required_foreign_imports_through_force) {
  11198. Entity *e = m->info->required_foreign_imports_through_force[i];
  11199. lb_add_foreign_library_path(m, e);
  11200. }
  11201. #undef TIME_SECTION
  11202. }