BfStmtEvaluator.cpp 256 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024
  1. #include "BfCompiler.h"
  2. #include "BfSystem.h"
  3. #include "BfParser.h"
  4. #include "BfCodeGen.h"
  5. #include "BfExprEvaluator.h"
  6. #include <fcntl.h>
  7. #include "BfConstResolver.h"
  8. #include "BfMangler.h"
  9. #include "BeefySysLib/util/PerfTimer.h"
  10. #include "BeefySysLib/util/BeefPerf.h"
  11. #include "BeefySysLib/util/StackHelper.h"
  12. #include "BfSourceClassifier.h"
  13. #include "BfAutoComplete.h"
  14. #include "BfDemangler.h"
  15. #include "BfResolvePass.h"
  16. #include "BfFixits.h"
  17. #include "BfIRCodeGen.h"
  18. #include "BfDefBuilder.h"
  19. #pragma warning(push)
  20. #pragma warning(disable:4141)
  21. #pragma warning(disable:4146)
  22. #pragma warning(disable:4291)
  23. #pragma warning(disable:4244)
  24. #pragma warning(disable:4267)
  25. #pragma warning(disable:4624)
  26. #pragma warning(disable:4800)
  27. #pragma warning(disable:4996)
  28. #include "llvm/IR/DIBuilder.h"
  29. #include "llvm/IR/Module.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/GlobalValue.h"
  32. #include "llvm/IR/GlobalVariable.h"
  33. #include "llvm/ADT/ArrayRef.h"
  34. #include "llvm/IR/InlineAsm.h"
  35. #include "llvm/Support/FileSystem.h"
  36. #include "BeefySysLib/util/AllocDebug.h"
  37. #pragma warning(pop)
  38. USING_NS_BF;
  39. bool BfModule::AddDeferredCallEntry(BfDeferredCallEntry* deferredCallEntry, BfScopeData* scopeData)
  40. {
  41. if ((((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)) ||
  42. (mBfIRBuilder->mIgnoreWrites)) && (deferredCallEntry->mDeferredBlock == NULL))
  43. {
  44. // For resolve entries, we only keep deferred blocks because we need to process them later so we can
  45. // resolve inside of them. This is also required for lambda bind scan-pass
  46. delete deferredCallEntry;
  47. return false;
  48. }
  49. if (mBfIRBuilder->mIgnoreWrites)
  50. {
  51. deferredCallEntry->mIgnored = true;
  52. scopeData->mDeferredCallEntries.PushBack(deferredCallEntry);
  53. return true;
  54. }
  55. // We don't need to do a "clear handlers" if we're just adding another dyn to an existing dyn list
  56. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  57. if (mCurMethodState->mPendingNullConditional != NULL)
  58. isDyn = true;
  59. deferredCallEntry->mOrigScopeArgs = deferredCallEntry->mScopeArgs;
  60. if (!isDyn)
  61. {
  62. mCurMethodState->mCurScope->ClearHandlers(scopeData);
  63. if (!mBfIRBuilder->mIgnoreWrites)
  64. {
  65. if ((IsTargetingBeefBackend()) && (deferredCallEntry->mModuleMethodInstance.mMethodInstance != NULL) &&
  66. (!mContext->IsSentinelMethod(deferredCallEntry->mModuleMethodInstance.mMethodInstance)))
  67. {
  68. SizedArray<BfIRType, 8> origParamTypes;
  69. BfIRType origReturnType;
  70. deferredCallEntry->mModuleMethodInstance.mMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  71. int sretIdx = deferredCallEntry->mModuleMethodInstance.mMethodInstance->GetStructRetIdx();
  72. BF_ASSERT(origParamTypes.size() == deferredCallEntry->mScopeArgs.size() + ((sretIdx != -1) ? 1 : 0));
  73. int argIdx = 0;
  74. int paramIdx = 0;
  75. for (int argIdx = 0; argIdx < (int)deferredCallEntry->mScopeArgs.size(); argIdx++, paramIdx++)
  76. {
  77. if (argIdx == sretIdx)
  78. paramIdx++;
  79. auto scopeArg = deferredCallEntry->mScopeArgs[argIdx];
  80. if ((scopeArg.IsConst()) || (scopeArg.IsFake()))
  81. continue;
  82. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  83. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  84. auto allocaInst = mBfIRBuilder->CreateAlloca(origParamTypes[paramIdx]);
  85. mBfIRBuilder->ClearDebugLocation_Last();
  86. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  87. if (WantsLifetimes())
  88. {
  89. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  90. mBfIRBuilder->ClearDebugLocation_Last();
  91. }
  92. mBfIRBuilder->CreateStore(scopeArg, allocaInst);
  93. mBfIRBuilder->ClearDebugLocation_Last();
  94. deferredCallEntry->mScopeArgs[argIdx] = allocaInst;
  95. if (WantsLifetimes())
  96. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  97. }
  98. deferredCallEntry->mArgsNeedLoad = true;
  99. }
  100. }
  101. scopeData->mDeferredCallEntries.PushFront(deferredCallEntry);
  102. return true;
  103. }
  104. bool isLooped = mCurMethodState->mCurScope->IsLooped(scopeData);
  105. BfDeferredCallEntry* listEntry = NULL;
  106. if (!scopeData->mDeferredCallEntries.IsEmpty())
  107. {
  108. listEntry = scopeData->mDeferredCallEntries.mHead;
  109. if (!listEntry->IsDynList())
  110. listEntry = NULL;
  111. }
  112. auto deferredCallEntryType = ResolveTypeDef(mCompiler->mDeferredCallTypeDef);
  113. AddDependency(deferredCallEntryType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  114. mBfIRBuilder->PopulateType(deferredCallEntryType);
  115. auto deferredCallEntryTypePtr = CreatePointerType(deferredCallEntryType);
  116. UpdateSrcPos(mCurMethodInstance->mMethodDef->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  117. if (listEntry == NULL)
  118. {
  119. listEntry = new BfDeferredCallEntry();
  120. if (!mBfIRBuilder->mIgnoreWrites)
  121. {
  122. listEntry->mDynCallTail = CreateAlloca(deferredCallEntryTypePtr, false, "deferredCallTail");
  123. if (WantsLifetimes())
  124. scopeData->mDeferredLifetimeEnds.push_back(listEntry->mDynCallTail);
  125. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  126. mBfIRBuilder->SaveDebugLocation();
  127. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  128. auto scopeHead = &mCurMethodState->mHeadScope;
  129. if (scopeHead->mDIScope)
  130. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, scopeHead->mDIScope, BfIRMDNode());
  131. if (WantsLifetimes())
  132. mBfIRBuilder->CreateLifetimeStart(listEntry->mDynCallTail);
  133. auto storeInst = mBfIRBuilder->CreateStore(GetDefaultValue(deferredCallEntryTypePtr), listEntry->mDynCallTail);
  134. mBfIRBuilder->ClearDebugLocation(storeInst);
  135. if (WantsDebugInfo())
  136. {
  137. auto deferredCallEntryType = ResolveTypeDef(mCompiler->mDeferredCallTypeDef);
  138. auto deferredCallEntryTypePtr = CreatePointerType(deferredCallEntryType);
  139. String varName = StrFormat("__deferred%d", mCurMethodState->mDeferredLoopListCount);
  140. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  141. if (scopeHead->mDIScope)
  142. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, scopeHead->mDIScope, BfIRMDNode());
  143. mBfIRBuilder->CreateStatementStart();
  144. //TODO: Make this work for LLVM - we need a proper debug location
  145. //if (IsTargetingBeefBackend())
  146. {
  147. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(scopeHead->mDIScope, varName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(deferredCallEntryTypePtr));
  148. mBfIRBuilder->DbgInsertDeclare(listEntry->mDynCallTail, diVariable);
  149. }
  150. mCurMethodState->mDeferredLoopListCount++;
  151. }
  152. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  153. mBfIRBuilder->RestoreDebugLocation();
  154. }
  155. mCurMethodState->mCurScope->ClearHandlers(scopeData);
  156. scopeData->mDeferredCallEntries.PushFront(listEntry);
  157. }
  158. BfIRValue deferredAlloca;
  159. SizedArray<BfType*, 4> types;
  160. SizedArray<String, 8> memberNames;
  161. int instAlign = 1;
  162. int dataPos = 0;
  163. int instSize = 0;
  164. Array<int> memberPositions;
  165. String typeName;
  166. BfDeferredMethodCallData* deferredMethodCallData = NULL;
  167. if (deferredCallEntry->mDeferredBlock != NULL)
  168. {
  169. HashContext hashCtx;
  170. hashCtx.Mixin(deferredCallEntry->mDeferredBlock->GetSrcStart());
  171. auto parserData = deferredCallEntry->mDeferredBlock->GetParserData();
  172. if (parserData != NULL)
  173. hashCtx.MixinStr(parserData->mFileName);
  174. int64 blockId = BfDeferredMethodCallData::GenerateMethodId(this, hashCtx.Finish64());
  175. deferredCallEntry->mBlockId = blockId;
  176. auto deferType = deferredCallEntryType;
  177. BfIRType deferIRType;
  178. auto int64Type = GetPrimitiveType(BfTypeCode_Int64);
  179. types.push_back(int64Type);
  180. memberNames.push_back("__methodId");
  181. types.push_back(deferredCallEntryTypePtr);
  182. memberNames.push_back("__next");
  183. for (auto& capture : deferredCallEntry->mCaptures)
  184. {
  185. BfType* type = capture.mValue.mType;
  186. types.push_back(type);
  187. memberNames.push_back(capture.mName);
  188. }
  189. SizedArray<BfIRType, 4> llvmTypes;
  190. SizedArray<BfIRMDNode, 8> diFieldTypes;
  191. typeName = StrFormat("_BF_DeferredData_%s", BfTypeUtils::HashEncode64(blockId).c_str());
  192. auto valueType = ResolveTypeDef(mCompiler->mValueTypeTypeDef);
  193. llvmTypes.push_back(mBfIRBuilder->MapType(valueType));
  194. //int dataPos = 0;
  195. for (int i = 0; i < (int)memberNames.size(); i++)
  196. {
  197. auto type = types[i];
  198. auto memberName = memberNames[i];
  199. if (!type->IsValuelessType())
  200. {
  201. llvmTypes.push_back(mBfIRBuilder->MapType(type));
  202. instAlign = BF_MAX(instAlign, (int)type->mAlign);
  203. int alignSize = (int)type->mAlign;
  204. int dataSize = type->mSize;
  205. if (alignSize > 1)
  206. dataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  207. memberPositions.push_back(dataPos);
  208. dataPos += type->mSize;
  209. }
  210. }
  211. instSize = dataPos;
  212. deferIRType = mBfIRBuilder->CreateStructType(typeName);
  213. mBfIRBuilder->StructSetBody(deferIRType, llvmTypes, instSize, instAlign, false);
  214. auto prevInsertPoint = mBfIRBuilder->GetInsertBlock();
  215. if (!isLooped)
  216. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  217. deferredAlloca = mBfIRBuilder->CreateAlloca(deferIRType);
  218. mBfIRBuilder->SetAllocaAlignment(deferredAlloca, instAlign);
  219. mBfIRBuilder->SetAllocaNoChkStkHint(deferredAlloca);
  220. if (!isLooped)
  221. mBfIRBuilder->SetInsertPoint(prevInsertPoint);
  222. auto gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, 2); // mNext
  223. auto prevVal = mBfIRBuilder->CreateLoad(listEntry->mDynCallTail);
  224. mBfIRBuilder->CreateStore(prevVal, gepInstance);
  225. gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, 1); // mMethodId
  226. mBfIRBuilder->CreateStore(GetConstValue64(blockId), gepInstance);
  227. if (!deferredCallEntry->mCaptures.empty())
  228. {
  229. int dataIdx = 3;
  230. for (int captureIdx = 0; captureIdx < (int)deferredCallEntry->mCaptures.size(); captureIdx++)
  231. {
  232. auto& capture = deferredCallEntry->mCaptures[captureIdx];
  233. if (!capture.mValue.mType->IsValuelessType())
  234. {
  235. auto gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, dataIdx);
  236. mBfIRBuilder->CreateStore(capture.mValue.mValue, gepInstance);
  237. dataIdx++;
  238. }
  239. }
  240. }
  241. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateBitCast(deferredAlloca, mBfIRBuilder->MapType(deferredCallEntryTypePtr)), listEntry->mDynCallTail);
  242. deferredCallEntry->mDeferredAlloca = deferredAlloca;
  243. listEntry->mDynList.PushFront(deferredCallEntry);
  244. }
  245. else
  246. {
  247. auto& llvmArgs = deferredCallEntry->mScopeArgs;
  248. auto moduleMethodInstance = deferredCallEntry->mModuleMethodInstance;
  249. auto methodInstance = moduleMethodInstance.mMethodInstance;
  250. auto methodDef = methodInstance->mMethodDef;
  251. auto owningType = methodInstance->mMethodInstanceGroup->mOwner;
  252. auto voidType = GetPrimitiveType(BfTypeCode_None);
  253. auto voidPtrType = CreatePointerType(voidType);
  254. BfDeferredMethodCallData** deferredMethodCallDataPtr = NULL;
  255. if (mDeferredMethodCallData.TryGetValue(methodInstance, &deferredMethodCallDataPtr))
  256. {
  257. deferredMethodCallData = *deferredMethodCallDataPtr;
  258. }
  259. else
  260. {
  261. deferredMethodCallData = new BfDeferredMethodCallData();
  262. mDeferredMethodCallData[methodInstance] = deferredMethodCallData;
  263. deferredMethodCallData->mMethodId = BfDeferredMethodCallData::GenerateMethodId(this, methodInstance->mIdHash);
  264. auto int64Type = GetPrimitiveType(BfTypeCode_Int64);
  265. auto methodDef = moduleMethodInstance.mMethodInstance->mMethodDef;
  266. auto thisType = moduleMethodInstance.mMethodInstance->mMethodInstanceGroup->mOwner;
  267. types.push_back(int64Type);
  268. memberNames.push_back("__methodId");
  269. types.push_back(deferredCallEntryTypePtr);
  270. memberNames.push_back("__next");
  271. if (!methodDef->mIsStatic)
  272. {
  273. types.push_back(thisType);
  274. memberNames.push_back("__this");
  275. }
  276. for (int paramIdx = 0; paramIdx < (int)methodInstance->GetParamCount(); paramIdx++)
  277. {
  278. if (methodInstance->IsParamSkipped(paramIdx))
  279. paramIdx++;
  280. types.push_back(methodInstance->GetParamType(paramIdx));
  281. memberNames.push_back(methodInstance->GetParamName(paramIdx));
  282. }
  283. SizedArray<BfIRType, 4> llvmTypes;
  284. //String typeName;
  285. typeName += StrFormat("_BF_DeferredData_%s", BfTypeUtils::HashEncode64(deferredMethodCallData->mMethodId).c_str());
  286. BfLogSysM("Building type: %s from methodInstance:%p\n", typeName.c_str(), methodInstance);
  287. //Array<int> memberPositions;
  288. //int instAlign = 1;
  289. //int dataPos = 0;
  290. BF_ASSERT(types.size() == memberNames.size());
  291. for (int i = 0; i < (int)types.size(); i++)
  292. {
  293. auto type = types[i];
  294. auto memberName = memberNames[i];
  295. if (!type->IsValuelessType())
  296. {
  297. llvmTypes.push_back(mBfIRBuilder->MapType(type));
  298. instAlign = BF_MAX(instAlign, (int)type->mAlign);
  299. int alignSize = (int)type->mAlign;
  300. int dataSize = type->mSize;
  301. if (alignSize > 1)
  302. dataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  303. memberPositions.push_back(dataPos);
  304. dataPos += type->mSize;
  305. }
  306. }
  307. instSize = dataPos;
  308. deferredMethodCallData->mAlign = instAlign;
  309. deferredMethodCallData->mSize = instSize;
  310. deferredMethodCallData->mDeferType = mBfIRBuilder->CreateStructType(typeName);
  311. mBfIRBuilder->StructSetBody(deferredMethodCallData->mDeferType, llvmTypes, instSize, instAlign, false);
  312. deferredMethodCallData->mDeferTypePtr = mBfIRBuilder->GetPointerTo(deferredMethodCallData->mDeferType);
  313. }
  314. auto deferType = deferredMethodCallData->mDeferType;
  315. auto prevInsertPoint = mBfIRBuilder->GetInsertBlock();
  316. if (!isLooped)
  317. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  318. deferredAlloca = mBfIRBuilder->CreateAlloca(BfIRType(deferredMethodCallData->mDeferType));
  319. mBfIRBuilder->ClearDebugLocation(deferredAlloca);
  320. mBfIRBuilder->SetAllocaAlignment(deferredAlloca, deferredMethodCallData->mAlign);
  321. mBfIRBuilder->SetAllocaNoChkStkHint(deferredAlloca);
  322. if (!isLooped)
  323. mBfIRBuilder->SetInsertPoint(prevInsertPoint);
  324. auto gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, 1);
  325. auto prevVal = mBfIRBuilder->CreateLoad(listEntry->mDynCallTail);
  326. mBfIRBuilder->CreateStore(prevVal, gepInstance);
  327. gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, 0);
  328. mBfIRBuilder->CreateStore(GetConstValue64(deferredMethodCallData->mMethodId), gepInstance);
  329. int dataIdx = 2;
  330. int argIdx = 0;
  331. if ((!methodDef->mIsStatic) && (!owningType->IsValuelessType()))
  332. {
  333. gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, 2);
  334. if (owningType->IsValueType())
  335. {
  336. if ((!methodDef->mIsMutating) && (owningType->IsSplattable()))
  337. {
  338. BfTypedValue splatVal(llvmArgs[0], owningType, BfTypedValueKind_ThisSplatHead);
  339. BfTypedValue aggVal = AggregateSplat(splatVal, &llvmArgs[0]);
  340. aggVal = LoadValue(aggVal);
  341. mBfIRBuilder->CreateStore(aggVal.mValue, gepInstance);
  342. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, owningType);
  343. }
  344. else
  345. {
  346. auto thisArg = mBfIRBuilder->CreateLoad(llvmArgs[0]);
  347. mBfIRBuilder->CreateStore(thisArg, gepInstance);
  348. argIdx++;
  349. }
  350. }
  351. else
  352. {
  353. mBfIRBuilder->CreateStore(llvmArgs[0], gepInstance);
  354. argIdx++;
  355. }
  356. dataIdx++;
  357. }
  358. for (int paramIdx = 0; paramIdx < (int)methodInstance->GetParamCount(); paramIdx++, dataIdx++)
  359. {
  360. if (methodInstance->IsParamSkipped(paramIdx))
  361. paramIdx++;
  362. auto paramType = methodInstance->GetParamType(paramIdx);
  363. bool paramIsSplat = methodInstance->GetParamIsSplat(paramIdx);
  364. gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, dataIdx/*, methodDef->mParams[paramIdx]->mName*/);
  365. if (paramType->IsStruct())
  366. {
  367. if (paramIsSplat)
  368. {
  369. BfTypedValue splatVal(llvmArgs[argIdx], paramType, BfTypedValueKind_SplatHead);
  370. BfTypedValue aggVal = AggregateSplat(splatVal, &llvmArgs[argIdx]);
  371. aggVal = LoadValue(aggVal);
  372. mBfIRBuilder->CreateStore(aggVal.mValue, gepInstance);
  373. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramType);
  374. }
  375. else
  376. {
  377. auto val = mBfIRBuilder->CreateLoad(llvmArgs[argIdx]);
  378. mBfIRBuilder->CreateStore(val, gepInstance);
  379. argIdx++;
  380. }
  381. }
  382. else
  383. {
  384. mBfIRBuilder->CreateStore(llvmArgs[argIdx], gepInstance);
  385. argIdx++;
  386. }
  387. }
  388. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateBitCast(deferredAlloca, mBfIRBuilder->MapType(deferredCallEntryTypePtr)), listEntry->mDynCallTail);
  389. deferredCallEntry->mDeferredAlloca = deferredAlloca;
  390. listEntry->mDynList.PushFront(deferredCallEntry);
  391. }
  392. if ((mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) && (mCompiler->mOptions.mEmitDebugInfo) && (mCurMethodState->mCurScope->mDIScope))
  393. {
  394. auto int64Type = GetPrimitiveType(BfTypeCode_Int64);
  395. auto moduleMethodInstance = deferredCallEntry->mModuleMethodInstance;
  396. auto methodInstance = moduleMethodInstance.mMethodInstance;
  397. BfIRMDNode deferDIType;
  398. if ((deferredMethodCallData != NULL) && (deferredMethodCallData->mDeferDIType))
  399. {
  400. deferDIType = deferredMethodCallData->mDeferDIType;
  401. }
  402. else
  403. {
  404. BfIRMDNode diForwardDecl;
  405. SizedArray<BfIRMDNode, 8> diFieldTypes;
  406. if ((mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  407. {
  408. String dbgTypeName;
  409. if (mCompiler->mOptions.IsCodeView())
  410. dbgTypeName += "_bf::";
  411. dbgTypeName += typeName;
  412. diForwardDecl = mBfIRBuilder->DbgCreateReplaceableCompositeType(llvm::dwarf::DW_TAG_structure_type, dbgTypeName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mFileInstance->mDIFile,
  413. mCurFilePosition.mCurLine, instSize * 8, instAlign * 8);
  414. if (methodInstance != NULL)
  415. {
  416. // We make a fake member to get inserted into the DbgModule data so we can show what method this deferred call goes to
  417. StringT<128> mangledName;
  418. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  419. auto memberType = mBfIRBuilder->DbgCreateMemberType(diForwardDecl, mangledName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine,
  420. 0, 0, -1, 0, mBfIRBuilder->DbgGetType(int64Type));
  421. diFieldTypes.push_back(memberType);
  422. }
  423. }
  424. for (int i = 0; i < (int)types.size(); i++)
  425. {
  426. auto type = types[i];
  427. auto memberName = memberNames[i];
  428. if ((mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  429. {
  430. int memberFlags = 0;
  431. auto memberType = mBfIRBuilder->DbgCreateMemberType(diForwardDecl, memberName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine,
  432. type->mSize * 8, type->mAlign * 8, memberPositions[i] * 8, memberFlags, mBfIRBuilder->DbgGetType(type));
  433. diFieldTypes.push_back(memberType);
  434. }
  435. }
  436. int diFlags = 0;
  437. mBfIRBuilder->DbgMakePermanent(diForwardDecl, BfIRMDNode(), diFieldTypes);
  438. deferDIType = mBfIRBuilder->DbgCreatePointerType(diForwardDecl);
  439. if (deferredMethodCallData != NULL)
  440. deferredMethodCallData->mDeferDIType = deferDIType;
  441. }
  442. // We don't actually want to see this, and it doesn't emit properly in LLVM CodeView anyway - it only accepts static allocs,
  443. // not dynamic allocas
  444. String varName = StrFormat("$__deferredCall_%d", mCurMethodState->mDeferredLoopListEntryCount);
  445. mCurMethodState->mDeferredLoopListEntryCount++;
  446. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  447. varName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, deferDIType);
  448. mBfIRBuilder->DbgInsertDeclare(deferredAlloca, diVariable);
  449. }
  450. return true;
  451. }
  452. BfDeferredCallEntry* BfModule::AddDeferredBlock(BfBlock* block, BfScopeData* scopeData, Array<BfDeferredCapture>* captures)
  453. {
  454. BfDeferredCallEntry* deferredCallEntry = new BfDeferredCallEntry();
  455. deferredCallEntry->mDeferredBlock = block;
  456. if (captures != NULL)
  457. deferredCallEntry->mCaptures = *captures;
  458. AddDeferredCallEntry(deferredCallEntry, scopeData);
  459. return deferredCallEntry;
  460. }
  461. BfDeferredCallEntry* BfModule::AddDeferredCall(const BfModuleMethodInstance& moduleMethodInstance, SizedArrayImpl<BfIRValue>& llvmArgs, BfScopeData* scopeData, BfAstNode* srcNode, bool bypassVirtual, bool doNullCheck)
  462. {
  463. BfDeferredCallEntry* deferredCallEntry = new BfDeferredCallEntry();
  464. BF_ASSERT(moduleMethodInstance);
  465. deferredCallEntry->mModuleMethodInstance = moduleMethodInstance;
  466. for (auto arg : llvmArgs)
  467. {
  468. deferredCallEntry->mScopeArgs.push_back(arg);
  469. }
  470. deferredCallEntry->mSrcNode = srcNode;
  471. deferredCallEntry->mBypassVirtual = bypassVirtual;
  472. deferredCallEntry->mDoNullCheck = doNullCheck;
  473. if (!AddDeferredCallEntry(deferredCallEntry, scopeData))
  474. return NULL;
  475. return deferredCallEntry;
  476. }
  477. void BfModule::EmitDeferredCall(BfModuleMethodInstance moduleMethodInstance, SizedArrayImpl<BfIRValue>& llvmArgs, BfDeferredBlockFlags flags)
  478. {
  479. if (moduleMethodInstance.mMethodInstance->GetOwner()->IsInstanceOf(mCompiler->mInternalTypeDef))
  480. {
  481. if (moduleMethodInstance.mMethodInstance->mMethodDef->mName.StartsWith("SetDeleted"))
  482. {
  483. intptr typeSize = 0;
  484. intptr typeAlign = 1;
  485. intptr clearSize = 0;
  486. bool isDynSize = false;
  487. bool mayBeZero = false;
  488. auto ptrValue = llvmArgs[0];
  489. BfIRValue arraySize;
  490. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeleted") ||
  491. (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeletedArray"))
  492. {
  493. auto constant = mBfIRBuilder->GetConstant(llvmArgs[1]);
  494. if (constant != NULL)
  495. typeSize = constant->mInt64;
  496. constant = mBfIRBuilder->GetConstant(llvmArgs[2]);
  497. if (constant != NULL)
  498. typeAlign = constant->mInt64;
  499. if (llvmArgs.size() >= 4)
  500. arraySize = llvmArgs[3];
  501. intptr allocSize = typeSize;
  502. if (arraySize)
  503. {
  504. allocSize = BF_ALIGN(typeSize, typeAlign);
  505. auto constant = mBfIRBuilder->GetConstant(arraySize);
  506. if (constant != NULL)
  507. allocSize = allocSize * (intptr)constant->mInt64;
  508. else
  509. {
  510. isDynSize = true;
  511. mayBeZero = true;
  512. }
  513. }
  514. clearSize = BF_MIN(allocSize, mSystem->mPtrSize);
  515. }
  516. else if (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeletedX")
  517. {
  518. // Note: this infers that mayBeZero is false still, because the deferred call would not have
  519. // been added if the array size was zero
  520. typeSize = 1;
  521. clearSize = typeSize;
  522. arraySize = llvmArgs[1];
  523. isDynSize = true;
  524. }
  525. else if (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeleted1")
  526. {
  527. clearSize = 1;
  528. }
  529. else if (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeleted2")
  530. {
  531. clearSize = 2;
  532. }
  533. else if (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeleted4")
  534. {
  535. clearSize = 4;
  536. }
  537. else if (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeleted8")
  538. {
  539. clearSize = 8;
  540. }
  541. else if (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeleted16")
  542. {
  543. clearSize = 16;
  544. }
  545. if (clearSize > 0)
  546. {
  547. BfTypeCode clearTypeCode = BfTypeCode_Int8;
  548. if (clearSize >= mSystem->mPtrSize)
  549. clearTypeCode = BfTypeCode_IntPtr;
  550. else if (clearSize >= 4)
  551. clearTypeCode = BfTypeCode_Int32;
  552. else if (clearSize >= 2)
  553. clearTypeCode = BfTypeCode_Int16;
  554. auto intType = GetPrimitiveType(clearTypeCode);
  555. auto intPtrType = CreatePointerType(intType);
  556. if (isDynSize)
  557. {
  558. if (clearSize >= mSystem->mPtrSize)
  559. {
  560. auto ddSize1Block = mBfIRBuilder->CreateBlock("DDSize1");
  561. auto ddDoneBlock = mBfIRBuilder->CreateBlock("DDDone");
  562. auto cmp = mBfIRBuilder->CreateCmpGT(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), true);
  563. mBfIRBuilder->CreateCondBr(cmp, ddSize1Block, ddDoneBlock);
  564. mBfIRBuilder->AddBlock(ddSize1Block);
  565. mBfIRBuilder->SetInsertPoint(ddSize1Block);
  566. auto intPtrVal = mBfIRBuilder->CreateBitCast(ptrValue, mBfIRBuilder->MapType(intPtrType));
  567. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateConst(clearTypeCode, (uint64)0xDDDDDDDDDDDDDDDDULL), intPtrVal);
  568. mBfIRBuilder->CreateBr(ddDoneBlock);
  569. mBfIRBuilder->AddBlock(ddDoneBlock);
  570. mBfIRBuilder->SetInsertPoint(ddDoneBlock);
  571. if ((flags & BfDeferredBlockFlag_MoveNewBlocksToEnd) != 0)
  572. {
  573. mCurMethodState->mCurScope->mAtEndBlocks.push_back(ddSize1Block);
  574. mCurMethodState->mCurScope->mAtEndBlocks.push_back(ddDoneBlock);
  575. }
  576. }
  577. else
  578. {
  579. // If we allocate at least this many then we can do an IntPtr-sized marking, otherwise just one element's worth
  580. int intPtrCount = (int)((mSystem->mPtrSize + typeSize - 1) / typeSize);
  581. BfIRBlock ddSizePtrBlock = mBfIRBuilder->CreateBlock("DDSizePtr");
  582. BfIRBlock ddCheck1Block = mBfIRBuilder->CreateBlock("DDCheck1");
  583. BfIRBlock ddSize1Block;
  584. if (mayBeZero)
  585. ddSize1Block = mBfIRBuilder->CreateBlock("DDSize1");
  586. BfIRBlock ddDoneBlock = mBfIRBuilder->CreateBlock("DDDone");
  587. auto intptrType = GetPrimitiveType(BfTypeCode_IntPtr);
  588. auto intptrPtrType = CreatePointerType(intptrType);
  589. auto cmpPtr = mBfIRBuilder->CreateCmpGTE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, intPtrCount), true);
  590. mBfIRBuilder->CreateCondBr(cmpPtr, ddSizePtrBlock, ddCheck1Block);
  591. mBfIRBuilder->AddBlock(ddSizePtrBlock);
  592. mBfIRBuilder->SetInsertPoint(ddSizePtrBlock);
  593. auto intptrPtrVal = mBfIRBuilder->CreateBitCast(ptrValue, mBfIRBuilder->MapType(intptrPtrType));
  594. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)0xDDDDDDDDDDDDDDDDULL), intptrPtrVal);
  595. mBfIRBuilder->CreateBr(ddDoneBlock);
  596. mBfIRBuilder->AddBlock(ddCheck1Block);
  597. mBfIRBuilder->SetInsertPoint(ddCheck1Block);
  598. if (mayBeZero)
  599. {
  600. auto cmp1 = mBfIRBuilder->CreateCmpGT(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), true);
  601. mBfIRBuilder->CreateCondBr(cmp1, ddSize1Block, ddDoneBlock);
  602. mBfIRBuilder->AddBlock(ddSize1Block);
  603. mBfIRBuilder->SetInsertPoint(ddSize1Block);
  604. }
  605. auto intPtrVal = mBfIRBuilder->CreateBitCast(ptrValue, mBfIRBuilder->MapType(intPtrType));
  606. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateConst(clearTypeCode, (uint64)0xDDDDDDDDDDDDDDDDULL), intPtrVal);
  607. mBfIRBuilder->CreateBr(ddDoneBlock);
  608. mBfIRBuilder->AddBlock(ddDoneBlock);
  609. mBfIRBuilder->SetInsertPoint(ddDoneBlock);
  610. if ((flags & BfDeferredBlockFlag_MoveNewBlocksToEnd) != 0)
  611. {
  612. mCurMethodState->mCurScope->mAtEndBlocks.push_back(ddSizePtrBlock);
  613. mCurMethodState->mCurScope->mAtEndBlocks.push_back(ddCheck1Block);
  614. if (mayBeZero)
  615. mCurMethodState->mCurScope->mAtEndBlocks.push_back(ddSize1Block);
  616. mCurMethodState->mCurScope->mAtEndBlocks.push_back(ddDoneBlock);
  617. }
  618. }
  619. }
  620. else
  621. {
  622. auto intPtrVal = mBfIRBuilder->CreateBitCast(ptrValue, mBfIRBuilder->MapType(intPtrType));
  623. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateConst(clearTypeCode, (uint64)0xDDDDDDDDDDDDDDDDULL), intPtrVal);
  624. }
  625. }
  626. return;
  627. }
  628. }
  629. if (moduleMethodInstance.mMethodInstance == mContext->mValueTypeDeinitSentinel)
  630. {
  631. BF_ASSERT(llvmArgs.size() == 3);
  632. auto sizeConstant = mBfIRBuilder->GetConstant(llvmArgs[1]);
  633. int clearSize = BF_MIN(sizeConstant->mInt32, 32);
  634. auto alignConstant = mBfIRBuilder->GetConstant(llvmArgs[2]);
  635. int clearAlign = alignConstant->mInt32;
  636. mBfIRBuilder->CreateMemSet(llvmArgs[0], GetConstValue8(0xDD), GetConstValue(clearSize), clearAlign);
  637. return;
  638. }
  639. auto methodInstance = moduleMethodInstance.mMethodInstance;
  640. auto methodOwner = methodInstance->mMethodInstanceGroup->mOwner;
  641. bool isDtor = methodInstance->mMethodDef->mMethodType == BfMethodType_Dtor;
  642. bool isScopeDtor = isDtor && ((flags & BfDeferredBlockFlag_BypassVirtual) != 0);
  643. if ((isDtor) && (methodInstance->GetParamCount() != 0))
  644. {
  645. // Dtor declared with params
  646. AssertErrorState();
  647. return;
  648. }
  649. BfIRBlock nullLabel;
  650. BfIRBlock notNullLabel;
  651. if ((flags & BfDeferredBlockFlag_DoNullChecks) != 0)
  652. {
  653. nullLabel = mBfIRBuilder->CreateBlock("deferred.isNull");
  654. notNullLabel = mBfIRBuilder->CreateBlock("deferred.notNull");
  655. auto notNullVal = mBfIRBuilder->CreateIsNotNull(llvmArgs[0]);
  656. mBfIRBuilder->CreateCondBr(notNullVal, notNullLabel, nullLabel);
  657. mBfIRBuilder->AddBlock(notNullLabel);
  658. mBfIRBuilder->SetInsertPoint(notNullLabel);
  659. }
  660. bool skipAccessCheck = false;
  661. if ((flags & BfDeferredBlockFlag_SkipObjectAccessCheck) != 0)
  662. skipAccessCheck = true;
  663. if ((!methodInstance->mMethodDef->mIsStatic) && (methodOwner->IsObjectOrInterface()) && (!isScopeDtor) &&
  664. (!skipAccessCheck))
  665. {
  666. EmitObjectAccessCheck(BfTypedValue(llvmArgs[0], methodOwner));
  667. }
  668. BfExprEvaluator expressionEvaluator(this);
  669. expressionEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, ((flags & BfDeferredBlockFlag_BypassVirtual) != 0), llvmArgs);
  670. if ((flags & BfDeferredBlockFlag_DoNullChecks) != 0)
  671. {
  672. mBfIRBuilder->CreateBr(nullLabel);
  673. mBfIRBuilder->AddBlock(nullLabel);
  674. mBfIRBuilder->SetInsertPoint(nullLabel);
  675. if (!mBfIRBuilder->mIgnoreWrites)
  676. {
  677. if ((flags & BfDeferredBlockFlag_MoveNewBlocksToEnd) != 0)
  678. {
  679. mCurMethodState->mCurScope->mAtEndBlocks.push_back(notNullLabel);
  680. mCurMethodState->mCurScope->mAtEndBlocks.push_back(nullLabel);
  681. }
  682. }
  683. }
  684. }
  685. void BfModule::EmitDeferredCallProcessorInstances(BfScopeData* scopeData)
  686. {
  687. BF_ASSERT(scopeData->mDone);
  688. for (auto& deferredProcessor : scopeData->mDeferredCallProcessorInstances)
  689. {
  690. SetAndRestoreValue<bool> prevHadReturn(mCurMethodState->mHadReturn, false);
  691. SetAndRestoreValue<bool> prevInPostReturn(mCurMethodState->mInPostReturn, false);
  692. SetAndRestoreValue<bool> prevLeftBlockUncond(mCurMethodState->mLeftBlockUncond, false);
  693. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  694. mBfIRBuilder->AddBlock(deferredProcessor.mProcessorBlock);
  695. mBfIRBuilder->SetInsertPoint(deferredProcessor.mProcessorBlock);
  696. EmitDeferredCallProcessor(scopeData, deferredProcessor.mDeferredCallEntry->mDynList, deferredProcessor.mDeferredCallEntry->mDynCallTail);
  697. mBfIRBuilder->CreateBr(deferredProcessor.mContinueBlock);
  698. mBfIRBuilder->SetInsertPoint(prevBlock);
  699. }
  700. }
  701. void BfModule::EmitDeferredCall(BfScopeData* scopeData, BfDeferredCallEntry& deferredCallEntry, bool moveBlocks)
  702. {
  703. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (deferredCallEntry.mHandlerCount > 0))
  704. {
  705. // We only want to process deferred blocks once, otherwise it could significantly slow down autocompletion
  706. return;
  707. }
  708. deferredCallEntry.mHandlerCount++;
  709. if (deferredCallEntry.IsDynList())
  710. {
  711. if (scopeData->mDone)
  712. {
  713. EmitDeferredCallProcessor(scopeData, deferredCallEntry.mDynList, deferredCallEntry.mDynCallTail);
  714. }
  715. else
  716. {
  717. BfDeferredCallProcessorInstance deferredProcessor;
  718. deferredProcessor.mProcessorBlock = mBfIRBuilder->CreateBlock("dyn.processor");
  719. deferredProcessor.mContinueBlock = mBfIRBuilder->CreateBlock("dyn.continue");
  720. deferredProcessor.mDeferredCallEntry = &deferredCallEntry;
  721. scopeData->mDeferredCallProcessorInstances.Add(deferredProcessor);
  722. mBfIRBuilder->CreateBr(deferredProcessor.mProcessorBlock);
  723. mBfIRBuilder->AddBlock(deferredProcessor.mContinueBlock);
  724. mBfIRBuilder->SetInsertPoint(deferredProcessor.mContinueBlock);
  725. SetIllegalSrcPos();
  726. EmitEnsureInstructionAt();
  727. }
  728. return;
  729. }
  730. if (deferredCallEntry.mDeferredBlock != NULL)
  731. {
  732. // Only show warnings on the first pass
  733. // For errors, show on the first pass OR as long as we haven't gotten any errors within this method. I'm not sure if there's a case
  734. // where the first emission succeeds but a subsequent one would fail, but we leave this logic to handle that possibility
  735. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, (deferredCallEntry.mHandlerCount > 1) && (mCurMethodInstance->mHasFailed));
  736. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, (deferredCallEntry.mHandlerCount > 1));
  737. BfScopeData scopeData;
  738. mCurMethodState->AddScope(&scopeData);
  739. NewScopeState();
  740. for (auto& capture : deferredCallEntry.mCaptures)
  741. {
  742. BfLocalVariable* localVar = new BfLocalVariable();
  743. localVar->mIsReadOnly = true;
  744. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  745. localVar->mReadFromId = 0;
  746. localVar->mName = capture.mName;
  747. localVar->mValue = capture.mValue.mValue;
  748. localVar->mResolvedType = capture.mValue.mType;
  749. if ((mBfIRBuilder->DbgHasInfo()) && (!localVar->mResolvedType->IsValuelessType()))
  750. {
  751. auto addr = CreateAlloca(localVar->mResolvedType);
  752. mBfIRBuilder->CreateAlignedStore(localVar->mValue, addr, localVar->mResolvedType->mAlign);
  753. localVar->mAddr = addr;
  754. }
  755. AddLocalVariableDef(localVar, true);
  756. }
  757. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry.mEmitRefNode);
  758. VisitEmbeddedStatement(deferredCallEntry.mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  759. RestoreScopeState();
  760. return;
  761. }
  762. auto args = deferredCallEntry.mScopeArgs;
  763. if (deferredCallEntry.mArgsNeedLoad)
  764. {
  765. for (auto& arg : args)
  766. {
  767. if (!arg.IsConst())
  768. arg = mBfIRBuilder->CreateLoad(arg);
  769. }
  770. }
  771. if (deferredCallEntry.mCastThis)
  772. {
  773. args[0] = mBfIRBuilder->CreateBitCast(args[0], mBfIRBuilder->MapTypeInstPtr(deferredCallEntry.mModuleMethodInstance.mMethodInstance->GetOwner()));
  774. }
  775. BfDeferredBlockFlags flags = BfDeferredBlockFlag_None;
  776. if (deferredCallEntry.mBypassVirtual)
  777. flags = (BfDeferredBlockFlags)(flags | BfDeferredBlockFlag_BypassVirtual);
  778. if (deferredCallEntry.mDoNullCheck)
  779. flags = (BfDeferredBlockFlags)(flags | BfDeferredBlockFlag_DoNullChecks | BfDeferredBlockFlag_SkipObjectAccessCheck | BfDeferredBlockFlag_MoveNewBlocksToEnd);
  780. if (moveBlocks)
  781. flags = (BfDeferredBlockFlags)(flags | BfDeferredBlockFlag_MoveNewBlocksToEnd);
  782. EmitDeferredCall(deferredCallEntry.mModuleMethodInstance, args, flags);
  783. }
  784. void BfModule::EmitDeferredCallProcessor(BfScopeData* scopeData, SLIList<BfDeferredCallEntry*>& callEntries, BfIRValue callTail)
  785. {
  786. int64 collisionId = 0;
  787. struct _CallInfo
  788. {
  789. BfModuleMethodInstance mModuleMethodInstance;
  790. bool mBypassVirtual;
  791. };
  792. //typedef std::map<int64, _CallInfo> MapType;
  793. //MapType methodInstanceMap;
  794. Dictionary<int64, _CallInfo> methodInstanceMap;
  795. int blockCount = 0;
  796. HashSet<BfMethodInstance*> nullCheckMethodSet;
  797. BfDeferredCallEntry* deferredCallEntry = callEntries.mHead;
  798. while (deferredCallEntry != NULL)
  799. {
  800. BfModuleMethodInstance moduleMethodInstance = deferredCallEntry->mModuleMethodInstance;
  801. int64 methodId = 0;
  802. if (moduleMethodInstance.mMethodInstance != NULL)
  803. {
  804. int64 idHash = moduleMethodInstance.mMethodInstance->mIdHash;
  805. auto deferredMethodCallData = mDeferredMethodCallData[moduleMethodInstance.mMethodInstance];
  806. BF_ASSERT(deferredMethodCallData->mMethodId != 0);
  807. //methodInstanceMap[deferredMethodCallData->mMethodId] = moduleMethodInstance;
  808. _CallInfo* callInfo = NULL;
  809. if (methodInstanceMap.TryAdd(deferredMethodCallData->mMethodId, NULL, &callInfo))
  810. {
  811. callInfo->mModuleMethodInstance = moduleMethodInstance;
  812. callInfo->mBypassVirtual = deferredCallEntry->mBypassVirtual;
  813. }
  814. else
  815. {
  816. // Only bypass virtual if ALL these calls are devirtualized
  817. callInfo->mBypassVirtual &= deferredCallEntry->mBypassVirtual;
  818. }
  819. }
  820. else
  821. blockCount++;
  822. if (deferredCallEntry->mDoNullCheck)
  823. nullCheckMethodSet.Add(deferredCallEntry->mModuleMethodInstance.mMethodInstance);
  824. deferredCallEntry = deferredCallEntry->mNext;
  825. }
  826. bool moveBlocks = mCurMethodState->mCurScope != mCurMethodState->mTailScope;
  827. auto valueScopeStart = ValueScopeStart();
  828. if (valueScopeStart)
  829. mBfIRBuilder->SetName(valueScopeStart, "deferredScopeVal");
  830. BfIRBlock condBB = mBfIRBuilder->CreateBlock("deferCall.cond", true);
  831. if (moveBlocks)
  832. mCurMethodState->mCurScope->mAtEndBlocks.push_back(condBB);
  833. mBfIRBuilder->CreateBr(condBB);
  834. auto deferredCallEntryType = ResolveTypeDef(mCompiler->mDeferredCallTypeDef);
  835. auto deferredCallEntryTypePtr = CreatePointerType(deferredCallEntryType);
  836. BfIRBlock bodyBB = mBfIRBuilder->CreateBlock("deferCall.body");
  837. if (moveBlocks)
  838. mCurMethodState->mCurScope->mAtEndBlocks.push_back(bodyBB);
  839. BfIRBlock endBB = mBfIRBuilder->CreateBlock("deferCall.end");
  840. if (moveBlocks)
  841. mCurMethodState->mCurScope->mAtEndBlocks.push_back(endBB);
  842. BfIRBlock exitBB = endBB;
  843. BfIRValue deferredCallTail;
  844. mBfIRBuilder->SetInsertPoint(condBB);
  845. deferredCallTail = mBfIRBuilder->CreateLoad(callTail);
  846. auto isNotNull = mBfIRBuilder->CreateIsNotNull(deferredCallTail);
  847. ValueScopeEnd(valueScopeStart);
  848. mBfIRBuilder->CreateCondBr(isNotNull, bodyBB, exitBB);
  849. mBfIRBuilder->AddBlock(bodyBB);
  850. mBfIRBuilder->SetInsertPoint(bodyBB);
  851. BfIRValue switchInst;
  852. bool wantsSwitch = ((int)methodInstanceMap.size() + blockCount) > 1;
  853. if (blockCount > 0)
  854. {
  855. // A block may embed a switch so we need a switch whenever we have blocks
  856. wantsSwitch = true;
  857. }
  858. if (mCurMethodState->mCancelledDeferredCall)
  859. wantsSwitch = true;
  860. if (wantsSwitch)
  861. {
  862. if (IsTargetingBeefBackend())
  863. deferredCallTail = mBfIRBuilder->CreateLoad(callTail);
  864. auto idPtr = mBfIRBuilder->CreateInBoundsGEP(deferredCallTail, 0, 1); // mMethodId
  865. auto id = mBfIRBuilder->CreateLoad(idPtr);
  866. switchInst = mBfIRBuilder->CreateSwitch(id, exitBB, (int)methodInstanceMap.size());
  867. ValueScopeEnd(valueScopeStart);
  868. }
  869. BfDeferredCallEntry* prevHead = callEntries.mHead;
  870. BfDeferredCallEntry* prevCallEntry = NULL;
  871. HashSet<BfDeferredCallEntry*> handledSet;
  872. deferredCallEntry = callEntries.mHead;
  873. while (deferredCallEntry != NULL)
  874. {
  875. auto block = deferredCallEntry->mDeferredBlock;
  876. if (block == NULL)
  877. {
  878. deferredCallEntry = deferredCallEntry->mNext;
  879. continue;
  880. }
  881. int64 blockId = deferredCallEntry->mBlockId;
  882. //auto itr = handledSet.insert(deferredCallEntry);
  883. //if (!itr.second)
  884. if (!handledSet.Add(deferredCallEntry))
  885. {
  886. // Already handled, can happen if we defer again within the block
  887. deferredCallEntry = deferredCallEntry->mNext;
  888. continue;
  889. }
  890. if (switchInst)
  891. {
  892. String caseName = StrFormat("deferCall.%s", BfTypeUtils::HashEncode64(blockId).c_str());
  893. auto caseBB = mBfIRBuilder->CreateBlock(caseName, true);
  894. if (moveBlocks)
  895. mCurMethodState->mCurScope->mAtEndBlocks.push_back(caseBB);
  896. mBfIRBuilder->AddSwitchCase(switchInst, GetConstValue64(blockId), caseBB);
  897. mBfIRBuilder->SetInsertPoint(caseBB);
  898. }
  899. // Update .mDeferredAlloca to use the deferredCallTail
  900. if (IsTargetingBeefBackend())
  901. deferredCallTail = mBfIRBuilder->CreateLoad(callTail);
  902. auto nextPtr = mBfIRBuilder->CreateInBoundsGEP(deferredCallTail, 0, 2); // mNext
  903. auto next = mBfIRBuilder->CreateLoad(nextPtr);
  904. mBfIRBuilder->CreateStore(next, callTail);
  905. deferredCallEntry->mDeferredAlloca = mBfIRBuilder->CreateBitCast(deferredCallTail, mBfIRBuilder->GetType(deferredCallEntry->mDeferredAlloca));
  906. int dataIdx = 3;
  907. // Update .mCaptures to contain the stored values at the time the defer occurred
  908. for (int captureIdx = 0; captureIdx < (int)deferredCallEntry->mCaptures.size(); captureIdx++)
  909. {
  910. auto& capture = deferredCallEntry->mCaptures[captureIdx];
  911. if (!capture.mValue.mType->IsValuelessType())
  912. {
  913. auto gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredCallEntry->mDeferredAlloca, 0, dataIdx);
  914. capture.mValue.mValue = mBfIRBuilder->CreateLoad(gepInstance);
  915. dataIdx++;
  916. }
  917. }
  918. auto prevHead = callEntries.mHead;
  919. EmitDeferredCall(scopeData, *deferredCallEntry, moveBlocks);
  920. ValueScopeEnd(valueScopeStart);
  921. mBfIRBuilder->CreateBr(condBB);
  922. if (prevHead != callEntries.mHead)
  923. {
  924. // The list changed, start over and ignore anything we've already handled
  925. deferredCallEntry = callEntries.mHead;
  926. }
  927. else
  928. deferredCallEntry = deferredCallEntry->mNext;
  929. }
  930. // Blocks may have added new method types, so rebuild map
  931. if (blockCount > 0)
  932. {
  933. deferredCallEntry = callEntries.mHead;
  934. while (deferredCallEntry != NULL)
  935. {
  936. BfModuleMethodInstance moduleMethodInstance = deferredCallEntry->mModuleMethodInstance;
  937. if (moduleMethodInstance.mMethodInstance != NULL)
  938. {
  939. auto deferredMethodCallData = mDeferredMethodCallData[moduleMethodInstance.mMethodInstance];
  940. //methodInstanceMap.insert(MapType::value_type(deferredMethodCallData->mMethodId, moduleMethodInstance));
  941. _CallInfo* callInfo = NULL;
  942. if (methodInstanceMap.TryAdd(deferredMethodCallData->mMethodId, NULL, &callInfo))
  943. {
  944. callInfo->mModuleMethodInstance = moduleMethodInstance;
  945. callInfo->mBypassVirtual = deferredCallEntry->mBypassVirtual;
  946. }
  947. }
  948. deferredCallEntry = deferredCallEntry->mNext;
  949. }
  950. }
  951. BfExprEvaluator exprEvaluator(this);
  952. //for (auto itr = methodInstanceMap.begin(); itr != methodInstanceMap.end(); ++itr)
  953. for (auto& callInfoKV : methodInstanceMap)
  954. {
  955. auto moduleMethodInstance = callInfoKV.mValue.mModuleMethodInstance;
  956. bool bypassVirtual = callInfoKV.mValue.mBypassVirtual;
  957. auto methodInstance = moduleMethodInstance.mMethodInstance;
  958. auto methodDef = methodInstance->mMethodDef;
  959. auto methodOwner = methodInstance->mMethodInstanceGroup->mOwner;
  960. BfIRValue deferredCallInst = deferredCallTail;
  961. auto deferredMethodCallData = mDeferredMethodCallData[methodInstance];
  962. int64 methodId = deferredMethodCallData->mMethodId;
  963. if (switchInst)
  964. {
  965. String caseName = StrFormat("deferCall.%s", BfTypeUtils::HashEncode64(methodId).c_str());
  966. auto caseBB = mBfIRBuilder->CreateBlock(caseName, true);
  967. if (moveBlocks)
  968. mCurMethodState->mCurScope->mAtEndBlocks.push_back(caseBB);
  969. mBfIRBuilder->AddSwitchCase(switchInst, GetConstValue64(methodId), caseBB);
  970. mBfIRBuilder->SetInsertPoint(caseBB);
  971. }
  972. if (IsTargetingBeefBackend())
  973. deferredCallTail = mBfIRBuilder->CreateLoad(callTail);
  974. auto nextPtr = mBfIRBuilder->CreateInBoundsGEP(deferredCallTail, 0, 2); // mNext
  975. auto next = mBfIRBuilder->CreateLoad(nextPtr);
  976. mBfIRBuilder->CreateStore(next, callTail);
  977. deferredCallInst = mBfIRBuilder->CreateBitCast(deferredCallTail, deferredMethodCallData->mDeferTypePtr);
  978. int paramIdx = 0;
  979. if (!methodDef->mIsStatic)
  980. paramIdx = -1;
  981. SizedArray<BfIRValue, 8> llvmArgs;
  982. for (int argIdx = 0; paramIdx < methodInstance->GetParamCount(); argIdx++, paramIdx++)
  983. {
  984. auto argPtr = mBfIRBuilder->CreateInBoundsGEP(deferredCallInst, 0, argIdx + 2);
  985. bool isStruct = false;
  986. bool doSplat = methodInstance->GetParamIsSplat(paramIdx);;
  987. BfTypedValue typedVal;
  988. if (paramIdx == -1)
  989. {
  990. typedVal = BfTypedValue(argPtr, methodOwner, true);
  991. }
  992. else
  993. {
  994. auto paramType = methodInstance->GetParamType(paramIdx);
  995. typedVal = BfTypedValue(argPtr, paramType, true);
  996. }
  997. if (doSplat)
  998. {
  999. exprEvaluator.SplatArgs(typedVal, llvmArgs);
  1000. continue;
  1001. }
  1002. if ((argIdx == 0) && (!methodDef->mIsStatic))
  1003. {
  1004. // 'this'
  1005. isStruct = methodOwner->IsValueType();
  1006. }
  1007. else
  1008. {
  1009. while (methodInstance->IsParamSkipped(paramIdx))
  1010. paramIdx++;
  1011. if (paramIdx >= methodInstance->GetParamCount())
  1012. break;
  1013. auto paramType = methodInstance->GetParamType(paramIdx);
  1014. isStruct = paramType->IsStruct();
  1015. }
  1016. if (isStruct)
  1017. {
  1018. llvmArgs.push_back(argPtr);
  1019. }
  1020. else
  1021. {
  1022. auto arg = mBfIRBuilder->CreateLoad(argPtr);
  1023. llvmArgs.push_back(arg);
  1024. }
  1025. }
  1026. BfDeferredBlockFlags flags = BfDeferredBlockFlag_None;
  1027. if (moveBlocks)
  1028. flags = (BfDeferredBlockFlags)(flags | BfDeferredBlockFlag_MoveNewBlocksToEnd);
  1029. if (nullCheckMethodSet.Contains(moduleMethodInstance.mMethodInstance))
  1030. flags = (BfDeferredBlockFlags)(flags | BfDeferredBlockFlag_DoNullChecks | BfDeferredBlockFlag_SkipObjectAccessCheck);
  1031. if (bypassVirtual)
  1032. flags = (BfDeferredBlockFlags)(flags | BfDeferredBlockFlag_BypassVirtual);
  1033. EmitDeferredCall(moduleMethodInstance, llvmArgs, flags);
  1034. ValueScopeEnd(valueScopeStart);
  1035. mBfIRBuilder->CreateBr(condBB);
  1036. }
  1037. if (endBB)
  1038. {
  1039. mBfIRBuilder->AddBlock(endBB);
  1040. mBfIRBuilder->SetInsertPoint(endBB);
  1041. }
  1042. }
  1043. void BfModule::TryInitVar(BfAstNode* checkNode, BfLocalVariable* localVar, BfTypedValue initValue, BfTypedValue& checkResult)
  1044. {
  1045. BF_ASSERT(!localVar->mAddr);
  1046. localVar->mAddr = AllocLocalVariable(localVar->mResolvedType, localVar->mName);
  1047. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  1048. auto varType = localVar->mResolvedType;
  1049. AddDependency(varType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  1050. if (!initValue)
  1051. {
  1052. AssertErrorState();
  1053. checkResult = BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolType);
  1054. return;
  1055. }
  1056. auto initType = initValue.mType;
  1057. bool isDynamicCast = false;
  1058. if (varType->IsGenericParam())
  1059. {
  1060. int pass = 0;
  1061. while (varType->IsGenericParam())
  1062. {
  1063. auto genericParamType = (BfGenericParamType*)varType;
  1064. auto genericParam = GetGenericParamInstance(genericParamType);
  1065. auto typeConstraint = genericParam->mTypeConstraint;
  1066. if ((typeConstraint == NULL) && (genericParam->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Interface)))
  1067. typeConstraint = mContext->mBfObjectType;
  1068. if (typeConstraint != NULL)
  1069. varType = typeConstraint;
  1070. else
  1071. break;
  1072. if (++pass >= 100) // Sanity - but we should have caught circular error before
  1073. break;
  1074. }
  1075. initValue = GetDefaultTypedValue(varType, false, BfDefaultValueKind_Undef);
  1076. }
  1077. BfTypeInstance* srcTypeInstance = initValue.mType->ToTypeInstance();
  1078. BfTypeInstance* varTypeInstance = varType->ToTypeInstance();
  1079. if (CanCast(initValue, varType))
  1080. {
  1081. if ((!varType->IsPointer()) && (!varType->IsObjectOrInterface()) && (!varType->IsVar()))
  1082. {
  1083. if (!IsInSpecializedSection())
  1084. {
  1085. if (initValue.mType != varType)
  1086. Warn(BfWarning_CS0472_ValueTypeNullCompare, StrFormat("Variable declaration is always 'true' because static cast cannot fail and a value of type '%s' can never be null",
  1087. TypeToString(varType).c_str()), checkNode);
  1088. else
  1089. Warn(BfWarning_CS0472_ValueTypeNullCompare, StrFormat("Variable declaration is always 'true' because a value of type '%s' can never be null",
  1090. TypeToString(varType).c_str()), checkNode);
  1091. }
  1092. }
  1093. }
  1094. // else if ((initType->IsInterface()) || (initType == mContext->mBfObjectType))
  1095. // {
  1096. // // Interface or System.Object -> *
  1097. // isDynamicCast = true;
  1098. // }
  1099. // else if ((srcTypeInstance != NULL) && (varTypeInstance != NULL) &&
  1100. // ((srcTypeInstance->IsObject()) && (TypeIsSubTypeOf(varTypeInstance, srcTypeInstance))))
  1101. // {
  1102. // // Class downcast
  1103. // isDynamicCast = true;
  1104. // }
  1105. // else if ((!CanCast(GetFakeTypedValue(varType), initType)) && (!initType->IsGenericParam()))
  1106. // {
  1107. // if (!IsInSpecializedSection())
  1108. // {
  1109. // Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  1110. // TypeToString(initValue.mType).c_str(), TypeToString(varType).c_str()), checkNode);
  1111. // }
  1112. // }
  1113. if (!isDynamicCast)
  1114. {
  1115. //initValue = Cast(checkNode, initValue, varType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  1116. initValue = Cast(checkNode, initValue, varType);
  1117. if (!initValue)
  1118. {
  1119. checkResult = BfTypedValue(GetConstValue(0, boolType), boolType);
  1120. }
  1121. else
  1122. {
  1123. if (localVar->mAddr)
  1124. {
  1125. initValue = LoadValue(initValue);
  1126. if (!initValue.mType->IsVar())
  1127. mBfIRBuilder->CreateAlignedStore(initValue.mValue, localVar->mAddr, initValue.mType->mAlign);
  1128. }
  1129. if (varType->IsVar())
  1130. {
  1131. checkResult = GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  1132. }
  1133. else if ((varType->IsPointer()) || (varType->IsObjectOrInterface()))
  1134. {
  1135. checkResult = BfTypedValue(mBfIRBuilder->CreateIsNotNull(initValue.mValue), boolType);
  1136. }
  1137. else
  1138. {
  1139. checkResult = BfTypedValue(GetConstValue(1, boolType), boolType);
  1140. }
  1141. }
  1142. return;
  1143. }
  1144. if (mCompiler->IsAutocomplete())
  1145. {
  1146. auto allocaResult = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(boolType));
  1147. auto val = mBfIRBuilder->CreateLoad(allocaResult);
  1148. checkResult = BfTypedValue(val, boolType);
  1149. return;
  1150. }
  1151. int wantTypeId = 0;
  1152. if (!varType->IsGenericParam())
  1153. wantTypeId = varType->mTypeId;
  1154. auto objectType = mContext->mBfObjectType;
  1155. PopulateType(objectType, BfPopulateType_Full);
  1156. initValue = LoadValue(initValue);
  1157. auto prevBB = mBfIRBuilder->GetInsertBlock();
  1158. auto matchBB = mBfIRBuilder->CreateBlock("is.match");
  1159. auto endBB = mBfIRBuilder->CreateBlock("is.done");
  1160. BfIRValue boolResult = CreateAlloca(boolType);
  1161. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolResult);
  1162. EmitDynamicCastCheck(initValue, varType, matchBB, endBB);
  1163. AddBasicBlock(matchBB);
  1164. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolResult);
  1165. mBfIRBuilder->CreateBr(endBB);
  1166. AddBasicBlock(endBB);
  1167. checkResult = BfTypedValue(mBfIRBuilder->CreateLoad(boolResult), boolType);
  1168. }
  1169. BfLocalVariable* BfModule::HandleVariableDeclaration(BfVariableDeclaration* varDecl, BfExprEvaluator* exprEvaluator)
  1170. {
  1171. if (mCurMethodState == NULL)
  1172. {
  1173. Fail("Invalid variable declaration", varDecl);
  1174. return NULL;
  1175. }
  1176. BfAutoComplete* bfAutocomplete = NULL;
  1177. // Just a check
  1178. mBfIRBuilder->GetInsertBlock();
  1179. if (mCompiler->mResolvePassData != NULL)
  1180. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  1181. if (bfAutocomplete != NULL)
  1182. bfAutocomplete->CheckTypeRef(varDecl->mTypeRef, true, true);
  1183. bool isConst = (varDecl->mModSpecifier != NULL) && (varDecl->mModSpecifier->GetToken() == BfToken_Const);
  1184. bool isReadOnly = (varDecl->mModSpecifier != NULL) && (varDecl->mModSpecifier->GetToken() == BfToken_ReadOnly);
  1185. bool isStatic = (varDecl->mModSpecifier != NULL) && (varDecl->mModSpecifier->GetToken() == BfToken_Static);
  1186. BfLocalVariable* localDef = new BfLocalVariable();
  1187. if (varDecl->mNameNode != NULL)
  1188. {
  1189. varDecl->mNameNode->ToString(localDef->mName);
  1190. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  1191. }
  1192. else
  1193. {
  1194. localDef->mName = "val";
  1195. }
  1196. localDef->mIsStatic = isStatic;
  1197. bool handledExprBoolResult = false;
  1198. bool handledVarInit = false;
  1199. bool handledVarStore = false;
  1200. BfType* unresolvedType = NULL;
  1201. BfType* resolvedType = NULL;
  1202. BfTypedValue initValue;
  1203. bool hadVarType = false;
  1204. bool isLet = varDecl->mTypeRef->IsA<BfLetTypeReference>();
  1205. bool initHandled = false;
  1206. auto _DoConditionalInit = [&](BfType* expectedType)
  1207. {
  1208. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  1209. auto _EmitCond = [&](BfIRValue condVal, BfTypedValue initValue)
  1210. {
  1211. initValue = Cast(varDecl->mInitializer, initValue, expectedType);
  1212. if (!initValue)
  1213. return;
  1214. initHandled = true;
  1215. if (localDef->mIsReadOnly)
  1216. {
  1217. if ((initValue.IsReadOnly()) ||
  1218. (initValue.mKind == BfTypedValueKind_TempAddr))
  1219. {
  1220. localDef->mAddr = initValue.mValue;
  1221. exprEvaluator->mResult = BfTypedValue(condVal, boolType);
  1222. return;
  1223. }
  1224. }
  1225. localDef->mAddr = AllocLocalVariable(resolvedType, localDef->mName);
  1226. auto doAssignBlock = mBfIRBuilder->CreateBlock("assign");
  1227. auto skipAssignBlock = mBfIRBuilder->CreateBlock("skipAssign");
  1228. auto insertBlock = mBfIRBuilder->GetInsertBlock();
  1229. mBfIRBuilder->CreateCondBr(condVal, doAssignBlock, skipAssignBlock);
  1230. mBfIRBuilder->AddBlock(doAssignBlock);
  1231. mBfIRBuilder->SetInsertPoint(doAssignBlock);
  1232. initValue = LoadValue(initValue);
  1233. mBfIRBuilder->CreateStore(initValue.mValue, localDef->mAddr);
  1234. mBfIRBuilder->CreateBr(skipAssignBlock);
  1235. mBfIRBuilder->AddBlock(skipAssignBlock);
  1236. mBfIRBuilder->SetInsertPoint(skipAssignBlock);
  1237. auto phiVal = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(boolType), 2);
  1238. mBfIRBuilder->AddPhiIncoming(phiVal, mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), insertBlock);
  1239. mBfIRBuilder->AddPhiIncoming(phiVal, mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), doAssignBlock);
  1240. exprEvaluator->mResult = BfTypedValue(phiVal, boolType);
  1241. };
  1242. bool handled = false;
  1243. if ((initValue) && (initValue.mType->IsPayloadEnum()))
  1244. {
  1245. auto typeInst = initValue.mType->ToTypeInstance();
  1246. PopulateType(typeInst);
  1247. BfType* outType = NULL;
  1248. int tagId = -1;
  1249. if (typeInst->GetResultInfo(outType, tagId))
  1250. {
  1251. int dscDataIdx = -1;
  1252. auto dscType = typeInst->GetDiscriminatorType(&dscDataIdx);
  1253. BfIRValue dscVal = ExtractValue(initValue, dscDataIdx);
  1254. auto eqVal = mBfIRBuilder->CreateCmpEQ(dscVal, GetConstValue(tagId, dscType));
  1255. exprEvaluator->mResult = BfTypedValue(eqVal, boolType);
  1256. PopulateType(outType);
  1257. if (!outType->IsValuelessType())
  1258. {
  1259. auto outPtrType = CreatePointerType(outType);
  1260. initValue = MakeAddressable(initValue);
  1261. auto payloadVal = mBfIRBuilder->CreateBitCast(initValue.mValue, mBfIRBuilder->MapType(outPtrType));
  1262. auto payload = BfTypedValue(payloadVal, outType, true);
  1263. if ((initValue.mKind == BfTypedValueKind_ReadOnlyAddr) ||
  1264. (initValue.mKind == BfTypedValueKind_TempAddr) ||
  1265. (initValue.mKind == BfTypedValueKind_ReadOnlyTempAddr))
  1266. payload.mKind = initValue.mKind;
  1267. _EmitCond(eqVal, payload);
  1268. }
  1269. handled = true;
  1270. }
  1271. }
  1272. if (handled)
  1273. {
  1274. handledExprBoolResult = true;
  1275. handledVarInit = true;
  1276. handledVarStore = true;
  1277. }
  1278. else if ((initValue) && (initValue.mType->IsNullable()))
  1279. {
  1280. auto underlyingType = initValue.mType->GetUnderlyingType();
  1281. exprEvaluator->mResult = BfTypedValue(ExtractValue(initValue, 2), boolType);
  1282. handledExprBoolResult = true;
  1283. if (!resolvedType->IsNullable())
  1284. {
  1285. if (initValue.IsAddr())
  1286. initValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(initValue.mValue, 0, 1), initValue.mType->GetUnderlyingType(), true);
  1287. else
  1288. initValue = BfTypedValue(mBfIRBuilder->CreateExtractValue(initValue.mValue, 1), initValue.mType->GetUnderlyingType());
  1289. }
  1290. if ((initValue) && (!initValue.mType->IsValuelessType()))
  1291. {
  1292. _EmitCond(exprEvaluator->mResult.mValue, initValue);
  1293. handledVarStore = true;
  1294. }
  1295. handledVarInit = true;
  1296. }
  1297. else if (initValue)
  1298. {
  1299. BfAstNode* refNode = varDecl;
  1300. if (varDecl->mInitializer != NULL)
  1301. refNode = varDecl->mInitializer;
  1302. TryInitVar(refNode, localDef, initValue, exprEvaluator->mResult);
  1303. handledExprBoolResult = true;
  1304. handledVarInit = true;
  1305. handledVarStore = true;
  1306. }
  1307. };
  1308. if ((varDecl->mTypeRef->IsA<BfVarTypeReference>()) || (isLet))
  1309. {
  1310. hadVarType = true;
  1311. if (varDecl->mInitializer == NULL)
  1312. {
  1313. if (!isLet)
  1314. {
  1315. BfLocalVarEntry* shadowEntry;
  1316. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localDef), &shadowEntry))
  1317. {
  1318. auto prevLocal = shadowEntry->mLocalVar;
  1319. if (prevLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx())
  1320. {
  1321. BfExprEvaluator exprEvaluator(this);
  1322. initValue = exprEvaluator.LoadLocal(prevLocal);
  1323. resolvedType = initValue.mType;
  1324. unresolvedType = resolvedType;
  1325. localDef->mLocalVarId = prevLocal->mLocalVarId;
  1326. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1327. localDef->mIsShadow = true;
  1328. exprEvaluator.mResultLocalVarRefNode = varDecl->mNameNode;
  1329. exprEvaluator.mResultLocalVar = prevLocal;
  1330. exprEvaluator.CheckResultForReading(initValue);
  1331. if (bfAutocomplete != NULL)
  1332. bfAutocomplete->CheckVarResolution(varDecl->mTypeRef, resolvedType);
  1333. }
  1334. }
  1335. }
  1336. if (!initValue)
  1337. {
  1338. Fail("Implicitly-typed variables must be initialized", varDecl);
  1339. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  1340. }
  1341. }
  1342. else
  1343. {
  1344. if (isConst)
  1345. {
  1346. BfConstResolver constResolver(this);
  1347. initValue = constResolver.Resolve(varDecl->mInitializer);
  1348. }
  1349. else
  1350. {
  1351. BfExprEvaluator valExprEvaluator(this);
  1352. valExprEvaluator.mAllowReadOnlyReference = isLet;
  1353. initValue = CreateValueFromExpression(valExprEvaluator, varDecl->mInitializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_VariableDeclaration));
  1354. if ((exprEvaluator != NULL) && (initValue))
  1355. {
  1356. if (initValue.mType->IsNullable())
  1357. {
  1358. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  1359. initValue = LoadValue(initValue);
  1360. exprEvaluator->mResult = BfTypedValue(mBfIRBuilder->CreateExtractValue(initValue.mValue, 2), boolType);
  1361. handledExprBoolResult = true;
  1362. initValue = BfTypedValue(mBfIRBuilder->CreateExtractValue(initValue.mValue, 1), initValue.mType->GetUnderlyingType());
  1363. }
  1364. else
  1365. {
  1366. auto typeInst = initValue.mType->ToTypeInstance();
  1367. if (typeInst != NULL)
  1368. {
  1369. PopulateType(typeInst);
  1370. BfType* outType = NULL;
  1371. int tagId = -1;
  1372. if (typeInst->GetResultInfo(outType, tagId))
  1373. {
  1374. handledExprBoolResult = true;
  1375. unresolvedType = outType;
  1376. resolvedType = outType;
  1377. isReadOnly = isLet;
  1378. localDef->mIsReadOnly = isLet;
  1379. _DoConditionalInit(outType);
  1380. }
  1381. }
  1382. }
  1383. }
  1384. }
  1385. }
  1386. if (!initValue)
  1387. {
  1388. initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_Var));
  1389. }
  1390. if (initValue.mType->IsNull())
  1391. {
  1392. Fail("Implicitly-typed variables cannot be initialized to 'null'", varDecl->mInitializer);
  1393. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  1394. }
  1395. if (unresolvedType == NULL)
  1396. unresolvedType = initValue.mType;
  1397. resolvedType = unresolvedType;
  1398. if ((initValue.IsTempAddr()) && (!localDef->mAddr) && (initValue.mType == resolvedType))
  1399. {
  1400. // Take over value
  1401. localDef->mAddr = initValue.mValue;
  1402. handledVarInit = true;
  1403. if (isLet)
  1404. {
  1405. localDef->mValue = mBfIRBuilder->CreateLoad(localDef->mAddr);
  1406. }
  1407. }
  1408. if (bfAutocomplete != NULL)
  1409. bfAutocomplete->CheckVarResolution(varDecl->mTypeRef, resolvedType);
  1410. }
  1411. else
  1412. {
  1413. BfTypeState typeState;
  1414. typeState.mCurVarInitializer = varDecl->mInitializer;
  1415. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  1416. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef);
  1417. if (varDecl->mInitializer != NULL)
  1418. flags = (BfResolveTypeRefFlags)(flags | BfResolveTypeRefFlag_AllowInferredSizedArray);
  1419. unresolvedType = ResolveTypeRef(varDecl->mTypeRef, BfPopulateType_Data, flags);
  1420. if (unresolvedType == NULL)
  1421. unresolvedType = GetPrimitiveType(BfTypeCode_Var);
  1422. resolvedType = unresolvedType;
  1423. }
  1424. auto _CheckConst = [&]
  1425. {
  1426. if (initValue.mValue.IsConst())
  1427. {
  1428. auto constant = mBfIRBuilder->GetConstant(initValue.mValue);
  1429. // NullPtr is stand-in for GlobalVar during autocomplete
  1430. if ((constant->mConstType == BfConstType_GlobalVar) ||
  1431. (constant->mTypeCode == BfTypeCode_NullPtr))
  1432. {
  1433. // Not really constant
  1434. // localNeedsAddr = false;
  1435. // isConst = false;
  1436. // initHandled = true;
  1437. // localDef->mValue = initValue.mValue;
  1438. if (GetStringPoolIdx(initValue.mValue, mBfIRBuilder) == -1)
  1439. isConst = false;
  1440. }
  1441. }
  1442. };
  1443. localDef->mResolvedType = resolvedType;
  1444. localDef->mIsReadOnly = isReadOnly;
  1445. if (!initHandled)
  1446. {
  1447. if (isLet)
  1448. {
  1449. localDef->mIsReadOnly = true;
  1450. if (initValue)
  1451. {
  1452. if ((initValue.mValue) && (initValue.mValue.IsConst()))
  1453. {
  1454. isConst = true;
  1455. }
  1456. }
  1457. }
  1458. }
  1459. _CheckConst();
  1460. bool localNeedsAddr = false;
  1461. bool allowValueAccess = true;
  1462. if (mHasFullDebugInfo)
  1463. {
  1464. //if (!IsTargetingBeefBackend())
  1465. if (!isConst)
  1466. localNeedsAddr = true;
  1467. /*if (mCurMethodInstance->mMethodDef->mName != "Boop2")
  1468. dbgNeedsAddr = true;*/
  1469. }
  1470. // This is required because of lifetime and LLVM domination rules for certain instances of variable declarations in binary conditionals.
  1471. // IE: if ((something) && (let a = somethingElse))
  1472. if ((exprEvaluator != NULL) && (!isConst))
  1473. {
  1474. localNeedsAddr = true;
  1475. allowValueAccess = false;
  1476. }
  1477. if ((varDecl->mEqualsNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!initHandled))
  1478. {
  1479. mCompiler->mResolvePassData->mAutoComplete->CheckEmptyStart(varDecl->mEqualsNode, resolvedType);
  1480. }
  1481. BfIRInitType initType = BfIRInitType_NotSet;
  1482. if (varDecl->mInitializer != NULL)
  1483. {
  1484. initType = BfIRInitType_NotNeeded_AliveOnDecl;
  1485. if ((!initValue) && (!initHandled))
  1486. {
  1487. if ((isConst) || (isStatic))
  1488. {
  1489. BfConstResolver constResolver(this);
  1490. initValue = constResolver.Resolve(varDecl->mInitializer, resolvedType, BfConstResolveFlag_ActualizeValues);
  1491. if (!initValue)
  1492. initValue = GetDefaultTypedValue(resolvedType);
  1493. }
  1494. else if (varDecl->mInitializer->IsA<BfUninitializedExpression>())
  1495. {
  1496. // Fake 'is assigned'
  1497. }
  1498. else
  1499. { //
  1500. auto expectedType = resolvedType;
  1501. if (expectedType->IsRef())
  1502. expectedType = expectedType->GetUnderlyingType();
  1503. BfExprEvaluator valExprEvaluator(this);
  1504. valExprEvaluator.mAllowReadOnlyReference = isReadOnly;
  1505. initValue = CreateValueFromExpression(valExprEvaluator, varDecl->mInitializer, expectedType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_VariableDeclaration));
  1506. if ((initValue) && (resolvedType->IsUndefSizedArray()))
  1507. {
  1508. int stringId = GetStringPoolIdx(initValue.mValue, mBfIRBuilder);
  1509. if (stringId >= 0)
  1510. {
  1511. BfStringPoolEntry* entry = NULL;
  1512. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  1513. resolvedType = CreateSizedArrayType(((BfSizedArrayType*)resolvedType)->mElementType, entry->mString.mLength);
  1514. }
  1515. }
  1516. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  1517. if (exprEvaluator != NULL)
  1518. _DoConditionalInit(expectedType);
  1519. if ((!handledVarInit) && (initValue))
  1520. initValue = Cast(varDecl->mInitializer, initValue, resolvedType, BfCastFlags_PreferAddr);
  1521. }
  1522. if ((initValue) && (resolvedType->IsUndefSizedArray()))
  1523. {
  1524. resolvedType = initValue.mType;
  1525. unresolvedType = resolvedType;
  1526. }
  1527. }
  1528. if ((!handledVarInit) && (!isConst))
  1529. {
  1530. if (initValue)
  1531. {
  1532. // Handled later
  1533. }
  1534. else if (varDecl->mInitializer->IsA<BfUninitializedExpression>())
  1535. {
  1536. // Fake 'is assigned'
  1537. initType = BfIRInitType_Uninitialized;
  1538. }
  1539. else
  1540. {
  1541. AssertErrorState();
  1542. }
  1543. }
  1544. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1545. }
  1546. else
  1547. {
  1548. if (isConst)
  1549. {
  1550. Fail("Const locals must be initialized", varDecl->mModSpecifier);
  1551. initValue = GetDefaultTypedValue(resolvedType, true);
  1552. }
  1553. else if (isReadOnly)
  1554. {
  1555. Fail("Readonly locals must be initialized", varDecl->mModSpecifier);
  1556. initValue = GetDefaultTypedValue(resolvedType, true);
  1557. }
  1558. else if (auto refTypeRef = BfNodeDynCast<BfRefTypeRef>(varDecl->mTypeRef))
  1559. {
  1560. Fail("Ref locals must be initialized", refTypeRef->mRefToken);
  1561. }
  1562. else
  1563. {
  1564. BF_ASSERT(!resolvedType->IsRef());
  1565. }
  1566. }
  1567. PopulateType(resolvedType);
  1568. AddDependency(resolvedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  1569. localDef->mResolvedType = resolvedType;
  1570. _CheckConst();
  1571. if ((initValue.mKind == BfTypedValueKind_TempAddr) && (!initHandled))
  1572. {
  1573. BF_ASSERT(initValue.IsAddr());
  1574. BF_ASSERT(initValue.mType->IsComposite());
  1575. handledVarInit = true;
  1576. handledVarStore = true;
  1577. if (!localDef->mAddr)
  1578. {
  1579. localDef->mAddr = initValue.mValue;
  1580. if (localDef->mIsReadOnly)
  1581. localDef->mValue = mBfIRBuilder->CreateLoad(localDef->mAddr);
  1582. }
  1583. if (WantsLifetimes())
  1584. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(localDef->mAddr);
  1585. }
  1586. if ((!localDef->mAddr) && (!isConst) && (!isStatic) && ((!localDef->mIsReadOnly) || (localNeedsAddr)))
  1587. {
  1588. if ((exprEvaluator != NULL) && (exprEvaluator->mResultIsTempComposite))
  1589. {
  1590. //TODO: Can we remove this one?
  1591. BF_ASSERT(initValue.IsAddr());
  1592. BF_ASSERT(initValue.mType->IsComposite());
  1593. localDef->mAddr = initValue.mValue;
  1594. }
  1595. else
  1596. localDef->mAddr = AllocLocalVariable(resolvedType, localDef->mName);
  1597. }
  1598. if (isStatic)
  1599. {
  1600. String name = mModuleName + "_" + mCurMethodInstance->mMethodDef->mName + "_" + localDef->mName;
  1601. HashContext closureHashCtx;
  1602. closureHashCtx.Mixin(varDecl->mSrcStart);
  1603. uint64 closureHash = closureHashCtx.Finish64();
  1604. name += "$";
  1605. name += BfTypeUtils::HashEncode64(closureHash);
  1606. initValue = LoadValue(initValue);
  1607. if ((initValue) && (!initValue.mValue.IsConst()))
  1608. {
  1609. Fail("Static local variables can only be initialized with a const value", varDecl->mInitializer);
  1610. initValue = BfTypedValue();
  1611. }
  1612. if (!initValue)
  1613. initValue = GetDefaultTypedValue(localDef->mResolvedType);
  1614. localDef->mAddr = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(localDef->mResolvedType), false, BfIRLinkageType_Internal, initValue.mValue, name);;
  1615. initHandled = true;
  1616. }
  1617. bool wantsStore = false;
  1618. if ((initValue) && (!handledVarStore) && (!isConst) && (!initHandled))
  1619. {
  1620. initValue = LoadValue(initValue);
  1621. if (initValue.IsSplat())
  1622. {
  1623. BF_ASSERT(!mIsComptimeModule);
  1624. if (!localDef->mAddr)
  1625. localDef->mAddr = AllocLocalVariable(resolvedType, localDef->mName);
  1626. AggregateSplatIntoAddr(initValue, localDef->mAddr);
  1627. initHandled = true;
  1628. }
  1629. else
  1630. {
  1631. initValue = AggregateSplat(initValue);
  1632. localDef->mValue = initValue.mValue;
  1633. if ((localDef->mAddr) && (!localDef->mResolvedType->IsValuelessType()))
  1634. {
  1635. if (!initValue.mType->IsVar())
  1636. wantsStore = true;
  1637. }
  1638. else
  1639. {
  1640. BF_ASSERT(isReadOnly || isLet || initValue.mType->IsValuelessType() || (mBfIRBuilder->mIgnoreWrites));
  1641. }
  1642. }
  1643. }
  1644. if ((localDef->mIsReadOnly) && (!isConst) && (!localDef->mValue) && (!initHandled))
  1645. {
  1646. if (!resolvedType->IsValuelessType())
  1647. {
  1648. AssertErrorState();
  1649. initValue = GetDefaultTypedValue(resolvedType, true, BfDefaultValueKind_Undef);
  1650. localDef->mValue = initValue.mValue;
  1651. }
  1652. }
  1653. if ((!localDef->mAddr) && (!isConst) && ((!localDef->mIsReadOnly) || (localNeedsAddr)))
  1654. {
  1655. localDef->mAddr = AllocLocalVariable(resolvedType, localDef->mName);
  1656. }
  1657. if ((exprEvaluator != NULL) && (!handledExprBoolResult))
  1658. {
  1659. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  1660. if (!initValue)
  1661. {
  1662. AssertErrorState();
  1663. exprEvaluator->mResult = BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolType);
  1664. }
  1665. else if ((resolvedType->IsPointer()) || (resolvedType->IsObjectOrInterface()))
  1666. {
  1667. exprEvaluator->mResult = BfTypedValue(mBfIRBuilder->CreateIsNotNull(initValue.mValue), boolType);
  1668. }
  1669. else if (resolvedType->IsVar())
  1670. {
  1671. exprEvaluator->mResult = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_Boolean), false, BfDefaultValueKind_Undef);
  1672. }
  1673. else
  1674. {
  1675. // Always true
  1676. if ((!IsInSpecializedSection()) && (!resolvedType->IsGenericParam()))
  1677. Warn(BfWarning_CS0472_ValueTypeNullCompare, StrFormat("Variable declaration is always 'true' since a value of type '%s' can never be null",
  1678. TypeToString(initValue.mType).c_str()), varDecl);
  1679. exprEvaluator->mResult = BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  1680. }
  1681. }
  1682. if ((unresolvedType->IsGenericParam()) && (resolvedType->IsValuelessType()) && (mHasFullDebugInfo))
  1683. {
  1684. // We do this in order to be able to bind to lines that contain valueless variable declarations in some generics
  1685. // We don't need to do this in non-generics because the breakpoint will just move to the next line that actually has instructions
  1686. EmitEnsureInstructionAt();
  1687. }
  1688. if ((resolvedType->IsVoid()) && (!IsInSpecializedSection()))
  1689. {
  1690. Warn(0, StrFormat("Variable '%s' is declared as 'void'", localDef->mName.c_str()), varDecl->mTypeRef);
  1691. }
  1692. if ((!handledVarInit) && (isConst))
  1693. localDef->mConstValue = initValue.mValue;
  1694. if (!allowValueAccess)
  1695. localDef->mValue = BfIRValue();
  1696. if (!localDef->mIsShadow)
  1697. CheckVariableDef(localDef);
  1698. ValidateAllocation(localDef->mResolvedType, varDecl->mTypeRef);
  1699. if ((exprEvaluator == NULL) && (varDecl->GetSourceData() != NULL))
  1700. UpdateSrcPos(varDecl);
  1701. localDef->Init();
  1702. if (localDef->mConstValue)
  1703. initType = BfIRInitType_NotNeeded;
  1704. BfLocalVariable* localVar = AddLocalVariableDef(localDef, true, false, BfIRValue(), initType);
  1705. if (wantsStore)
  1706. mBfIRBuilder->CreateAlignedStore(initValue.mValue, localVar->mAddr, localVar->mResolvedType->mAlign);
  1707. if ((mCurMethodState->mConstResolveState != NULL) && (mCurMethodState->mConstResolveState->mInCalcAppend))
  1708. {
  1709. if (localDef->mValue.IsConst())
  1710. localDef->mConstValue = localDef->mValue;
  1711. }
  1712. return localVar;
  1713. }
  1714. BfLocalVariable* BfModule::HandleVariableDeclaration(BfType* type, BfAstNode* nameNode, BfTypedValue val, bool updateSrcLoc, bool forceAddr)
  1715. {
  1716. BfLocalVariable* localDef = new BfLocalVariable();
  1717. nameNode->ToString(localDef->mName);
  1718. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(nameNode);
  1719. localDef->mResolvedType = type;
  1720. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1721. localDef->mValue = val.mValue;
  1722. if ((!localDef->mIsReadOnly) || (mHasFullDebugInfo))
  1723. {
  1724. localDef->mAddr = AllocLocalVariable(localDef->mResolvedType, localDef->mName);
  1725. if ((val.mValue) && (!localDef->mResolvedType->IsValuelessType()) && (!localDef->mResolvedType->IsVar()))
  1726. {
  1727. if (localDef->mResolvedType->IsRef())
  1728. val = MakeAddressable(val, true, true);
  1729. if (val.IsSplat())
  1730. {
  1731. AggregateSplatIntoAddr(val, localDef->mAddr);
  1732. }
  1733. else
  1734. mBfIRBuilder->CreateAlignedStore(val.mValue, localDef->mAddr, localDef->mResolvedType->mAlign);
  1735. }
  1736. }
  1737. CheckVariableDef(localDef);
  1738. if (nameNode->GetSourceData() != NULL)
  1739. UpdateSrcPos(nameNode);
  1740. localDef->Init();
  1741. return AddLocalVariableDef(localDef, true);
  1742. }
  1743. BfLocalVariable* BfModule::HandleVariableDeclaration(BfVariableDeclaration* varDecl, BfTypedValue val, bool updateSrcLoc, bool forceAddr)
  1744. {
  1745. if (varDecl->mEqualsNode != NULL)
  1746. Fail("Unexpected initialization", varDecl->mEqualsNode);
  1747. if (varDecl->mInitializer != NULL)
  1748. CreateValueFromExpression(varDecl->mInitializer);
  1749. auto isLet = varDecl->mTypeRef->IsA<BfLetTypeReference>();
  1750. auto isVar = varDecl->mTypeRef->IsA<BfVarTypeReference>();
  1751. bool isRef = false;
  1752. if (auto varRefTypeReference = BfNodeDynCast<BfVarRefTypeReference>(varDecl->mTypeRef))
  1753. {
  1754. isRef = true;
  1755. isLet = varRefTypeReference->mVarToken->GetToken() == BfToken_Let;
  1756. isVar = varRefTypeReference->mVarToken->GetToken() == BfToken_Var;
  1757. }
  1758. else
  1759. {
  1760. BF_ASSERT(!val.IsAddr());
  1761. }
  1762. auto autoComplete = mCompiler->GetAutoComplete();
  1763. if ((autoComplete != NULL) && ((isLet) || (isVar)))
  1764. autoComplete->CheckVarResolution(varDecl->mTypeRef, val.mType);
  1765. // BfType* type = val.mType;
  1766. // if (type == NULL)
  1767. // {
  1768. // type = ResolveTypeRef(varDecl->mTypeRef);
  1769. // if (type == NULL)
  1770. // type = mContext->mBfObjectType;
  1771. // }
  1772. BfType* type = NULL;
  1773. if ((isLet) || (isVar))
  1774. {
  1775. type = val.mType;
  1776. }
  1777. else
  1778. {
  1779. type = ResolveTypeRef(varDecl->mTypeRef);
  1780. }
  1781. if (type == NULL)
  1782. {
  1783. type = GetPrimitiveType(BfTypeCode_Var);
  1784. val = GetDefaultTypedValue(type);
  1785. }
  1786. if ((type->IsVar()) || (type->IsLet()))
  1787. {
  1788. }
  1789. if (isRef)
  1790. {
  1791. type = CreateRefType(type);
  1792. }
  1793. BfLocalVariable* localDef = new BfLocalVariable();
  1794. if (varDecl->mNameNode != NULL)
  1795. varDecl->mNameNode->ToString(localDef->mName);
  1796. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  1797. localDef->mResolvedType = type;
  1798. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1799. localDef->mValue = val.mValue;
  1800. if (isLet)
  1801. {
  1802. localDef->mIsReadOnly = true;
  1803. }
  1804. if ((!localDef->mIsReadOnly) || (mHasFullDebugInfo) || (forceAddr))
  1805. {
  1806. localDef->mAddr = AllocLocalVariable(localDef->mResolvedType, localDef->mName);
  1807. if ((val.mValue) && (!localDef->mResolvedType->IsValuelessType()) && (!localDef->mResolvedType->IsVar()))
  1808. {
  1809. if (localDef->mResolvedType->IsRef())
  1810. val = MakeAddressable(val, true, true);
  1811. if (val.IsSplat())
  1812. {
  1813. AggregateSplatIntoAddr(val, localDef->mAddr);
  1814. }
  1815. else
  1816. mBfIRBuilder->CreateAlignedStore(val.mValue, localDef->mAddr, localDef->mResolvedType->mAlign);
  1817. }
  1818. if (forceAddr)
  1819. localDef->mValue = BfIRValue();
  1820. }
  1821. CheckVariableDef(localDef);
  1822. if ((updateSrcLoc) && (varDecl->GetSourceData() != NULL))
  1823. UpdateSrcPos(varDecl);
  1824. localDef->Init();
  1825. return AddLocalVariableDef(localDef, true);
  1826. }
  1827. void BfModule::CheckTupleVariableDeclaration(BfTupleExpression* tupleExpr, BfType* initType)
  1828. {
  1829. if (initType == NULL)
  1830. return;
  1831. BfTypeInstance* initTupleType = NULL;
  1832. if ((initType != NULL) && (initType->IsTuple()))
  1833. initTupleType = (BfTypeInstance*)initType;
  1834. if (initTupleType != NULL)
  1835. {
  1836. mBfIRBuilder->PopulateType(initTupleType);
  1837. AddDependency(initTupleType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  1838. int paramCountDiff = (int)tupleExpr->mValues.size() - (int)initTupleType->mFieldInstances.size();
  1839. if (paramCountDiff > 0)
  1840. {
  1841. Fail(StrFormat("Too many variable names, expected %d fewer.", paramCountDiff), tupleExpr->mValues[(int)initTupleType->mFieldInstances.size()]);
  1842. }
  1843. else if (paramCountDiff < 0)
  1844. {
  1845. BfAstNode* refNode = tupleExpr->mCloseParen;
  1846. if (refNode == NULL)
  1847. refNode = tupleExpr;
  1848. Fail(StrFormat("Too few variable names, expected %d more.", -paramCountDiff), refNode);
  1849. }
  1850. }
  1851. else
  1852. {
  1853. Fail(StrFormat("Value result type '%s' must be a tuple type to be applicable for tuple decomposition", TypeToString(initType).c_str()), tupleExpr);
  1854. }
  1855. }
  1856. void BfModule::HandleTupleVariableDeclaration(BfVariableDeclaration* varDecl, BfTupleExpression* tupleExpr, BfTypedValue initTupleValue, bool isReadOnly, bool isConst, bool forceAddr, BfIRBlock* declBlock)
  1857. {
  1858. BfTypeInstance* initTupleType = NULL;
  1859. if ((initTupleValue) && (initTupleValue.mType->IsTuple()))
  1860. initTupleType = (BfTypeInstance*)initTupleValue.mType;
  1861. CheckTupleVariableDeclaration(tupleExpr, initTupleValue.mType);
  1862. for (int varIdx = 0; varIdx < (int)tupleExpr->mValues.size(); varIdx++)
  1863. {
  1864. BfType* resolvedType = NULL;
  1865. BfTypedValue initValue;
  1866. if ((initTupleType != NULL) && (varIdx < (int)initTupleType->mFieldInstances.size()))
  1867. {
  1868. auto fieldInstance = &initTupleType->mFieldInstances[varIdx];
  1869. auto fieldDef = fieldInstance->GetFieldDef();
  1870. resolvedType = fieldInstance->GetResolvedType();
  1871. if (fieldInstance->mDataIdx != -1)
  1872. {
  1873. if (initTupleValue.IsAddr())
  1874. {
  1875. initValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(initTupleValue.mValue, 0, fieldInstance->mDataIdx), resolvedType, true);
  1876. initValue = LoadValue(initValue);
  1877. }
  1878. else
  1879. initValue = BfTypedValue(mBfIRBuilder->CreateExtractValue(initTupleValue.mValue, fieldInstance->mDataIdx), resolvedType);
  1880. }
  1881. BfTupleNameNode* tupleNameNode = NULL;
  1882. if (varIdx < (int)tupleExpr->mNames.size())
  1883. tupleNameNode = tupleExpr->mNames[varIdx];
  1884. if (!fieldDef->IsUnnamedTupleField())
  1885. {
  1886. if (tupleNameNode != NULL)
  1887. {
  1888. if (fieldDef->mName != tupleNameNode->mNameNode->ToString())
  1889. {
  1890. Fail(StrFormat("Mismatched tuple field name, expected '%s'", fieldDef->mName.c_str()), tupleNameNode->mNameNode);
  1891. }
  1892. }
  1893. }
  1894. else if ((tupleNameNode != NULL) && (tupleNameNode->mNameNode != NULL))
  1895. {
  1896. Fail(StrFormat("Unexpected tuple field name, expected unnamed tuple field", fieldDef->mName.c_str()), tupleNameNode->mNameNode);
  1897. }
  1898. }
  1899. else
  1900. {
  1901. resolvedType = mContext->mBfObjectType;
  1902. initValue = GetDefaultTypedValue(resolvedType);
  1903. }
  1904. BfExpression* varNameNode = tupleExpr->mValues[varIdx];
  1905. if (!varNameNode->IsExact<BfIdentifierNode>())
  1906. {
  1907. if (BfTupleExpression* innerTupleExpr = BfNodeDynCast<BfTupleExpression>(varNameNode))
  1908. {
  1909. HandleTupleVariableDeclaration(varDecl, innerTupleExpr, initValue, isReadOnly, isConst, false, declBlock);
  1910. }
  1911. else if (!varNameNode->IsExact<BfUninitializedExpression>())
  1912. Fail("Variable name expected", varNameNode);
  1913. continue;
  1914. }
  1915. bool initHandled = false;
  1916. BfLocalVariable* localDef = new BfLocalVariable();
  1917. varNameNode->ToString(localDef->mName);
  1918. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varNameNode);
  1919. localDef->mResolvedType = resolvedType;
  1920. localDef->mReadFromId = 0; // Don't give usage errors for binds
  1921. if (isReadOnly)
  1922. {
  1923. localDef->mIsReadOnly = true;
  1924. if ((initValue) && (initValue.mValue.IsConst()))
  1925. {
  1926. isConst = true;
  1927. }
  1928. }
  1929. CheckVariableDef(localDef);
  1930. if ((!isConst) && ((forceAddr) || (!localDef->mIsReadOnly) || (mHasFullDebugInfo)))
  1931. {
  1932. localDef->mAddr = AllocLocalVariable(resolvedType, localDef->mName);
  1933. }
  1934. if ((varDecl != NULL) && (varDecl->mEqualsNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!initHandled))
  1935. {
  1936. mCompiler->mResolvePassData->mAutoComplete->CheckEmptyStart(varDecl->mEqualsNode, resolvedType);
  1937. }
  1938. if ((varDecl == NULL) || (varDecl->mInitializer != NULL))
  1939. {
  1940. if ((!isConst) && (!initHandled))
  1941. {
  1942. if (initValue)
  1943. {
  1944. if (!forceAddr)
  1945. localDef->mValue = initValue.mValue;
  1946. if (localDef->mAddr)
  1947. {
  1948. mBfIRBuilder->CreateStore(initValue.mValue, localDef->mAddr);
  1949. }
  1950. }
  1951. else if ((varDecl == NULL) || (varDecl->mInitializer->IsA<BfUninitializedExpression>()))
  1952. {
  1953. // Fake 'is assigned'
  1954. }
  1955. else
  1956. {
  1957. AssertErrorState();
  1958. }
  1959. }
  1960. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1961. }
  1962. else if ((varDecl != NULL) && (varDecl->mInitializer == NULL))
  1963. {
  1964. if (auto refTypeRef = BfNodeDynCast<BfRefTypeRef>(varDecl->mTypeRef))
  1965. {
  1966. Fail("Ref variables must be initialized", refTypeRef->mRefToken);
  1967. }
  1968. else
  1969. {
  1970. BF_ASSERT(!localDef->mResolvedType->IsRef());
  1971. }
  1972. }
  1973. if (isConst)
  1974. localDef->mConstValue = initValue.mValue;
  1975. CheckVariableDef(localDef);
  1976. if ((varDecl != NULL) && (varDecl->GetSourceData() != NULL))
  1977. UpdateSrcPos(varDecl);
  1978. localDef->Init();
  1979. auto defBlock = mBfIRBuilder->GetInsertBlock();
  1980. if (declBlock != NULL)
  1981. mBfIRBuilder->SetInsertPoint(*declBlock);
  1982. AddLocalVariableDef(localDef, true, false, BfIRValue(), BfIRInitType_NotNeeded);
  1983. if (declBlock != NULL)
  1984. mBfIRBuilder->SetInsertPoint(defBlock);
  1985. }
  1986. }
  1987. void BfModule::HandleTupleVariableDeclaration(BfVariableDeclaration* varDecl)
  1988. {
  1989. BfAutoComplete* bfAutocomplete = mCompiler->GetAutoComplete();
  1990. if (bfAutocomplete != NULL)
  1991. bfAutocomplete->CheckTypeRef(varDecl->mTypeRef, true);
  1992. BfTupleExpression* tupleExpr = BfNodeDynCast<BfTupleExpression>(varDecl->mNameNode);
  1993. bool isConst = (varDecl->mModSpecifier != NULL) && (varDecl->mModSpecifier->GetToken() == BfToken_Const);
  1994. bool isReadOnly = (varDecl->mModSpecifier != NULL) && (varDecl->mModSpecifier->GetToken() == BfToken_ReadOnly);
  1995. BfTypedValue initTupleValue;
  1996. bool hadVarType = false;
  1997. bool isLet = varDecl->mTypeRef->IsA<BfLetTypeReference>();
  1998. bool isVar = varDecl->mTypeRef->IsA<BfVarTypeReference>();
  1999. bool wasVarOrLet = isVar || isLet;
  2000. if ((!isLet) && (!isVar))
  2001. {
  2002. ResolveTypeRef(varDecl->mTypeRef);
  2003. Fail("'var' or 'let' expected", varDecl->mTypeRef);
  2004. isVar = true;
  2005. }
  2006. if ((isVar) || (isLet))
  2007. {
  2008. hadVarType = true;
  2009. if (varDecl->mInitializer == NULL)
  2010. {
  2011. Fail("Implicitly-typed variables must be initialized", varDecl);
  2012. initTupleValue = GetDefaultTypedValue(mContext->mBfObjectType);
  2013. }
  2014. else
  2015. {
  2016. if (isConst)
  2017. {
  2018. BfConstResolver constResolver(this);
  2019. initTupleValue = constResolver.Resolve(varDecl->mInitializer);
  2020. }
  2021. else
  2022. {
  2023. initTupleValue = CreateValueFromExpression(varDecl->mInitializer, NULL);
  2024. }
  2025. }
  2026. initTupleValue = LoadValue(initTupleValue);
  2027. if ((bfAutocomplete != NULL) && (wasVarOrLet))
  2028. bfAutocomplete->CheckVarResolution(varDecl->mTypeRef, initTupleValue.mType);
  2029. }
  2030. bool isCompatible = false;
  2031. if (initTupleValue)
  2032. HandleTupleVariableDeclaration(varDecl, tupleExpr, initTupleValue, isLet || isReadOnly, isConst, false);
  2033. else
  2034. AssertErrorState();
  2035. }
  2036. void BfModule::HandleCaseEnumMatch_Tuple(BfTypedValue tupleVal, const BfSizedArray<BfExpression*>& arguments, BfAstNode* tooFewRef, BfIRValue phiVal, BfIRBlock& matchedBlockStart, BfIRBlock& matchedBlockEnd, BfIRBlock& falseBlockStart, BfIRBlock& falseBlockEnd, bool& hadConditional, bool clearOutOnMismatch, bool prevHadFallthrough)
  2037. {
  2038. SetAndRestoreValue<bool> prevInCondBlock(mCurMethodState->mInConditionalBlock);
  2039. auto tupleType = tupleVal.mType->ToTypeInstance();
  2040. struct DeferredAssign
  2041. {
  2042. BfExpression* mExpr;
  2043. BfTypedValue mArgValue;
  2044. BfTypedValue mTupleElement;
  2045. int mFieldIdx;
  2046. };
  2047. Array<DeferredAssign> deferredAssigns;
  2048. auto autoComplete = mCompiler->GetAutoComplete();
  2049. for (int tupleFieldIdx = 0; tupleFieldIdx < (int)tupleType->mFieldInstances.size(); tupleFieldIdx++)
  2050. {
  2051. auto tupleFieldInstance = &tupleType->mFieldInstances[tupleFieldIdx];
  2052. if (tupleFieldIdx >= arguments.size())
  2053. {
  2054. BfError* error = Fail(StrFormat("Not enough parameters specified, expected %d more.", tupleType->mFieldInstances.size() - (int)arguments.size()), tooFewRef);
  2055. break;
  2056. }
  2057. BfTypedValue tupleElement;
  2058. if (tupleFieldInstance->mDataIdx >= 0)
  2059. {
  2060. tupleElement = ExtractValue(tupleVal, tupleFieldInstance, tupleFieldInstance->mDataIdx);
  2061. }
  2062. else
  2063. tupleElement = GetDefaultTypedValue(tupleFieldInstance->GetResolvedType());
  2064. auto expr = BfNodeDynCast<BfExpression>(arguments[tupleFieldIdx]);
  2065. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(expr))
  2066. {
  2067. bool isVarOrLet = (varDecl->mTypeRef->IsExact<BfLetTypeReference>()) || (varDecl->mTypeRef->IsExact<BfVarTypeReference>());
  2068. bool isRef = false;
  2069. if (varDecl->mTypeRef->IsExact<BfVarRefTypeReference>())
  2070. {
  2071. isVarOrLet = true;
  2072. isRef = true;
  2073. }
  2074. if (!isVarOrLet)
  2075. {
  2076. auto wantType = ResolveTypeRef(varDecl->mTypeRef);
  2077. if (wantType == NULL)
  2078. wantType = mContext->mBfObjectType;
  2079. if (wantType != NULL)
  2080. tupleElement = Cast(varDecl->mTypeRef, tupleElement, wantType);
  2081. if (!tupleElement)
  2082. tupleElement = GetDefaultTypedValue(wantType);
  2083. }
  2084. PopulateType(tupleElement.mType);
  2085. if (!isRef)
  2086. tupleElement = LoadValue(tupleElement);
  2087. if (prevHadFallthrough)
  2088. Fail("Destructuring cannot be used when the previous case contains a fallthrough", expr);
  2089. auto localVar = HandleVariableDeclaration(varDecl, tupleElement, false, true);
  2090. localVar->mReadFromId = 0; // Don't give usage errors for binds
  2091. continue;
  2092. }
  2093. if (auto binOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(expr))
  2094. {
  2095. if (binOpExpr->mOp == BfBinaryOp_Multiply)
  2096. {
  2097. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  2098. auto resolvedType = ResolveTypeRef(binOpExpr->mLeft, NULL);
  2099. prevIgnoreError.Restore();
  2100. if (resolvedType != NULL)
  2101. {
  2102. resolvedType = CreatePointerType(resolvedType);
  2103. PopulateType(tupleElement.mType);
  2104. tupleElement = LoadValue(tupleElement);
  2105. tupleElement = Cast(binOpExpr->mLeft, tupleElement, resolvedType);
  2106. if (prevHadFallthrough)
  2107. Fail("Destructuring cannot be used when the previous case contains a fallthrough", expr);
  2108. auto localVar = HandleVariableDeclaration(resolvedType, binOpExpr->mRight, tupleElement, false, true);
  2109. localVar->mReadFromId = 0; // Don't give usage errors for binds
  2110. continue;
  2111. }
  2112. }
  2113. }
  2114. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(expr))
  2115. {
  2116. continue;
  2117. }
  2118. if (tupleFieldInstance->mDataIdx >= 0)
  2119. {
  2120. if (auto tupleExpr = BfNodeDynCast<BfTupleExpression>(expr))
  2121. {
  2122. if (tupleElement.mType->IsTuple())
  2123. {
  2124. BfAstNode* tooFewRef = tupleExpr->mCloseParen;
  2125. if (tupleExpr->mValues.size() > 0)
  2126. tooFewRef = tupleExpr->mValues[tupleExpr->mValues.size() - 1];
  2127. if (tooFewRef == NULL)
  2128. tooFewRef = tupleExpr->mOpenParen;
  2129. HandleCaseEnumMatch_Tuple(tupleElement, tupleExpr->mValues, tooFewRef, phiVal, matchedBlockStart, matchedBlockEnd, falseBlockStart, falseBlockEnd, hadConditional, clearOutOnMismatch, prevHadFallthrough);
  2130. continue;
  2131. }
  2132. }
  2133. }
  2134. if (expr == NULL)
  2135. {
  2136. // Error would have occured in the parser
  2137. //AssertErrorState();
  2138. }
  2139. else
  2140. {
  2141. mCurMethodState->mInConditionalBlock = true;
  2142. auto tupleElementAddr = tupleElement;
  2143. BfTypedValue exprResult;
  2144. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(expr))
  2145. {
  2146. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  2147. {
  2148. if (memberRefExpr->mTarget == NULL)
  2149. {
  2150. if (tupleElement.mType->IsPayloadEnum())
  2151. {
  2152. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  2153. BfTypedValue enumTagVal;
  2154. if (tupleElement.IsAddr())
  2155. {
  2156. enumTagVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(tupleElement.mValue, 0, 2), intType, true);
  2157. enumTagVal = LoadValue(enumTagVal);
  2158. }
  2159. else
  2160. enumTagVal = BfTypedValue(mBfIRBuilder->CreateExtractValue(tupleElement.mValue, 2), intType, false);
  2161. int uncondTagId = -1;
  2162. bool hadConditional = false;
  2163. exprResult = TryCaseEnumMatch(tupleElementAddr, enumTagVal, expr, NULL, NULL, NULL, uncondTagId, hadConditional, clearOutOnMismatch, prevHadFallthrough);
  2164. }
  2165. }
  2166. }
  2167. }
  2168. if (!exprResult)
  2169. {
  2170. tupleElement = LoadValue(tupleElement);
  2171. bool isMatchedBlockEnd = matchedBlockEnd == mBfIRBuilder->GetInsertBlock();
  2172. bool isFalseBlockEnd = falseBlockEnd == mBfIRBuilder->GetInsertBlock();
  2173. BfExprEvaluator exprEvaluator(this);
  2174. exprEvaluator.mExpectingType = tupleFieldInstance->GetResolvedType();
  2175. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_AllowOutExpr;
  2176. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  2177. {
  2178. SetAndRestoreValue<bool> prevIsIfCondition(mCurMethodState->mDeferredLocalAssignData->mIsIfCondition, true);
  2179. SetAndRestoreValue<bool> prevIfMayBeSkipped(mCurMethodState->mDeferredLocalAssignData->mIfMayBeSkipped, true);
  2180. exprEvaluator.Evaluate(expr);
  2181. }
  2182. else
  2183. {
  2184. exprEvaluator.Evaluate(expr);
  2185. }
  2186. if (isMatchedBlockEnd)
  2187. matchedBlockEnd = mBfIRBuilder->GetInsertBlock();
  2188. if (isFalseBlockEnd)
  2189. falseBlockEnd = mBfIRBuilder->GetInsertBlock();
  2190. auto argValue = exprEvaluator.mResult;
  2191. if (!argValue)
  2192. continue;
  2193. if (argValue.mType->IsRef())
  2194. {
  2195. auto refType = (BfRefType*)argValue.mType;
  2196. if (refType->mRefKind != BfRefType::RefKind_Out)
  2197. {
  2198. BfAstNode* refNode = expr;
  2199. if (auto unaryOperatorExpr = BfNodeDynCast<BfUnaryOperatorExpression>(expr))
  2200. refNode = unaryOperatorExpr->mOpToken;
  2201. Fail("Only 'out' refs can be used to assign to an existing value", refNode);
  2202. }
  2203. DeferredAssign deferredAssign = { expr, argValue, tupleElement, tupleFieldIdx };
  2204. deferredAssigns.push_back(deferredAssign);
  2205. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  2206. {
  2207. SetAndRestoreValue<bool> prevIsIfCondition(mCurMethodState->mDeferredLocalAssignData->mIsIfCondition, true);
  2208. SetAndRestoreValue<bool> prevIfMayBeSkipped(mCurMethodState->mDeferredLocalAssignData->mIfMayBeSkipped, true);
  2209. exprEvaluator.MarkResultAssigned();
  2210. }
  2211. else
  2212. {
  2213. exprEvaluator.MarkResultAssigned();
  2214. }
  2215. continue;
  2216. }
  2217. if (!argValue.mType->IsValueType())
  2218. argValue = LoadValue(argValue);
  2219. argValue = Cast(expr, argValue, tupleFieldInstance->GetResolvedType());
  2220. if (!argValue)
  2221. continue;
  2222. exprEvaluator.PerformBinaryOperation(expr, expr, BfBinaryOp_Equality, expr, BfBinOpFlag_NoClassify, tupleElement, argValue);
  2223. exprResult = exprEvaluator.mResult;
  2224. }
  2225. if (exprResult)
  2226. {
  2227. hadConditional = true;
  2228. if (phiVal)
  2229. {
  2230. auto insertBlock = mBfIRBuilder->GetInsertBlock();
  2231. mBfIRBuilder->AddPhiIncoming(phiVal, mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), insertBlock);
  2232. }
  2233. matchedBlockStart = matchedBlockEnd = mBfIRBuilder->CreateBlock("match", false);
  2234. mBfIRBuilder->CreateCondBr(exprResult.mValue, matchedBlockStart, falseBlockStart);
  2235. mBfIRBuilder->AddBlock(matchedBlockStart);
  2236. mBfIRBuilder->SetInsertPoint(matchedBlockStart);
  2237. }
  2238. }
  2239. }
  2240. if (!deferredAssigns.empty())
  2241. mBfIRBuilder->SetInsertPoint(matchedBlockEnd);
  2242. // We assign these only after the value checks succeed
  2243. for (auto& deferredAssign : deferredAssigns)
  2244. {
  2245. auto argValue = RemoveRef(deferredAssign.mArgValue);
  2246. auto tupleElement = Cast(deferredAssign.mExpr, deferredAssign.mTupleElement, argValue.mType);
  2247. if (!tupleElement)
  2248. continue;
  2249. tupleElement = LoadOrAggregateValue(tupleElement);
  2250. if (!tupleElement.mType->IsValuelessType())
  2251. mBfIRBuilder->CreateStore(tupleElement.mValue, argValue.mValue);
  2252. }
  2253. if ((clearOutOnMismatch) && (!deferredAssigns.IsEmpty()))
  2254. {
  2255. auto curInsertPoint = mBfIRBuilder->GetInsertBlock();
  2256. mBfIRBuilder->SetInsertPoint(falseBlockEnd);
  2257. for (auto& deferredAssign : deferredAssigns)
  2258. {
  2259. auto tupleFieldInstance = &tupleType->mFieldInstances[deferredAssign.mFieldIdx];
  2260. // We have to re-process the expr because we haven't done it in this branch, and then clear the result out
  2261. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, mHadBuildError); // Don't fail twice
  2262. BfExprEvaluator exprEvaluator(this);
  2263. exprEvaluator.mExpectingType = tupleFieldInstance->GetResolvedType();
  2264. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_AllowOutExpr;
  2265. exprEvaluator.Evaluate(deferredAssign.mExpr);
  2266. auto argValue = exprEvaluator.mResult;
  2267. if (!argValue)
  2268. continue;
  2269. mBfIRBuilder->CreateMemSet(argValue.mValue, GetConstValue8(0), GetConstValue(argValue.mType->mSize), GetConstValue(argValue.mType->mAlign));
  2270. }
  2271. falseBlockEnd = mBfIRBuilder->GetInsertBlock();
  2272. mBfIRBuilder->SetInsertPoint(curInsertPoint);
  2273. }
  2274. if (arguments.size() > tupleType->mFieldInstances.size())
  2275. {
  2276. for (int i = (int)tupleType->mFieldInstances.size(); i < (int)arguments.size(); i++)
  2277. {
  2278. // For autocomplete and such
  2279. auto expr = arguments[i];
  2280. if (expr != NULL)
  2281. CreateValueFromExpression(expr);
  2282. }
  2283. BfAstNode* errorRef = arguments[(int)tupleType->mFieldInstances.size()];
  2284. BfError* error = Fail(StrFormat("Too many arguments, expected %d fewer.", arguments.size() - tupleType->mFieldInstances.size()), errorRef);
  2285. }
  2286. }
  2287. BfTypedValue BfModule::TryCaseTupleMatch(BfTypedValue tupleVal, BfTupleExpression* tupleExpr, BfIRBlock* eqBlock, BfIRBlock* notEqBlock, BfIRBlock* matchBlock, bool& hadConditional, bool clearOutOnMismatch, bool prevHadFallthrough)
  2288. {
  2289. if (!tupleVal.mType->IsTuple())
  2290. return BfTypedValue();
  2291. auto tupleType = (BfTypeInstance*)tupleVal.mType;
  2292. BfAstNode* tooFewRef = tupleExpr->mCloseParen;
  2293. if ((tooFewRef == NULL) && (!tupleExpr->mCommas.IsEmpty()))
  2294. tooFewRef = tupleExpr->mCommas[tupleExpr->mCommas.size() - 1];
  2295. else if (tooFewRef == NULL)
  2296. tooFewRef = tupleExpr->mOpenParen;
  2297. ///
  2298. auto autoComplete = mCompiler->GetAutoComplete();
  2299. bool wasCapturingMethodInfo = false;
  2300. if (autoComplete != NULL)
  2301. {
  2302. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  2303. autoComplete->CheckInvocation(tupleExpr, tupleExpr->mOpenParen, tupleExpr->mCloseParen, tupleExpr->mCommas);
  2304. if (autoComplete->mIsCapturingMethodMatchInfo)
  2305. {
  2306. autoComplete->mMethodMatchInfo->mInstanceList.Clear();
  2307. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  2308. // auto methodDef = tupleType->mTypeDef->mMethods[0];
  2309. //
  2310. // BfAutoComplete::MethodMatchEntry methodMatchEntry;
  2311. // methodMatchEntry.mMethodDef = methodDef;
  2312. // methodMatchEntry.mTypeInstance = tupleType;
  2313. // methodMatchEntry.mCurMethodInstance = mCurMethodInstance;
  2314. // //methodMatchEntry.mPayloadEnumField = fieldInstance;
  2315. //autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  2316. methodMatchInfo->mBestIdx = 0;
  2317. methodMatchInfo->mMostParamsMatched = 0;
  2318. int cursorIdx = tupleExpr->GetParser()->mCursorIdx;
  2319. if ((tupleExpr->mCloseParen == NULL) || (cursorIdx <= tupleExpr->mCloseParen->GetSrcStart()))
  2320. {
  2321. int paramIdx = 0;
  2322. for (int commaIdx = 0; commaIdx < (int)tupleExpr->mCommas.size(); commaIdx++)
  2323. {
  2324. auto commaNode = tupleExpr->mCommas[commaIdx];
  2325. if ((commaNode != NULL) && (cursorIdx >= commaNode->GetSrcStart()))
  2326. paramIdx = commaIdx + 1;
  2327. }
  2328. bool isEmpty = true;
  2329. if (paramIdx < (int)tupleExpr->mValues.size())
  2330. {
  2331. auto paramNode = tupleExpr->mValues[paramIdx];
  2332. if (paramNode != NULL)
  2333. isEmpty = false;
  2334. }
  2335. if (isEmpty)
  2336. {
  2337. if (paramIdx < (int)tupleType->mFieldInstances.size())
  2338. {
  2339. auto fieldDef = tupleType->mFieldInstances[paramIdx].GetFieldDef();
  2340. String insertStr;
  2341. if (fieldDef->IsUnnamedTupleField())
  2342. insertStr = "p";
  2343. insertStr += fieldDef->mName;
  2344. insertStr.Insert(0, "let ");
  2345. autoComplete->mEntriesSet.Clear();
  2346. autoComplete->AddEntry(AutoCompleteEntry("paramName", insertStr));
  2347. autoComplete->mInsertStartIdx = cursorIdx;
  2348. autoComplete->mInsertEndIdx = cursorIdx;
  2349. }
  2350. }
  2351. }
  2352. }
  2353. }
  2354. defer
  2355. (
  2356. if (autoComplete != NULL)
  2357. autoComplete->mIsCapturingMethodMatchInfo = (wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo);
  2358. );
  2359. ///
  2360. //BfIRValue phiVal;
  2361. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  2362. //phiVal = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(boolType), 2);
  2363. auto startBlock = mBfIRBuilder->GetInsertBlock();
  2364. //auto dscrType = enumType->GetDiscriminatorType();
  2365. //BfIRValue eqResult = mBfIRBuilder->CreateCmpEQ(tagVal.mValue, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagId));
  2366. BfIRBlock falseBlockStart;
  2367. BfIRBlock falseBlockEnd;
  2368. BfIRBlock doneBlockStart;
  2369. if (notEqBlock != NULL)
  2370. doneBlockStart = *notEqBlock;
  2371. else
  2372. doneBlockStart = mBfIRBuilder->CreateBlock("caseDone", false);
  2373. BfIRBlock doneBlockEnd = doneBlockStart;
  2374. if (clearOutOnMismatch)
  2375. {
  2376. falseBlockStart = falseBlockEnd = mBfIRBuilder->CreateBlock("caseNotEq", false);
  2377. mBfIRBuilder->AddBlock(falseBlockStart);
  2378. }
  2379. BfIRBlock matchedBlockStart = mBfIRBuilder->CreateBlock("caseMatch", false);
  2380. if (matchBlock != NULL)
  2381. *matchBlock = matchedBlockStart;
  2382. mBfIRBuilder->CreateBr(matchedBlockStart);
  2383. mBfIRBuilder->AddBlock(matchedBlockStart);
  2384. mBfIRBuilder->SetInsertPoint(doneBlockEnd);
  2385. BfIRValue phiVal;
  2386. if (eqBlock == NULL)
  2387. phiVal = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(boolType), 2);
  2388. mBfIRBuilder->SetInsertPoint(matchedBlockStart);
  2389. BfIRBlock matchedBlockEnd = matchedBlockStart;
  2390. HandleCaseEnumMatch_Tuple(tupleVal, tupleExpr->mValues, tooFewRef, falseBlockStart ? BfIRValue() : phiVal, matchedBlockStart, matchedBlockEnd,
  2391. falseBlockStart ? falseBlockStart : doneBlockStart, falseBlockEnd ? falseBlockEnd : doneBlockEnd, hadConditional, clearOutOnMismatch, prevHadFallthrough);
  2392. if (phiVal)
  2393. {
  2394. auto falseVal = mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0);
  2395. if (falseBlockEnd)
  2396. mBfIRBuilder->AddPhiIncoming(phiVal, falseVal, falseBlockEnd);
  2397. auto trueVal = mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1);
  2398. mBfIRBuilder->AddPhiIncoming(phiVal, trueVal, matchedBlockEnd);
  2399. }
  2400. if (eqBlock != NULL)
  2401. mBfIRBuilder->CreateBr(*eqBlock);
  2402. else
  2403. mBfIRBuilder->CreateBr(doneBlockStart);
  2404. if (falseBlockEnd)
  2405. {
  2406. mBfIRBuilder->SetInsertPoint(falseBlockEnd);
  2407. mBfIRBuilder->CreateBr(doneBlockStart);
  2408. //mBfIRBuilder->AddPhiIncoming(phiVal, mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), falseBlock);
  2409. }
  2410. mBfIRBuilder->AddBlock(doneBlockStart);
  2411. mBfIRBuilder->SetInsertPoint(doneBlockEnd);
  2412. if (phiVal)
  2413. return BfTypedValue(phiVal, boolType);
  2414. else
  2415. return GetDefaultTypedValue(boolType);
  2416. }
  2417. BfTypedValue BfModule::TryCaseEnumMatch(BfTypedValue enumVal, BfTypedValue tagVal, BfExpression* expr, BfIRBlock* eqBlock, BfIRBlock* notEqBlock, BfIRBlock* matchBlock, int& tagId, bool& hadConditional, bool clearOutOnMismatch, bool prevHadFallthrough)
  2418. {
  2419. auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(expr);
  2420. if (invocationExpr == NULL)
  2421. return BfTypedValue();
  2422. auto activeTypeDef = GetActiveTypeDef();
  2423. BfType* targetType = NULL;
  2424. BfIdentifierNode* nameNode = NULL;
  2425. BfTokenNode* dotNode = NULL;
  2426. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  2427. {
  2428. if (memberRefExpr->mTarget == NULL)
  2429. {
  2430. targetType = enumVal.mType;
  2431. }
  2432. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpr->mTarget))
  2433. {
  2434. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  2435. targetType = ResolveTypeRef(typeRef);
  2436. }
  2437. else if (auto identifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mTarget))
  2438. {
  2439. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  2440. targetType = ResolveTypeRef(identifier, NULL);
  2441. }
  2442. if (auto nameIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  2443. {
  2444. dotNode = memberRefExpr->mDotToken;
  2445. nameNode = nameIdentifier;
  2446. }
  2447. else
  2448. return BfTypedValue();
  2449. }
  2450. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(invocationExpr->mTarget))
  2451. {
  2452. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  2453. targetType = ResolveTypeRef(qualifiedNameNode->mLeft, NULL);
  2454. nameNode = qualifiedNameNode->mRight;
  2455. }
  2456. else if (auto identiferNode = BfNodeDynCast<BfIdentifierNode>(invocationExpr->mTarget))
  2457. {
  2458. targetType = mCurTypeInstance;
  2459. nameNode = identiferNode;
  2460. }
  2461. else
  2462. return BfTypedValue();
  2463. // These may have been colorized as methods, so change that
  2464. SetElementType(nameNode, BfSourceElementType_Normal);
  2465. if ((targetType == NULL) || (!targetType->IsPayloadEnum()))
  2466. return BfTypedValue();
  2467. auto enumType = targetType->ToTypeInstance();
  2468. PopulateType(enumType);
  2469. StringT<128> enumCaseName;
  2470. if (nameNode != NULL)
  2471. nameNode->ToString(enumCaseName);
  2472. auto tagType = GetPrimitiveType(BfTypeCode_Int32);
  2473. if (enumVal.mType != enumType)
  2474. {
  2475. Fail(StrFormat("Cannot match enum type '%s' with type '%s'",
  2476. TypeToString(enumVal.mType).c_str(), TypeToString(enumType).c_str()));
  2477. enumVal = GetDefaultTypedValue(enumType);
  2478. tagVal = GetDefaultTypedValue(tagType);
  2479. }
  2480. for (int fieldIdx = 0; fieldIdx < (int)enumType->mFieldInstances.size(); fieldIdx++)
  2481. {
  2482. auto fieldInstance = &enumType->mFieldInstances[fieldIdx];
  2483. auto fieldDef = fieldInstance->GetFieldDef();
  2484. if (fieldDef == NULL)
  2485. continue;
  2486. if ((fieldInstance->mIsEnumPayloadCase) && (fieldDef->mName == enumCaseName))
  2487. {
  2488. if (!IsInSpecializedSection())
  2489. {
  2490. if ((!enumType->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, this)) ||
  2491. (!enumType->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  2492. continue;
  2493. }
  2494. auto resolvePassData = mCompiler->mResolvePassData;
  2495. if (resolvePassData != NULL)
  2496. {
  2497. if (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field)
  2498. resolvePassData->HandleFieldReference(nameNode, enumType->mTypeDef, fieldDef);
  2499. String filter;
  2500. auto autoComplete = resolvePassData->mAutoComplete;
  2501. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(dotNode, nameNode, filter)))
  2502. autoComplete->AddEnumTypeMembers(enumType, enumCaseName, false, enumType == mCurTypeInstance);
  2503. }
  2504. BF_ASSERT(fieldInstance->mResolvedType->IsTuple());
  2505. auto tupleType = (BfTypeInstance*)fieldInstance->mResolvedType;
  2506. PopulateType(tupleType);
  2507. mBfIRBuilder->PopulateType(tupleType);
  2508. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  2509. tagId = -fieldInstance->mDataIdx - 1;
  2510. auto startBlock = mBfIRBuilder->GetInsertBlock();
  2511. auto dscrType = enumType->GetDiscriminatorType();
  2512. BfIRValue eqResult = mBfIRBuilder->CreateCmpEQ(tagVal.mValue, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagId));
  2513. BfIRBlock falseBlockStart;
  2514. BfIRBlock falseBlockEnd;
  2515. BfIRBlock doneBlockStart;
  2516. BfIRBlock doneBlockEnd;
  2517. if (notEqBlock != NULL)
  2518. doneBlockStart = doneBlockEnd = *notEqBlock;
  2519. else
  2520. doneBlockStart = doneBlockEnd = mBfIRBuilder->CreateBlock("caseDone", false);
  2521. if (clearOutOnMismatch)
  2522. {
  2523. falseBlockStart = falseBlockEnd = mBfIRBuilder->CreateBlock("caseNotEq", false);
  2524. mBfIRBuilder->AddBlock(falseBlockStart);
  2525. }
  2526. BfIRBlock matchedBlockStart = mBfIRBuilder->CreateBlock("caseMatch", false);
  2527. BfIRBlock matchedBlockEnd = matchedBlockStart;
  2528. if (matchBlock != NULL)
  2529. *matchBlock = matchedBlockStart;
  2530. mBfIRBuilder->CreateCondBr(eqResult, matchedBlockStart, falseBlockStart ? falseBlockStart : doneBlockStart);
  2531. mBfIRBuilder->AddBlock(matchedBlockStart);
  2532. mBfIRBuilder->SetInsertPoint(doneBlockEnd);
  2533. BfIRValue phiVal;
  2534. if (eqBlock == NULL)
  2535. phiVal = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(boolType), 1 + (int)tupleType->mFieldInstances.size());
  2536. mBfIRBuilder->SetInsertPoint(matchedBlockEnd);
  2537. BfTypedValue tupleVal;
  2538. if (!enumVal.IsAddr())
  2539. {
  2540. auto unionInnerType = enumType->GetUnionInnerType();
  2541. if (unionInnerType == tupleType)
  2542. {
  2543. tupleVal = ExtractValue(enumVal, NULL, 1);
  2544. }
  2545. }
  2546. if (!tupleVal)
  2547. {
  2548. if (!tupleType->IsValuelessType())
  2549. {
  2550. tupleVal = ExtractValue(enumVal, NULL, 1);
  2551. tupleVal = Cast(NULL, tupleVal, tupleType, BfCastFlags_Force);
  2552. }
  2553. else
  2554. tupleVal = GetDefaultTypedValue(tupleType);
  2555. }
  2556. ////
  2557. BfAstNode* tooFewRef = invocationExpr->mCloseParen;
  2558. if ((tooFewRef == NULL) && (!invocationExpr->mCommas.IsEmpty()))
  2559. tooFewRef = invocationExpr->mCommas[invocationExpr->mCommas.size() - 1];
  2560. else if (tooFewRef == NULL)
  2561. tooFewRef = invocationExpr->mOpenParen;
  2562. ///
  2563. auto autoComplete = mCompiler->GetAutoComplete();
  2564. bool wasCapturingMethodInfo = false;
  2565. if (autoComplete != NULL)
  2566. {
  2567. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  2568. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  2569. if (autoComplete->mIsCapturingMethodMatchInfo)
  2570. {
  2571. autoComplete->mMethodMatchInfo->mInstanceList.Clear();
  2572. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  2573. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  2574. methodMatchEntry.mTypeInstance = enumType;
  2575. methodMatchEntry.mCurMethodInstance = mCurMethodInstance;
  2576. methodMatchEntry.mPayloadEnumField = fieldInstance;
  2577. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  2578. methodMatchInfo->mBestIdx = 0;
  2579. methodMatchInfo->mMostParamsMatched = 0;
  2580. int cursorIdx = invocationExpr->GetParser()->mCursorIdx;
  2581. if ((invocationExpr->mCloseParen == NULL) || (cursorIdx <= invocationExpr->mCloseParen->GetSrcStart()))
  2582. {
  2583. int paramIdx = 0;
  2584. for (int commaIdx = 0; commaIdx < (int)invocationExpr->mCommas.size(); commaIdx++)
  2585. {
  2586. auto commaNode = invocationExpr->mCommas[commaIdx];
  2587. if ((commaNode != NULL) && (cursorIdx >= commaNode->GetSrcStart()))
  2588. paramIdx = commaIdx + 1;
  2589. }
  2590. bool isEmpty = true;
  2591. if (paramIdx < (int)invocationExpr->mArguments.size())
  2592. {
  2593. auto paramNode = invocationExpr->mArguments[paramIdx];
  2594. if (paramNode != NULL)
  2595. isEmpty = false;
  2596. }
  2597. if (isEmpty)
  2598. {
  2599. if (paramIdx < (int)tupleType->mFieldInstances.size())
  2600. {
  2601. auto fieldDef = tupleType->mFieldInstances[paramIdx].GetFieldDef();
  2602. String insertStr;
  2603. if (fieldDef->IsUnnamedTupleField())
  2604. insertStr = "p";
  2605. insertStr += fieldDef->mName;
  2606. insertStr.Insert(0, "let ");
  2607. autoComplete->mEntriesSet.Clear();
  2608. autoComplete->AddEntry(AutoCompleteEntry("paramName", insertStr));
  2609. autoComplete->mInsertStartIdx = cursorIdx;
  2610. autoComplete->mInsertEndIdx = cursorIdx;
  2611. }
  2612. }
  2613. }
  2614. }
  2615. }
  2616. defer
  2617. (
  2618. if (autoComplete != NULL)
  2619. autoComplete->mIsCapturingMethodMatchInfo = (wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo);
  2620. );
  2621. ///
  2622. HandleCaseEnumMatch_Tuple(tupleVal, invocationExpr->mArguments, tooFewRef, falseBlockStart ? BfIRValue() : phiVal, matchedBlockStart, matchedBlockEnd,
  2623. falseBlockStart ? falseBlockStart : doneBlockStart, falseBlockEnd ? falseBlockEnd : doneBlockEnd,
  2624. hadConditional, clearOutOnMismatch, prevHadFallthrough);
  2625. ///////
  2626. if (phiVal)
  2627. {
  2628. auto falseVal = mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0);
  2629. if (falseBlockEnd)
  2630. mBfIRBuilder->AddPhiIncoming(phiVal, falseVal, falseBlockEnd);
  2631. else
  2632. mBfIRBuilder->AddPhiIncoming(phiVal, falseVal, startBlock);
  2633. auto trueVal = mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1);
  2634. mBfIRBuilder->AddPhiIncoming(phiVal, trueVal, matchedBlockEnd);
  2635. }
  2636. if (eqBlock != NULL)
  2637. mBfIRBuilder->CreateBr(*eqBlock);
  2638. else
  2639. mBfIRBuilder->CreateBr(doneBlockStart);
  2640. if (falseBlockEnd)
  2641. {
  2642. mBfIRBuilder->SetInsertPoint(falseBlockEnd);
  2643. mBfIRBuilder->CreateBr(doneBlockStart);
  2644. //mBfIRBuilder->AddPhiIncoming(phiVal, mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), falseBlock);
  2645. }
  2646. mBfIRBuilder->AddBlock(doneBlockStart);
  2647. mBfIRBuilder->SetInsertPoint(doneBlockEnd);
  2648. if (phiVal)
  2649. return BfTypedValue(phiVal, boolType);
  2650. else
  2651. return GetDefaultTypedValue(boolType);
  2652. }
  2653. }
  2654. return BfTypedValue();
  2655. }
  2656. BfTypedValue BfModule::HandleCaseBind(BfTypedValue enumVal, const BfTypedValue& tagVal, BfEnumCaseBindExpression* bindExpr, BfIRBlock* eqBlock, BfIRBlock* notEqBlock, BfIRBlock* matchBlock, int* outEnumIdx)
  2657. {
  2658. BfTypeInstance* tupleType = NULL;
  2659. auto activeTypeDef = GetActiveTypeDef();
  2660. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  2661. BfIRValue eqResult;
  2662. if (bindExpr->mEnumMemberExpr != NULL)
  2663. {
  2664. int enumIdx = -1;
  2665. String findName;
  2666. BfType* type = NULL;
  2667. BfAstNode* targetNode = NULL;
  2668. BfAstNode* nameNode = NULL;
  2669. BfAstNode* dotNode = NULL;
  2670. if (auto memberExpr = BfNodeDynCast<BfMemberReferenceExpression>(bindExpr->mEnumMemberExpr))
  2671. {
  2672. dotNode = memberExpr->mDotToken;
  2673. if (memberExpr->mMemberName != NULL)
  2674. {
  2675. nameNode = memberExpr->mMemberName;
  2676. findName = memberExpr->mMemberName->ToString();
  2677. if (memberExpr->mTarget == NULL)
  2678. {
  2679. type = enumVal.mType;
  2680. }
  2681. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberExpr->mTarget))
  2682. {
  2683. type = ResolveTypeRef(typeRef);
  2684. }
  2685. }
  2686. targetNode = memberExpr->mTarget;
  2687. }
  2688. else if (auto identiferNode = BfNodeDynCast<BfIdentifierNode>(bindExpr->mEnumMemberExpr))
  2689. {
  2690. if (mCurTypeInstance->IsPayloadEnum())
  2691. {
  2692. nameNode = identiferNode;
  2693. findName = nameNode->ToString();
  2694. targetNode = identiferNode;
  2695. type = mCurTypeInstance;
  2696. }
  2697. else
  2698. {
  2699. Fail("Expected a qualified enum case name. Consider prefixing name with a dot to infer enum type name.", bindExpr->mEnumMemberExpr);
  2700. }
  2701. }
  2702. if (!findName.empty())
  2703. {
  2704. if (type != NULL)
  2705. {
  2706. if (type != enumVal.mType)
  2707. {
  2708. Fail(StrFormat("Enum case type '%s' does not match compared value of type '%s'",
  2709. TypeToString(enumVal.mType).c_str(), TypeToString(type).c_str()), targetNode);
  2710. }
  2711. if (type->IsEnum())
  2712. {
  2713. auto enumType = (BfTypeInstance*)type;
  2714. for (auto& fieldInstance : enumType->mFieldInstances)
  2715. {
  2716. auto fieldDef = fieldInstance.GetFieldDef();
  2717. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()) && (fieldDef->mName == findName))
  2718. {
  2719. if ((!enumType->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, this)) ||
  2720. (!enumType->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  2721. continue;
  2722. auto resolvePassData = mCompiler->mResolvePassData;
  2723. if (resolvePassData != NULL)
  2724. {
  2725. if (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field)
  2726. resolvePassData->HandleFieldReference(nameNode, enumType->mTypeDef, fieldDef);
  2727. String filter;
  2728. auto autoComplete = resolvePassData->mAutoComplete;
  2729. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(dotNode, nameNode, filter)))
  2730. autoComplete->AddEnumTypeMembers(enumType, findName, false, enumType == mCurTypeInstance);
  2731. }
  2732. enumIdx = -fieldInstance.mDataIdx - 1;
  2733. if (outEnumIdx != NULL)
  2734. *outEnumIdx = enumIdx;
  2735. if (fieldInstance.mIsEnumPayloadCase)
  2736. tupleType = fieldInstance.mResolvedType->ToTypeInstance();
  2737. }
  2738. }
  2739. if (enumIdx == -1)
  2740. {
  2741. Fail("Enum case not found", nameNode);
  2742. }
  2743. }
  2744. else
  2745. {
  2746. Fail(StrFormat("Type '%s' is not an enum type", TypeToString(type).c_str()), targetNode);
  2747. }
  2748. }
  2749. }
  2750. BF_ASSERT(tagVal.mType->IsPrimitiveType());
  2751. eqResult = mBfIRBuilder->CreateCmpEQ(tagVal.mValue, mBfIRBuilder->CreateConst(((BfPrimitiveType*)tagVal.mType)->mTypeDef->mTypeCode, enumIdx));
  2752. }
  2753. else
  2754. {
  2755. eqResult = mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0);
  2756. }
  2757. BfIRBlock falseBlock;
  2758. if (notEqBlock != NULL)
  2759. {
  2760. falseBlock = *notEqBlock;
  2761. }
  2762. else
  2763. {
  2764. falseBlock = mBfIRBuilder->CreateBlock("notEqBlock", false);
  2765. }
  2766. auto mainBlock = mBfIRBuilder->GetInsertBlock();
  2767. BfIRBlock trueBlock = mBfIRBuilder->CreateBlock("eqBlock", false);
  2768. if (matchBlock != NULL)
  2769. *matchBlock = trueBlock;
  2770. mBfIRBuilder->AddBlock(trueBlock);
  2771. mBfIRBuilder->SetInsertPoint(trueBlock);
  2772. if ((tupleType != NULL) && (bindExpr->mBindNames != NULL))
  2773. {
  2774. BfIRValue valueScopeStart;
  2775. if (IsTargetingBeefBackend())
  2776. valueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  2777. bool isVar = bindExpr->mBindToken->GetToken() == BfToken_Var;
  2778. bool isLet = bindExpr->mBindToken->GetToken() == BfToken_Let;
  2779. BfTypedValue tupleVal;
  2780. if (enumVal.IsAddr())
  2781. {
  2782. auto ptrVal = mBfIRBuilder->CreateInBoundsGEP(enumVal.mValue, 0, 1);
  2783. tupleVal = BfTypedValue(mBfIRBuilder->CreateBitCast(ptrVal, mBfIRBuilder->MapTypeInstPtr(tupleType)), tupleType, true);
  2784. }
  2785. else
  2786. {
  2787. auto unionInnerType = enumVal.mType->ToTypeInstance()->GetUnionInnerType();
  2788. tupleVal = ExtractValue(enumVal, NULL, 1);
  2789. if (unionInnerType != tupleType)
  2790. {
  2791. tupleVal = MakeAddressable(tupleVal);
  2792. tupleVal = BfTypedValue(mBfIRBuilder->CreateBitCast(tupleVal.mValue, mBfIRBuilder->MapTypeInstPtr(tupleType)), tupleType, true);
  2793. }
  2794. }
  2795. HandleTupleVariableDeclaration(NULL, bindExpr->mBindNames, tupleVal, isLet, false, true /*, &mainBlock*/);
  2796. auto autoComplete = mCompiler->GetAutoComplete();
  2797. if ((autoComplete != NULL) && ((isVar || isLet)))
  2798. autoComplete->CheckVarResolution(bindExpr->mBindToken, tupleType);
  2799. if (valueScopeStart)
  2800. mBfIRBuilder->CreateValueScopeSoftEnd(valueScopeStart);
  2801. }
  2802. if (eqBlock != NULL)
  2803. mBfIRBuilder->CreateBr(*eqBlock);
  2804. else
  2805. mBfIRBuilder->CreateBr(falseBlock);
  2806. // Don't create the condBr until now, so HandleTupleVariableDeclaration can create the variable declarations in mainBlock--
  2807. // we need them there since the code that uses the new variables is created outside the eqBlock
  2808. mBfIRBuilder->SetInsertPoint(mainBlock);
  2809. mBfIRBuilder->CreateCondBr(eqResult, trueBlock, falseBlock);
  2810. mBfIRBuilder->AddBlock(falseBlock);
  2811. mBfIRBuilder->SetInsertPoint(falseBlock);
  2812. return BfTypedValue(eqResult, boolType);
  2813. }
  2814. void BfModule::AddBasicBlock(BfIRBlock bb, bool activate)
  2815. {
  2816. mBfIRBuilder->AddBlock(bb);
  2817. if (activate)
  2818. mBfIRBuilder->SetInsertPoint(bb);
  2819. }
  2820. void BfModule::VisitEmbeddedStatement(BfAstNode* stmt, BfExprEvaluator* exprEvaluator, BfEmbeddedStatementFlags flags)
  2821. {
  2822. if ((flags & BfEmbeddedStatementFlags_CheckStack) != 0)
  2823. {
  2824. BP_ZONE("BfModule.VisitEmbeddedStatement");
  2825. StackHelper stackHelper;
  2826. if (!stackHelper.CanStackExpand(64 * 1024))
  2827. {
  2828. if (!stackHelper.Execute([&]()
  2829. {
  2830. VisitEmbeddedStatement(stmt, exprEvaluator, flags);
  2831. }))
  2832. {
  2833. Fail("Statement too complex to parse", stmt);
  2834. }
  2835. return;
  2836. }
  2837. }
  2838. auto block = BfNodeDynCast<BfBlock>(stmt);
  2839. BfLabelNode* labelNode = NULL;
  2840. if (block == NULL)
  2841. {
  2842. auto labeledBlock = BfNodeDynCast<BfLabeledBlock>(stmt);
  2843. if (labeledBlock != NULL)
  2844. {
  2845. block = labeledBlock->mBlock;
  2846. labelNode = labeledBlock->mLabelNode;
  2847. }
  2848. }
  2849. BfAstNode* openBrace = NULL;
  2850. BfAstNode* closeBrace = NULL;
  2851. if (block != NULL)
  2852. {
  2853. openBrace = block->mOpenBrace;
  2854. closeBrace = block->mCloseBrace;
  2855. if (openBrace == NULL)
  2856. {
  2857. auto checkScope = mCurMethodState->mCurScope;
  2858. while ((checkScope != NULL) && (closeBrace == NULL))
  2859. {
  2860. closeBrace = checkScope->mCloseNode;
  2861. checkScope = checkScope->mPrevScope;
  2862. }
  2863. BF_ASSERT(closeBrace != NULL);
  2864. }
  2865. }
  2866. if ((block != NULL) && (openBrace != NULL))
  2867. UpdateSrcPos(openBrace);
  2868. if ((flags & BfEmbeddedStatementFlags_Unscoped) != 0)
  2869. {
  2870. SetAndRestoreValue<BfExprEvaluator*> prevExprEvaluator(mCurMethodState->mCurScope->mExprEvaluator, exprEvaluator);
  2871. SetAndRestoreValue<bool> prevAllowReturn(mCurMethodState->mDisableReturns, true);
  2872. VisitCodeBlock(block);
  2873. }
  2874. else if (mCurMethodState != NULL)
  2875. {
  2876. bool isIgnore = mBfIRBuilder->mIgnoreWrites;
  2877. mCurMethodState->mInHeadScope = false;
  2878. BfScopeData scopeData;
  2879. if (IsTargetingBeefBackend())
  2880. scopeData.mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  2881. mCurMethodState->AddScope(&scopeData);
  2882. if (block != NULL)
  2883. {
  2884. mCurMethodState->mCurScope->mAstBlock = block;
  2885. mCurMethodState->mCurScope->mCloseNode = closeBrace;
  2886. }
  2887. if (labelNode != NULL)
  2888. scopeData.mLabelNode = labelNode->mLabel;
  2889. NewScopeState(block != NULL);
  2890. mCurMethodState->mCurScope->mOuterIsConditional = (flags & BfEmbeddedStatementFlags_IsConditional) != 0;
  2891. mCurMethodState->mCurScope->mIsDeferredBlock = (flags & BfEmbeddedStatementFlags_IsDeferredBlock) != 0;
  2892. mCurMethodState->mCurScope->mExprEvaluator = exprEvaluator;
  2893. //
  2894. {
  2895. SetAndRestoreValue<bool> inDeferredBlock(mCurMethodState->mInDeferredBlock, mCurMethodState->mInDeferredBlock || mCurMethodState->mCurScope->mIsDeferredBlock);
  2896. if (block != NULL)
  2897. {
  2898. if (labelNode != NULL)
  2899. VisitCodeBlock(block, BfIRBlock(), BfIRBlock(), BfIRBlock(), false, NULL, labelNode);
  2900. else
  2901. VisitCodeBlock(block);
  2902. }
  2903. else
  2904. {
  2905. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(stmt))
  2906. {
  2907. Fail("Variable declarations must be wrapped in a block statement", varDecl);
  2908. }
  2909. VisitChild(stmt);
  2910. }
  2911. }
  2912. if ((block != NULL) && (closeBrace != NULL))
  2913. {
  2914. UpdateSrcPos(closeBrace);
  2915. if (!mCurMethodState->mLeftBlockUncond)
  2916. EmitEnsureInstructionAt();
  2917. }
  2918. if (block != NULL)
  2919. {
  2920. BfAutoParentNodeEntry autoParentNodeEntry(this, block);
  2921. RestoreScopeState();
  2922. }
  2923. else
  2924. RestoreScopeState();
  2925. BF_ASSERT(isIgnore == mBfIRBuilder->mIgnoreWrites);
  2926. }
  2927. else
  2928. {
  2929. if (block != NULL)
  2930. VisitCodeBlock(block);
  2931. else
  2932. VisitChild(stmt);
  2933. }
  2934. }
  2935. void BfModule::VisitCodeBlock(BfBlock* block, BfIRBlock continueBlock, BfIRBlock breakBlock, BfIRBlock fallthroughBlock, bool defaultBreak, bool* hadReturn, BfLabelNode* labelNode, bool closeScope, BfEmbeddedStatementFlags flags)
  2936. {
  2937. BfBreakData breakData;
  2938. breakData.mIRContinueBlock = continueBlock;
  2939. breakData.mIRBreakBlock = breakBlock;
  2940. breakData.mIRFallthroughBlock = fallthroughBlock;
  2941. breakData.mScope = mCurMethodState->mCurScope;
  2942. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  2943. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  2944. VisitEmbeddedStatement(block, NULL, flags);
  2945. if (closeScope)
  2946. RestoreScopeState();
  2947. if ((!mCurMethodState->mLeftBlockUncond) && (defaultBreak))
  2948. {
  2949. mBfIRBuilder->CreateBr(breakBlock);
  2950. }
  2951. if (hadReturn != NULL)
  2952. {
  2953. *hadReturn = mCurMethodState->mHadReturn;
  2954. mCurMethodState->SetHadReturn(false);
  2955. mCurMethodState->mLeftBlockUncond = false;
  2956. }
  2957. }
  2958. void BfModule::VisitCodeBlock(BfBlock* block)
  2959. {
  2960. //BP_ZONE("BfModule::VisitCodeBlock");
  2961. BfAutoParentNodeEntry autoParentNodeEntry(this, block);
  2962. BfIRBlock prevInsertBlock;
  2963. bool hadReturn = false;
  2964. int startLocalMethod = 0; // was -1
  2965. auto rootMethodState = mCurMethodState->GetRootMethodState();
  2966. BfIRBlock startInsertBlock = mBfIRBuilder->GetInsertBlock();
  2967. bool allowLocalMethods = mCurMethodInstance != NULL;
  2968. //int startDeferredLocalIdx = (int)rootMethodState->mDeferredLocalMethods.size();
  2969. int curLocalMethodIdx = -1;
  2970. // Scan for any local method declarations
  2971. if (allowLocalMethods)
  2972. {
  2973. startLocalMethod = (int)mCurMethodState->mLocalMethods.size();
  2974. curLocalMethodIdx = startLocalMethod;
  2975. auto itr = block->begin();
  2976. while (itr != block->end())
  2977. {
  2978. BfAstNode* child = *itr;
  2979. if (auto localMethodDecl = BfNodeDynCastExact<BfLocalMethodDeclaration>(child))
  2980. {
  2981. BfLocalMethod* localMethod;
  2982. auto rootMethodState = mCurMethodState->GetRootMethodState();
  2983. String methodName;
  2984. if (localMethodDecl->mMethodDeclaration->mNameNode != NULL)
  2985. {
  2986. methodName = GetLocalMethodName(localMethodDecl->mMethodDeclaration->mNameNode->ToString(), localMethodDecl->mMethodDeclaration->mOpenParen, mCurMethodState, mCurMethodState->mMixinState);
  2987. BfLocalMethod** localMethodPtr = NULL;
  2988. if (rootMethodState->mLocalMethodCache.TryGetValue(methodName, &localMethodPtr))
  2989. {
  2990. localMethod = *localMethodPtr;
  2991. }
  2992. else
  2993. {
  2994. localMethod = new BfLocalMethod();
  2995. localMethod->mSystem = mSystem;
  2996. localMethod->mModule = this;
  2997. localMethod->mMethodDeclaration = localMethodDecl->mMethodDeclaration;
  2998. localMethod->mSource = mCurTypeInstance->mTypeDef->mSource;
  2999. localMethod->mSource->mRefCount++;
  3000. if (mCurMethodState->mClosureState != NULL)
  3001. localMethod->mOuterLocalMethod = mCurMethodState->mClosureState->mLocalMethod;
  3002. auto autoComplete = mCompiler->GetAutoComplete();
  3003. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_Autocomplete))
  3004. {
  3005. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  3006. if (!autoComplete->IsAutocompleteNode(localMethod->mMethodDeclaration))
  3007. localMethod->mDeclOnly = true;
  3008. }
  3009. if (localMethod->mMethodDeclaration->mNameNode != NULL)
  3010. localMethod->mMethodName = localMethod->mMethodDeclaration->mNameNode->ToString();
  3011. localMethod->mExpectedFullName = methodName;
  3012. rootMethodState->mLocalMethodCache[methodName] = localMethod;
  3013. mContext->mLocalMethodGraveyard.push_back(localMethod);
  3014. }
  3015. BF_ASSERT(mCurMethodState->mCurScope != NULL);
  3016. localMethod->mDeclDIScope = mCurMethodState->mCurScope->mDIScope;
  3017. localMethod->mDeclMethodState = mCurMethodState;
  3018. localMethod->mDeclMixinState = mCurMethodState->mMixinState;
  3019. if (localMethod->mDeclMixinState != NULL)
  3020. localMethod->mDeclMixinState->mHasDeferredUsage = true;
  3021. mCurMethodState->mLocalMethods.push_back(localMethod);
  3022. String* namePtr;
  3023. if (!mCurMethodState->mLocalMethodMap.TryAdd(localMethod->mMethodName, &namePtr, &localMethodPtr))
  3024. {
  3025. BF_ASSERT(localMethod != *localMethodPtr);
  3026. localMethod->mNextWithSameName = *localMethodPtr;
  3027. }
  3028. *localMethodPtr = localMethod;
  3029. }
  3030. }
  3031. ++itr;
  3032. }
  3033. }
  3034. bool wantsAllLocalMethods = true;
  3035. auto autoComplete = mCompiler->GetAutoComplete();
  3036. if (autoComplete != NULL)
  3037. {
  3038. // If we only need reasoning "at the cursor" then we don't need all local methods
  3039. if ((!autoComplete->mIsAutoComplete) ||
  3040. (autoComplete->mResolveType == BfResolveType_GetCurrentLocation) ||
  3041. (autoComplete->mResolveType == BfResolveType_GetFixits) ||
  3042. (autoComplete->mResolveType == BfResolveType_GetResultString) ||
  3043. (autoComplete->mResolveType == BfResolveType_GetSymbolInfo) ||
  3044. (autoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  3045. wantsAllLocalMethods = false;
  3046. }
  3047. /*if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType == BfResolveType_ShowFileSymbolReferences))
  3048. {
  3049. if (mCompiler->mResolvePassData->mSymbolReferenceLocalIdx != -1)
  3050. {
  3051. // We need to reproduce the behavior when we found the symbol - only process autocomplete nodes, otherwise local method ids will be wrong
  3052. // when we have local methods that were skipped the first time but not the second
  3053. wantsAllLocalMethods = false;
  3054. }
  3055. }*/
  3056. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites);
  3057. bool hadUnreachableCode = false;
  3058. // Handle statements
  3059. auto itr = block->begin();
  3060. while (itr != block->end())
  3061. {
  3062. BfAstNode* child = *itr;
  3063. if (auto localMethodDecl = BfNodeDynCastExact<BfLocalMethodDeclaration>(child))
  3064. {
  3065. /*if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  3066. Fail("Mixins cannot contain local methods", child);*/
  3067. if (!allowLocalMethods)
  3068. {
  3069. Fail("Invalid use of local methods", child);
  3070. }
  3071. else if (localMethodDecl->mMethodDeclaration->mNameNode != NULL)
  3072. {
  3073. BfLocalMethod* localMethod = mCurMethodState->mLocalMethods[curLocalMethodIdx];
  3074. BF_ASSERT(localMethod->mMethodDeclaration == localMethodDecl->mMethodDeclaration);
  3075. bool wantsLocalMethod = (wantsAllLocalMethods) || (autoComplete->IsAutocompleteNode(localMethod->mMethodDeclaration));
  3076. if ((!wantsLocalMethod) && (mCurMethodInstance->mMethodDef->mIsLocalMethod))
  3077. wantsLocalMethod = true;
  3078. if (wantsLocalMethod)
  3079. {
  3080. if (!mCurMethodInstance->IsSpecializedGenericMethodOrType())
  3081. GetLocalMethodInstance(localMethod, BfTypeVector(), NULL, true); // Only necessary on unspecialized pass
  3082. }
  3083. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  3084. mCompiler->mResolvePassData->mAutoComplete->CheckMethod(localMethod->mMethodDeclaration, true);
  3085. curLocalMethodIdx++;
  3086. }
  3087. ++itr;
  3088. continue;
  3089. }
  3090. if ((mCurMethodState != NULL) && (mCurMethodState->mLeftBlockUncond)) // mLeftBlock is cleared after conditional block is completed
  3091. {
  3092. if (mCurMethodState->mHadReturn)
  3093. hadReturn = true;
  3094. if ((!hadUnreachableCode) && (!mCurMethodState->mInPostReturn))
  3095. {
  3096. if ((mCurMethodState->mCurScope == NULL) || (!mCurMethodState->mCurScope->mSupressNextUnreachable))
  3097. Warn(BfWarning_CS0162_UnreachableCode, "Unreachable code", child);
  3098. hadUnreachableCode = true;
  3099. prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3100. mCurMethodState->mInPostReturn = true;
  3101. mBfIRBuilder->mIgnoreWrites = true;
  3102. }
  3103. }
  3104. if ((mCurMethodState != NULL) && (mCurMethodState->mCurScope != NULL))
  3105. mCurMethodState->mCurScope->mSupressNextUnreachable = false;
  3106. if (itr.IsLast())
  3107. {
  3108. if (auto expr = BfNodeDynCast<BfExpression>(child))
  3109. {
  3110. if (expr->IsExpression())
  3111. {
  3112. if (mCurMethodState != NULL)
  3113. {
  3114. if (mCurMethodState->mCurScope->mExprEvaluator != NULL)
  3115. {
  3116. if ((mAttributeState != NULL) &&
  3117. ((mAttributeState->mFlags & (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)) == (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)))
  3118. {
  3119. // Resolve as just 'false'
  3120. mCurMethodState->mCurScope->mExprEvaluator->mResult = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_Boolean));
  3121. }
  3122. else
  3123. {
  3124. auto exprEvaluator = mCurMethodState->mCurScope->mExprEvaluator;
  3125. // Evaluate last child as an expression
  3126. exprEvaluator->VisitChild(expr);
  3127. exprEvaluator->FinishExpressionResult();
  3128. if ((exprEvaluator->mResult) && (!exprEvaluator->mResult.mType->IsValuelessType()) && (!exprEvaluator->mResult.mValue.IsConst()) &&
  3129. (!exprEvaluator->mResult.IsAddr()) && (exprEvaluator->mResult.mValue) && (!exprEvaluator->mResult.mValue.IsFake()))
  3130. {
  3131. if ((mCurMethodState->mCurScope != NULL) && (mCurMethodState->mCurScope->mPrevScope != NULL))
  3132. {
  3133. // We need to make sure we don't retain any values through the scope's ValueScopeHardEnd - and extend alloca through previous scope
  3134. bool wasReadOnly = exprEvaluator->mResult.IsReadOnly();
  3135. FixIntUnknown(exprEvaluator->mResult, exprEvaluator->mExpectingType);
  3136. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3137. auto tempVar = CreateAlloca(exprEvaluator->mResult.mType, false, "blockExpr");
  3138. mBfIRBuilder->SetInsertPointAtStart(startInsertBlock);
  3139. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(tempVar);
  3140. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  3141. if ((!mBfIRBuilder->mIgnoreWrites) && (IsTargetingBeefBackend()))
  3142. mCurMethodState->mCurScope->mPrevScope->mDeferredLifetimeEnds.push_back(tempVar);
  3143. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3144. if (exprEvaluator->mResult.IsSplat())
  3145. AggregateSplatIntoAddr(exprEvaluator->mResult, tempVar);
  3146. else if (!exprEvaluator->mResult.mType->IsValuelessType())
  3147. mBfIRBuilder->CreateAlignedStore(exprEvaluator->mResult.mValue, tempVar, exprEvaluator->mResult.mType->mAlign);
  3148. exprEvaluator->mResult = BfTypedValue(tempVar, exprEvaluator->mResult.mType,
  3149. exprEvaluator->mResult.IsThis() ?
  3150. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  3151. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  3152. }
  3153. }
  3154. if (exprEvaluator->mResult.IsAddr())
  3155. {
  3156. if (mCurMethodState->mCurScope->ExtendLifetime(exprEvaluator->mResult.mValue))
  3157. mBfIRBuilder->CreateLifetimeSoftEnd(exprEvaluator->mResult.mValue);
  3158. }
  3159. }
  3160. break;
  3161. }
  3162. else if (mCurMethodState->InMainMixinScope())
  3163. {
  3164. mCurMethodState->mMixinState->mResultExpr = expr;
  3165. break;
  3166. }
  3167. else if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin()) && (mCurMethodState->mCurScope == &mCurMethodState->mHeadScope))
  3168. {
  3169. // Only in mixin definition - result ignored
  3170. CreateValueFromExpression(expr, NULL, BfEvalExprFlags_AllowRefExpr);
  3171. break;
  3172. }
  3173. else
  3174. {
  3175. FailAfter("Expression block cannot be used here. Consider adding semicolon if a statement was intended.", expr);
  3176. }
  3177. }
  3178. }
  3179. }
  3180. }
  3181. UpdateSrcPos(child);
  3182. BfAutoParentNodeEntry autoParentNode(this, child);
  3183. if ((mAttributeState != NULL) &&
  3184. ((mAttributeState->mFlags & (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)) == (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)))
  3185. {
  3186. // Ignore child
  3187. }
  3188. else
  3189. child->Accept(this);
  3190. mContext->CheckLockYield();
  3191. ++itr;
  3192. }
  3193. if (mCurMethodState != NULL)
  3194. {
  3195. // Any local method that hasn't been called needs to be processed now
  3196. for (int localMethodIdx = startLocalMethod; localMethodIdx < (int)mCurMethodState->mLocalMethods.size(); localMethodIdx++)
  3197. {
  3198. auto localMethod = mCurMethodState->mLocalMethods[localMethodIdx];
  3199. if ((wantsAllLocalMethods) || (autoComplete->IsAutocompleteNode(localMethod->mMethodDeclaration)))
  3200. {
  3201. //??
  3202. auto moduleMethodInstance = GetLocalMethodInstance(localMethod, BfTypeVector(), NULL, true);
  3203. }
  3204. mContext->CheckLockYield();
  3205. }
  3206. while ((int)mCurMethodState->mLocalMethods.size() > startLocalMethod)
  3207. {
  3208. auto localMethod = mCurMethodState->mLocalMethods.back();
  3209. #if _DEBUG
  3210. BfLocalMethod** localMethodPtr = NULL;
  3211. mCurMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &localMethodPtr);
  3212. BF_ASSERT(*localMethodPtr == localMethod);
  3213. #endif
  3214. if (localMethod->mNextWithSameName == NULL)
  3215. mCurMethodState->mLocalMethodMap.Remove(localMethod->mMethodName);
  3216. else
  3217. {
  3218. mCurMethodState->mLocalMethodMap[localMethod->mMethodName] = localMethod->mNextWithSameName;
  3219. localMethod->mNextWithSameName = NULL;
  3220. }
  3221. mCurMethodState->mLocalMethods.pop_back();
  3222. }
  3223. if (hadUnreachableCode)
  3224. {
  3225. if (hadReturn)
  3226. mCurMethodState->SetHadReturn(true);
  3227. mCurMethodState->mLeftBlockUncond = true;
  3228. mCurMethodState->mInPostReturn = false;
  3229. if (prevInsertBlock)
  3230. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3231. }
  3232. }
  3233. }
  3234. void BfModule::Visit(BfAstNode* astNode)
  3235. {
  3236. AssertErrorState();
  3237. }
  3238. void BfModule::Visit(BfIdentifierNode* identifierNode)
  3239. {
  3240. Visit((BfExpression*)identifierNode);
  3241. }
  3242. void BfModule::Visit(BfTypeReference* typeRef)
  3243. {
  3244. Visit((BfAstNode*)typeRef);
  3245. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  3246. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(typeRef, true);
  3247. }
  3248. void BfModule::Visit(BfEmptyStatement* astNode)
  3249. {
  3250. }
  3251. void BfModule::Visit(BfTryStatement* tryStmt)
  3252. {
  3253. Fail("Exceptions not supported", tryStmt->mTryToken);
  3254. VisitChild(tryStmt->mStatement);
  3255. }
  3256. void BfModule::Visit(BfCatchStatement* catchStmt)
  3257. {
  3258. Fail("Exceptions not supported", catchStmt->mCatchToken);
  3259. }
  3260. void BfModule::Visit(BfFinallyStatement* finallyStmt)
  3261. {
  3262. Fail("Exceptions not supported", finallyStmt->mFinallyToken);
  3263. VisitChild(finallyStmt->mStatement);
  3264. }
  3265. void BfModule::Visit(BfCheckedStatement* checkedStmt)
  3266. {
  3267. Fail("'checked' not supported", checkedStmt->mCheckedToken);
  3268. VisitChild(checkedStmt->mStatement);
  3269. }
  3270. void BfModule::Visit(BfUncheckedStatement* uncheckedStmt)
  3271. {
  3272. VisitChild(uncheckedStmt->mStatement);
  3273. }
  3274. void BfModule::DoIfStatement(BfIfStatement* ifStmt, bool includeTrueStmt, bool includeFalseStmt)
  3275. {
  3276. auto autoComplete = mCompiler->GetAutoComplete();
  3277. if (autoComplete != NULL)
  3278. autoComplete->CheckIdentifier(ifStmt->mIfToken, true);
  3279. if (ifStmt->mCondition == NULL)
  3280. {
  3281. AssertErrorState();
  3282. return;
  3283. }
  3284. //TODO: Only conditionally create the scopeData here if we create a variable inside the condition statement
  3285. UpdateSrcPos(ifStmt);
  3286. BfScopeData newScope;
  3287. newScope.mOuterIsConditional = true;
  3288. newScope.mScopeKind = BfScopeKind_StatementTarget;
  3289. if (ifStmt->mLabelNode != NULL)
  3290. newScope.mLabelNode = ifStmt->mLabelNode->mLabel;
  3291. mCurMethodState->AddScope(&newScope);
  3292. NewScopeState();
  3293. BfBreakData breakData;
  3294. breakData.mScope = &newScope;
  3295. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  3296. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  3297. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3298. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  3299. deferredLocalAssignData.mIsIfCondition = true;
  3300. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, true);
  3301. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  3302. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  3303. BfAutoParentNodeEntry autoParentNodeEntry(this, ifStmt);
  3304. BfTypedValue condValue = CreateValueFromExpression(ifStmt->mCondition, boolType);
  3305. newScope.mScopeKind = BfScopeKind_Normal;
  3306. deferredLocalAssignData.mIsIfCondition = false;
  3307. // The "extend chain" is only valid for the conditional -- since that expression may contain unconditionally executed and
  3308. // conditionally executed code (in the case of "(GetVal(out a) && GetVal(out b))" for example
  3309. mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  3310. if (!condValue)
  3311. {
  3312. AssertErrorState();
  3313. condValue = BfTypedValue(GetDefaultValue(boolType), boolType);
  3314. }
  3315. BfIRBlock trueBB;
  3316. BfIRBlock falseBB;
  3317. bool isConstBranch = false;
  3318. bool constResult = false;
  3319. if (condValue.mValue.IsConst())
  3320. {
  3321. auto constant = mBfIRBuilder->GetConstant(condValue.mValue);
  3322. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_Boolean))
  3323. {
  3324. isConstBranch = true;
  3325. constResult = constant->mBool;
  3326. }
  3327. }
  3328. if (!isConstBranch)
  3329. {
  3330. trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  3331. falseBB = (ifStmt->mFalseStatement == NULL) ? BfIRBlock() : mBfIRBuilder->CreateBlock("if.else");
  3332. }
  3333. else
  3334. EmitEnsureInstructionAt();
  3335. auto contBB = mBfIRBuilder->CreateBlock("if.end");
  3336. if (!isConstBranch)
  3337. {
  3338. mBfIRBuilder->CreateCondBr(condValue.mValue, trueBB, (falseBB) ? falseBB : contBB);
  3339. }
  3340. // TRUE statement
  3341. bool ignoredLastBlock = true;
  3342. if (includeTrueStmt)
  3343. {
  3344. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites);
  3345. SetAndRestoreValue<bool> prevInConstIgnore(mCurMethodState->mCurScope->mInConstIgnore);
  3346. if (trueBB)
  3347. mBfIRBuilder->SetInsertPoint(trueBB);
  3348. if ((isConstBranch) && (constResult != true))
  3349. {
  3350. mBfIRBuilder->mIgnoreWrites = true;
  3351. mCurMethodState->mCurScope->mInConstIgnore = true;
  3352. }
  3353. else
  3354. ignoredLastBlock = false;
  3355. VisitEmbeddedStatement(ifStmt->mTrueStatement);
  3356. }
  3357. prevDLA.Restore();
  3358. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  3359. mCurMethodState->mDeferredLocalAssignData->mHadBreak |= deferredLocalAssignData.mHadBreak;
  3360. bool trueHadReturn = mCurMethodState->mHadReturn;
  3361. // We restore the scopeData before the False block because we don't want variables created in the if condition to
  3362. // be visible in the false section
  3363. //RestoreScopeState();
  3364. RestoreScoreState_LocalVariables(mCurMethodState->mCurScope->mLocalVarStart);
  3365. if ((!mCurMethodState->mLeftBlockUncond) && (!ignoredLastBlock))
  3366. mBfIRBuilder->CreateBr_NoCollapse(contBB);
  3367. if (mCurMethodState->mLeftBlockUncond)
  3368. {
  3369. deferredLocalAssignData.mLeftBlockUncond = true;
  3370. mCurMethodState->mLeftBlockCond = true;
  3371. }
  3372. mCurMethodState->mLeftBlockUncond = false;
  3373. mCurMethodState->SetHadReturn(false);
  3374. bool falseHadReturn = false;
  3375. if (ifStmt->mFalseStatement != NULL)
  3376. {
  3377. BfDeferredLocalAssignData falseDeferredLocalAssignData(&newScope);
  3378. falseDeferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  3379. if (falseBB)
  3380. {
  3381. mBfIRBuilder->AddBlock(falseBB);
  3382. mBfIRBuilder->SetInsertPoint(falseBB);
  3383. }
  3384. ignoredLastBlock = true;
  3385. //
  3386. {
  3387. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites);
  3388. SetAndRestoreValue<bool> prevInConstIgnore(mCurMethodState->mCurScope->mInConstIgnore);
  3389. if ((isConstBranch) && (constResult != false))
  3390. {
  3391. mBfIRBuilder->mIgnoreWrites = true;
  3392. mCurMethodState->mCurScope->mInConstIgnore = true;
  3393. }
  3394. else
  3395. ignoredLastBlock = false;
  3396. falseDeferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData);
  3397. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &falseDeferredLocalAssignData);
  3398. if (includeFalseStmt)
  3399. VisitEmbeddedStatement(ifStmt->mFalseStatement, NULL, (BfEmbeddedStatementFlags)(BfEmbeddedStatementFlags_IsConditional | BfEmbeddedStatementFlags_CheckStack));
  3400. }
  3401. if ((!mCurMethodState->mLeftBlockUncond) && (!ignoredLastBlock))
  3402. {
  3403. if (IsTargetingBeefBackend())
  3404. {
  3405. // If we don't do this, then with:
  3406. // if (a) { } else if (b) { }
  3407. // Then we hit the closing second brace even if 'b' is false
  3408. //SetIllegalSrcPos();
  3409. //BfIRBuilder->ClearDebugLocation();
  3410. }
  3411. auto br = mBfIRBuilder->CreateBr_NoCollapse(contBB);
  3412. //mBfIRBuilder->ClearDebugLocation(br);
  3413. }
  3414. falseHadReturn = mCurMethodState->mHadReturn;
  3415. if (mCurMethodState->mLeftBlockUncond)
  3416. {
  3417. falseDeferredLocalAssignData.mLeftBlockUncond = true;
  3418. mCurMethodState->mLeftBlockCond = true;
  3419. }
  3420. mCurMethodState->mLeftBlockUncond = false;
  3421. mCurMethodState->SetHadReturn(false);
  3422. deferredLocalAssignData.SetIntersection(falseDeferredLocalAssignData);
  3423. mCurMethodState->ApplyDeferredLocalAssignData(deferredLocalAssignData);
  3424. }
  3425. else
  3426. {
  3427. // If we had a const-ignored if statement with no else
  3428. if (ignoredLastBlock)
  3429. {
  3430. if (!mCurMethodState->mLeftBlockUncond)
  3431. mBfIRBuilder->CreateBr_NoCollapse(contBB);
  3432. }
  3433. }
  3434. mBfIRBuilder->AddBlock(contBB);
  3435. mBfIRBuilder->SetInsertPoint(contBB);
  3436. if (isConstBranch)
  3437. mCurMethodState->SetHadReturn(constResult ? trueHadReturn : falseHadReturn);
  3438. else
  3439. mCurMethodState->SetHadReturn(trueHadReturn && falseHadReturn);
  3440. mCurMethodState->mLeftBlockUncond = mCurMethodState->mHadReturn;
  3441. if (mCurMethodState->mHadReturn)
  3442. {
  3443. mBfIRBuilder->EraseFromParent(contBB);
  3444. }
  3445. else
  3446. {
  3447. mBfIRBuilder->SetInsertPoint(contBB);
  3448. }
  3449. RestoreScopeState();
  3450. }
  3451. void BfModule::Visit(BfIfStatement* ifStmt)
  3452. {
  3453. DoIfStatement(ifStmt, true, true);
  3454. }
  3455. void BfModule::Visit(BfVariableDeclaration* varDecl)
  3456. {
  3457. //BP_ZONE("BfModule::Visit(BfVariableDeclaration)");
  3458. UpdateSrcPos(varDecl);
  3459. BfTupleExpression* tupleVariableDeclaration = BfNodeDynCast<BfTupleExpression>(varDecl->mNameNode);
  3460. if (tupleVariableDeclaration != NULL)
  3461. {
  3462. HandleTupleVariableDeclaration(varDecl);
  3463. }
  3464. else
  3465. HandleVariableDeclaration(varDecl);
  3466. }
  3467. void BfModule::Visit(BfLocalMethodDeclaration* methodDecl)
  3468. {
  3469. Fail("Local method declarations must be wrapped in a block statement", methodDecl->mMethodDeclaration->mNameNode);
  3470. }
  3471. void BfModule::Visit(BfAttributedStatement* attribStmt)
  3472. {
  3473. BfAttributeState attributeState;
  3474. attributeState.mSrc = attribStmt->mAttributes;
  3475. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  3476. if (auto block = BfNodeDynCast<BfBlock>(attribStmt->mStatement))
  3477. attributeState.mTarget = BfAttributeTargets_Block;
  3478. attributeState.mCustomAttributes = GetCustomAttributes(attribStmt->mAttributes, attributeState.mTarget);
  3479. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  3480. if (auto ignoreErrorsAttrib = attributeState.mCustomAttributes->Get(mCompiler->mIgnoreErrorsAttributeTypeDef))
  3481. {
  3482. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  3483. if (!ignoreErrorsAttrib->mCtorArgs.IsEmpty())
  3484. {
  3485. auto constant = mCurTypeInstance->mConstHolder->GetConstant(ignoreErrorsAttrib->mCtorArgs[0]);
  3486. if (constant->mBool)
  3487. attributeState.mFlags = BfAttributeState::Flag_StopOnError;
  3488. }
  3489. VisitChild(attribStmt->mStatement);
  3490. attributeState.mUsed = true;
  3491. }
  3492. else if (attributeState.mCustomAttributes->Contains(mCompiler->mConstSkipAttributeTypeDef))
  3493. {
  3494. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope == NULL) || (!mCurMethodState->mCurScope->mInConstIgnore))
  3495. {
  3496. VisitChild(attribStmt->mStatement);
  3497. }
  3498. else
  3499. {
  3500. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  3501. }
  3502. attributeState.mUsed = true;
  3503. }
  3504. else
  3505. {
  3506. VisitChild(attribStmt->mStatement);
  3507. }
  3508. FinishAttributeState(&attributeState);
  3509. }
  3510. void BfModule::Visit(BfExpression* expression)
  3511. {
  3512. UpdateSrcPos(expression);
  3513. BfExprEvaluator exprEvaluator(this);
  3514. exprEvaluator.mUsedAsStatement = true;
  3515. exprEvaluator.Evaluate(expression);
  3516. }
  3517. void BfModule::Visit(BfExpressionStatement* expressionStmt)
  3518. {
  3519. expressionStmt->mExpression->Accept(this);
  3520. }
  3521. void BfModule::Visit(BfThrowStatement* throwStmt)
  3522. {
  3523. if (throwStmt->mExpression == NULL)
  3524. {
  3525. AssertErrorState();
  3526. return;
  3527. }
  3528. UpdateSrcPos(throwStmt->mThrowToken);
  3529. auto throwValue = CreateValueFromExpression(throwStmt->mExpression);
  3530. Fail("Exceptions are not supported", throwStmt->mThrowToken);
  3531. if (mCurMethodInstance->mReturnType->IsVoid())
  3532. EmitReturn(BfTypedValue());
  3533. else
  3534. EmitReturn(GetDefaultTypedValue(mCurMethodInstance->mReturnType));
  3535. }
  3536. void BfModule::Visit(BfDeleteStatement* deleteStmt)
  3537. {
  3538. UpdateSrcPos(deleteStmt);
  3539. auto autoComplete = mCompiler->GetAutoComplete();
  3540. if (autoComplete != NULL)
  3541. autoComplete->CheckIdentifier(deleteStmt->mDeleteToken, true);
  3542. bool isAppendDelete = false;
  3543. BfTypedValue customAllocator;
  3544. if (deleteStmt->mAllocExpr != NULL)
  3545. {
  3546. if (auto expr = BfNodeDynCast<BfExpression>(deleteStmt->mAllocExpr))
  3547. customAllocator = CreateValueFromExpression(expr);
  3548. else if (auto tokenNode = BfNodeDynCast<BfTokenNode>(deleteStmt->mAllocExpr))
  3549. {
  3550. if (tokenNode->mToken == BfToken_Append)
  3551. isAppendDelete = true;
  3552. }
  3553. }
  3554. BfAttributeState attributeState;
  3555. attributeState.mTarget = BfAttributeTargets_Delete;
  3556. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  3557. attributeState.mCustomAttributes = GetCustomAttributes(deleteStmt->mAttributes, attributeState.mTarget);
  3558. if (deleteStmt->mExpression == NULL)
  3559. {
  3560. AssertErrorState();
  3561. return;
  3562. }
  3563. auto val = CreateValueFromExpression(deleteStmt->mExpression);
  3564. if (!val)
  3565. return;
  3566. if (val.mType->IsAllocType())
  3567. val.mType = val.mType->GetUnderlyingType();
  3568. BfGenericParamType* genericType = NULL;
  3569. if (val.mType->IsGenericParam())
  3570. genericType = (BfGenericParamType*)val.mType;
  3571. if ((val.mType->IsPointer()) && (val.mType->GetUnderlyingType()->IsGenericParam()))
  3572. genericType = (BfGenericParamType*)val.mType->GetUnderlyingType();
  3573. auto checkType = val.mType;
  3574. if (genericType != NULL)
  3575. {
  3576. BfGenericParamFlags genericParamFlags = BfGenericParamFlag_None;
  3577. BfType* typeConstraint = NULL;
  3578. auto genericParam = GetMergedGenericParamData(genericType, genericParamFlags, typeConstraint);
  3579. if (typeConstraint != NULL)
  3580. checkType = typeConstraint;
  3581. bool canAlwaysDelete = checkType->IsDelegate() || checkType->IsFunction() || checkType->IsArray();
  3582. if (auto checkTypeInst = checkType->ToTypeInstance())
  3583. {
  3584. if ((checkTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) ||
  3585. (checkTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef)))
  3586. canAlwaysDelete = true;
  3587. }
  3588. if (!canAlwaysDelete)
  3589. {
  3590. if (genericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var))
  3591. return;
  3592. if (genericParamFlags & BfGenericParamFlag_StructPtr)
  3593. return;
  3594. if ((genericParamFlags & BfGenericParamFlag_Struct) && (checkType->IsPointer()))
  3595. return;
  3596. auto genericParamInst = GetGenericParamInstance(genericType);
  3597. Fail(StrFormat("Must add 'where %s : delete' constraint to generic parameter to delete generic type '%s'",
  3598. genericParamInst->GetGenericParamDef()->mName.c_str(), TypeToString(val.mType).c_str()), deleteStmt->mExpression);
  3599. return;
  3600. }
  3601. }
  3602. if (checkType->IsVar())
  3603. {
  3604. // Mixin or unconstrained generic
  3605. return;
  3606. }
  3607. if ((!checkType->IsPointer()) && (!checkType->IsObjectOrInterface()))
  3608. {
  3609. Fail(StrFormat("Cannot delete a value of type '%s'", TypeToString(val.mType).c_str()), deleteStmt->mExpression);
  3610. return;
  3611. }
  3612. if (val.mType->IsGenericParam())
  3613. return;
  3614. auto bodyBB = mBfIRBuilder->CreateBlock("delete.body");
  3615. auto endBB = mBfIRBuilder->CreateBlock("delete.end");
  3616. bool mayBeSentinel = false;
  3617. if (checkType->IsPointer())
  3618. {
  3619. auto innerType = checkType->GetUnderlyingType();
  3620. PopulateType(innerType);
  3621. if (innerType->IsValuelessType())
  3622. mayBeSentinel = true;
  3623. }
  3624. BfIRValue isNotNull;
  3625. if (mayBeSentinel)
  3626. {
  3627. auto intVal = mBfIRBuilder->CreatePtrToInt(val.mValue, BfTypeCode_IntPtr);
  3628. isNotNull = mBfIRBuilder->CreateCmpGT(intVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), false);
  3629. }
  3630. else
  3631. {
  3632. isNotNull = mBfIRBuilder->CreateIsNotNull(val.mValue);
  3633. }
  3634. mBfIRBuilder->CreateCondBr(isNotNull, bodyBB, endBB);
  3635. mBfIRBuilder->AddBlock(bodyBB);
  3636. mBfIRBuilder->SetInsertPoint(bodyBB);
  3637. if (val.mType->IsObjectOrInterface())
  3638. {
  3639. EmitObjectAccessCheck(val);
  3640. }
  3641. SizedArray<BfIRValue, 4> llvmArgs;
  3642. auto bitAddr = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  3643. llvmArgs.push_back(bitAddr);
  3644. if (val.mType->IsObjectOrInterface())
  3645. {
  3646. auto objectType = mContext->mBfObjectType;
  3647. BfTypeInstance* checkTypeInst = val.mType->ToTypeInstance();
  3648. bool allowPrivate = checkTypeInst == mCurTypeInstance;
  3649. bool allowProtected = allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst);
  3650. while (checkTypeInst != NULL)
  3651. {
  3652. auto dtorMethodDef = checkTypeInst->mTypeDef->GetMethodByName("~this");
  3653. if (dtorMethodDef)
  3654. {
  3655. if (!CheckProtection(dtorMethodDef->mProtection, checkTypeInst->mTypeDef, allowProtected, allowPrivate))
  3656. {
  3657. auto error = Fail(StrFormat("'%s.~this()' is inaccessible due to its protection level", TypeToString(checkTypeInst).c_str()), deleteStmt->mExpression); // CS0122
  3658. }
  3659. }
  3660. checkTypeInst = checkTypeInst->mBaseType;
  3661. allowPrivate = false;
  3662. }
  3663. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  3664. {
  3665. auto preDelete = GetInternalMethod((deleteStmt->mTargetTypeToken != NULL) ? "Dbg_ObjectPreCustomDelete" : "Dbg_ObjectPreDelete");
  3666. SizedArray<BfIRValue, 4> llvmArgs;
  3667. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  3668. mBfIRBuilder->CreateCall(preDelete.mFunc, llvmArgs);
  3669. }
  3670. // call dtor
  3671. BfExprEvaluator expressionEvaluator(this);
  3672. PopulateType(val.mType);
  3673. PopulateType(objectType, BfPopulateType_DataAndMethods);
  3674. if (objectType->mVirtualMethodTable.size() == 0)
  3675. {
  3676. if (!mCompiler->IsAutocomplete())
  3677. AssertErrorState();
  3678. }
  3679. else if (!IsSkippingExtraResolveChecks())
  3680. {
  3681. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  3682. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  3683. SizedArray<BfIRValue, 4> llvmArgs;
  3684. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  3685. expressionEvaluator.CreateCall(deleteStmt->mDeleteToken, methodInstance, mBfIRBuilder->GetFakeVal(), false, llvmArgs);
  3686. }
  3687. if ((deleteStmt->mTargetTypeToken != NULL) && (!isAppendDelete))
  3688. {
  3689. if (deleteStmt->mAllocExpr != NULL)
  3690. {
  3691. if (customAllocator)
  3692. {
  3693. auto customAllocTypeInst = customAllocator.mType->ToTypeInstance();
  3694. if (customAllocTypeInst != NULL)
  3695. {
  3696. if ((customAllocTypeInst != NULL) && (customAllocTypeInst->mTypeDef->GetMethodByName("FreeObject") != NULL))
  3697. {
  3698. BfTypedValueExpression typedValueExpr;
  3699. typedValueExpr.Init(val);
  3700. typedValueExpr.mRefNode = deleteStmt->mAllocExpr;
  3701. BfExprEvaluator exprEvaluator(this);
  3702. SizedArray<BfExpression*, 2> argExprs;
  3703. argExprs.push_back(&typedValueExpr);
  3704. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  3705. BfResolvedArgs argValues(&sizedArgExprs);
  3706. exprEvaluator.ResolveArgValues(argValues);
  3707. exprEvaluator.mNoBind = true;
  3708. exprEvaluator.MatchMethod(deleteStmt->mAllocExpr, NULL, customAllocator, false, true, "FreeObject", argValues, BfMethodGenericArguments());
  3709. customAllocator = BfTypedValue();
  3710. }
  3711. }
  3712. }
  3713. }
  3714. }
  3715. else
  3716. {
  3717. if ((mCompiler->mOptions.mEnableRealtimeLeakCheck) && (!mIsComptimeModule))
  3718. {
  3719. SizedArray<BfIRValue, 4> llvmArgs;
  3720. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  3721. auto moduleMethodInstance = GetInternalMethod("Dbg_MarkObjectDeleted");
  3722. mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  3723. }
  3724. else if (!isAppendDelete)
  3725. {
  3726. mBfIRBuilder->CreateCall(GetBuiltInFunc(BfBuiltInFuncType_Free), llvmArgs);
  3727. }
  3728. }
  3729. }
  3730. else
  3731. {
  3732. if ((isAppendDelete) || (customAllocator))
  3733. {
  3734. // Do nothing
  3735. }
  3736. else
  3737. {
  3738. auto func = GetBuiltInFunc(BfBuiltInFuncType_Free);
  3739. if (!func)
  3740. {
  3741. BF_ASSERT(mCompiler->mIsResolveOnly);
  3742. }
  3743. else
  3744. mBfIRBuilder->CreateCall(func, llvmArgs);
  3745. }
  3746. }
  3747. if (customAllocator.mType == GetPrimitiveType(BfTypeCode_NullPtr))
  3748. {
  3749. if (!checkType->IsObjectOrInterface())
  3750. Warn(0, "Type '%' has no destructor, so delete:null has no effect", deleteStmt->mExpression);
  3751. }
  3752. else if (customAllocator)
  3753. {
  3754. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3755. auto ptrValue = BfTypedValue(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(voidPtrType)), voidPtrType);
  3756. BfTypedValueExpression typedValueExpr;
  3757. typedValueExpr.Init(ptrValue);
  3758. BfExprEvaluator exprEvaluator(this);
  3759. SizedArray<BfExpression*, 2> argExprs;
  3760. argExprs.push_back(&typedValueExpr);
  3761. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  3762. BfResolvedArgs argValues(&sizedArgExprs);
  3763. exprEvaluator.ResolveArgValues(argValues);
  3764. exprEvaluator.mNoBind = true;
  3765. exprEvaluator.MatchMethod(deleteStmt->mAllocExpr, NULL, customAllocator, false, false, "Free", argValues, BfMethodGenericArguments());
  3766. }
  3767. mBfIRBuilder->CreateBr(endBB);
  3768. mBfIRBuilder->AddBlock(endBB);
  3769. mBfIRBuilder->SetInsertPoint(endBB);
  3770. }
  3771. void BfModule::Visit(BfSwitchStatement* switchStmt)
  3772. {
  3773. if (mModuleName == "BeefTest_TestProgram")
  3774. {
  3775. NOP;
  3776. }
  3777. BfScopeData outerScope;
  3778. outerScope.mInnerIsConditional = false;
  3779. outerScope.mCloseNode = switchStmt;
  3780. if (switchStmt->mCloseBrace != NULL)
  3781. outerScope.mCloseNode = switchStmt->mCloseBrace;
  3782. mCurMethodState->AddScope(&outerScope);
  3783. NewScopeState();
  3784. auto valueScopeStartOuter = ValueScopeStart();
  3785. BfTypedValue switchValue;
  3786. if (switchStmt->mSwitchValue == NULL)
  3787. {
  3788. AssertErrorState();
  3789. UpdateSrcPos(switchStmt->mSwitchToken);
  3790. }
  3791. else
  3792. {
  3793. UpdateExprSrcPos(switchStmt->mSwitchValue);
  3794. BfEvalExprFlags flags = BfEvalExprFlags_None;
  3795. flags = BfEvalExprFlags_AllowSplat;
  3796. switchValue = CreateValueFromExpression(switchStmt->mSwitchValue, NULL, flags);
  3797. }
  3798. EmitEnsureInstructionAt();
  3799. if (!switchValue)
  3800. {
  3801. AssertErrorState();
  3802. switchValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3803. }
  3804. if (switchValue.mType->IsPointer())
  3805. {
  3806. auto underlyingType = switchValue.mType->GetUnderlyingType();
  3807. if (underlyingType->IsEnum())
  3808. {
  3809. switchValue = LoadValue(switchValue);
  3810. switchValue = BfTypedValue(switchValue.mValue, underlyingType, true);
  3811. }
  3812. }
  3813. // We make the switch value conditional, but all other uses of this scope is conditional since it's conditional on cases
  3814. BfScopeData newScope;
  3815. newScope.mInnerIsConditional = true;
  3816. newScope.mCloseNode = switchStmt;
  3817. if (switchStmt->mCloseBrace != NULL)
  3818. newScope.mCloseNode = switchStmt->mCloseBrace;
  3819. if (switchStmt->mLabelNode != NULL)
  3820. newScope.mLabelNode = switchStmt->mLabelNode->mLabel;
  3821. mCurMethodState->AddScope(&newScope);
  3822. NewScopeState();
  3823. BfTypedValue switchValueAddr = switchValue;
  3824. BfLocalVariable* localDef = new BfLocalVariable();
  3825. localDef->mName = "_";
  3826. localDef->mResolvedType = switchValueAddr.mType;
  3827. localDef->mIsReadOnly = true;
  3828. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  3829. if (switchValue.IsAddr())
  3830. {
  3831. localDef->mAddr = switchValue.mValue;
  3832. }
  3833. else
  3834. {
  3835. localDef->mValue = switchValue.mValue;
  3836. localDef->mIsSplat = switchValue.IsSplat();
  3837. }
  3838. bool wantsDebugInfo = mHasFullDebugInfo && !mBfIRBuilder->mIgnoreWrites;
  3839. bool tryExtendValue = false;
  3840. bool addDebugInfo = true;
  3841. if ((wantsDebugInfo) && (!switchValue.mType->IsValuelessType()) && (!switchValue.mType->IsVar()))
  3842. {
  3843. if (IsTargetingBeefBackend())
  3844. {
  3845. // We don't need to make a copy
  3846. if (switchValue.IsSplat())
  3847. {
  3848. localDef->mIsSplat = true;
  3849. if (WantsDebugInfo())
  3850. {
  3851. bool found = false;
  3852. String varName = "_";
  3853. for (auto dbgVar : mCurMethodState->mLocals)
  3854. {
  3855. if (dbgVar->mAddr == switchValue.mValue)
  3856. {
  3857. varName += "$a$" + dbgVar->mName;
  3858. found = true;
  3859. break;
  3860. }
  3861. }
  3862. if (found)
  3863. {
  3864. auto fakeVal = CreateAlloca(GetPrimitiveType(BfTypeCode_Int32), true, "_fake");
  3865. addDebugInfo = false;
  3866. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope, varName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(localDef->mResolvedType), BfIRInitType_NotNeeded_AliveOnDecl);
  3867. mBfIRBuilder->DbgInsertDeclare(fakeVal, diVariable);
  3868. }
  3869. }
  3870. }
  3871. else
  3872. {
  3873. // if (!localDef->mAddr)
  3874. // {
  3875. // BfIRValue value = localDef->mValue;
  3876. // if (newLocalVar->mConstValue)
  3877. // value = localDef->mConstValue;
  3878. // auto aliasValue = mBfIRBuilder->CreateAliasValue(value);
  3879. // mBfIRBuilder->DbgInsertValueIntrinsic(aliasValue, diVariable);
  3880. // scopeData.mDeferredLifetimeEnds.push_back(aliasValue);
  3881. // }
  3882. tryExtendValue = true;
  3883. }
  3884. }
  3885. else if ((switchValue.mType->IsComposite()) && (switchValue.IsAddr()))
  3886. {
  3887. auto refType = CreateRefType(switchValue.mType);
  3888. auto allocaVal = CreateAlloca(refType);
  3889. mBfIRBuilder->CreateStore(switchValue.mValue, allocaVal);
  3890. auto diType = mBfIRBuilder->DbgGetType(refType);
  3891. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  3892. localDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  3893. mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  3894. addDebugInfo = false;
  3895. }
  3896. else
  3897. {
  3898. if (switchValueAddr.IsSplat())
  3899. {
  3900. auto addr = CreateAlloca(switchValue.mType);
  3901. if (switchValue.IsSplat())
  3902. AggregateSplatIntoAddr(switchValue, addr);
  3903. else
  3904. mBfIRBuilder->CreateStore(switchValue.mValue, addr);
  3905. localDef->mAddr = addr;
  3906. localDef->mValue = BfIRValue();
  3907. localDef->mIsSplat = false;
  3908. }
  3909. }
  3910. }
  3911. if (!localDef->mResolvedType->IsVar())
  3912. AddLocalVariableDef(localDef, addDebugInfo, true);
  3913. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  3914. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  3915. int numExpressions = 0;
  3916. SizedArray<BfIRBlock, 8> blocks;
  3917. SizedArray<BfWhenExpression*, 8> whenExprs;
  3918. SizedArray<BfIRBlock, 8> whenFailBlocks;
  3919. BfIRBlock defaultBlock;
  3920. auto endBlock = mBfIRBuilder->CreateBlock("switch.end");
  3921. for (BfSwitchCase* switchCase : switchStmt->mSwitchCases)
  3922. {
  3923. auto caseBlock = mBfIRBuilder->CreateBlock(StrFormat("switch.%d", blocks.size()));
  3924. blocks.push_back(caseBlock);
  3925. numExpressions += (int)switchCase->mCaseExpressions.size();
  3926. }
  3927. defaultBlock = mBfIRBuilder->CreateBlock("default");
  3928. bool hasDefaultCase = switchStmt->mDefaultCase != NULL;
  3929. if (hasDefaultCase)
  3930. blocks.push_back(defaultBlock);
  3931. SizedArray<BfDeferredLocalAssignData, 8> deferredLocalAssignDataVec;
  3932. deferredLocalAssignDataVec.resize(blocks.size());
  3933. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3934. BfTypedValue enumTagVal;
  3935. // Declare cases
  3936. int blockIdx = 0;
  3937. bool hadConstIntVals = false;
  3938. bool hadWhen = false;
  3939. BfIRValue switchStatement;
  3940. auto switchBlock = mBfIRBuilder->GetInsertBlock();
  3941. BfIRBlock noSwitchBlock = mBfIRBuilder->CreateBlock("noSwitch", true);
  3942. BfPrimitiveType* intCoercibleType = GetIntCoercibleType(switchValue.mType);
  3943. bool isConstSwitch = false;
  3944. if ((switchValue.mValue.IsConst()) || (switchValue.mType->IsValuelessType()))
  3945. {
  3946. isConstSwitch = true;
  3947. }
  3948. if (switchValue.mValue)
  3949. {
  3950. mBfIRBuilder->PopulateType(switchValue.mType);
  3951. if (intCoercibleType != NULL)
  3952. {
  3953. auto intValue = GetIntCoercible(switchValue);
  3954. switchStatement = mBfIRBuilder->CreateSwitch(intValue.mValue, noSwitchBlock, numExpressions);
  3955. }
  3956. else if (switchValue.mType->IsPayloadEnum())
  3957. {
  3958. enumTagVal = ExtractValue(switchValue, NULL, 2);
  3959. enumTagVal = LoadValue(enumTagVal);
  3960. switchStatement = mBfIRBuilder->CreateSwitch(enumTagVal.mValue, noSwitchBlock, numExpressions);
  3961. }
  3962. else if ((!isConstSwitch) && (!switchValue.mType->IsVar()))
  3963. switchStatement = mBfIRBuilder->CreateSwitch(switchValue.mValue, noSwitchBlock, numExpressions);
  3964. }
  3965. auto valueScopeStartInner = ValueScopeStart();
  3966. mBfIRBuilder->SetInsertPoint(noSwitchBlock);
  3967. bool isPayloadEnum = switchValue.mType->IsPayloadEnum();
  3968. bool isTuple = switchValue.mType->IsTuple();
  3969. bool isIntegralSwitch = switchValue.mType->IsIntegral() || (intCoercibleType != NULL) || ((switchValue.mType->IsEnum()) && (!isPayloadEnum));
  3970. auto _ShowCaseError = [&] (int64 id, BfAstNode* errNode)
  3971. {
  3972. if (isPayloadEnum)
  3973. {
  3974. auto enumType = switchValue.mType->ToTypeInstance();
  3975. for (auto fieldInstance : enumType->mFieldInstances)
  3976. {
  3977. auto fieldDef = fieldInstance.GetFieldDef();
  3978. if (fieldDef->IsEnumCaseEntry())
  3979. {
  3980. int enumIdx = -fieldInstance.mDataIdx - 1;
  3981. if (enumIdx == id)
  3982. {
  3983. Fail(StrFormat("The switch statement already contains a case for the the value '%s'", fieldDef->mName.c_str()), errNode);
  3984. return;
  3985. }
  3986. }
  3987. }
  3988. }
  3989. Fail(StrFormat("The switch statement already contains a case for the the value '%lld'", id), errNode);
  3990. };
  3991. int caseCount = 0;
  3992. bool allHadReturns = true;
  3993. bool hadCondCase = false;
  3994. BfIRBlock lastDefaultBlock;
  3995. struct _CaseState
  3996. {
  3997. BfIRBlock mCondBlock;
  3998. BfIRBlock mUncondBlock;
  3999. };
  4000. bool hadConstMatch = false;
  4001. auto startingLocalVarId = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  4002. bool prevHadFallthrough = false;
  4003. Dictionary<int64, _CaseState> handledCases;
  4004. HashSet<int64> condCases;
  4005. for (BfSwitchCase* switchCase : switchStmt->mSwitchCases)
  4006. {
  4007. deferredLocalAssignDataVec[blockIdx].mScopeData = mCurMethodState->mCurScope;
  4008. deferredLocalAssignDataVec[blockIdx].ExtendFrom(mCurMethodState->mDeferredLocalAssignData);
  4009. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignDataVec[blockIdx]);
  4010. mCurMethodState->mDeferredLocalAssignData->mVarIdBarrier = startingLocalVarId;
  4011. SetIllegalSrcPos();
  4012. auto caseBlock = blocks[blockIdx];
  4013. BfScopeData caseScopeData;
  4014. bool openedScope = false;
  4015. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  4016. {
  4017. // This does the enum autocomplete popup
  4018. BfAstNode* checkNode = NULL;
  4019. int caseExprIdx = (int)switchCase->mCaseExpressions.size();
  4020. if (caseExprIdx == 0)
  4021. checkNode = switchCase->mCaseToken;
  4022. else if (caseExprIdx - 1 < (int)switchCase->mCaseCommas.size())
  4023. checkNode = switchCase->mCaseCommas[caseExprIdx - 1];
  4024. if (checkNode != NULL)
  4025. mCompiler->mResolvePassData->mAutoComplete->CheckEmptyStart(checkNode, switchValue.mType);
  4026. }
  4027. bool mayHaveMatch = false;
  4028. BfWhenExpression* whenExpr = NULL;
  4029. for (BfExpression* caseExpr : switchCase->mCaseExpressions)
  4030. {
  4031. if (auto checkWhenExpr = BfNodeDynCast<BfWhenExpression>(caseExpr))
  4032. {
  4033. hadWhen = true;
  4034. whenExpr = checkWhenExpr;
  4035. }
  4036. }
  4037. bool wantsOpenedScope = isPayloadEnum || isTuple;
  4038. BfIRBlock lastNotEqBlock;
  4039. for (BfExpression* caseExpr : switchCase->mCaseExpressions)
  4040. {
  4041. BfConstant* constantInt = NULL;
  4042. if (auto checkWhenExpr = BfNodeDynCast<BfWhenExpression>(caseExpr))
  4043. continue;
  4044. if ((!openedScope) && (wantsOpenedScope))
  4045. {
  4046. openedScope = true;
  4047. caseScopeData.mOuterIsConditional = true;
  4048. caseScopeData.mIsSharedTempBlock = true;
  4049. mCurMethodState->AddScope(&caseScopeData);
  4050. NewScopeState();
  4051. UpdateSrcPos(caseExpr);
  4052. SetIllegalSrcPos();
  4053. }
  4054. BfIRValue eqResult;
  4055. BfIRBlock notEqBB;
  4056. bool handled = false;
  4057. BfTypedValue caseValue;
  4058. BfIRBlock doBlock = caseBlock;
  4059. bool hadConditional = false;
  4060. bool isEnumDescValue = isPayloadEnum;
  4061. if (isPayloadEnum)
  4062. {
  4063. auto dscrType = switchValue.mType->ToTypeInstance()->GetDiscriminatorType();
  4064. if (!enumTagVal)
  4065. {
  4066. enumTagVal = ExtractValue(switchValue, NULL, 2);
  4067. enumTagVal = LoadValue(enumTagVal);
  4068. }
  4069. notEqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.notEq.%d", blockIdx), false);
  4070. int tagId = -1;
  4071. BfIRBlock matchBlock;
  4072. BfTypedValue eqTypedResult;
  4073. if (auto bindExpr = BfNodeDynCast<BfEnumCaseBindExpression>(caseExpr))
  4074. {
  4075. eqTypedResult = HandleCaseBind(switchValueAddr, enumTagVal, bindExpr, &caseBlock, &notEqBB, &matchBlock, &tagId);
  4076. }
  4077. else
  4078. {
  4079. eqTypedResult = TryCaseEnumMatch(switchValueAddr, enumTagVal, caseExpr, &caseBlock, &notEqBB, &matchBlock, tagId, hadConditional, false, prevHadFallthrough);
  4080. if (hadConditional)
  4081. hadCondCase = true;
  4082. }
  4083. if (tagId != -1)
  4084. {
  4085. doBlock = matchBlock; // Jump to binds rather than just the code
  4086. caseValue = BfTypedValue(GetConstValue(tagId, GetPrimitiveType(dscrType->mTypeDef->mTypeCode)), dscrType);
  4087. }
  4088. else
  4089. hadCondCase = true;
  4090. if (eqTypedResult)
  4091. {
  4092. handled = true;
  4093. eqResult = eqTypedResult.mValue;
  4094. }
  4095. }
  4096. else if (auto tupleExpr = BfNodeDynCast<BfTupleExpression>(caseExpr))
  4097. {
  4098. notEqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.notEq.%d", blockIdx), false);
  4099. BfIRBlock matchBlock;
  4100. BfTypedValue eqTypedResult = TryCaseTupleMatch(switchValue, tupleExpr, &caseBlock, &notEqBB, &matchBlock, hadConditional, false, prevHadFallthrough);
  4101. if (hadConditional)
  4102. hadCondCase = true;
  4103. if (eqTypedResult)
  4104. {
  4105. mayHaveMatch = true;
  4106. handled = true;
  4107. eqResult = eqTypedResult.mValue;
  4108. }
  4109. }
  4110. if (!eqResult)
  4111. {
  4112. caseValue = CreateValueFromExpression(caseExpr, switchValue.mType, (BfEvalExprFlags)(BfEvalExprFlags_AllowEnumId | BfEvalExprFlags_NoCast));
  4113. if (!caseValue)
  4114. continue;
  4115. isEnumDescValue = false;
  4116. }
  4117. BfTypedValue caseIntVal = caseValue;
  4118. if ((isIntegralSwitch) || (isPayloadEnum))
  4119. {
  4120. if ((intCoercibleType != NULL) &&
  4121. (caseValue.mType == switchValue.mType) &&
  4122. (caseValue.mValue.IsConst()))
  4123. {
  4124. caseIntVal = GetIntCoercible(caseValue);
  4125. constantInt = mBfIRBuilder->GetConstant(caseIntVal.mValue);
  4126. }
  4127. else
  4128. {
  4129. // For a non-const case, allow for conversion operators, otherwise cast now
  4130. if ((isIntegralSwitch) && (caseValue.mValue.IsConst()))
  4131. {
  4132. if (caseValue.mType != switchValue.mType)
  4133. {
  4134. caseValue = Cast(caseExpr, caseValue, switchValue.mType);
  4135. if (!caseValue)
  4136. continue;
  4137. caseIntVal = caseValue;
  4138. }
  4139. }
  4140. if ((caseValue.mType == switchValue.mType) || (eqResult))
  4141. {
  4142. constantInt = mBfIRBuilder->GetConstant(caseValue.mValue);
  4143. if ((constantInt != NULL) && (!mBfIRBuilder->IsInt(constantInt->mTypeCode)))
  4144. constantInt = NULL;
  4145. }
  4146. }
  4147. }
  4148. if ((!switchStatement) && (!isConstSwitch))
  4149. {
  4150. // Do nothing
  4151. mayHaveMatch = true;
  4152. }
  4153. else if ((constantInt != NULL) && (!hadWhen) && (!isConstSwitch))
  4154. {
  4155. if (hadConditional)
  4156. {
  4157. condCases.Add(constantInt->mInt64);
  4158. }
  4159. else
  4160. {
  4161. _CaseState* caseState = NULL;
  4162. handledCases.TryAdd(constantInt->mInt64, NULL, &caseState);
  4163. if (condCases.Contains(constantInt->mInt64))
  4164. {
  4165. // This is a 'case .A:' after a 'case .A(let value):'
  4166. eqResult = mBfIRBuilder->CreateCmpEQ(enumTagVal.mValue, caseValue.mValue);
  4167. notEqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.notEq.%d", blockIdx));
  4168. mayHaveMatch = true;
  4169. mBfIRBuilder->CreateCondBr(eqResult, caseBlock, notEqBB);
  4170. mBfIRBuilder->AddBlock(notEqBB);
  4171. mBfIRBuilder->SetInsertPoint(notEqBB);
  4172. }
  4173. else
  4174. {
  4175. if (caseState->mUncondBlock)
  4176. {
  4177. _ShowCaseError(constantInt->mInt64, caseExpr);
  4178. }
  4179. else
  4180. {
  4181. caseState->mUncondBlock = doBlock;
  4182. mBfIRBuilder->AddSwitchCase(switchStatement, caseIntVal.mValue, doBlock);
  4183. hadConstIntVals = true;
  4184. }
  4185. }
  4186. }
  4187. mayHaveMatch = true;
  4188. }
  4189. else if (!handled)
  4190. {
  4191. hadCondCase = true;
  4192. if (!eqResult)
  4193. {
  4194. BfExprEvaluator exprEvaluator(this);
  4195. BfAstNode* refNode = switchCase->mColonToken;
  4196. if ((caseValue.mType->IsPayloadEnum()) && (caseValue.mValue.IsConst()) && (switchValue.mType == caseValue.mType) && (isEnumDescValue))
  4197. {
  4198. if (!enumTagVal)
  4199. {
  4200. enumTagVal = ExtractValue(switchValue, NULL, 2);
  4201. enumTagVal = LoadValue(enumTagVal);
  4202. }
  4203. eqResult = mBfIRBuilder->CreateCmpEQ(enumTagVal.mValue, caseValue.mValue);
  4204. }
  4205. else
  4206. {
  4207. exprEvaluator.PerformBinaryOperation(switchStmt->mSwitchValue, caseExpr, BfBinaryOp_Equality, refNode, (BfBinOpFlags)(BfBinOpFlag_ForceLeftType), switchValue, caseValue);
  4208. if (switchStmt->mSwitchValue != NULL)
  4209. UpdateSrcPos(switchStmt->mSwitchValue);
  4210. SetIllegalSrcPos();
  4211. eqResult = exprEvaluator.mResult.mValue;
  4212. if (!eqResult)
  4213. eqResult = GetConstValue(0, boolType);
  4214. }
  4215. }
  4216. ValueScopeEnd(valueScopeStartInner);
  4217. bool isConstResult = false;
  4218. bool constResult = false;
  4219. if (eqResult.IsConst())
  4220. {
  4221. auto constant = mBfIRBuilder->GetConstant(eqResult);
  4222. if (constant->mTypeCode == BfTypeCode_Boolean)
  4223. {
  4224. isConstResult = true;
  4225. constResult = constant->mBool;
  4226. }
  4227. }
  4228. if (isConstResult)
  4229. {
  4230. if (constResult)
  4231. {
  4232. mBfIRBuilder->CreateBr(caseBlock);
  4233. mayHaveMatch = true;
  4234. if (whenExpr == NULL)
  4235. {
  4236. hadConstMatch = true;
  4237. }
  4238. else
  4239. {
  4240. notEqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.notEq.%d", blockIdx));
  4241. mBfIRBuilder->AddBlock(notEqBB);
  4242. mBfIRBuilder->SetInsertPoint(notEqBB);
  4243. }
  4244. }
  4245. }
  4246. else
  4247. {
  4248. notEqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.notEq.%d", blockIdx));
  4249. mayHaveMatch = true;
  4250. mBfIRBuilder->CreateCondBr(eqResult, caseBlock, notEqBB);
  4251. mBfIRBuilder->AddBlock(notEqBB);
  4252. mBfIRBuilder->SetInsertPoint(notEqBB);
  4253. }
  4254. }
  4255. if (notEqBB)
  4256. lastNotEqBlock = notEqBB;
  4257. if ((!hadCondCase) && (notEqBB))
  4258. lastDefaultBlock = notEqBB;
  4259. }
  4260. if ((whenExpr != NULL) && (switchCase->mCaseExpressions.size() == 1))
  4261. {
  4262. // This was a "case when" expression, always matches
  4263. mayHaveMatch = true;
  4264. auto notEqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.notEq_when.%d", blockIdx));
  4265. mBfIRBuilder->CreateBr(caseBlock);
  4266. mBfIRBuilder->AddBlock(notEqBB);
  4267. mBfIRBuilder->SetInsertPoint(notEqBB);
  4268. lastNotEqBlock = notEqBB;
  4269. }
  4270. if ((lastDefaultBlock) && (switchStatement))
  4271. mBfIRBuilder->SetSwitchDefaultDest(switchStatement, lastDefaultBlock);
  4272. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  4273. bool isConstIgnore = !mayHaveMatch && !prevHadFallthrough;
  4274. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true, isConstIgnore);
  4275. SetAndRestoreValue<bool> prevInConstIgnore(mCurMethodState->mCurScope->mInConstIgnore, true, isConstIgnore);
  4276. mBfIRBuilder->AddBlock(caseBlock);
  4277. mBfIRBuilder->SetInsertPoint(caseBlock);
  4278. if (whenExpr != NULL)
  4279. {
  4280. UpdateSrcPos(whenExpr);
  4281. BfTypedValue whenValue;
  4282. if (whenExpr->mExpression != NULL)
  4283. whenValue = CreateValueFromExpression(whenExpr->mExpression, boolType, BfEvalExprFlags_AllowEnumId);
  4284. if (!whenValue)
  4285. {
  4286. AssertErrorState();
  4287. whenValue = GetDefaultTypedValue(boolType);
  4288. }
  4289. bool constResult = false;
  4290. if (mBfIRBuilder->TryGetBool(whenValue.mValue, constResult))
  4291. {
  4292. if (!constResult)
  4293. prevIgnoreWrites.Set();
  4294. }
  4295. else
  4296. {
  4297. BfIRBlock eqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.when.%d", blockIdx));
  4298. mBfIRBuilder->CreateCondBr(whenValue.mValue, eqBB, lastNotEqBlock);
  4299. mBfIRBuilder->AddBlock(eqBB);
  4300. mBfIRBuilder->SetInsertPoint(eqBB);
  4301. }
  4302. }
  4303. BfIRBlock fallthroughBlock;
  4304. if (blockIdx < (int) blocks.size() - 1)
  4305. fallthroughBlock = blocks[blockIdx + 1];
  4306. else
  4307. fallthroughBlock = defaultBlock;
  4308. bool hadReturn = false;
  4309. if ((switchCase->mCodeBlock != NULL) && (!switchCase->mCodeBlock->mChildArr.IsEmpty()))
  4310. {
  4311. UpdateSrcPos(switchCase->mCodeBlock);
  4312. VisitCodeBlock(switchCase->mCodeBlock, BfIRBlock(), endBlock, fallthroughBlock, true, &hadReturn, switchStmt->mLabelNode, openedScope /*, BfEmbeddedStatementFlags_RescopeDLA*/);
  4313. openedScope = false;
  4314. deferredLocalAssignDataVec[blockIdx].mHadReturn = hadReturn;
  4315. caseCount++;
  4316. if ((!hadReturn) &&
  4317. ((!mCurMethodState->mDeferredLocalAssignData->mHadFallthrough) || (mCurMethodState->mDeferredLocalAssignData->mHadBreak)))
  4318. allHadReturns = false;
  4319. if (auto block = BfNodeDynCast<BfBlock>(switchCase->mCodeBlock))
  4320. {
  4321. //
  4322. }
  4323. else
  4324. {
  4325. if (switchStmt->mCloseBrace != NULL)
  4326. {
  4327. UpdateSrcPos(switchStmt->mCloseBrace);
  4328. }
  4329. EmitEnsureInstructionAt();
  4330. }
  4331. //UpdateSrcPos(switchCase->mCodeBlock);
  4332. //SetIllegalSrcPos();
  4333. mBfIRBuilder->ClearDebugLocation();
  4334. }
  4335. else
  4336. {
  4337. if (openedScope)
  4338. RestoreScopeState();
  4339. mBfIRBuilder->CreateBr(endBlock);
  4340. allHadReturns = false;
  4341. }
  4342. prevIgnoreWrites.Restore();
  4343. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  4344. prevHadFallthrough = mCurMethodState->mDeferredLocalAssignData->mHadFallthrough;
  4345. blockIdx++;
  4346. }
  4347. // Check for comprehensiveness
  4348. bool isComprehensive = true;
  4349. if ((switchValue) && (switchStmt->mDefaultCase == NULL))
  4350. {
  4351. if (switchValue.mType->IsEnum())
  4352. {
  4353. if (hadConstMatch)
  4354. {
  4355. // Already handled
  4356. }
  4357. else
  4358. {
  4359. auto enumType = switchValue.mType->ToTypeInstance();
  4360. if (enumType->IsPayloadEnum())
  4361. {
  4362. int lastTagId = -1;
  4363. for (auto& field : enumType->mFieldInstances)
  4364. {
  4365. auto fieldDef = field.GetFieldDef();
  4366. if (fieldDef == NULL)
  4367. continue;
  4368. if (!fieldDef->IsEnumCaseEntry())
  4369. continue;
  4370. if (field.mDataIdx < 0)
  4371. lastTagId = -field.mDataIdx - 1;
  4372. }
  4373. isComprehensive = lastTagId == (int)handledCases.size() - 1;
  4374. }
  4375. else
  4376. {
  4377. for (auto& field : enumType->mFieldInstances)
  4378. {
  4379. auto fieldDef = field.GetFieldDef();
  4380. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4381. {
  4382. if (field.mConstIdx != -1)
  4383. {
  4384. auto constant = enumType->mConstHolder->GetConstantById(field.mConstIdx);
  4385. isComprehensive &= handledCases.ContainsKey(constant->mInt64);
  4386. }
  4387. }
  4388. }
  4389. }
  4390. }
  4391. if (!isComprehensive)
  4392. {
  4393. BfAstNode* refNode = switchStmt->mSwitchToken;
  4394. Fail("Switch must be exhaustive, consider adding a default clause", switchStmt->mSwitchToken);
  4395. if ((switchStmt->mCloseBrace) && (mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  4396. {
  4397. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  4398. if (parser != NULL)
  4399. {
  4400. int fileLoc = switchStmt->mCloseBrace->GetSrcStart();
  4401. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("default:\tdefault:|%s|%d||default:", parser->mFileName.c_str(), fileLoc).c_str()));
  4402. }
  4403. }
  4404. }
  4405. }
  4406. else
  4407. isComprehensive = false;
  4408. }
  4409. if (!hadConstMatch)
  4410. mBfIRBuilder->CreateBr(defaultBlock);
  4411. mBfIRBuilder->SetInsertPoint(switchBlock);
  4412. if (!hadConstIntVals)
  4413. {
  4414. if (switchStatement)
  4415. mBfIRBuilder->EraseInstFromParent(switchStatement);
  4416. mBfIRBuilder->CreateBr(noSwitchBlock);
  4417. }
  4418. if (switchStmt->mDefaultCase != NULL)
  4419. {
  4420. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true, hadConstMatch);
  4421. SetAndRestoreValue<bool> prevInConstIgnore(mCurMethodState->mCurScope->mInConstIgnore, true, hadConstMatch);
  4422. mBfIRBuilder->AddBlock(defaultBlock);
  4423. mBfIRBuilder->SetInsertPoint(defaultBlock);
  4424. auto switchCase = switchStmt->mDefaultCase;
  4425. if (switchCase->mCodeBlock != NULL)
  4426. {
  4427. isComprehensive = true;
  4428. UpdateSrcPos(switchCase->mCodeBlock);
  4429. deferredLocalAssignDataVec[blockIdx].mScopeData = mCurMethodState->mCurScope;
  4430. deferredLocalAssignDataVec[blockIdx].ExtendFrom(mCurMethodState->mDeferredLocalAssignData);
  4431. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignDataVec[blockIdx]);
  4432. mCurMethodState->mDeferredLocalAssignData->mVarIdBarrier = startingLocalVarId;
  4433. BfScopeData caseScopeData;
  4434. caseScopeData.mOuterIsConditional = true;
  4435. caseScopeData.mIsSharedTempBlock = true;
  4436. mCurMethodState->AddScope(&caseScopeData);
  4437. NewScopeState();
  4438. bool hadReturn = false;
  4439. VisitCodeBlock(switchCase->mCodeBlock, BfIRBlock(), endBlock, BfIRBlock(), true, &hadReturn, switchStmt->mLabelNode);
  4440. deferredLocalAssignDataVec[blockIdx].mHadReturn = hadReturn;
  4441. caseCount++;
  4442. if (!hadReturn)
  4443. allHadReturns = false;
  4444. RestoreScopeState();
  4445. }
  4446. }
  4447. else
  4448. {
  4449. mBfIRBuilder->AddBlock(defaultBlock);
  4450. mBfIRBuilder->SetInsertPoint(defaultBlock);
  4451. if (isComprehensive)
  4452. {
  4453. mBfIRBuilder->CreateUnreachable();
  4454. //TODO: This masks a bug in our backend
  4455. if (IsTargetingBeefBackend())
  4456. mBfIRBuilder->CreateBr(endBlock);
  4457. }
  4458. else
  4459. mBfIRBuilder->CreateBr(endBlock);
  4460. }
  4461. if (isComprehensive)
  4462. {
  4463. // Merge and apply deferred local assign data
  4464. // We only do this if there's a default case, otherwise we assume we may have missed a case
  4465. // that by definition had no local assigns
  4466. BfDeferredLocalAssignData* mergedDeferredLocalAssignData = NULL;
  4467. for (blockIdx = 0; blockIdx < (int)blocks.size(); blockIdx++)
  4468. {
  4469. auto deferredLocalAssignData = &deferredLocalAssignDataVec[blockIdx];
  4470. if (deferredLocalAssignData->mHadFallthrough)
  4471. continue;
  4472. if (mergedDeferredLocalAssignData == NULL)
  4473. mergedDeferredLocalAssignData = deferredLocalAssignData;
  4474. else
  4475. mergedDeferredLocalAssignData->SetIntersection(*deferredLocalAssignData);
  4476. }
  4477. if (mergedDeferredLocalAssignData != NULL)
  4478. mCurMethodState->ApplyDeferredLocalAssignData(*mergedDeferredLocalAssignData);
  4479. }
  4480. if ((caseCount > 0) && (allHadReturns) &&
  4481. ((hasDefaultCase) || (isComprehensive)))
  4482. {
  4483. mCurMethodState->SetHadReturn(true);
  4484. mCurMethodState->mLeftBlockUncond = true;
  4485. if ((!hasDefaultCase) && (!isComprehensive))
  4486. mBfIRBuilder->DeleteBlock(endBlock);
  4487. else
  4488. {
  4489. if (switchStmt->mCloseBrace != NULL)
  4490. UpdateSrcPos(switchStmt->mCloseBrace);
  4491. mBfIRBuilder->AddBlock(endBlock);
  4492. mBfIRBuilder->SetInsertPoint(endBlock);
  4493. mBfIRBuilder->CreateUnreachable();
  4494. }
  4495. }
  4496. else
  4497. {
  4498. if (switchStmt->mCloseBrace != NULL)
  4499. UpdateSrcPos(switchStmt->mCloseBrace);
  4500. mBfIRBuilder->AddBlock(endBlock);
  4501. mBfIRBuilder->SetInsertPoint(endBlock);
  4502. }
  4503. BfIRValue lifetimeExtendVal;
  4504. if (tryExtendValue)
  4505. {
  4506. if (localDef->mAddr)
  4507. lifetimeExtendVal = localDef->mAddr;
  4508. else
  4509. lifetimeExtendVal = localDef->mValue;
  4510. }
  4511. RestoreScopeState(); // newScope
  4512. RestoreScopeState(); // outerScope
  4513. if (lifetimeExtendVal)
  4514. mBfIRBuilder->CreateLifetimeExtend(lifetimeExtendVal);
  4515. ValueScopeEnd(valueScopeStartOuter);
  4516. }
  4517. static int gRetIdx = 0;
  4518. void BfModule::Visit(BfReturnStatement* returnStmt)
  4519. {
  4520. if ((mCurMethodInstance == NULL) || (mCurMethodState->mDisableReturns))
  4521. {
  4522. Fail("Unexpected return", returnStmt);
  4523. if (returnStmt->mExpression != NULL)
  4524. {
  4525. BfExprEvaluator exprEvaluator(this);
  4526. CreateValueFromExpression(exprEvaluator, returnStmt->mExpression);
  4527. }
  4528. return;
  4529. }
  4530. UpdateSrcPos(returnStmt);
  4531. EmitEnsureInstructionAt();
  4532. auto retType = mCurMethodInstance->mReturnType;
  4533. if (mCurMethodInstance->IsMixin())
  4534. retType = NULL;
  4535. bool inferReturnType = false;
  4536. if (mCurMethodState->mClosureState != NULL)
  4537. {
  4538. retType = mCurMethodState->mClosureState->mReturnType;
  4539. inferReturnType = (mCurMethodState->mClosureState->mReturnTypeInferState != BfReturnTypeInferState_None);
  4540. }
  4541. auto checkScope = mCurMethodState->mCurScope;
  4542. while (checkScope != NULL)
  4543. {
  4544. if (checkScope->mIsDeferredBlock)
  4545. {
  4546. Fail("Deferred blocks cannot contain 'return' statements", returnStmt);
  4547. if (returnStmt->mExpression != NULL)
  4548. {
  4549. BfExprEvaluator exprEvaluator(this);
  4550. CreateValueFromExpression(exprEvaluator, returnStmt->mExpression, GetPrimitiveType(BfTypeCode_Var), BfEvalExprFlags_None);
  4551. }
  4552. return;
  4553. }
  4554. if (checkScope->mInInitBlock)
  4555. {
  4556. Fail("Initialization blocks cannot contain 'return' statements", returnStmt);
  4557. }
  4558. checkScope = checkScope->mPrevScope;
  4559. }
  4560. auto checkLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  4561. while (checkLocalAssignData != NULL)
  4562. {
  4563. if (checkLocalAssignData->mScopeData != NULL)
  4564. checkLocalAssignData->mLeftBlock = true;
  4565. checkLocalAssignData = checkLocalAssignData->mChainedAssignData;
  4566. }
  4567. if ((retType == NULL) && (!inferReturnType))
  4568. {
  4569. if (returnStmt->mExpression != NULL)
  4570. {
  4571. BfExprEvaluator exprEvaluator(this);
  4572. CreateValueFromExpression(exprEvaluator, returnStmt->mExpression, GetPrimitiveType(BfTypeCode_Var), BfEvalExprFlags_None);
  4573. }
  4574. MarkScopeLeft(&mCurMethodState->mHeadScope);
  4575. return;
  4576. }
  4577. if (returnStmt->mExpression == NULL)
  4578. {
  4579. MarkScopeLeft(&mCurMethodState->mHeadScope);
  4580. if ((retType != NULL) && (retType->IsVoid()))
  4581. {
  4582. EmitReturn(BfTypedValue());
  4583. return;
  4584. }
  4585. Fail("Expected return value", returnStmt);
  4586. if (retType != NULL)
  4587. EmitReturn(GetDefaultTypedValue(retType));
  4588. else
  4589. EmitReturn(BfTypedValue());
  4590. return;
  4591. }
  4592. BfType* expectingReturnType = retType;
  4593. BfType* origType;
  4594. BfExprEvaluator exprEvaluator(this);
  4595. bool alreadyWritten = false;
  4596. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  4597. exprEvaluator.mReceivingValue = &mCurMethodState->mRetVal;
  4598. if (mCurMethodInstance->mMethodDef->mIsReadOnly)
  4599. exprEvaluator.mAllowReadOnlyReference = true;
  4600. if (inferReturnType)
  4601. expectingReturnType = NULL;
  4602. auto retValue = CreateValueFromExpression(exprEvaluator, returnStmt->mExpression, expectingReturnType, BfEvalExprFlags_AllowRefExpr, &origType);
  4603. if ((retValue) && (inferReturnType))
  4604. {
  4605. if (mCurMethodState->mClosureState->mReturnType == NULL)
  4606. mCurMethodState->mClosureState->mReturnType = retValue.mType;
  4607. else
  4608. {
  4609. if ((retValue.mType == mCurMethodState->mClosureState->mReturnType) ||
  4610. (CanCast(retValue, mCurMethodState->mClosureState->mReturnType)))
  4611. {
  4612. // Leave as-is
  4613. }
  4614. else if (CanCast(GetFakeTypedValue(mCurMethodState->mClosureState->mReturnType), retValue.mType))
  4615. {
  4616. mCurMethodState->mClosureState->mReturnType = retValue.mType;
  4617. }
  4618. else
  4619. {
  4620. mCurMethodState->mClosureState->mReturnTypeInferState = BfReturnTypeInferState_Fail;
  4621. }
  4622. }
  4623. }
  4624. if ((retType == NULL) && (inferReturnType))
  4625. retType = mCurMethodState->mClosureState->mReturnType;
  4626. if (retType == NULL)
  4627. retType = GetPrimitiveType(BfTypeCode_None);
  4628. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  4629. alreadyWritten = exprEvaluator.mReceivingValue == NULL;
  4630. MarkScopeLeft(&mCurMethodState->mHeadScope);
  4631. if (!retValue)
  4632. {
  4633. AssertErrorState();
  4634. if ((expectingReturnType != NULL) && (!expectingReturnType->IsVoid()))
  4635. {
  4636. retValue = GetDefaultTypedValue(expectingReturnType, true);
  4637. }
  4638. else
  4639. {
  4640. EmitReturn(BfTypedValue());
  4641. return;
  4642. }
  4643. }
  4644. if (retValue.mType->IsVar())
  4645. {
  4646. EmitReturn(BfTypedValue());
  4647. }
  4648. else if (retValue.mType->IsVoid())
  4649. {
  4650. if (retType->IsVoid())
  4651. {
  4652. Warn(0, "Returning void value", returnStmt->mReturnToken);
  4653. EmitReturn(BfTypedValue());
  4654. }
  4655. }
  4656. else
  4657. {
  4658. if (retType->IsVoid())
  4659. {
  4660. expectingReturnType = NULL;
  4661. Fail("Attempting to return value from void method", returnStmt->mExpression);
  4662. EmitReturn(BfTypedValue());
  4663. return;
  4664. }
  4665. if ((origType != NULL) && (origType->IsStructOrStructPtr()) && (retValue.mType->IsObjectOrInterface()))
  4666. {
  4667. Fail(StrFormat("Stack boxing of type '%s' is not allowed on return statements. Use 'new box' to box on the heap.", TypeToString(origType).c_str()), returnStmt->mExpression);
  4668. }
  4669. if (!alreadyWritten)
  4670. EmitReturn(LoadOrAggregateValue(retValue));
  4671. else
  4672. EmitReturn(BfTypedValue());
  4673. }
  4674. }
  4675. void BfModule::Visit(BfYieldStatement* yieldStmt)
  4676. {
  4677. Fail("Yield not supported", yieldStmt);
  4678. }
  4679. void BfModule::Visit(BfBreakStatement* breakStmt)
  4680. {
  4681. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  4682. UpdateSrcPos(breakStmt);
  4683. EmitEnsureInstructionAt();
  4684. BfBreakData* breakData = mCurMethodState->mBreakData;
  4685. if (breakStmt->mLabel != NULL)
  4686. {
  4687. breakData = FindBreakData(breakStmt->mLabel);
  4688. }
  4689. else
  4690. {
  4691. while (breakData != NULL)
  4692. {
  4693. if (breakData->mIRBreakBlock)
  4694. break;
  4695. breakData = breakData->mPrevBreakData;
  4696. }
  4697. }
  4698. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  4699. {
  4700. BfScopeData* scope = NULL;
  4701. if (breakData != NULL)
  4702. scope = breakData->mScope;
  4703. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(breakStmt->mLabel))
  4704. mCompiler->mResolvePassData->mAutoComplete->CheckLabel(identifer, breakStmt->mBreakNode, scope);
  4705. }
  4706. if ((breakData == NULL) || (!breakData->mIRBreakBlock))
  4707. {
  4708. if (inMixinDecl)
  4709. {
  4710. // Our mixin may just require that we're injected into a breakable scope
  4711. }
  4712. else
  4713. Fail("'break' not applicable in this block", breakStmt);
  4714. return;
  4715. }
  4716. if (mCurMethodState->mInDeferredBlock)
  4717. {
  4718. auto checkScope = mCurMethodState->mCurScope;
  4719. while (checkScope != NULL)
  4720. {
  4721. if (checkScope == breakData->mScope)
  4722. break;
  4723. if (checkScope->mIsDeferredBlock)
  4724. {
  4725. Fail("The break target crosses a deferred block boundary", breakStmt);
  4726. return;
  4727. }
  4728. checkScope = checkScope->mPrevScope;
  4729. }
  4730. }
  4731. if (HasDeferredScopeCalls(breakData->mScope))
  4732. {
  4733. EmitDeferredScopeCalls(true, breakData->mScope, breakData->mIRBreakBlock);
  4734. }
  4735. else
  4736. {
  4737. mBfIRBuilder->CreateBr(breakData->mIRBreakBlock);
  4738. }
  4739. mCurMethodState->mLeftBlockUncond = true;
  4740. bool isCond = false;
  4741. int uncondScopeDepth = 0;
  4742. if (mCurMethodState->mCurScope != NULL)
  4743. uncondScopeDepth = mCurMethodState->mCurScope->mScopeDepth + 1;
  4744. BfIRValue earliestValueScopeStart;
  4745. auto checkScope = mCurMethodState->mCurScope;
  4746. while (checkScope != NULL)
  4747. {
  4748. if (!isCond)
  4749. uncondScopeDepth = checkScope->mScopeDepth;
  4750. if ((checkScope->mOuterIsConditional) && (!checkScope->mIsSharedTempBlock))
  4751. isCond = true;
  4752. if (checkScope->mValueScopeStart)
  4753. earliestValueScopeStart = checkScope->mValueScopeStart;
  4754. if (checkScope == breakData->mScope)
  4755. break;
  4756. checkScope = checkScope->mPrevScope;
  4757. }
  4758. auto checkLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  4759. while (checkLocalAssignData != NULL)
  4760. {
  4761. if ((checkLocalAssignData->mScopeData != NULL) && (checkLocalAssignData->mScopeData->mScopeDepth >= breakData->mScope->mScopeDepth))
  4762. {
  4763. if (checkLocalAssignData->mScopeData->mScopeDepth >= uncondScopeDepth)
  4764. checkLocalAssignData->mLeftBlockUncond = true;
  4765. checkLocalAssignData->mLeftBlock = true;
  4766. checkLocalAssignData->mHadBreak = true;
  4767. }
  4768. checkLocalAssignData = checkLocalAssignData->mChainedAssignData;
  4769. }
  4770. MarkScopeLeft(breakData->mScope);
  4771. ValueScopeEnd(earliestValueScopeStart);
  4772. auto checkBreakData = mCurMethodState->mBreakData;
  4773. while (true)
  4774. {
  4775. checkBreakData->mHadBreak = true;
  4776. if (checkBreakData == breakData)
  4777. break;
  4778. checkBreakData = checkBreakData->mPrevBreakData;
  4779. }
  4780. }
  4781. void BfModule::Visit(BfContinueStatement* continueStmt)
  4782. {
  4783. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  4784. UpdateSrcPos(continueStmt);
  4785. EmitEnsureInstructionAt();
  4786. // If we're in a switch, 'break' is valid but we need to continue looking outward for a 'continue' target
  4787. BfBreakData* breakData = mCurMethodState->mBreakData;
  4788. if (continueStmt->mLabel != NULL)
  4789. {
  4790. breakData = FindBreakData(continueStmt->mLabel);
  4791. if ((breakData != NULL) && (!breakData->mIRContinueBlock))
  4792. {
  4793. Fail(StrFormat("'continue' not applicable in '%s", continueStmt->mLabel->ToString().c_str()), continueStmt);
  4794. return;
  4795. }
  4796. }
  4797. else
  4798. {
  4799. while (breakData != NULL)
  4800. {
  4801. if (breakData->mIRContinueBlock)
  4802. break;
  4803. breakData = breakData->mPrevBreakData;
  4804. }
  4805. }
  4806. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  4807. {
  4808. BfScopeData* scope = NULL;
  4809. if (breakData != NULL)
  4810. scope = breakData->mScope;
  4811. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(continueStmt->mLabel))
  4812. mCompiler->mResolvePassData->mAutoComplete->CheckLabel(identifer, continueStmt->mContinueNode, scope);
  4813. }
  4814. if ((breakData == NULL) || (!breakData->mIRContinueBlock))
  4815. {
  4816. if (inMixinDecl)
  4817. {
  4818. // Our mixin may just require that we're injected into a breakable scope
  4819. }
  4820. else
  4821. Fail("'continue' not applicable in this block", continueStmt);
  4822. return;
  4823. }
  4824. BfIRValue earliestValueScopeStart;
  4825. // We don't want to close out our own scope, we want to close out any scopes that were opened after us
  4826. auto nextScope = mCurMethodState->mCurScope;
  4827. while (nextScope != NULL)
  4828. {
  4829. if (nextScope->mValueScopeStart)
  4830. earliestValueScopeStart = nextScope->mValueScopeStart;
  4831. if (nextScope->mPrevScope == breakData->mScope)
  4832. break;
  4833. nextScope = nextScope->mPrevScope;
  4834. }
  4835. if (breakData->mInnerValueScopeStart)
  4836. earliestValueScopeStart = breakData->mInnerValueScopeStart;
  4837. if (mCurMethodState->mInDeferredBlock)
  4838. {
  4839. auto checkScope = mCurMethodState->mCurScope;
  4840. while (checkScope != NULL)
  4841. {
  4842. if (checkScope == breakData->mScope)
  4843. break;
  4844. if (checkScope->mIsDeferredBlock)
  4845. {
  4846. Fail("The continue target crosses a deferred block boundary", continueStmt);
  4847. return;
  4848. }
  4849. checkScope = checkScope->mPrevScope;
  4850. }
  4851. }
  4852. if ((nextScope != NULL) && (HasDeferredScopeCalls(nextScope)))
  4853. {
  4854. EmitDeferredScopeCalls(true, nextScope, breakData->mIRContinueBlock);
  4855. }
  4856. else
  4857. {
  4858. mBfIRBuilder->CreateBr(breakData->mIRContinueBlock);
  4859. }
  4860. MarkScopeLeft(breakData->mScope);
  4861. ValueScopeEnd(earliestValueScopeStart);
  4862. mCurMethodState->mLeftBlockUncond = true;
  4863. if (!mCurMethodState->mInPostReturn)
  4864. mCurMethodState->mHadContinue = true;
  4865. }
  4866. void BfModule::Visit(BfFallthroughStatement* fallthroughStmt)
  4867. {
  4868. UpdateSrcPos(fallthroughStmt);
  4869. BfBreakData* breakData = mCurMethodState->mBreakData;
  4870. if (fallthroughStmt->mLabel != NULL)
  4871. {
  4872. breakData = FindBreakData(fallthroughStmt->mLabel);
  4873. }
  4874. else
  4875. {
  4876. while (breakData != NULL)
  4877. {
  4878. if (breakData->mIRFallthroughBlock)
  4879. break;
  4880. breakData = breakData->mPrevBreakData;
  4881. }
  4882. }
  4883. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  4884. {
  4885. BfScopeData* scope = NULL;
  4886. if (breakData != NULL)
  4887. scope = breakData->mScope;
  4888. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(fallthroughStmt->mLabel))
  4889. mCompiler->mResolvePassData->mAutoComplete->CheckLabel(identifer, fallthroughStmt->mFallthroughToken, scope);
  4890. }
  4891. if (mCurMethodState->mInDeferredBlock)
  4892. {
  4893. auto checkScope = mCurMethodState->mCurScope;
  4894. while (checkScope != NULL)
  4895. {
  4896. if (checkScope == breakData->mScope)
  4897. break;
  4898. if (checkScope->mIsDeferredBlock)
  4899. {
  4900. Fail("The fallthrough crosses a deferred block boundary", fallthroughStmt);
  4901. return;
  4902. }
  4903. checkScope = checkScope->mPrevScope;
  4904. }
  4905. }
  4906. if (breakData == NULL)
  4907. {
  4908. Fail("'fallthrough' not applicable in this block", fallthroughStmt);
  4909. return;
  4910. }
  4911. EmitDeferredScopeCalls(true, breakData->mScope, breakData->mIRFallthroughBlock);
  4912. mCurMethodState->mLeftBlockUncond = true; // Not really a return, but handled the same way
  4913. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  4914. mCurMethodState->mDeferredLocalAssignData->mHadFallthrough = true;
  4915. auto checkBreakData = mCurMethodState->mBreakData;
  4916. while (true)
  4917. {
  4918. if (checkBreakData == breakData)
  4919. break;
  4920. checkBreakData->mHadBreak = true;
  4921. checkBreakData = checkBreakData->mPrevBreakData;
  4922. }
  4923. }
  4924. void BfModule::Visit(BfUsingStatement* usingStmt)
  4925. {
  4926. UpdateSrcPos(usingStmt);
  4927. mCurMethodState->mInHeadScope = false;
  4928. BfScopeData newScope;
  4929. mCurMethodState->AddScope(&newScope);
  4930. NewScopeState();
  4931. if (usingStmt->mVariableDeclaration != NULL)
  4932. UpdateSrcPos(usingStmt->mVariableDeclaration);
  4933. BfTypedValue embeddedValue;
  4934. SizedArray<BfIRValue, 1> llvmArgs;
  4935. BfModuleMethodInstance moduleMethodInstance;
  4936. BfFunctionBindResult functionBindResult;
  4937. BfExprEvaluator exprEvaluator(this);
  4938. bool failed = false;
  4939. if (usingStmt->mVariableDeclaration == NULL)
  4940. {
  4941. AssertErrorState();
  4942. failed = true;
  4943. }
  4944. else if (usingStmt->mVariableDeclaration->mNameNode != NULL)
  4945. {
  4946. BfLocalVariable* localVar = HandleVariableDeclaration(usingStmt->mVariableDeclaration);
  4947. if (localVar == NULL)
  4948. {
  4949. AssertErrorState();
  4950. failed = true;
  4951. }
  4952. else
  4953. {
  4954. embeddedValue = exprEvaluator.LoadLocal(localVar);
  4955. }
  4956. //exprEvaluator.CheckModifyResult(embeddedValue, usingStmt->mVariableDeclaration->mNameNode,);
  4957. }
  4958. else
  4959. {
  4960. embeddedValue = CreateValueFromExpression(usingStmt->mVariableDeclaration->mInitializer);
  4961. if (!embeddedValue)
  4962. failed = true;
  4963. }
  4964. if (!failed)
  4965. {
  4966. auto iDisposableType = ResolveTypeDef(mCompiler->mIDisposableTypeDef)->ToTypeInstance();
  4967. auto dispMethod = GetMethodByName(iDisposableType, "Dispose");
  4968. if ((!dispMethod) || (!CanCast(embeddedValue, iDisposableType)))
  4969. {
  4970. Fail(StrFormat("Type '%s' must be implicitly convertible to 'System.IDisposable' for use in 'using' statement", TypeToString(embeddedValue.mType).c_str()), usingStmt->mVariableDeclaration);
  4971. failed = true;
  4972. }
  4973. else
  4974. {
  4975. bool mayBeNull = true;
  4976. if (embeddedValue.mType->IsStruct())
  4977. {
  4978. // It's possible that a struct can convert to an IDisposable through a conversion operator that CAN
  4979. // return null, so the only way we can know we are not null is if we are a struct that directly
  4980. // implements the interface
  4981. if (TypeIsSubTypeOf(embeddedValue.mType->ToTypeInstance(), iDisposableType))
  4982. mayBeNull = false;
  4983. }
  4984. exprEvaluator.mFunctionBindResult = &functionBindResult;
  4985. SizedArray<BfResolvedArg, 0> resolvedArgs;
  4986. BfMethodMatcher methodMatcher(usingStmt->mVariableDeclaration, this, dispMethod.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  4987. methodMatcher.CheckType(iDisposableType, embeddedValue, false);
  4988. methodMatcher.TryDevirtualizeCall(embeddedValue);
  4989. auto retVal = exprEvaluator.CreateCall(&methodMatcher, embeddedValue);
  4990. if (functionBindResult.mMethodInstance != NULL)
  4991. {
  4992. moduleMethodInstance = BfModuleMethodInstance(functionBindResult.mMethodInstance, functionBindResult.mFunc);
  4993. AddDeferredCall(moduleMethodInstance, functionBindResult.mIRArgs, mCurMethodState->mCurScope, NULL, false, mayBeNull);
  4994. }
  4995. }
  4996. }
  4997. if (usingStmt->mEmbeddedStatement == NULL)
  4998. {
  4999. AssertErrorState();
  5000. }
  5001. else
  5002. {
  5003. VisitEmbeddedStatement(usingStmt->mEmbeddedStatement);
  5004. }
  5005. RestoreScopeState();
  5006. }
  5007. void BfModule::Visit(BfDoStatement* doStmt)
  5008. {
  5009. UpdateSrcPos(doStmt);
  5010. auto bodyBB = mBfIRBuilder->CreateBlock("do.body", true);
  5011. auto endBB = mBfIRBuilder->CreateBlock("do.end");
  5012. BfScopeData scopeData;
  5013. if (doStmt->mLabelNode != NULL)
  5014. scopeData.mLabelNode = doStmt->mLabelNode->mLabel;
  5015. mCurMethodState->AddScope(&scopeData);
  5016. NewScopeState();
  5017. BfBreakData breakData;
  5018. breakData.mIRBreakBlock = endBB;
  5019. breakData.mScope = &scopeData;
  5020. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  5021. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  5022. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  5023. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  5024. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  5025. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  5026. // We may have a call in the loop body
  5027. mCurMethodState->mMayNeedThisAccessCheck = true;
  5028. mBfIRBuilder->CreateBr(bodyBB);
  5029. mBfIRBuilder->SetInsertPoint(bodyBB);
  5030. VisitEmbeddedStatement(doStmt->mEmbeddedStatement);
  5031. prevDLA.Restore();
  5032. mCurMethodState->ApplyDeferredLocalAssignData(deferredLocalAssignData);
  5033. RestoreScopeState();
  5034. if (!mCurMethodState->mLeftBlockUncond)
  5035. mBfIRBuilder->CreateBr(endBB);
  5036. mCurMethodState->SetHadReturn(false);
  5037. mCurMethodState->mLeftBlockUncond = false;
  5038. mBfIRBuilder->AddBlock(endBB);
  5039. mBfIRBuilder->SetInsertPoint(endBB);
  5040. }
  5041. void BfModule::Visit(BfRepeatStatement* repeatStmt)
  5042. {
  5043. // if (repeatStmt->mCondition != NULL)
  5044. // UpdateSrcPos(repeatStmt->mCondition);
  5045. // else
  5046. UpdateSrcPos(repeatStmt);
  5047. if (repeatStmt->mRepeatToken->mToken == BfToken_Do)
  5048. {
  5049. Fail("Repeat block requires 'repeat' token", repeatStmt->mRepeatToken);
  5050. }
  5051. auto bodyBB = mBfIRBuilder->CreateBlock("repeat.body", true);
  5052. auto condBB = mBfIRBuilder->CreateBlock("repeat.cond");
  5053. auto endBB = mBfIRBuilder->CreateBlock("repeat.end");
  5054. BfScopeData scopeData;
  5055. // We set mIsLoop later
  5056. if (repeatStmt->mLabelNode != NULL)
  5057. scopeData.mLabelNode = repeatStmt->mLabelNode->mLabel;
  5058. mCurMethodState->AddScope(&scopeData);
  5059. NewScopeState();
  5060. BfBreakData breakData;
  5061. breakData.mIRContinueBlock = condBB;
  5062. breakData.mIRBreakBlock = endBB;
  5063. breakData.mScope = &scopeData;
  5064. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  5065. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  5066. // We may have a call in the loop body
  5067. mCurMethodState->mMayNeedThisAccessCheck = true;
  5068. mBfIRBuilder->CreateBr(bodyBB);
  5069. mBfIRBuilder->SetInsertPoint(bodyBB);
  5070. scopeData.mIsLoop = true;
  5071. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  5072. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  5073. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  5074. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  5075. VisitEmbeddedStatement(repeatStmt->mEmbeddedStatement);
  5076. if (!mCurMethodState->mLeftBlockUncond)
  5077. mBfIRBuilder->CreateBr(condBB);
  5078. mCurMethodState->SetHadReturn(false);
  5079. mCurMethodState->mLeftBlockUncond = false;
  5080. mCurMethodState->mLeftBlockCond = false;
  5081. mBfIRBuilder->AddBlock(condBB);
  5082. mBfIRBuilder->SetInsertPoint(condBB);
  5083. bool isInfiniteLoop = false;
  5084. if (repeatStmt->mCondition != NULL)
  5085. {
  5086. UpdateSrcPos(repeatStmt->mCondition);
  5087. auto checkVal = CreateValueFromExpression(repeatStmt->mCondition, GetPrimitiveType(BfTypeCode_Boolean));
  5088. if (checkVal)
  5089. {
  5090. if ((!breakData.mHadBreak) && (checkVal.mValue.IsConst()))
  5091. {
  5092. auto constVal = mBfIRBuilder->GetConstantById(checkVal.mValue.mId);
  5093. if (constVal->mTypeCode == BfTypeCode_Boolean)
  5094. isInfiniteLoop = constVal->mBool;
  5095. }
  5096. mBfIRBuilder->CreateCondBr(checkVal.mValue, bodyBB, endBB);
  5097. mBfIRBuilder->AddBlock(endBB);
  5098. mBfIRBuilder->SetInsertPoint(endBB);
  5099. }
  5100. }
  5101. RestoreScopeState();
  5102. prevDLA.Restore();
  5103. mCurMethodState->ApplyDeferredLocalAssignData(deferredLocalAssignData);
  5104. if (isInfiniteLoop)
  5105. EmitDefaultReturn();
  5106. }
  5107. void BfModule::Visit(BfWhileStatement* whileStmt)
  5108. {
  5109. UpdateSrcPos(whileStmt);
  5110. bool prevHadReturn = mCurMethodState->mHadReturn;
  5111. auto condBB = mBfIRBuilder->CreateBlock("while.cond");
  5112. auto bodyBB = mBfIRBuilder->CreateBlock("while.body");
  5113. auto endBB = mBfIRBuilder->CreateBlock("while.end");
  5114. mCurMethodState->mInHeadScope = false;
  5115. BfScopeData scopeData;
  5116. scopeData.mScopeKind = BfScopeKind_StatementTarget_Conditional;
  5117. scopeData.mIsLoop = true;
  5118. if (whileStmt->mLabelNode != NULL)
  5119. scopeData.mLabelNode = whileStmt->mLabelNode->mLabel;
  5120. scopeData.mValueScopeStart = ValueScopeStart();
  5121. mCurMethodState->AddScope(&scopeData);
  5122. NewScopeState();
  5123. BfBreakData breakData;
  5124. breakData.mIRContinueBlock = condBB;
  5125. breakData.mIRBreakBlock = endBB;
  5126. breakData.mScope = &scopeData;
  5127. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  5128. breakData.mInnerValueScopeStart = scopeData.mValueScopeStart;
  5129. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  5130. mBfIRBuilder->AddBlock(condBB);
  5131. mBfIRBuilder->CreateBr(condBB);
  5132. mBfIRBuilder->SetInsertPoint(condBB);
  5133. BfTypedValue checkVal;
  5134. if (whileStmt->mCondition != NULL)
  5135. {
  5136. UpdateSrcPos(whileStmt->mCondition);
  5137. checkVal = CreateValueFromExpression(whileStmt->mCondition, GetPrimitiveType(BfTypeCode_Boolean));
  5138. }
  5139. if (!checkVal)
  5140. {
  5141. AssertErrorState();
  5142. checkVal = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_Boolean));
  5143. }
  5144. bool isInfiniteLoop = false;
  5145. bool isFalseLoop = false;
  5146. if (checkVal.mValue.IsConst())
  5147. {
  5148. EmitEnsureInstructionAt();
  5149. auto constVal = mBfIRBuilder->GetConstantById(checkVal.mValue.mId);
  5150. if (constVal->mTypeCode == BfTypeCode_Boolean)
  5151. {
  5152. isInfiniteLoop = constVal->mBool;
  5153. isFalseLoop = !isInfiniteLoop;
  5154. }
  5155. }
  5156. // We may have a call in the loop body
  5157. mCurMethodState->mMayNeedThisAccessCheck = true;
  5158. // For BeefBackend we continue to do CondBr because it helps our flow analysis and we optimize it anyway
  5159. if ((isInfiniteLoop) && (!IsTargetingBeefBackend()))
  5160. mBfIRBuilder->CreateBr(bodyBB);
  5161. else if (isFalseLoop)
  5162. mBfIRBuilder->CreateBr(endBB);
  5163. else
  5164. mBfIRBuilder->CreateCondBr(checkVal.mValue, bodyBB, endBB);
  5165. // Apply deferred local assign to mEmbeddedStatement and itrStmt
  5166. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  5167. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  5168. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  5169. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  5170. deferredLocalAssignData.mIsUnconditional = isInfiniteLoop;
  5171. mBfIRBuilder->AddBlock(bodyBB);
  5172. mBfIRBuilder->SetInsertPoint(bodyBB);
  5173. if (whileStmt->mEmbeddedStatement != NULL)
  5174. {
  5175. if (isFalseLoop)
  5176. {
  5177. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  5178. SetAndRestoreValue<bool> prevInConstIgnore(mCurMethodState->mCurScope->mInConstIgnore, true);
  5179. VisitEmbeddedStatement(whileStmt->mEmbeddedStatement);
  5180. }
  5181. else
  5182. VisitEmbeddedStatement(whileStmt->mEmbeddedStatement);
  5183. }
  5184. else
  5185. {
  5186. AssertErrorState();
  5187. }
  5188. if (breakData.mHadBreak)
  5189. {
  5190. isInfiniteLoop = false;
  5191. }
  5192. if ((!mCurMethodState->mLeftBlockUncond) && (!isFalseLoop))
  5193. {
  5194. mBfIRBuilder->CreateBr(condBB);
  5195. }
  5196. if (!isInfiniteLoop)
  5197. mCurMethodState->mHadReturn = prevHadReturn;
  5198. mCurMethodState->mLeftBlockUncond = false;
  5199. mCurMethodState->mLeftBlockCond = false;
  5200. mBfIRBuilder->AddBlock(endBB);
  5201. mBfIRBuilder->SetInsertPoint(endBB);
  5202. if (isFalseLoop)
  5203. {
  5204. mBfIRBuilder->EraseFromParent(bodyBB);
  5205. }
  5206. RestoreScopeState();
  5207. if ((isInfiniteLoop) && (mCurMethodInstance != NULL))
  5208. EmitDefaultReturn();
  5209. }
  5210. void BfModule::Visit(BfForStatement* forStmt)
  5211. {
  5212. auto autoComplete = mCompiler->GetAutoComplete();
  5213. if (autoComplete != NULL)
  5214. autoComplete->CheckIdentifier(forStmt->mForToken, true);
  5215. UpdateSrcPos(forStmt);
  5216. auto startBB = mBfIRBuilder->CreateBlock("for.start", true);
  5217. mBfIRBuilder->CreateBr(startBB);
  5218. mBfIRBuilder->SetInsertPoint(startBB);
  5219. BfScopeData scopeData;
  5220. scopeData.mIsLoop = true;
  5221. if (forStmt->mLabelNode != NULL)
  5222. scopeData.mLabelNode = forStmt->mLabelNode->mLabel;
  5223. scopeData.mCloseNode = forStmt;
  5224. scopeData.mValueScopeStart = ValueScopeStart();
  5225. mCurMethodState->AddScope(&scopeData);
  5226. NewScopeState();
  5227. for (auto initializer : forStmt->mInitializers)
  5228. {
  5229. VisitChild(initializer);
  5230. }
  5231. // We may have a call in the loop body
  5232. mCurMethodState->mMayNeedThisAccessCheck = true;
  5233. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  5234. auto condBB = mBfIRBuilder->CreateBlock("for.cond", true);
  5235. auto bodyBB = mBfIRBuilder->CreateBlock("for.body");
  5236. auto incBB = mBfIRBuilder->CreateBlock("for.inc");
  5237. auto endBB = mBfIRBuilder->CreateBlock("for.end");
  5238. BfBreakData breakData;
  5239. breakData.mIRContinueBlock = incBB;
  5240. breakData.mIRBreakBlock = endBB;
  5241. breakData.mScope = &scopeData;
  5242. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  5243. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  5244. mBfIRBuilder->CreateBr(condBB);
  5245. bool isInfiniteLoop = false;
  5246. mBfIRBuilder->SetInsertPoint(condBB);
  5247. if (forStmt->mCondition != NULL)
  5248. {
  5249. auto conditionValue = CreateValueFromExpression(forStmt->mCondition, boolType);
  5250. if (!conditionValue)
  5251. conditionValue = GetDefaultTypedValue(boolType);
  5252. auto constant = mBfIRBuilder->GetConstant(conditionValue.mValue);
  5253. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_Boolean))
  5254. isInfiniteLoop = constant->mBool;
  5255. ValueScopeEnd(scopeData.mValueScopeStart);
  5256. mBfIRBuilder->CreateCondBr(conditionValue.mValue, bodyBB, endBB);
  5257. }
  5258. else
  5259. {
  5260. isInfiniteLoop = true;
  5261. mBfIRBuilder->CreateBr(bodyBB);
  5262. }
  5263. // Apply deferred local assign to mEmbeddedStatement and itrStmt
  5264. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  5265. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  5266. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  5267. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  5268. mBfIRBuilder->AddBlock(bodyBB);
  5269. mBfIRBuilder->SetInsertPoint(bodyBB);
  5270. if (forStmt->mEmbeddedStatement != NULL)
  5271. {
  5272. VisitEmbeddedStatement(forStmt->mEmbeddedStatement);
  5273. }
  5274. if (!mCurMethodState->mLeftBlockUncond)
  5275. mBfIRBuilder->CreateBr(incBB);
  5276. mBfIRBuilder->AddBlock(incBB);
  5277. mBfIRBuilder->SetInsertPoint(incBB);
  5278. for (auto itrStmt : forStmt->mIterators)
  5279. {
  5280. VisitChild(itrStmt);
  5281. if ((mCurMethodState->mLeftBlockUncond) && (!mCurMethodState->mHadContinue) && (!mCurMethodState->mInPostReturn))
  5282. Warn(BfWarning_CS0162_UnreachableCode, "Unreachable code", itrStmt);
  5283. }
  5284. ValueScopeEnd(scopeData.mValueScopeStart);
  5285. mBfIRBuilder->CreateBr(condBB);
  5286. mBfIRBuilder->AddBlock(endBB);
  5287. mBfIRBuilder->SetInsertPoint(endBB);
  5288. // The 'return' may have been inside the block, which may not have been entered if preconditions were not met
  5289. mCurMethodState->SetHadReturn(false);
  5290. mCurMethodState->mLeftBlockUncond = false;
  5291. mCurMethodState->mLeftBlockCond = false;
  5292. if (breakData.mHadBreak)
  5293. isInfiniteLoop = false;
  5294. RestoreScopeState();
  5295. if (isInfiniteLoop)
  5296. EmitDefaultReturn();
  5297. }
  5298. void BfModule::DoForLess(BfForEachStatement* forEachStmt)
  5299. {
  5300. UpdateSrcPos(forEachStmt);
  5301. auto startBB = mBfIRBuilder->GetInsertBlock();
  5302. auto condBB = mBfIRBuilder->CreateBlock("forless.cond", true);
  5303. mBfIRBuilder->SetInsertPoint(condBB);
  5304. BfScopeData scopeData;
  5305. // We set mIsLoop later
  5306. if (forEachStmt->mLabelNode != NULL)
  5307. scopeData.mLabelNode = forEachStmt->mLabelNode->mLabel;
  5308. mCurMethodState->AddScope(&scopeData);
  5309. NewScopeState();
  5310. auto autoComplete = mCompiler->GetAutoComplete();
  5311. auto isLet = BfNodeDynCast<BfLetTypeReference>(forEachStmt->mVariableTypeRef) != 0;
  5312. auto isVar = BfNodeDynCast<BfVarTypeReference>(forEachStmt->mVariableTypeRef) != 0;
  5313. BfTypedValue target;
  5314. BfType* varType = NULL;
  5315. bool didInference = false;
  5316. if (isLet || isVar)
  5317. {
  5318. if (forEachStmt->mCollectionExpression != NULL)
  5319. target = CreateValueFromExpression(forEachStmt->mCollectionExpression);
  5320. if (target)
  5321. {
  5322. FixIntUnknown(target);
  5323. varType = target.mType;
  5324. }
  5325. if (autoComplete != NULL)
  5326. autoComplete->CheckVarResolution(forEachStmt->mVariableTypeRef, varType);
  5327. didInference = true;
  5328. }
  5329. else
  5330. {
  5331. varType = ResolveTypeRef(forEachStmt->mVariableTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  5332. if (forEachStmt->mCollectionExpression != NULL)
  5333. target = CreateValueFromExpression(forEachStmt->mCollectionExpression, varType);
  5334. }
  5335. if (varType == NULL)
  5336. varType = GetPrimitiveType(BfTypeCode_IntPtr);
  5337. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  5338. deferredLocalAssignData.mIsIfCondition = true;
  5339. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, true);
  5340. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  5341. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  5342. deferredLocalAssignData.mIsIfCondition = false;
  5343. // The "extend chain" is only valid for the conditional -- since that expression may contain unconditionally executed and
  5344. // conditionally executed code (in the case of "(GetVal(out a) && GetVal(out b))" for example
  5345. mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  5346. BfType* checkType = varType;
  5347. if (checkType->IsTypedPrimitive())
  5348. checkType = checkType->GetUnderlyingType();
  5349. if (!checkType->IsIntegral())
  5350. {
  5351. Fail(StrFormat("Cannot iterate over '%s' in for-less statements, only integer types are allowed", TypeToString(varType).c_str()), forEachStmt->mVariableTypeRef);
  5352. varType = GetPrimitiveType(BfTypeCode_IntPtr);
  5353. if (didInference)
  5354. target = GetDefaultTypedValue(varType);
  5355. }
  5356. PopulateType(varType, BfPopulateType_Data);
  5357. auto condEndBB = mBfIRBuilder->GetInsertBlock();
  5358. mBfIRBuilder->SetInsertPoint(startBB);
  5359. BfLocalVariable* localDef = new BfLocalVariable();
  5360. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(forEachStmt->mVariableName);
  5361. localDef->mName = localDef->mNameNode->ToString();
  5362. localDef->mResolvedType = varType;
  5363. BfIRValue varInst;
  5364. if (!varType->IsValuelessType())
  5365. {
  5366. varInst = CreateAlloca(varType);
  5367. }
  5368. localDef->mAddr = varInst;
  5369. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  5370. localDef->mReadFromId = 0;
  5371. localDef->mIsReadOnly = isLet || (forEachStmt->mReadOnlyToken != NULL);
  5372. CheckVariableDef(localDef);
  5373. mBfIRBuilder->CreateAlignedStore(GetDefaultValue(varType), localDef->mAddr, varType->mAlign);
  5374. localDef->Init();
  5375. UpdateExprSrcPos(forEachStmt->mVariableName);
  5376. AddLocalVariableDef(localDef, true);
  5377. auto bodyBB = mBfIRBuilder->CreateBlock("forless.body");
  5378. auto incBB = mBfIRBuilder->CreateBlock("forless.inc");
  5379. auto endBB = mBfIRBuilder->CreateBlock("forless.end");
  5380. BfBreakData breakData;
  5381. breakData.mIRContinueBlock = incBB;
  5382. breakData.mIRBreakBlock = endBB;
  5383. breakData.mScope = &scopeData;
  5384. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  5385. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  5386. mBfIRBuilder->CreateBr(condBB);
  5387. mBfIRBuilder->SetInsertPoint(condEndBB);
  5388. if (forEachStmt->mCollectionExpression != NULL)
  5389. UpdateExprSrcPos(forEachStmt->mCollectionExpression);
  5390. BfIRValue conditionValue;
  5391. // We may have a call in the loop body
  5392. mCurMethodState->mMayNeedThisAccessCheck = true;
  5393. // Cond
  5394. auto valueScopeStart = ValueScopeStart();
  5395. auto localVal = mBfIRBuilder->CreateAlignedLoad(localDef->mAddr, localDef->mResolvedType->mAlign);
  5396. if (!target)
  5397. {
  5398. // Soldier on
  5399. target = GetDefaultTypedValue(varType);
  5400. }
  5401. if (forEachStmt->mInToken->mToken == BfToken_LessEquals)
  5402. conditionValue = mBfIRBuilder->CreateCmpLTE(localVal, target.mValue, varType->IsSigned());
  5403. else
  5404. conditionValue = mBfIRBuilder->CreateCmpLT(localVal, target.mValue, varType->IsSigned());
  5405. mBfIRBuilder->CreateCondBr(conditionValue, bodyBB, endBB);
  5406. ValueScopeEnd(valueScopeStart);
  5407. mBfIRBuilder->AddBlock(bodyBB);
  5408. mBfIRBuilder->SetInsertPoint(bodyBB);
  5409. // Body
  5410. scopeData.mIsLoop = true;
  5411. if (forEachStmt->mEmbeddedStatement != NULL)
  5412. {
  5413. VisitEmbeddedStatement(forEachStmt->mEmbeddedStatement);
  5414. }
  5415. // Inc
  5416. if (!mCurMethodState->mLeftBlockUncond)
  5417. {
  5418. mBfIRBuilder->CreateBr(incBB);
  5419. }
  5420. mBfIRBuilder->AddBlock(incBB);
  5421. mBfIRBuilder->SetInsertPoint(incBB);
  5422. if (forEachStmt->mCollectionExpression != NULL)
  5423. UpdateExprSrcPos(forEachStmt->mCollectionExpression);
  5424. auto one = GetConstValue(1, localDef->mResolvedType);
  5425. // We have to reload localVal before the inc, user logic could have changed it
  5426. localVal = mBfIRBuilder->CreateAlignedLoad(localDef->mAddr, localDef->mResolvedType->mAlign);
  5427. auto result = mBfIRBuilder->CreateAdd(localVal, one);
  5428. mBfIRBuilder->CreateAlignedStore(result, localDef->mAddr, localDef->mResolvedType->mAlign);
  5429. ValueScopeEnd(valueScopeStart);
  5430. mBfIRBuilder->CreateBr(condBB);
  5431. mBfIRBuilder->AddBlock(endBB);
  5432. mBfIRBuilder->SetInsertPoint(endBB);
  5433. // The 'return' may have been inside the block, which may not have been entered if preconditions were not met
  5434. mCurMethodState->SetHadReturn(false);
  5435. mCurMethodState->mLeftBlockUncond = false;
  5436. mCurMethodState->mLeftBlockCond = false;
  5437. bool definitelyExecuted = false;
  5438. if (target.mValue.IsConst())
  5439. {
  5440. auto constant = mBfIRBuilder->GetConstant(target.mValue);
  5441. if (constant->mInt32 > 0)
  5442. definitelyExecuted = true;
  5443. }
  5444. prevDLA.Restore();
  5445. if (definitelyExecuted)
  5446. mCurMethodState->ApplyDeferredLocalAssignData(deferredLocalAssignData);
  5447. RestoreScopeState();
  5448. }
  5449. void BfModule::Visit(BfForEachStatement* forEachStmt)
  5450. {
  5451. if ((forEachStmt->mInToken != NULL) &&
  5452. ((forEachStmt->mInToken->GetToken() == BfToken_LChevron) || (forEachStmt->mInToken->GetToken() == BfToken_LessEquals)))
  5453. {
  5454. DoForLess(forEachStmt);
  5455. return;
  5456. }
  5457. auto autoComplete = mCompiler->GetAutoComplete();
  5458. UpdateSrcPos(forEachStmt);
  5459. BfScopeData scopeData;
  5460. // We set mIsLoop after the non-looped initializations
  5461. scopeData.mValueScopeStart = ValueScopeStart();
  5462. mCurMethodState->AddScope(&scopeData);
  5463. NewScopeState();
  5464. bool isRefExpression = false;
  5465. BfExpression* collectionExpr = forEachStmt->mCollectionExpression;
  5466. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(collectionExpr))
  5467. {
  5468. if ((unaryOpExpr->mOp == BfUnaryOp_Ref) || (unaryOpExpr->mOp == BfUnaryOp_Mut))
  5469. {
  5470. isRefExpression = true;
  5471. collectionExpr = unaryOpExpr->mExpression;
  5472. }
  5473. }
  5474. BfTypedValue target;
  5475. if (collectionExpr != NULL)
  5476. target = CreateValueFromExpression(collectionExpr);
  5477. if (!target)
  5478. {
  5479. // Soldier on
  5480. target = BfTypedValue(GetDefaultValue(mContext->mBfObjectType), mContext->mBfObjectType);
  5481. }
  5482. bool isLet = (forEachStmt->mVariableTypeRef != NULL) && (forEachStmt->mVariableTypeRef->IsA<BfLetTypeReference>());
  5483. BfType* varType = NULL;
  5484. bool inferVarType = false;
  5485. if ((forEachStmt->mVariableTypeRef == NULL) || (forEachStmt->mVariableTypeRef->IsA<BfVarTypeReference>()) || (isLet))
  5486. {
  5487. if (target.mType->IsSizedArray())
  5488. {
  5489. varType = target.mType->GetUnderlyingType();
  5490. if (isRefExpression)
  5491. varType = CreateRefType(varType);
  5492. }
  5493. else if (target.mType->IsArray())
  5494. {
  5495. varType = target.mType->GetUnderlyingType();
  5496. if (isRefExpression)
  5497. varType = CreateRefType(varType);
  5498. }
  5499. else
  5500. inferVarType = true;
  5501. }
  5502. else
  5503. {
  5504. if (autoComplete != NULL)
  5505. autoComplete->CheckTypeRef(forEachStmt->mVariableTypeRef, false);
  5506. varType = ResolveTypeRef(forEachStmt->mVariableTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  5507. }
  5508. if (varType == NULL)
  5509. varType = GetPrimitiveType(BfTypeCode_Var);
  5510. bool isArray = target.mType->IsArray();
  5511. bool isSizedArray = target.mType->IsSizedArray();
  5512. bool isVarEnumerator = target.mType->IsVar();
  5513. // Array
  5514. BfType* itrType;
  5515. BfTypedValue itr;
  5516. BfTypeInstance* itrInterface = NULL;
  5517. BfTypeInstance* refItrInterface = NULL;
  5518. if (isVarEnumerator)
  5519. varType = GetPrimitiveType(BfTypeCode_Var);
  5520. BfGenericParamInstance* genericParamInst = NULL;
  5521. if (target.mType->IsGenericParam())
  5522. {
  5523. genericParamInst = GetGenericParamInstance((BfGenericParamType*)target.mType);
  5524. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  5525. {
  5526. varType = GetPrimitiveType(BfTypeCode_Var);
  5527. isVarEnumerator = true;
  5528. }
  5529. if (genericParamInst->mTypeConstraint != NULL)
  5530. {
  5531. if (genericParamInst->mTypeConstraint->IsVar())
  5532. {
  5533. varType = GetPrimitiveType(BfTypeCode_Var);
  5534. isVarEnumerator = true;
  5535. }
  5536. if (genericParamInst->mTypeConstraint->IsGenericTypeInstance())
  5537. {
  5538. auto genericConstraintType = (BfTypeInstance*)genericParamInst->mTypeConstraint;
  5539. if (genericConstraintType->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  5540. {
  5541. varType = genericConstraintType->mGenericTypeInfo->mTypeGenericArguments[0];
  5542. isVarEnumerator = true;
  5543. }
  5544. }
  5545. }
  5546. }
  5547. if (target.mType->IsConcreteInterfaceType())
  5548. target.mType = target.mType->GetUnderlyingType();
  5549. if (isArray || isSizedArray)
  5550. {
  5551. itrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5552. BfIRValue itrInst = CreateAlloca(itrType);
  5553. itr = BfTypedValue(itrInst, itrType, true);
  5554. }
  5555. else if (isVarEnumerator)
  5556. {
  5557. // Generic method or mixin decl
  5558. }
  5559. else if ((!target.mType->IsTypeInstance()) && (genericParamInst == NULL))
  5560. {
  5561. Fail(StrFormat("Type '%s' cannot be used in enumeration", TypeToString(target.mType).c_str()), forEachStmt->mCollectionExpression);
  5562. }
  5563. else if (forEachStmt->mCollectionExpression != NULL)
  5564. {
  5565. auto targetTypeInstance = target.mType->ToTypeInstance();
  5566. itr = target;
  5567. bool hadGetEnumeratorType = false;
  5568. if (genericParamInst != NULL)
  5569. {
  5570. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  5571. {
  5572. if (ifaceConstraint->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef))
  5573. {
  5574. if (targetTypeInstance != NULL)
  5575. {
  5576. targetTypeInstance = NULL;
  5577. break;
  5578. }
  5579. targetTypeInstance = ifaceConstraint->ToTypeInstance();
  5580. }
  5581. }
  5582. }
  5583. if (targetTypeInstance != NULL)
  5584. {
  5585. PopulateType(targetTypeInstance, BfPopulateType_DataAndMethods);
  5586. auto getEnumeratorMethod = GetMethodByName(targetTypeInstance, "GetEnumerator", 0, true);
  5587. if (!getEnumeratorMethod)
  5588. {
  5589. hadGetEnumeratorType = false;
  5590. }
  5591. else if (getEnumeratorMethod.mMethodInstance->mMethodDef->mIsStatic)
  5592. {
  5593. hadGetEnumeratorType = true;
  5594. Fail(StrFormat("Type '%s' does not contain a non-static 'GetEnumerator' method", TypeToString(targetTypeInstance).c_str()), forEachStmt->mCollectionExpression);
  5595. }
  5596. else
  5597. {
  5598. if (getEnumeratorMethod.mMethodInstance->mMethodDef->mIsConcrete)
  5599. {
  5600. hadGetEnumeratorType = true;
  5601. if (genericParamInst != NULL)
  5602. {
  5603. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) == 0)
  5604. Fail(StrFormat("Iteration requires a concrete implementation of '%s', consider adding 'concrete' constraint to '%s'", TypeToString(targetTypeInstance).c_str(), genericParamInst->GetName().c_str()), forEachStmt->mCollectionExpression);
  5605. }
  5606. else
  5607. Fail(StrFormat("Iteration requires a concrete implementation of '%s'", TypeToString(targetTypeInstance).c_str()), forEachStmt->mCollectionExpression);
  5608. }
  5609. hadGetEnumeratorType = true;
  5610. BfExprEvaluator exprEvaluator(this);
  5611. SizedArray<BfIRValue, 1> args;
  5612. auto castedTarget = Cast(forEachStmt->mCollectionExpression, target, getEnumeratorMethod.mMethodInstance->GetOwner());
  5613. exprEvaluator.PushThis(forEachStmt->mCollectionExpression, castedTarget, getEnumeratorMethod.mMethodInstance, args);
  5614. itr = exprEvaluator.CreateCall(forEachStmt->mCollectionExpression, getEnumeratorMethod.mMethodInstance, IsSkippingExtraResolveChecks() ? BfIRValue() : getEnumeratorMethod.mFunc, false, args);
  5615. if (itr.mType->IsConcreteInterfaceType())
  5616. itr.mType = itr.mType->GetUnderlyingType();
  5617. }
  5618. }
  5619. if (itr)
  5620. {
  5621. PopulateType(itr.mType, BfPopulateType_DataAndMethods);
  5622. BfTypeInstance* genericItrInterface = NULL;
  5623. auto _CheckInterface = [&](BfTypeInstance* interface)
  5624. {
  5625. if (interface->IsInstanceOf(isRefExpression ? mCompiler->mGenericIRefEnumeratorTypeDef : mCompiler->mGenericIEnumeratorTypeDef))
  5626. {
  5627. if (genericItrInterface != NULL)
  5628. {
  5629. Fail(StrFormat("Type '%s' implements multiple %s<T> interfaces", TypeToString(itr.mType).c_str(), isRefExpression ? "IRefEnumerator" : "IEnumerator"), forEachStmt->mCollectionExpression);
  5630. }
  5631. itrInterface = interface;
  5632. genericItrInterface = itrInterface->ToGenericTypeInstance();
  5633. if (inferVarType)
  5634. {
  5635. varType = genericItrInterface->mGenericTypeInfo->mTypeGenericArguments[0];
  5636. if (isRefExpression)
  5637. {
  5638. if (varType->IsPointer())
  5639. varType = CreateRefType(varType->GetUnderlyingType());
  5640. }
  5641. }
  5642. }
  5643. };
  5644. auto enumeratorTypeInst = itr.mType->ToTypeInstance();
  5645. while (enumeratorTypeInst != NULL)
  5646. {
  5647. PopulateType(enumeratorTypeInst, Beefy::BfPopulateType_Interfaces_All);
  5648. for (auto& interfaceRef : enumeratorTypeInst->mInterfaces)
  5649. {
  5650. BfTypeInstance* interface = interfaceRef.mInterfaceType;
  5651. _CheckInterface(interface);
  5652. }
  5653. if (enumeratorTypeInst->IsInstanceOf(isRefExpression ? mCompiler->mGenericIRefEnumeratorTypeDef : mCompiler->mGenericIEnumeratorTypeDef))
  5654. {
  5655. itrInterface = enumeratorTypeInst;
  5656. genericItrInterface = itrInterface->ToGenericTypeInstance();
  5657. if (inferVarType)
  5658. {
  5659. varType = genericItrInterface->mGenericTypeInfo->mTypeGenericArguments[0];
  5660. if (isRefExpression)
  5661. {
  5662. if (varType->IsPointer())
  5663. varType = CreateRefType(varType);
  5664. }
  5665. }
  5666. break;
  5667. }
  5668. if (itrInterface != NULL)
  5669. break;
  5670. enumeratorTypeInst = enumeratorTypeInst->mBaseType;
  5671. }
  5672. if ((genericItrInterface == NULL) && (genericParamInst != NULL))
  5673. {
  5674. for (auto interface : genericParamInst->mInterfaceConstraints)
  5675. _CheckInterface(interface);
  5676. }
  5677. if (genericItrInterface == NULL)
  5678. {
  5679. if (!hadGetEnumeratorType)
  5680. {
  5681. Fail(StrFormat("Type '%s' must contain a 'GetEnumerator' method or implement an IEnumerator<T> interface", TypeToString(target.mType).c_str()), forEachStmt->mCollectionExpression);
  5682. }
  5683. else
  5684. Fail(StrFormat("Enumerator type '%s' must implement an %s<T> interface", TypeToString(itr.mType).c_str(), isRefExpression ? "IRefEnumerator" : "IEnumerator"), forEachStmt->mCollectionExpression);
  5685. itrInterface = NULL;
  5686. itr = BfTypedValue();
  5687. }
  5688. else
  5689. {
  5690. itrInterface = genericItrInterface;
  5691. if (isRefExpression)
  5692. {
  5693. refItrInterface = itrInterface;
  5694. PopulateType(refItrInterface);
  5695. // Must IRefEnumeratorf<T> must include only IEnumerator<T>
  5696. // BF_ASSERT(refItrInterface->mInterfaces.size() == 1);
  5697. // if (refItrInterface->mInterfaces.size() == 1)
  5698. // itrInterface = refItrInterface->mInterfaces[0].mInterfaceType;
  5699. }
  5700. itr = MakeAddressable(itr);
  5701. itr = RemoveReadOnly(itr);
  5702. }
  5703. }
  5704. }
  5705. else
  5706. {
  5707. AssertErrorState();
  5708. }
  5709. PopulateType(varType, BfPopulateType_Data);
  5710. // Apply deferred local assign to mEmbeddedStatement and itrStmt
  5711. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  5712. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  5713. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  5714. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  5715. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites);
  5716. if ((target.mType->IsSizedArray()) && (((BfSizedArrayType*)target.mType)->mElementCount == 0))
  5717. {
  5718. EmitEnsureInstructionAt();
  5719. mBfIRBuilder->mIgnoreWrites = true;
  5720. }
  5721. BfIdentifierNode* nameNode = NULL;
  5722. String variableName;
  5723. struct _TupleBind
  5724. {
  5725. BfIdentifierNode* mNameNode;
  5726. String mName;
  5727. BfType* mType;
  5728. BfLocalVariable* mVariable;
  5729. };
  5730. Array<_TupleBind> tupleBinds;
  5731. if (forEachStmt->mVariableName != NULL)
  5732. {
  5733. if (auto tupleExpr = BfNodeDynCast<BfTupleExpression>(forEachStmt->mVariableName))
  5734. {
  5735. CheckTupleVariableDeclaration(tupleExpr, varType);
  5736. if (varType->IsTuple())
  5737. {
  5738. auto tupleType = (BfTypeInstance*)varType;
  5739. for (int idx = 0; idx < BF_MIN((int)tupleExpr->mValues.size(), (int)tupleType->mFieldInstances.size()); idx++)
  5740. {
  5741. auto nameNode = tupleExpr->mValues[idx];
  5742. _TupleBind tupleBind;
  5743. tupleBind.mNameNode = BfNodeDynCast<BfIdentifierNode>(nameNode);
  5744. if ((tupleBind.mNameNode == NULL) && (nameNode != NULL))
  5745. {
  5746. Fail("Variable name expected", nameNode);
  5747. }
  5748. tupleBind.mName = nameNode->ToString();
  5749. tupleBind.mType = tupleType->mFieldInstances[idx].mResolvedType;
  5750. tupleBind.mVariable = NULL;
  5751. tupleBinds.Add(tupleBind);
  5752. if (idx == 0)
  5753. variableName = tupleBind.mName;
  5754. }
  5755. }
  5756. }
  5757. else
  5758. {
  5759. nameNode = BfNodeDynCast<BfIdentifierNode>(forEachStmt->mVariableName);
  5760. if (nameNode != NULL)
  5761. variableName = nameNode->ToString();
  5762. }
  5763. }
  5764. if (variableName.IsEmpty())
  5765. variableName = "_";
  5766. BfModuleMethodInstance getNextMethodInst;
  5767. BfType* nextEmbeddedType = NULL;
  5768. BfTypedValue nextResult;
  5769. if ((refItrInterface) || (itrInterface))
  5770. {
  5771. if (isRefExpression)
  5772. {
  5773. PopulateType(refItrInterface, BfPopulateType_Full_Force);
  5774. getNextMethodInst = GetMethodByName(refItrInterface, "GetNextRef");
  5775. }
  5776. else
  5777. {
  5778. PopulateType(itrInterface, BfPopulateType_Full_Force);
  5779. getNextMethodInst = GetMethodByName(itrInterface, "GetNext");
  5780. }
  5781. if (getNextMethodInst)
  5782. {
  5783. nextResult = BfTypedValue(CreateAlloca(getNextMethodInst.mMethodInstance->mReturnType), getNextMethodInst.mMethodInstance->mReturnType, true);
  5784. if (nextResult.mType->IsGenericTypeInstance())
  5785. {
  5786. nextEmbeddedType = ((BfTypeInstance*)nextResult.mType)->mGenericTypeInfo->mTypeGenericArguments[0];
  5787. }
  5788. }
  5789. else
  5790. {
  5791. InternalError("Failed to find GetNext");
  5792. }
  5793. }
  5794. if (nextEmbeddedType == NULL)
  5795. nextEmbeddedType = GetPrimitiveType(BfTypeCode_Var);
  5796. BfLocalVariable* itrLocalDef = NULL;
  5797. // Iterator local def
  5798. if (itr)
  5799. {
  5800. BfLocalVariable* localDef = new BfLocalVariable();
  5801. itrLocalDef = localDef;
  5802. localDef->mNameNode = nameNode;
  5803. localDef->mName = variableName;
  5804. localDef->mResolvedType = itr.mType;
  5805. localDef->mAddr = itr.mValue;
  5806. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  5807. localDef->mReadFromId = 0;
  5808. localDef->Init();
  5809. UpdateSrcPos(forEachStmt);
  5810. CheckVariableDef(localDef);
  5811. AddLocalVariableDef(localDef, true);
  5812. }
  5813. BfIRValue varInst;
  5814. BfTypedValue varTypedVal;
  5815. bool needsValCopy = true;
  5816. // Local variable
  5817. {
  5818. if (!tupleBinds.IsEmpty())
  5819. {
  5820. BF_ASSERT(varType->IsTuple());
  5821. auto tupleType = (BfTypeInstance*)varType;
  5822. // Tuple binds
  5823. needsValCopy = false;
  5824. if (!nextResult)
  5825. {
  5826. varInst = CreateAlloca(varType);
  5827. varTypedVal = BfTypedValue(varInst, varType, true);
  5828. }
  5829. // Local
  5830. for (int idx = 0; idx < (int)tupleBinds.size(); idx++)
  5831. {
  5832. auto& tupleBind = tupleBinds[idx];
  5833. BfLocalVariable* localDef = new BfLocalVariable();
  5834. localDef->mNameNode = tupleBind.mNameNode;
  5835. localDef->mName = tupleBind.mName;
  5836. localDef->mResolvedType = tupleBind.mType;
  5837. if (!needsValCopy)
  5838. localDef->mResolvedType = CreateRefType(localDef->mResolvedType);
  5839. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  5840. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  5841. localDef->mReadFromId = 0;
  5842. if ((isLet) || (forEachStmt->mReadOnlyToken != NULL))
  5843. localDef->mIsReadOnly = true;
  5844. localDef->Init();
  5845. auto fieldInstance = &tupleType->mFieldInstances[idx];
  5846. if (fieldInstance->mDataIdx >= 0)
  5847. {
  5848. auto tuplePtrType = CreatePointerType(varType);
  5849. BfIRValue tuplePtr;
  5850. if (nextResult)
  5851. tuplePtr = mBfIRBuilder->CreateBitCast(nextResult.mValue, mBfIRBuilder->MapType(tuplePtrType));
  5852. else
  5853. tuplePtr = mBfIRBuilder->CreateBitCast(varInst, mBfIRBuilder->MapType(tuplePtrType));
  5854. auto valAddr = mBfIRBuilder->CreateInBoundsGEP(tuplePtr, 0, fieldInstance->mDataIdx);
  5855. mBfIRBuilder->CreateAlignedStore(valAddr, localDef->mAddr, localDef->mResolvedType->mAlign);
  5856. }
  5857. UpdateSrcPos(forEachStmt);
  5858. if ((itrLocalDef != NULL) && (idx == 0))
  5859. {
  5860. localDef->mLocalVarId = itrLocalDef->mLocalVarId;
  5861. localDef->mIsShadow = true;
  5862. }
  5863. else
  5864. {
  5865. CheckVariableDef(localDef);
  5866. }
  5867. AddLocalVariableDef(localDef, true, false, BfIRValue(), BfIRInitType_NotNeeded_AliveOnDecl);
  5868. }
  5869. }
  5870. else
  5871. {
  5872. // Normal case
  5873. if ((nextResult) && (varType->IsComposite()) && (!varType->IsValuelessType()) && (!isRefExpression))
  5874. {
  5875. needsValCopy = false;
  5876. varType = CreateRefType(varType);
  5877. }
  5878. // Local
  5879. BfLocalVariable* localDef = new BfLocalVariable();
  5880. localDef->mNameNode = nameNode;
  5881. localDef->mName = variableName;
  5882. localDef->mResolvedType = varType;
  5883. if (!varType->IsValuelessType())
  5884. varInst = CreateAlloca(varType);
  5885. else
  5886. varInst = mBfIRBuilder->GetFakeVal();
  5887. localDef->mAddr = varInst;
  5888. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  5889. localDef->mReadFromId = 0;
  5890. if ((isLet) || (forEachStmt->mReadOnlyToken != NULL))
  5891. localDef->mIsReadOnly = true;
  5892. localDef->Init();
  5893. if (!needsValCopy)
  5894. {
  5895. auto valAddr = mBfIRBuilder->CreateBitCast(nextResult.mValue, mBfIRBuilder->MapType(varType));
  5896. mBfIRBuilder->CreateAlignedStore(valAddr, varInst, varType->mAlign);
  5897. }
  5898. UpdateSrcPos(forEachStmt);
  5899. if (itrLocalDef != NULL)
  5900. {
  5901. localDef->mLocalVarId = itrLocalDef->mLocalVarId;
  5902. localDef->mIsShadow = true;
  5903. }
  5904. else
  5905. {
  5906. CheckVariableDef(localDef);
  5907. }
  5908. AddLocalVariableDef(localDef, true, false, BfIRValue(), BfIRInitType_NotNeeded_AliveOnDecl);
  5909. varTypedVal = BfTypedValue(varInst, varType, true);
  5910. }
  5911. }
  5912. // Iterator
  5913. if (itr)
  5914. {
  5915. if ((!isArray) && (!isSizedArray))
  5916. {
  5917. BfFunctionBindResult functionBindResult;
  5918. BfExprEvaluator exprEvaluator(this);
  5919. exprEvaluator.mFunctionBindResult = &functionBindResult;
  5920. // Allow for "Dispose" not to exist
  5921. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  5922. BfResolvedArgs resolvedArgs;
  5923. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete);
  5924. exprEvaluator.MatchMethod(forEachStmt->mCollectionExpression, NULL, itr, false, false, "Dispose", resolvedArgs, BfMethodGenericArguments());
  5925. if (functionBindResult.mMethodInstance != NULL)
  5926. {
  5927. BfModuleMethodInstance moduleMethodInstance;
  5928. moduleMethodInstance = BfModuleMethodInstance(functionBindResult.mMethodInstance, functionBindResult.mFunc);
  5929. AddDeferredCall(moduleMethodInstance, functionBindResult.mIRArgs, mCurMethodState->mCurScope);
  5930. }
  5931. }
  5932. }
  5933. BfScopeData innerScopeData;
  5934. if (forEachStmt->mLabelNode != NULL)
  5935. innerScopeData.mLabelNode = forEachStmt->mLabelNode->mLabel;
  5936. innerScopeData.mValueScopeStart = ValueScopeStart();
  5937. mCurMethodState->AddScope(&innerScopeData);
  5938. NewScopeState(true, false);
  5939. innerScopeData.mIsLoop = true;
  5940. if ((autoComplete != NULL) && (forEachStmt->mVariableTypeRef != NULL))
  5941. autoComplete->CheckVarResolution(forEachStmt->mVariableTypeRef, varType);
  5942. if (isArray || isSizedArray)
  5943. mBfIRBuilder->CreateAlignedStore(GetConstValue(0), itr.mValue, itr.mType->mAlign);
  5944. auto valueScopeStartInner = ValueScopeStart();
  5945. // We may have a call in the loop body
  5946. mCurMethodState->mMayNeedThisAccessCheck = true;
  5947. auto condBB = mBfIRBuilder->CreateBlock("foreach.cond", true);
  5948. auto bodyBB = mBfIRBuilder->CreateBlock("foreach.body");
  5949. auto incBB = mBfIRBuilder->CreateBlock("foreach.inc");
  5950. auto endBB = mBfIRBuilder->CreateBlock("foreach.end");
  5951. BfBreakData breakData;
  5952. breakData.mIRContinueBlock = incBB;
  5953. breakData.mIRBreakBlock = endBB;
  5954. breakData.mScope = &innerScopeData;
  5955. breakData.mInnerValueScopeStart = valueScopeStartInner;
  5956. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  5957. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  5958. mBfIRBuilder->CreateBr(condBB);
  5959. mBfIRBuilder->SetInsertPoint(condBB);
  5960. if (forEachStmt->mCollectionExpression != NULL)
  5961. UpdateExprSrcPos(forEachStmt->mCollectionExpression);
  5962. BfIRValue conditionValue;
  5963. if (isSizedArray) // if (i < lengthof(array)
  5964. {
  5965. auto itrVal = mBfIRBuilder->CreateLoad(itr.mValue);
  5966. auto arrayType = (BfSizedArrayType*)target.mType;
  5967. PopulateType(arrayType, BfPopulateType_DataAndMethods);
  5968. BfIRValue lengthVal = GetConstValue(arrayType->mElementCount);
  5969. conditionValue = mBfIRBuilder->CreateCmpLT(itrVal, lengthVal, true);
  5970. mBfIRBuilder->CreateCondBr(conditionValue, bodyBB, endBB);
  5971. ValueScopeEnd(valueScopeStartInner);
  5972. }
  5973. else if (isArray) // if (i < array.mLength)
  5974. {
  5975. auto itrVal = mBfIRBuilder->CreateAlignedLoad(itr.mValue, itr.mType->mAlign);
  5976. auto arrayType = (BfArrayType*)target.mType;
  5977. PopulateType(arrayType);
  5978. auto arrayBaseValue = mBfIRBuilder->CreateBitCast(target.mValue, mBfIRBuilder->MapType(arrayType->mBaseType, BfIRPopulateType_Full));
  5979. int getLengthBitCount = arrayType->GetLengthBitCount();
  5980. BfIRValue lengthVal;
  5981. if (arrayType->mBaseType->mTypeFailed)
  5982. {
  5983. AssertErrorState();
  5984. if (getLengthBitCount == 64)
  5985. lengthVal = GetConstValue64(0);
  5986. else
  5987. lengthVal = GetConstValue32(0);
  5988. }
  5989. else
  5990. {
  5991. auto fieldInst = GetFieldInstance(arrayType->mBaseType, 0, "mLength");
  5992. if (fieldInst != NULL)
  5993. {
  5994. auto lengthValAddr = mBfIRBuilder->CreateInBoundsGEP(arrayBaseValue, 0, fieldInst->mDataIdx);
  5995. lengthVal = mBfIRBuilder->CreateAlignedLoad(lengthValAddr, fieldInst->mResolvedType->mAlign);
  5996. }
  5997. }
  5998. lengthVal = mBfIRBuilder->CreateNumericCast(lengthVal, true, BfTypeCode_IntPtr);
  5999. conditionValue = mBfIRBuilder->CreateCmpLT(itrVal, lengthVal, true);
  6000. mBfIRBuilder->CreateCondBr(conditionValue, bodyBB, endBB);
  6001. ValueScopeEnd(valueScopeStartInner);
  6002. }
  6003. else // if (itr.MoveNext())
  6004. {
  6005. if (!itr)
  6006. {
  6007. if (!isVarEnumerator)
  6008. AssertErrorState();
  6009. mBfIRBuilder->CreateBr(endBB);
  6010. }
  6011. else
  6012. {
  6013. BfExprEvaluator exprEvaluator(this);
  6014. auto itrTypeInstance = itr.mType->ToTypeInstance();
  6015. SizedArray<BfResolvedArg, 0> resolvedArgs;
  6016. BfMethodMatcher methodMatcher(forEachStmt->mCollectionExpression, this, getNextMethodInst.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  6017. if (isRefExpression)
  6018. methodMatcher.CheckType(refItrInterface, itr, false);
  6019. else
  6020. methodMatcher.CheckType(itrInterface, itr, false);
  6021. methodMatcher.TryDevirtualizeCall(itr);
  6022. exprEvaluator.mReceivingValue = &nextResult;
  6023. auto retVal = exprEvaluator.CreateCall(&methodMatcher, itr);
  6024. if (exprEvaluator.mReceivingValue != NULL)
  6025. {
  6026. if (mIsComptimeModule)
  6027. {
  6028. retVal = LoadValue(retVal);
  6029. mBfIRBuilder->CreateStore(retVal.mValue, nextResult.mValue);
  6030. }
  6031. else
  6032. AssertErrorState();
  6033. }
  6034. if ((retVal) && (!retVal.mType->IsVar()))
  6035. {
  6036. auto i8Result = ExtractValue(nextResult, NULL, 2);
  6037. i8Result = LoadValue(i8Result);
  6038. BF_ASSERT(i8Result.mType == GetPrimitiveType(BfTypeCode_Int8));
  6039. conditionValue = mBfIRBuilder->CreateCmpEQ(i8Result.mValue, GetConstValue8(0));
  6040. }
  6041. else
  6042. conditionValue = GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean));
  6043. mBfIRBuilder->CreateCondBr(conditionValue, bodyBB, endBB);
  6044. ValueScopeEnd(valueScopeStartInner);
  6045. }
  6046. }
  6047. mBfIRBuilder->AddBlock(bodyBB);
  6048. mBfIRBuilder->SetInsertPoint(bodyBB);
  6049. if (!varTypedVal)
  6050. {
  6051. // Nothing to do...
  6052. }
  6053. else if (isSizedArray) // val = array[i]
  6054. {
  6055. auto itrVal = mBfIRBuilder->CreateLoad(itr.mValue);
  6056. auto arrayType = (BfSizedArrayType*)target.mType;
  6057. BfType* ptrType = CreatePointerType(arrayType->mElementType);
  6058. BfTypedValue arrayItem;
  6059. if (arrayType->mElementType->IsValuelessType())
  6060. {
  6061. arrayItem = GetDefaultTypedValue(arrayType->mElementType);
  6062. }
  6063. else
  6064. {
  6065. target = MakeAddressable(target);
  6066. arrayItem = BfTypedValue(CreateIndexedValue(arrayType->mElementType, target.mValue, itrVal, true), arrayType->mElementType, true);
  6067. if (isRefExpression)
  6068. arrayItem = BfTypedValue(arrayItem.mValue, CreateRefType(arrayItem.mType));
  6069. }
  6070. arrayItem = Cast(forEachStmt->mCollectionExpression, arrayItem, varType, BfCastFlags_Explicit);
  6071. if ((arrayItem) && (!arrayItem.mValue.IsFake()))
  6072. {
  6073. arrayItem = LoadValue(arrayItem);
  6074. if (arrayItem)
  6075. mBfIRBuilder->CreateStore(arrayItem.mValue, varInst);
  6076. }
  6077. }
  6078. else if (isArray) // val = array[i]
  6079. {
  6080. auto itrVal = mBfIRBuilder->CreateLoad(itr.mValue);
  6081. BfTypedValueExpression typedValueExpr;
  6082. typedValueExpr.Init(BfTypedValue(itrVal, itrType));
  6083. BfExprEvaluator exprEvaluator(this);
  6084. SizedArray<BfExpression*, 1> indices;
  6085. indices.push_back(&typedValueExpr);
  6086. BfSizedArray<BfExpression*> sizedArgExprs(indices);
  6087. BfResolvedArgs argValues(&sizedArgExprs);
  6088. exprEvaluator.ResolveArgValues(argValues);
  6089. bool boundsCheck = mCompiler->mOptions.mRuntimeChecks;
  6090. auto typeOptions = GetTypeOptions();
  6091. if (typeOptions != NULL)
  6092. boundsCheck = typeOptions->Apply(boundsCheck, BfOptionFlags_RuntimeChecks);
  6093. BfMethodMatcher methodMatcher(forEachStmt->mVariableName, this, "get__", argValues.mResolvedArgs, BfMethodGenericArguments());
  6094. methodMatcher.mMethodType = BfMethodType_PropertyGetter;
  6095. methodMatcher.CheckType(target.mType->ToTypeInstance(), target, false);
  6096. if (methodMatcher.mBestMethodDef == NULL)
  6097. {
  6098. Fail("Failed to find indexer method in array", forEachStmt);
  6099. }
  6100. else
  6101. {
  6102. methodMatcher.mCheckedKind = boundsCheck ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  6103. BfTypedValue arrayItem = exprEvaluator.CreateCall(&methodMatcher, target);
  6104. if ((varInst) && (arrayItem))
  6105. {
  6106. if (isRefExpression)
  6107. arrayItem = BfTypedValue(arrayItem.mValue, CreateRefType(arrayItem.mType));
  6108. else if (!arrayItem.mType->IsComposite())
  6109. arrayItem = LoadValue(arrayItem);
  6110. arrayItem = Cast(forEachStmt->mCollectionExpression, arrayItem, varType, BfCastFlags_Explicit);
  6111. arrayItem = LoadValue(arrayItem);
  6112. if (arrayItem)
  6113. mBfIRBuilder->CreateStore(arrayItem.mValue, varInst);
  6114. }
  6115. }
  6116. }
  6117. else
  6118. {
  6119. if (!itr)
  6120. {
  6121. if (!isVarEnumerator)
  6122. AssertErrorState();
  6123. }
  6124. else if (mCompiler->IsAutocomplete())
  6125. {
  6126. // If we don't do this shortcut, we can end up creating temporary "boxed" objects
  6127. }
  6128. else
  6129. {
  6130. if (needsValCopy)
  6131. {
  6132. auto nextVal = BfTypedValue(mBfIRBuilder->CreateBitCast(nextResult.mValue, mBfIRBuilder->MapType(CreatePointerType(nextEmbeddedType))), nextEmbeddedType, true);
  6133. if (isRefExpression)
  6134. {
  6135. if (nextVal.mType->IsPointer())
  6136. nextVal = BfTypedValue(nextVal.mValue, CreateRefType(nextVal.mType->GetUnderlyingType()), true);
  6137. }
  6138. nextVal = Cast(forEachStmt->mCollectionExpression, nextVal, varType, BfCastFlags_Explicit);
  6139. nextVal = LoadValue(nextVal);
  6140. if ((nextVal) && (!nextVal.mType->IsValuelessType()))
  6141. mBfIRBuilder->CreateAlignedStore(nextVal.mValue, varInst, nextVal.mType->mAlign);
  6142. }
  6143. }
  6144. }
  6145. if (forEachStmt->mEmbeddedStatement != NULL)
  6146. {
  6147. VisitEmbeddedStatement(forEachStmt->mEmbeddedStatement);
  6148. }
  6149. if (!mCurMethodState->mLeftBlockUncond)
  6150. {
  6151. ValueScopeEnd(valueScopeStartInner);
  6152. mBfIRBuilder->CreateBr(incBB);
  6153. }
  6154. mBfIRBuilder->AddBlock(incBB);
  6155. mBfIRBuilder->SetInsertPoint(incBB);
  6156. if (isArray || isSizedArray)
  6157. {
  6158. auto val = mBfIRBuilder->CreateLoad(itr.mValue);
  6159. auto result = mBfIRBuilder->CreateAdd(val, GetConstValue(1));
  6160. mBfIRBuilder->CreateStore(result, itr.mValue);
  6161. }
  6162. else
  6163. {
  6164. // Nothing to do
  6165. }
  6166. mBfIRBuilder->CreateBr(condBB);
  6167. mBfIRBuilder->AddBlock(endBB);
  6168. mBfIRBuilder->SetInsertPoint(endBB);
  6169. if ((itrLocalDef != NULL) && (itrLocalDef->mDbgVarInst) && (IsTargetingBeefBackend()))
  6170. {
  6171. // If this shadows another enumerator variable then we need to explicitly mark the end of this one
  6172. mBfIRBuilder->DbgLifetimeEnd(itrLocalDef->mDbgVarInst);
  6173. }
  6174. // The 'return' may have been inside the block, which may not have been entered if preconditions were not met
  6175. mCurMethodState->SetHadReturn(false);
  6176. mCurMethodState->mLeftBlockUncond = false;
  6177. mCurMethodState->mLeftBlockCond = false;
  6178. RestoreScopeState();
  6179. RestoreScopeState();
  6180. }
  6181. void BfModule::Visit(BfDeferStatement* deferStmt)
  6182. {
  6183. if (deferStmt->mTargetNode == NULL)
  6184. {
  6185. AssertErrorState();
  6186. return;
  6187. }
  6188. //TODO: Why in the world didn't we want to be able to step onto a defer statement?
  6189. // We only want the breakpoint to hit on execution of the defer, not on insertion of it
  6190. //SetAndRestoreValue<bool> prevSetIllegalSrcPos(mSetIllegalSrcPosition, true);
  6191. UpdateSrcPos(deferStmt);
  6192. EmitEnsureInstructionAt();
  6193. BfScopeData* scope = NULL;
  6194. if (deferStmt->mScopeToken != NULL)
  6195. {
  6196. if (deferStmt->mScopeToken->GetToken() == BfToken_Scope)
  6197. scope = mCurMethodState->mCurScope->GetTargetable();
  6198. else
  6199. scope = &mCurMethodState->mHeadScope;
  6200. }
  6201. else if (deferStmt->mScopeName != NULL)
  6202. scope = FindScope(deferStmt->mScopeName, true);
  6203. else
  6204. scope = mCurMethodState->mCurScope;
  6205. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  6206. {
  6207. auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(deferStmt->mScopeName);
  6208. if ((deferStmt->mScopeName == NULL) || (targetIdentifier != NULL))
  6209. mCompiler->mResolvePassData->mAutoComplete->CheckLabel(targetIdentifier, deferStmt->mColonToken, scope);
  6210. }
  6211. if ((scope == mCurMethodState->mCurScope) && (scope->mCloseNode == NULL))
  6212. {
  6213. auto parser = deferStmt->GetParser();
  6214. if ((parser == NULL) || (!parser->mIsEmitted))
  6215. Warn(0, "This defer will immediately execute. Consider specifying a wider scope target such as 'defer::'", deferStmt->mDeferToken);
  6216. }
  6217. if (auto block = BfNodeDynCast<BfBlock>(deferStmt->mTargetNode))
  6218. {
  6219. if (deferStmt->mBind != NULL)
  6220. {
  6221. Array<BfDeferredCapture> captures;
  6222. for (auto identifier : deferStmt->mBind->mParams)
  6223. {
  6224. BfDeferredCapture deferredCapture;
  6225. deferredCapture.mName = identifier->ToString();
  6226. deferredCapture.mValue = CreateValueFromExpression(identifier);
  6227. if (deferredCapture.mValue)
  6228. {
  6229. captures.push_back(deferredCapture);
  6230. }
  6231. }
  6232. AddDeferredBlock(block, scope, &captures);
  6233. }
  6234. else
  6235. AddDeferredBlock(block, scope);
  6236. }
  6237. else if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(deferStmt->mTargetNode))
  6238. {
  6239. BfExprEvaluator expressionEvaluator(this);
  6240. expressionEvaluator.mDeferCallRef = exprStmt->mExpression;
  6241. expressionEvaluator.mDeferScopeAlloc = scope;
  6242. expressionEvaluator.VisitChild(exprStmt->mExpression);
  6243. if (mCurMethodState->mPendingNullConditional != NULL)
  6244. FlushNullConditional(expressionEvaluator.mResult, true);
  6245. }
  6246. else if (auto deleteStmt = BfNodeDynCast<BfDeleteStatement>(deferStmt->mTargetNode))
  6247. {
  6248. if (deleteStmt->mExpression == NULL)
  6249. {
  6250. AssertErrorState();
  6251. return;
  6252. }
  6253. auto val = CreateValueFromExpression(deleteStmt->mExpression);
  6254. if (!val)
  6255. return;
  6256. if (mCompiler->IsAutocomplete())
  6257. return;
  6258. bool isGenericParam = false;
  6259. auto checkType = val.mType;
  6260. if (val.mType->IsGenericParam())
  6261. {
  6262. isGenericParam = true;
  6263. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)val.mType);
  6264. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete)
  6265. return;
  6266. if (genericParamInst->mTypeConstraint != NULL)
  6267. checkType = genericParamInst->mTypeConstraint;
  6268. }
  6269. bool isAppendDelete = false;
  6270. BfTypedValue customAllocator;
  6271. if (deleteStmt->mAllocExpr != NULL)
  6272. {
  6273. if (auto expr = BfNodeDynCast<BfExpression>(deleteStmt->mAllocExpr))
  6274. customAllocator = CreateValueFromExpression(expr);
  6275. else if (auto tokenNode = BfNodeDynCast<BfTokenNode>(deleteStmt->mAllocExpr))
  6276. {
  6277. if (tokenNode->mToken == BfToken_Append)
  6278. isAppendDelete = true;
  6279. }
  6280. }
  6281. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  6282. PopulateType(checkType);
  6283. if (checkType->IsVar())
  6284. return;
  6285. if ((!checkType->IsObjectOrInterface()) && (!checkType->IsPointer()))
  6286. {
  6287. VisitChild(deferStmt->mTargetNode);
  6288. Fail(StrFormat("Cannot delete a value of type '%s'", TypeToString(val.mType).c_str()), deferStmt->mTargetNode);
  6289. return;
  6290. }
  6291. if (isGenericParam)
  6292. return;
  6293. bool isDtorOnly = false;
  6294. if (customAllocator.mType == GetPrimitiveType(BfTypeCode_NullPtr))
  6295. {
  6296. if (!checkType->IsObjectOrInterface())
  6297. Warn(0, "Type '%' has no destructor, so delete:null has no effect", deleteStmt->mExpression);
  6298. }
  6299. else if (customAllocator)
  6300. {
  6301. BfFunctionBindResult functionBindResult;
  6302. functionBindResult.mWantsArgs = true;
  6303. auto customAllocTypeInst = customAllocator.mType->ToTypeInstance();
  6304. if ((checkType->IsObjectOrInterface()) && (customAllocTypeInst != NULL) && (customAllocTypeInst->mTypeDef->GetMethodByName("FreeObject") != NULL))
  6305. {
  6306. BfTypedValueExpression typedValueExpr;
  6307. typedValueExpr.Init(val);
  6308. typedValueExpr.mRefNode = deleteStmt->mAllocExpr;
  6309. BfExprEvaluator exprEvaluator(this);
  6310. SizedArray<BfExpression*, 2> argExprs;
  6311. argExprs.push_back(&typedValueExpr);
  6312. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6313. BfResolvedArgs argValues(&sizedArgExprs);
  6314. exprEvaluator.ResolveArgValues(argValues);
  6315. exprEvaluator.mNoBind = true;
  6316. exprEvaluator.mFunctionBindResult = &functionBindResult;
  6317. exprEvaluator.MatchMethod(deleteStmt->mAllocExpr, NULL, customAllocator, false, false, "FreeObject", argValues, BfMethodGenericArguments());
  6318. }
  6319. else
  6320. {
  6321. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  6322. auto ptrValue = BfTypedValue(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(voidPtrType)), voidPtrType);
  6323. BfTypedValueExpression typedValueExpr;
  6324. typedValueExpr.Init(ptrValue);
  6325. BfExprEvaluator exprEvaluator(this);
  6326. SizedArray<BfExpression*, 2> argExprs;
  6327. argExprs.push_back(&typedValueExpr);
  6328. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6329. BfResolvedArgs argValues(&sizedArgExprs);
  6330. exprEvaluator.ResolveArgValues(argValues);
  6331. exprEvaluator.mNoBind = true;
  6332. exprEvaluator.mFunctionBindResult = &functionBindResult;
  6333. exprEvaluator.MatchMethod(deleteStmt->mAllocExpr, NULL, customAllocator, false, false, "Free", argValues, BfMethodGenericArguments());
  6334. }
  6335. if (functionBindResult.mMethodInstance != NULL)
  6336. {
  6337. AddDeferredCall(BfModuleMethodInstance(functionBindResult.mMethodInstance, functionBindResult.mFunc), functionBindResult.mIRArgs, scope, deleteStmt, true);
  6338. }
  6339. }
  6340. if (checkType->IsObjectOrInterface())
  6341. {
  6342. auto objectType = mContext->mBfObjectType;
  6343. PopulateType(objectType);
  6344. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  6345. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  6346. SizedArray<BfIRValue, 1> llvmArgs;
  6347. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  6348. if (!customAllocator)
  6349. {
  6350. if ((mCompiler->mOptions.mEnableRealtimeLeakCheck) && (!mIsComptimeModule))
  6351. {
  6352. auto moduleMethodInstance = GetInternalMethod("Dbg_MarkObjectDeleted");
  6353. AddDeferredCall(moduleMethodInstance, llvmArgs, scope, deleteStmt, false, true);
  6354. }
  6355. else
  6356. {
  6357. auto moduleMethodInstance = GetInternalMethod("Free");
  6358. SizedArray<BfIRValue, 1> llvmArgs;
  6359. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr)));
  6360. AddDeferredCall(moduleMethodInstance, llvmArgs, scope, deleteStmt, false, true);
  6361. }
  6362. }
  6363. auto moduleMethodInstance = GetMethodInstance(objectType, methodInstance->mMethodDef, BfTypeVector());
  6364. AddDeferredCall(moduleMethodInstance, llvmArgs, scope, deleteStmt, false, true);
  6365. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  6366. {
  6367. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), (deleteStmt->mTargetTypeToken != NULL) ? "Dbg_ObjectPreCustomDelete" : "Dbg_ObjectPreDelete");
  6368. AddDeferredCall(moduleMethodInstance, llvmArgs, scope, deleteStmt, false, true);
  6369. }
  6370. }
  6371. else
  6372. {
  6373. if ((!customAllocator) && (!isAppendDelete))
  6374. {
  6375. val = LoadValue(val);
  6376. BfModuleMethodInstance moduleMethodInstance;
  6377. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6378. moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), "Dbg_RawFree");
  6379. else
  6380. moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), "Free");
  6381. SizedArray<BfIRValue, 1> llvmArgs;
  6382. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr)));
  6383. AddDeferredCall(moduleMethodInstance, llvmArgs, scope, deleteStmt, false, true);
  6384. }
  6385. }
  6386. }
  6387. else
  6388. {
  6389. AssertErrorState();
  6390. VisitChild(deferStmt->mTargetNode);
  6391. }
  6392. }
  6393. void BfModule::Visit(BfBlock* block)
  6394. {
  6395. VisitEmbeddedStatement(block);
  6396. }
  6397. void BfModule::Visit(BfUnscopedBlock* block)
  6398. {
  6399. VisitEmbeddedStatement(block, NULL, BfEmbeddedStatementFlags_Unscoped);
  6400. }
  6401. void BfModule::Visit(BfLabeledBlock* labeledBlock)
  6402. {
  6403. VisitEmbeddedStatement(labeledBlock);
  6404. }
  6405. void BfModule::Visit(BfRootNode* rootNode)
  6406. {
  6407. VisitMembers(rootNode);
  6408. }
  6409. void BfModule::Visit(BfInlineAsmStatement* asmStmt)
  6410. {
  6411. #if 0
  6412. enum RegClobberFlags //CDH TODO add support for mmx/xmm/fpst etc (how are these signified in LLVM? check LangRef inline asm docs clobber list info)
  6413. {
  6414. // please keep eax through edx in alphabetical order (grep $BYTEREGS for why)
  6415. REGCLOBBERF_EAX = (1 << 0),
  6416. REGCLOBBERF_EBX = (1 << 1),
  6417. REGCLOBBERF_ECX = (1 << 2),
  6418. REGCLOBBERF_EDX = (1 << 3),
  6419. REGCLOBBERF_ESI = (1 << 4),
  6420. REGCLOBBERF_EDI = (1 << 5),
  6421. REGCLOBBERF_ESP = (1 << 6),
  6422. REGCLOBBERF_EBP = (1 << 7),
  6423. REGCLOBBERF_XMM0 = (1 << 8),
  6424. REGCLOBBERF_XMM1 = (1 << 9),
  6425. REGCLOBBERF_XMM2 = (1 << 10),
  6426. REGCLOBBERF_XMM3 = (1 << 11),
  6427. REGCLOBBERF_XMM4 = (1 << 12),
  6428. REGCLOBBERF_XMM5 = (1 << 13),
  6429. REGCLOBBERF_XMM6 = (1 << 14),
  6430. REGCLOBBERF_XMM7 = (1 << 15),
  6431. REGCLOBBERF_FPST0 = (1 << 16),
  6432. REGCLOBBERF_FPST1 = (1 << 17),
  6433. REGCLOBBERF_FPST2 = (1 << 18),
  6434. REGCLOBBERF_FPST3 = (1 << 19),
  6435. REGCLOBBERF_FPST4 = (1 << 20),
  6436. REGCLOBBERF_FPST5 = (1 << 21),
  6437. REGCLOBBERF_FPST6 = (1 << 22),
  6438. REGCLOBBERF_FPST7 = (1 << 23),
  6439. REGCLOBBERF_MM0 = (1 << 24),
  6440. REGCLOBBERF_MM1 = (1 << 25),
  6441. REGCLOBBERF_MM2 = (1 << 26),
  6442. REGCLOBBERF_MM3 = (1 << 27),
  6443. REGCLOBBERF_MM4 = (1 << 28),
  6444. REGCLOBBERF_MM5 = (1 << 29),
  6445. REGCLOBBERF_MM6 = (1 << 30),
  6446. REGCLOBBERF_MM7 = (1 << 31),
  6447. };
  6448. const char* regClobberNames[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "esp", "ebp", nullptr }; // must be in same order as flags
  6449. unsigned long regClobberFlags = 0;
  6450. std::function<bool(const StringImpl&, bool)> matchRegFunc = [this, &regClobberNames, &regClobberFlags](const StringImpl& name, bool isClobber)
  6451. {
  6452. bool found = false;
  6453. int nameLen = name.length();
  6454. if (nameLen == 3)
  6455. {
  6456. if ((name[0] == 's') && (name[1] == 't') && (name[2] >= '0') && (name[2] <= '7'))
  6457. {
  6458. // st# regs (unparenthesized at this point)
  6459. if (isClobber)
  6460. regClobberFlags |= (REGCLOBBERF_FPST0 << (name[2] - '0'));
  6461. found = true;
  6462. }
  6463. else if ((name[0] == 'm') && (name[1] == 'm') && (name[2] >= '0') && (name[2] <= '7'))
  6464. {
  6465. // mm regs
  6466. if (isClobber)
  6467. regClobberFlags |= (REGCLOBBERF_MM0 << (name[2] - '0'));
  6468. found = true;
  6469. }
  6470. else
  6471. {
  6472. // dword regs
  6473. for (int iRegCheck = 0; regClobberNames[iRegCheck] != nullptr; ++iRegCheck)
  6474. {
  6475. if (!strcmp(name.c_str(), regClobberNames[iRegCheck]))
  6476. {
  6477. if (isClobber)
  6478. regClobberFlags |= (1 << iRegCheck);
  6479. found = true;
  6480. break;
  6481. }
  6482. }
  6483. }
  6484. }
  6485. else if (nameLen == 2)
  6486. {
  6487. // word & byte regs
  6488. for (int iRegCheck = 0; regClobberNames[iRegCheck] != nullptr; ++iRegCheck)
  6489. {
  6490. if (!strcmp(name.c_str(), regClobberNames[iRegCheck] + 1)) // skip leading 'e'
  6491. {
  6492. if (isClobber)
  6493. regClobberFlags |= (1 << iRegCheck);
  6494. found = true;
  6495. break;
  6496. }
  6497. }
  6498. if (!found)
  6499. {
  6500. // check for byte regs for eax through edx (e.g. al, ah, bl, bh....)
  6501. if ((nameLen == 2) && (name[0] >= 'a') && (name[0] <= 'd') && ((name[1] == 'l') || (name[1] == 'h')))
  6502. {
  6503. if (isClobber)
  6504. regClobberFlags |= (1 << (name[0] - 'a'));// $BYTEREGS this is why we want alphabetical order
  6505. found = true;
  6506. }
  6507. }
  6508. }
  6509. else if ((nameLen == 4) && (name[0] == 'x') && (name[1] == 'm') && (name[2] == 'm') && (name[3] >= '0') && (name[3] <= '7'))
  6510. {
  6511. // xmm regs
  6512. if (isClobber)
  6513. regClobberFlags |= (REGCLOBBERF_XMM0 << (name[3] - '0'));
  6514. found = true;
  6515. }
  6516. return found;
  6517. };
  6518. int asmInstCount = (int)asmStmt->mInstructions.size();
  6519. typedef std::map<String, int> StrToVarIndexMap;
  6520. StrToVarIndexMap strToVarIndexMap;
  6521. if (mCompiler->IsAutocomplete())
  6522. {
  6523. // auto-complete "fast-pass" just to eliminate unused/unassigned variable yellow warning flashes
  6524. for (int iInst=0; iInst<asmInstCount; ++iInst)
  6525. {
  6526. auto instNode = asmStmt->mInstructions[iInst];
  6527. BfInlineAsmInstruction::AsmInst& asmInst = instNode->mAsmInst;
  6528. bool hasLabel = !asmInst.mLabel.empty();
  6529. bool hasOpCode = !asmInst.mOpCode.empty();
  6530. if (hasLabel || hasOpCode) // check against blank lines
  6531. {
  6532. if (hasOpCode) // check against label-only lines (which still get written out, but don't do any other processing)
  6533. {
  6534. int argCount = (int)asmInst.mArgs.size();
  6535. for (int iArg=0; iArg<argCount; ++iArg)
  6536. {
  6537. BfInlineAsmInstruction::AsmArg* arg = &asmInst.mArgs[iArg];
  6538. if (arg->mType == BfInlineAsmInstruction::AsmArg::ARGTYPE_IntReg)
  6539. {
  6540. bool found = matchRegFunc(arg->mReg, false);
  6541. if (!found)
  6542. {
  6543. StrToVarIndexMap::iterator it = strToVarIndexMap.find(arg->mReg);
  6544. if (it == strToVarIndexMap.end())
  6545. {
  6546. for (int i = 0; i < (int) mCurMethodState->mLocals.size(); i++)
  6547. {
  6548. auto& checkLocal = mCurMethodState->mLocals[i];
  6549. if (checkLocal.mName == arg->mReg)
  6550. {
  6551. // if you access a variable in asm, we suppress any warnings related to used or assigned, regardless of usage
  6552. checkLocal.mIsReadFrom = true;
  6553. checkLocal.mAssignedKind = BfLocalVarAssignKind_Unconditional;
  6554. found = true;
  6555. break;
  6556. }
  6557. }
  6558. }
  6559. }
  6560. }
  6561. }
  6562. }
  6563. }
  6564. }
  6565. return;
  6566. }
  6567. int debugLocOffset = 0;
  6568. if (!asmStmt->mInstructions.empty())
  6569. debugLocOffset = asmStmt->mInstructions.front()->GetSrcStart() - asmStmt->GetSrcStart();
  6570. UpdateSrcPos(asmStmt, true, debugLocOffset);
  6571. mCurMethodState->mInHeadScope = false;
  6572. BfScopeData prevScope = mCurMethodState->mCurScope;
  6573. mCurMethodState->mCurScope->mPrevScope = &prevScope;
  6574. NewScopeState();
  6575. bool failed = false;
  6576. if (!mCpu)
  6577. mCpu = new Beefy::X86Cpu();
  6578. //const char* srcAsmText = "nop\nnop\n\n\nmov eax, i\ninc eax\nmov i, eax\n_emit 0x0F\n_emit 0xC7\n_emit 0xF0\n\n\nnop\nnop"; //CDH TODO extract from actual lexical text block
  6579. //const char* srcAsmText = "nop\nnop\n\n\nmov eax, i\ninc eax\nmov i, eax\nrdrand eax\n\n\nnop\nnop"; //CDH TODO extract from actual lexical text block
  6580. //String srcAsmTextStr(&asmStmt->mParser->mSrc[asmStmt->mSrcStart], asmStmt->mSrcEnd - asmStmt->mSrcStart);
  6581. //const char* srcAsmText = srcAsmTextStr.c_str();
  6582. String dstAsmText;
  6583. String constraintStr, clobberStr;
  6584. int constraintCount = 0;
  6585. bool hasMemoryClobber = false;
  6586. Array<Type*> paramTypes;
  6587. SizedArray<Value*, 1> llvmArgs;
  6588. int lastDebugLine = -1;
  6589. int curDebugLineDeltaValue = 0, curDebugLineDeltaRunCount = 0;
  6590. String debugLineSequenceStr;
  6591. int isFirstDebugLine = 1;
  6592. auto maybeEmitDebugLineRun = [&curDebugLineDeltaValue, &curDebugLineDeltaRunCount, &debugLineSequenceStr, &isFirstDebugLine]()
  6593. {
  6594. if (curDebugLineDeltaRunCount > 0)
  6595. {
  6596. for (int i=isFirstDebugLine; i<2; ++i)
  6597. {
  6598. int value = i ? curDebugLineDeltaValue : curDebugLineDeltaRunCount;
  6599. String encodedValue;
  6600. EncodeULEB32(value, encodedValue);
  6601. if (encodedValue.length() > 1)
  6602. debugLineSequenceStr += String("$") + encodedValue + "$";
  6603. else
  6604. debugLineSequenceStr += encodedValue;
  6605. }
  6606. curDebugLineDeltaRunCount = 0;
  6607. isFirstDebugLine = 0;
  6608. }
  6609. };
  6610. auto mangledLabelName = [&asmStmt](const StringImpl& labelName, int numericLabel) -> String
  6611. {
  6612. return StrFormat("%d", numericLabel);
  6613. //return String(".") + labelName;
  6614. //return StrFormat("%s_%p_%d", labelName.c_str(), asmStmt->mSource, asmStmt->mSrcStart); // suffix label name with location information to make it block-specific (since labels get external linkage)
  6615. };
  6616. typedef std::pair<String, int> LabelPair;
  6617. std::unordered_map<String, LabelPair> labelNames;
  6618. // pre-scan instructions for label names
  6619. for (int iInst=0; iInst<asmInstCount; ++iInst)
  6620. {
  6621. auto instNode = asmStmt->mInstructions[iInst];
  6622. BfInlineAsmInstruction::AsmInst& asmInst = instNode->mAsmInst;
  6623. if (!asmInst.mLabel.empty())
  6624. {
  6625. if (labelNames.find(asmInst.mLabel) != labelNames.end())
  6626. {
  6627. Fail(StrFormat("Label \"%s\" already defined in asm block", asmInst.mLabel.c_str()), instNode, true);
  6628. failed = true;
  6629. }
  6630. else
  6631. {
  6632. String mangledLabel(mangledLabelName(asmInst.mLabel, instNode->GetSrcStart()));
  6633. labelNames[asmInst.mLabel] = LabelPair(mangledLabel, instNode->GetSrcStart());
  6634. asmInst.mLabel = mangledLabel;
  6635. }
  6636. }
  6637. }
  6638. for (int iInst=0; iInst<asmInstCount; ++iInst)
  6639. {
  6640. auto instNode = asmStmt->mInstructions[iInst];
  6641. BfInlineAsmInstruction::AsmInst& asmInst = instNode->mAsmInst;
  6642. bool hasLabel = !asmInst.mLabel.empty();
  6643. bool hasOpCode = !asmInst.mOpCode.empty();
  6644. if (hasLabel || hasOpCode) // check against blank lines
  6645. {
  6646. if (hasOpCode) // check against label-only lines (which still get written out, but don't do any other processing)
  6647. {
  6648. int argCount = (int)asmInst.mArgs.size();
  6649. // reasonable defaults for clobber info
  6650. int clobberCount = 1; // destination is usually first arg in Intel syntax
  6651. bool mayClobberMem = true; // we only care about this when it gets turned to false by GetClobbersForMnemonic (no operand form of the instruction clobbers mem)
  6652. // pseudo-ops
  6653. if (asmInst.mOpCode == "_emit")
  6654. {
  6655. asmInst.mOpCode = ".byte";
  6656. }
  6657. else
  6658. {
  6659. Array<int> opcodes;
  6660. if (!mCpu->GetOpcodesForMnemonic(asmInst.mOpCode, opcodes))
  6661. {
  6662. Fail(StrFormat("Unrecognized instruction mnemonic \"%s\"", asmInst.mOpCode.c_str()), instNode, true);
  6663. failed = true;
  6664. }
  6665. else
  6666. {
  6667. Array<int> implicitClobbers;
  6668. mCpu->GetClobbersForMnemonic(asmInst.mOpCode, argCount, implicitClobbers, clobberCount, mayClobberMem);
  6669. for (int iClobberReg : implicitClobbers)
  6670. {
  6671. String regName = CPURegisters::GetRegisterName(iClobberReg);
  6672. std::transform(regName.begin(), regName.end(), regName.begin(), ::tolower);
  6673. matchRegFunc(regName, true);
  6674. }
  6675. }
  6676. }
  6677. String fakeLabel; // used when running label-using instructions through LLVM semantic pre-check
  6678. for (int iArg=0; iArg<argCount; ++iArg)
  6679. {
  6680. BfInlineAsmInstruction::AsmArg* arg = &asmInst.mArgs[iArg];
  6681. if (arg->mType == BfInlineAsmInstruction::AsmArg::ARGTYPE_IntReg)
  6682. {
  6683. bool isClobber = (iArg < clobberCount);
  6684. bool found = matchRegFunc(arg->mReg, isClobber);
  6685. if (!found)
  6686. {
  6687. StrToVarIndexMap::iterator it = strToVarIndexMap.find(arg->mReg);
  6688. if (it != strToVarIndexMap.end())
  6689. {
  6690. arg->mReg = StrFormat("$%d", it->second);
  6691. if (isClobber)
  6692. mayClobberMem = true;
  6693. found = true;
  6694. }
  6695. else
  6696. {
  6697. for (int i = 0; i < (int) mCurMethodState->mLocals.size(); i++)
  6698. {
  6699. auto& checkLocal = mCurMethodState->mLocals[i];
  6700. if (checkLocal.mName == arg->mReg)
  6701. {
  6702. BfIRValue testValue = checkLocal.mAddr;
  6703. llvmArgs.push_back(testValue);
  6704. paramTypes.push_back(testValue->getType());
  6705. arg->mReg = StrFormat("$%d", constraintCount);//CDH TODO does this need size qualifiers for "dword ptr $0" or whatever?
  6706. strToVarIndexMap[checkLocal.mName] = constraintCount;
  6707. constraintStr += "=*m,";
  6708. ++constraintCount;
  6709. if (isClobber)
  6710. mayClobberMem = true;
  6711. // if you access a variable in asm, we suppress any warnings related to used or assigned, regardless of usage
  6712. checkLocal.mIsReadFrom = true;
  6713. checkLocal.mAssignedKind = BfLocalVarAssignKind_Unconditional;
  6714. found = true;
  6715. break;
  6716. }
  6717. }
  6718. }
  6719. }
  6720. if (!found)
  6721. {
  6722. auto labelIt = labelNames.find(arg->mReg);
  6723. if (labelIt != labelNames.end())
  6724. {
  6725. arg->mReg = labelIt->second.first;
  6726. if (labelIt->second.second <= instNode->GetSrcStart())
  6727. {
  6728. fakeLabel = arg->mReg;
  6729. arg->mReg += "b";
  6730. }
  6731. else
  6732. arg->mReg += "f";
  6733. }
  6734. else
  6735. {
  6736. Fail(StrFormat("Unrecognized variable \"%s\"", arg->mReg.c_str()), instNode, true);
  6737. failed = true;
  6738. }
  6739. }
  6740. }
  6741. else if (arg->mType == BfInlineAsmInstruction::AsmArg::ARGTYPE_FloatReg)
  6742. {
  6743. //CDH individual reg clobber is probably insufficient for fp regs since it's stack-based; without deeper knowledge of how individual instructions
  6744. // manipulate the FP stack, the safest approach is to clobber all FP regs as soon as one of them is involved
  6745. //bool isClobber = (iArg == 0); // destination is first arg in Intel syntax
  6746. //bool found = matchRegFunc(StrFormat("st%d", arg->mInt), isClobber);
  6747. //BF_ASSERT(found);
  6748. for (int iRegCheck=0; iRegCheck<8; ++iRegCheck)
  6749. regClobberFlags |= (REGCLOBBERF_FPST0 << iRegCheck);
  6750. }
  6751. else if (arg->mType == BfInlineAsmInstruction::AsmArg::ARGTYPE_Memory)
  6752. {
  6753. bool isClobber = (iArg < clobberCount);
  6754. // check regs for clobber flags
  6755. /*
  6756. //CDH TODO do we need to set clobber flags for regs that are used *indirectly* like this? Actually I don't think so; commenting out for now
  6757. if (!arg->mReg.empty())
  6758. matchRegFunc(arg->mReg, isClobber);
  6759. if (!arg->mAdjReg.empty())
  6760. matchRegFunc(arg->mAdjReg, isClobber);
  6761. */
  6762. if (isClobber)
  6763. mayClobberMem = true;
  6764. if (!arg->mMemberSuffix.empty())
  6765. {
  6766. //CDH TODO add member support once I know the right way to look up struct member offsets. Once we know the offset,
  6767. // add it to arg->mInt, and set ARGMEMF_ImmediateDisp if it's not set already (member support is just used as an offset)
  6768. Fail("Member suffix syntax is not yet supported", instNode, true);
  6769. failed = true;
  6770. }
  6771. }
  6772. }
  6773. if (mayClobberMem)
  6774. hasMemoryClobber = true;
  6775. //debugLineSequenceStr += StrFormat("%d_", asmInst.mDebugLine);
  6776. int curDebugLine = asmInst.mDebugLine;
  6777. int debugLineDelta = (lastDebugLine > 0) ? curDebugLine - lastDebugLine : curDebugLine;
  6778. lastDebugLine = curDebugLine;
  6779. //String encodedDebugLineDelta;
  6780. //EncodeULEB32(debugLineDelta, encodedDebugLineDelta);
  6781. //debugLineSequenceStr += encodedDebugLineDelta + "_";
  6782. if (curDebugLineDeltaValue != debugLineDelta)
  6783. {
  6784. maybeEmitDebugLineRun();
  6785. curDebugLineDeltaValue = debugLineDelta;
  6786. }
  6787. ++curDebugLineDeltaRunCount;
  6788. // run instruction through LLVM for better semantic errors (can be slow in debug; feel free to comment out this scopeData if it's intolerable; the errors will still be caught at compile time)
  6789. //if (false)
  6790. {
  6791. BfInlineAsmInstruction::AsmInst tempAsmInst(asmInst);
  6792. tempAsmInst.mLabel = fakeLabel;
  6793. for (auto & arg : tempAsmInst.mArgs)
  6794. {
  6795. if ((arg.mType == BfInlineAsmInstruction::AsmArg::ARGTYPE_IntReg) && !arg.mReg.empty() && (arg.mReg[0] == '$'))
  6796. {
  6797. // if we've rewritten a local variable instruction arg to use a $-prefixed input, we can't pass that to LLVM
  6798. // at this stage as it won't recognize it; the actual compilation would have changed all these to use actual
  6799. // memory operand syntax first. However, those changes all work down in LLVM to printIntelMemReference inside
  6800. // of X86AsmPrinter.cpp, and that always results in a [bracketed] memory access string no matter what, which
  6801. // means for our semantic checking purposes here it's sufficient to just use "[eax]" for all such cases,
  6802. // rather than go through an even more expensive setup & teardown process to use the AsmPrinter itself.
  6803. arg.mType = BfInlineAsmInstruction::AsmArg::ARGTYPE_Memory;
  6804. arg.mMemFlags = BfInlineAsmInstruction::AsmArg::ARGMEMF_BaseReg;
  6805. arg.mReg = "eax";
  6806. }
  6807. }
  6808. String llvmError;
  6809. if (!mCpu->ParseInlineAsmInstructionLLVM(tempAsmInst.ToString(), llvmError))
  6810. {
  6811. Fail(StrFormat("Inline asm error: %s", llvmError.c_str()), instNode, true);
  6812. failed = true;
  6813. }
  6814. }
  6815. }
  6816. dstAsmText += asmInst.ToString();
  6817. dstAsmText += "\n";
  6818. }
  6819. }
  6820. maybeEmitDebugLineRun(); // leftovers
  6821. if (failed)
  6822. {
  6823. RestoreScopeState(&prevScope);
  6824. return;
  6825. }
  6826. // prepare constraints/clobbers
  6827. {
  6828. for (int iRegCheck = 0; regClobberNames[iRegCheck] != nullptr; ++iRegCheck)
  6829. {
  6830. if (regClobberFlags & (1 << iRegCheck))
  6831. clobberStr += StrFormat("~{%s},", regClobberNames[iRegCheck]);
  6832. }
  6833. for (int iRegCheck=0; iRegCheck<8; ++iRegCheck)
  6834. {
  6835. if (regClobberFlags & (REGCLOBBERF_XMM0 << iRegCheck))
  6836. clobberStr += StrFormat("~{xmm%d},", iRegCheck);
  6837. if (regClobberFlags & (REGCLOBBERF_FPST0 << iRegCheck))
  6838. clobberStr += StrFormat("~{fp%d},~{st(%d)},", iRegCheck, iRegCheck); // both fp# and st(#) are listed in X86RegisterInfo.td
  6839. if (regClobberFlags & (REGCLOBBERF_MM0 << iRegCheck))
  6840. clobberStr += StrFormat("~{mm%d},", iRegCheck);
  6841. }
  6842. // add wrapping instructions to preserve certain regs (e.g. ESI), due to LLVM bypassing register allocator when choosing a base register
  6843. //CDH TODO currently I'm only shielding against ESI stompage; people generally know not to mess with ESP & EBP, but ESI is still a "general" reg and should be allowed to be clobbered
  6844. //if (regClobberFlags & REGCLOBBERF_ESI)
  6845. //{
  6846. //CDH TODO Bah! This doesn't actually work, because if you do any local variable access after mutating ESI, the variable substitution could have generated a base address dependency
  6847. // on ESI which will not expect it to have changed, e.g. "mov esi, var\ninc esi\nmov var, esi\n" dies if "var" gets internally rewritten to "[esi + displacement]". What to do? Hmm.
  6848. //dstAsmText = String("push esi\n") + dstAsmText + String("pop esi\n");
  6849. //}
  6850. if (hasMemoryClobber)
  6851. clobberStr += "~{memory},";
  6852. clobberStr += "~{dirflag},~{fpsr},~{flags}";
  6853. constraintStr += clobberStr;
  6854. }
  6855. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  6856. if (wantsDIData)
  6857. {
  6858. static int sVarNum = 0;
  6859. String varName(StrFormat("__asmLines_%d.%s", ++sVarNum, debugLineSequenceStr.c_str()));
  6860. auto varType = GetPrimitiveType(BfTypeCode_Int32);
  6861. auto allocaInst = mBfIRBuilder->CreateAlloca(varType->mLLVMType, 0, varName + ".addr");
  6862. allocaInst->setAlignment(varType->mAlign);
  6863. //paramVar->mAddr = allocaInst;
  6864. auto varValue = GetConstValue(0, varType);
  6865. auto diVariable = mDIBuilder->createAutoVariable(mCurMethodState->mCurScope->mDIScope,
  6866. varName.c_str(), mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, varType->mDIType/*, true*/);
  6867. //auto varValue = llvm::ConstantInt::getTrue(*mLLVMContext);
  6868. //auto varValue = GetDefaultValue(varType);
  6869. //auto varValue = CreateGlobalConstValue(varName, llvm::ConstantInt::getTrue(*mLLVMContext), true);
  6870. //auto varValue = AllocGlobalVariable(*mIRModule, diType->getType(), false, GlobalValue::ExternalLinkage, llvm::ConstantInt::getTrue(*mLLVMContext), varName.c_str());
  6871. //auto diVariable = mDIBuilder->createGlobalVariable(mCurMethodState->mCurScope->mDIScope, varName.c_str(), "", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, false, varValue);
  6872. //BasicBlock* block = mBfIRBuilder->GetInsertBlock();
  6873. //auto declareVar = mDIBuilder->insertDeclare(varValue, diVariable, mBfIRBuilder->GetInsertBlock());
  6874. auto declareVar = mDIBuilder->insertDeclare(allocaInst, diVariable, mDIBuilder->createExpression(),
  6875. mIRBuilder->getCurrentDebugLocation(), mBfIRBuilder->GetInsertBlock());
  6876. //auto declareVar = mDIBuilder->insertDbgValueIntrinsic(varValue, 0, diVariable, mBfIRBuilder->GetInsertBlock());
  6877. declareVar->setDebugLoc(mIRBuilder->getCurrentDebugLocation());
  6878. }
  6879. /*
  6880. BfIRValue testValue = NULL;
  6881. for (int i = 0; i < (int) mCurMethodState->mLocals.size(); i++)
  6882. {
  6883. auto& checkLocal = mCurMethodState->mLocals[i];
  6884. if (checkLocal.mName == "i")
  6885. {
  6886. testValue = checkLocal.mAddr;
  6887. break;
  6888. }
  6889. }
  6890. */
  6891. //BF_ASSERT((testValue != NULL) && "Need local variable \"i\"");
  6892. //if (testValue != NULL)
  6893. {
  6894. //Type* voidPtrType = Type::getInt8PtrTy(*mLLVMContext);
  6895. //if (mContext->mAsmObjectCheckFuncType == NULL)
  6896. //{
  6897. //Array<Type*> paramTypes;
  6898. //paramTypes.push_back(voidPtrType);
  6899. //mContext->mAsmObjectCheckFuncType = FunctionType::get(Type::getVoidTy(*mLLVMContext), paramTypes, false);
  6900. //}
  6901. FunctionType* funcType = FunctionType::get(Type::getVoidTy(*mLLVMContext), paramTypes, false);
  6902. //SizedArray<Value*, 1> llvmArgs;
  6903. //llvmArgs.push_back(testValue);
  6904. //CDH REMOVE NOTE
  6905. //generates IR (e.g.):
  6906. // call void asm sideeffect "#4\0Anop\0Anop\0Amovl %eax, %eax\0Anop\0Anop", "~{cc},~{dirflag},~{fpsr},~{flags},~{eax}"() #0, !dbg !492
  6907. static int asmIdx = 0;
  6908. asmIdx++;
  6909. String asmStr = StrFormat("#%d\n", asmIdx) +
  6910. //"nop\nnop\nmovl $0, %eax\nincl %eax\nmovl %eax, $0\nmovl $$0, %ecx\nmovl $$0, %esp\nnop\nnop";
  6911. //"nop\nnop\nmovl ($0), %eax\nincl %eax\nmovl %eax, ($0)\nmovl $$0, %ecx\nmovl $$0, %esp\nnop\nnop";
  6912. //"nop\nnop\nmovl %eax, %eax\nmovl $$0, %ecx\nmovl $$0, %esp\nnop\nnop";
  6913. //"nop\nnop\nmovl %eax, %eax\nnop\nnop";
  6914. //"nop\nnop\n.byte 0x0F\n.byte 0xC7\n.byte 0xF0\nmov eax, 7\nmov ecx, 0\ncpuid\nmov eax, dword ptr $0\ninc eax\nmov dword ptr $0, eax\nmov ecx, 0\nmov esp, 0\nnop\nnop"; // rdrand test
  6915. dstAsmText;
  6916. llvm::InlineAsm* inlineAsm = llvm::InlineAsm::get(funcType,
  6917. //asmStr.c_str(), "~{r},~{cc},~{dirflag},~{fpsr},~{flags},~{eax},~{memory},~{esi},~{esp}", true,
  6918. //asmStr.c_str(), "~{cc},~{dirflag},~{fpsr},~{flags},~{memory},~{ecx},~{esp}", true,
  6919. //DOES NOT WORK (mem not written back to from reg:
  6920. //asmStr.c_str(), "+r,~{cc},~{dirflag},~{fpsr},~{flags},~{memory},~{eax},~{ecx},~{esp}", true,
  6921. //asmStr.c_str(), "+rm,~{cc},~{dirflag},~{fpsr},~{flags},~{memory},~{eax},~{ecx},~{esp}", true,
  6922. asmStr.c_str(), constraintStr.c_str(), true,
  6923. false, /*llvm::InlineAsm::AD_ATT*/llvm::InlineAsm::AD_Intel);
  6924. llvm::CallInst* callInst = mIRBuilder->CreateCall(inlineAsm, llvmArgs);
  6925. //llvm::CallInst* callInst = mIRBuilder->CreateCall(inlineAsm);
  6926. callInst->addAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::NoUnwind);
  6927. }
  6928. RestoreScopeState(&prevScope);
  6929. #endif
  6930. }