2
0

BfModule.cpp 700 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(push) // 6
  4. #pragma warning(disable:4996)
  5. #include "BfCompiler.h"
  6. #include "BfSystem.h"
  7. #include "BfParser.h"
  8. #include "BfCodeGen.h"
  9. #include "BfExprEvaluator.h"
  10. #include "../Backend/BeLibManger.h"
  11. #include <fcntl.h>
  12. #include "BfConstResolver.h"
  13. #include "BfMangler.h"
  14. #include "BeefySysLib/util/PerfTimer.h"
  15. #include "BeefySysLib/util/BeefPerf.h"
  16. #include "BeefySysLib/util/StackHelper.h"
  17. #include "BfSourceClassifier.h"
  18. #include "BfAutoComplete.h"
  19. #include "BfDemangler.h"
  20. #include "BfResolvePass.h"
  21. #include "BfFixits.h"
  22. #include "BfIRCodeGen.h"
  23. #include "BfDefBuilder.h"
  24. #include "BfDeferEvalChecker.h"
  25. #pragma warning(pop)
  26. //////////////////////////////////////////////////////////////////////////
  27. static bool gDebugStuff = false;
  28. USING_NS_BF;
  29. //////////////////////////////////////////////////////////////////////////
  30. void BfLocalVariable::Init()
  31. {
  32. if (mResolvedType->IsValuelessType())
  33. {
  34. mIsAssigned = true;
  35. return;
  36. }
  37. if (mIsAssigned)
  38. return;
  39. bool isStruct = mResolvedType->IsStruct();
  40. if (mResolvedType->IsRef())
  41. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  42. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  43. {
  44. auto resolvedTypeRef = mResolvedType;
  45. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  46. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  47. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  48. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  49. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  50. {
  51. // Base ctor is responsible for initializing its own fields
  52. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  53. }
  54. if (mUnassignedFieldFlags == 0)
  55. mIsAssigned = true;
  56. }
  57. else
  58. {
  59. mUnassignedFieldFlags = 1;
  60. }
  61. }
  62. BfLocalMethod::~BfLocalMethod()
  63. {
  64. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  65. if (mMethodDeclaration != NULL)
  66. {
  67. mSource->mRefCount--;
  68. BF_ASSERT(mSource->mRefCount >= 0);
  69. }
  70. delete mMethodDef;
  71. delete mMethodInstanceGroup;
  72. }
  73. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  74. {
  75. mIsChained = doChain;
  76. if (outerLocalAssignData == NULL)
  77. return;
  78. mChainedAssignData = outerLocalAssignData;
  79. if (!doChain)
  80. {
  81. outerLocalAssignData->BreakExtendChain();
  82. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  83. }
  84. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  85. }
  86. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  87. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  88. // if ((GetValue(out a)) && (GetValue(out b)) {}
  89. void BfDeferredLocalAssignData::BreakExtendChain()
  90. {
  91. if (!mIsChained)
  92. return;
  93. mIsChained = false;
  94. if (mChainedAssignData == NULL)
  95. return;
  96. mChainedAssignData->BreakExtendChain();
  97. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  98. }
  99. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  100. {
  101. BreakExtendChain();
  102. //TODO: We got rid of this case because we now set the proper assigned data when we do a return
  103. // If one of these had a return then treat that case as if it did have an assign -- because it doesn't
  104. // cause an UNASSIGNED value to be used
  105. // if (mHadReturn || otherLocalAssignData.mHadReturn)
  106. // {
  107. // SetUnion(otherLocalAssignData);
  108. // mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  109. // return;
  110. // }
  111. for (int i = 0; i < (int)mAssignedLocals.size(); )
  112. {
  113. auto& local = mAssignedLocals[i];
  114. if (!otherLocalAssignData.mAssignedLocals.Contains(local))
  115. {
  116. mAssignedLocals.RemoveAt(i);
  117. }
  118. else
  119. i++;
  120. }
  121. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  122. }
  123. void BfDeferredLocalAssignData::Validate() const
  124. {
  125. for (auto var : mAssignedLocals)
  126. {
  127. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  128. }
  129. }
  130. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  131. {
  132. BreakExtendChain();
  133. Validate();
  134. otherLocalAssignData.Validate();
  135. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  136. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  137. {
  138. if (!mAssignedLocals.Contains(*otherItr))
  139. mAssignedLocals.push_back(*otherItr);
  140. ++otherItr;
  141. }
  142. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  143. }
  144. BfMethodState::~BfMethodState()
  145. {
  146. BF_ASSERT(mPendingNullConditional == NULL);
  147. if (mPrevMethodState != NULL)
  148. {
  149. BF_ASSERT(mCurAccessId == 1);
  150. BF_ASSERT(mCurLocalVarId <= 0);
  151. }
  152. for (auto local : mLocals)
  153. delete local;
  154. for (auto& kv : mLambdaCache)
  155. delete kv.mValue;
  156. }
  157. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  158. {
  159. auto checkMethodState = this;
  160. while (checkMethodState != NULL)
  161. {
  162. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  163. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  164. return checkMethodState;
  165. checkMethodState = checkMethodState->mPrevMethodState;
  166. }
  167. BF_FATAL("Failed to find method state for localvar");
  168. return NULL;
  169. }
  170. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx)
  171. {
  172. auto localVarMethodState = GetMethodStateForLocal(localVar);
  173. if (localVarMethodState != this)
  174. {
  175. return;
  176. }
  177. //BF_ASSERT(localVarMethodState == this);
  178. if (!localVar->mIsAssigned)
  179. {
  180. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  181. // 'a' is always defined, but 'b' isn't:
  182. // if (Check(out a) || Check(out b)) { } int z = a;
  183. auto deferredLocalAssignData = mDeferredLocalAssignData;
  184. if ((deferredLocalAssignData != NULL) &&
  185. (deferredLocalAssignData->mIsIfCondition) &&
  186. (!deferredLocalAssignData->mIfMayBeSkipped))
  187. {
  188. ifDeferredLocalAssignData = deferredLocalAssignData;
  189. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  190. }
  191. while ((deferredLocalAssignData != NULL) &&
  192. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  193. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  194. if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  195. {
  196. if (fieldIdx >= 0)
  197. {
  198. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  199. /*if ((localVar->mResolvedTypeRef != NULL) && (localVar->mResolvedTypeRef->IsUnion()))
  200. {
  201. }*/
  202. if (localVar->mUnassignedFieldFlags == 0)
  203. localVar->mIsAssigned = true;
  204. }
  205. else
  206. {
  207. localVar->mIsAssigned = true;
  208. }
  209. }
  210. else
  211. {
  212. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  213. BfAssignedLocal defineVal = {localVar, fieldIdx + 1};
  214. auto& assignedLocals = deferredLocalAssignData->mAssignedLocals;
  215. if (!assignedLocals.Contains(defineVal))
  216. assignedLocals.push_back(defineVal);
  217. if (ifDeferredLocalAssignData != NULL)
  218. {
  219. auto& assignedLocals = ifDeferredLocalAssignData->mAssignedLocals;
  220. if (!assignedLocals.Contains(defineVal))
  221. assignedLocals.push_back(defineVal);
  222. }
  223. }
  224. }
  225. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  226. }
  227. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  228. {
  229. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  230. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  231. {
  232. LocalDefined(assignedLocal.mLocalVar);
  233. }
  234. }
  235. void BfMethodState::Reset()
  236. {
  237. mHeadScope.mDeferredCallEntries.DeleteAll();
  238. }
  239. //////////////////////////////////////////////////////////////////////////
  240. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  241. {
  242. Entry* entry = NULL;
  243. if (mEntries.TryAdd(id, NULL, &entry))
  244. {
  245. entry->mInterfaceEntry = interfaceEntry;
  246. entry->mMethodIdx = methodIdx;
  247. }
  248. if (!entry->mCandidates.Contains(candidateA))
  249. entry->mCandidates.push_back(candidateA);
  250. if (!entry->mCandidates.Contains(candidateB))
  251. entry->mCandidates.push_back(candidateB);
  252. }
  253. void BfAmbiguityContext::Remove(int id)
  254. {
  255. mEntries.Remove(id);
  256. }
  257. void BfAmbiguityContext::Finish()
  258. {
  259. for (auto& entryPair : mEntries)
  260. {
  261. int id = entryPair.mKey;
  262. auto entry = &entryPair.mValue;
  263. if (id >= 0)
  264. {
  265. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  266. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  267. for (auto candidate : entry->mCandidates)
  268. {
  269. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  270. }
  271. }
  272. else
  273. {
  274. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  275. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  276. for (auto candidate : entry->mCandidates)
  277. {
  278. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  279. }
  280. }
  281. }
  282. }
  283. //////////////////////////////////////////////////////////////////////////
  284. class HasAppendAllocVisitor : BfElementVisitor
  285. {
  286. public:
  287. bool mHas;
  288. public:
  289. HasAppendAllocVisitor()
  290. {
  291. mHas = false;
  292. }
  293. void Visit(BfObjectCreateExpression* objCreateExpr)
  294. {
  295. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  296. {
  297. if (newToken->GetToken() == BfToken_Append)
  298. {
  299. mHas = true;
  300. }
  301. }
  302. }
  303. bool HasAppendAlloc(BfAstNode* node)
  304. {
  305. mHas = false;
  306. VisitChild(node);
  307. return mHas;
  308. }
  309. };
  310. class AppendAllocVisitor : public BfStructuralVisitor
  311. {
  312. public:
  313. BfModule* mModule;
  314. HasAppendAllocVisitor mHasAppendAllocVisitor;
  315. BfTypedValue mConstAccum;
  316. bool mFailed;
  317. bool mIsFirstConstPass;
  318. int mCurAppendAlign;
  319. public:
  320. AppendAllocVisitor()
  321. {
  322. mFailed = false;
  323. mIsFirstConstPass = false;
  324. mCurAppendAlign = 0;
  325. }
  326. void EmitAppendAlign(int align, int sizeMultiple = 0)
  327. {
  328. if (mIsFirstConstPass)
  329. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  330. if (sizeMultiple == 0)
  331. sizeMultiple = align;
  332. if (mCurAppendAlign == 0)
  333. mCurAppendAlign = sizeMultiple;
  334. else
  335. {
  336. if (sizeMultiple % align == 0)
  337. mCurAppendAlign = align;
  338. else
  339. mCurAppendAlign = sizeMultiple % align;
  340. }
  341. if (mConstAccum)
  342. {
  343. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  344. if (constant != NULL)
  345. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  346. else
  347. BF_ASSERT(mIsFirstConstPass);
  348. return;
  349. }
  350. mModule->EmitAppendAlign(align, sizeMultiple);
  351. }
  352. void Visit(BfAstNode* astNode) override
  353. {
  354. mModule->VisitChild(astNode);
  355. }
  356. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  357. {
  358. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  359. {
  360. if (newToken->GetToken() == BfToken_Append)
  361. {
  362. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  363. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  364. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  365. BfArrayType* arrayType = NULL;
  366. bool isArrayAlloc = false;
  367. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  368. SizedArray<BfIRValue, 2> dimLengthVals;
  369. BfType* origResolvedTypeRef = NULL;
  370. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  371. {
  372. if (variableDecl != NULL)
  373. {
  374. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  375. if (origResolvedTypeRef->IsObject())
  376. {
  377. if (origResolvedTypeRef->IsArray())
  378. {
  379. arrayType = (BfArrayType*)origResolvedTypeRef;
  380. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  381. isArrayAlloc = true;
  382. }
  383. }
  384. else if (origResolvedTypeRef->IsPointer())
  385. {
  386. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  387. }
  388. }
  389. }
  390. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  391. {
  392. isArrayAlloc = true;
  393. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  394. int dimensions = 1;
  395. if (arrayTypeRef->mParams.size() != 0)
  396. {
  397. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  398. for (auto arg : arrayTypeRef->mParams)
  399. {
  400. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  401. {
  402. if (tokenNode->GetToken() == BfToken_Comma)
  403. {
  404. if (isRawArrayAlloc)
  405. {
  406. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  407. continue;
  408. }
  409. dimensions++;
  410. continue;
  411. }
  412. }
  413. auto expr = BfNodeDynCast<BfExpression>(arg);
  414. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  415. {
  416. mModule->CreateValueFromExpression(expr, intType);
  417. continue;
  418. }
  419. BfTypedValue dimLength;
  420. if (expr == NULL)
  421. {
  422. // Not specified
  423. dimLengthVals.push_back(BfIRValue());
  424. continue;
  425. }
  426. if (arg != NULL)
  427. dimLength = mModule->CreateValueFromExpression(expr, intType);
  428. if (!dimLength)
  429. {
  430. dimLength = mModule->GetDefaultTypedValue(intType);
  431. }
  432. dimLengthVals.push_back(dimLength.mValue);
  433. }
  434. }
  435. if (!isRawArrayAlloc)
  436. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  437. }
  438. if (origResolvedTypeRef == NULL)
  439. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  440. if (origResolvedTypeRef == NULL)
  441. {
  442. mModule->AssertErrorState();
  443. return;
  444. }
  445. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  446. auto resolvedTypeRef = origResolvedTypeRef;
  447. auto resultType = resolvedTypeRef;
  448. BfIRValue sizeValue;
  449. int curAlign = 0;
  450. if (isArrayAlloc)
  451. {
  452. int dimensions = 1;
  453. if (arrayType != NULL)
  454. dimensions = arrayType->mDimensions;
  455. bool sizeFailed = false;
  456. //
  457. {
  458. BfAstNode* initNode = objCreateExpr;
  459. for (int dim = 0; dim < dimensions; dim++)
  460. {
  461. BfAstNode* nextInitNode = NULL;
  462. int dimSize = -1;
  463. if (initNode == objCreateExpr)
  464. {
  465. dimSize = objCreateExpr->mArguments.size();
  466. if (!objCreateExpr->mArguments.IsEmpty())
  467. nextInitNode = objCreateExpr->mArguments[0];
  468. }
  469. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  470. {
  471. dimSize = (int)tupleNode->mCommas.size() + 1;
  472. }
  473. if (dimSize >= 0)
  474. {
  475. if (dim >= dimLengthVals.size())
  476. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  477. }
  478. else
  479. {
  480. sizeFailed = true;
  481. }
  482. }
  483. }
  484. BfIRValue allocCount;
  485. if (!sizeFailed)
  486. {
  487. if (!dimLengthVals.IsEmpty())
  488. {
  489. allocCount = dimLengthVals[0];
  490. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  491. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  492. }
  493. }
  494. if (!allocCount)
  495. {
  496. mFailed = true;
  497. if (!mIsFirstConstPass)
  498. {
  499. if (!mConstAccum)
  500. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  501. return;
  502. }
  503. }
  504. if (isRawArrayAlloc)
  505. {
  506. curAlign = resultType->mAlign;
  507. EmitAppendAlign(resultType->mAlign);
  508. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  509. }
  510. else
  511. {
  512. if (arrayType == NULL)
  513. arrayType = mModule->CreateArrayType(resultType, 1);
  514. // Array is a special case where the total size isn't aligned with mAlign
  515. // since we add arbitrary elements to the end without padding the end to align
  516. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  517. curAlign = arrayType->mAlign;
  518. auto firstElementField = &arrayType->mFieldInstances.back();
  519. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  520. sizeValue = mModule->GetConstValue(arrayClassSize);
  521. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  522. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  523. }
  524. }
  525. else
  526. {
  527. auto typeInst = resultType->ToTypeInstance();
  528. if (typeInst != NULL)
  529. {
  530. curAlign = typeInst->mInstAlign;
  531. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  532. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  533. }
  534. else
  535. {
  536. curAlign = resultType->mAlign;
  537. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  538. sizeValue = mModule->GetConstValue(resultType->mSize);
  539. }
  540. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  541. BfExprEvaluator exprEvaluator(mModule);
  542. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  543. BfFunctionBindResult bindResult;
  544. bindResult.mWantsArgs = true;
  545. exprEvaluator.mFunctionBindResult = &bindResult;
  546. SizedArray<BfExpression*, 8> copiedArgs;
  547. for (BfExpression* arg : objCreateExpr->mArguments)
  548. copiedArgs.push_back(arg);
  549. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  550. BfResolvedArgs argValues(&sizedArgExprs);
  551. if (typeInst != NULL)
  552. {
  553. exprEvaluator.ResolveArgValues(argValues);
  554. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  555. }
  556. exprEvaluator.mFunctionBindResult = NULL;
  557. if (bindResult.mMethodInstance != NULL)
  558. {
  559. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  560. {
  561. auto calcAppendArgs = bindResult.mIRArgs;
  562. BF_ASSERT(calcAppendArgs[0].IsFake());
  563. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  564. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  565. auto subDependSize = mModule->TryConstCalcAppend(bindResult.mMethodInstance, calcAppendArgs);
  566. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  567. {
  568. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  569. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  570. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  571. }
  572. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  573. if ((!subDependSize) && (!mConstAccum))
  574. {
  575. BF_ASSERT(calcAppendMethodModule.mFunc);
  576. subDependSize = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  577. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  578. }
  579. if (subDependSize)
  580. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  581. else
  582. mFailed = true;
  583. }
  584. }
  585. }
  586. if (sizeValue)
  587. {
  588. if (mConstAccum)
  589. {
  590. if (!sizeValue.IsConst())
  591. {
  592. mFailed = true;
  593. if (!mIsFirstConstPass)
  594. return;
  595. }
  596. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  597. }
  598. else
  599. {
  600. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  601. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  602. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  603. }
  604. }
  605. }
  606. }
  607. }
  608. void Visit(BfObjectCreateExpression* objCreateExpr) override
  609. {
  610. DoObjectCreate(objCreateExpr, NULL);
  611. }
  612. void Visit(BfVariableDeclaration* varDecl) override
  613. {
  614. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  615. {
  616. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  617. DoObjectCreate(objectCreateExpr, varDecl);
  618. else
  619. VisitChild(varDecl->mInitializer);
  620. if (varDecl->mNameNode != NULL)
  621. {
  622. BfLocalVariable* localDef = new BfLocalVariable();
  623. localDef->mName = varDecl->mNameNode->ToString();
  624. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  625. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  626. localDef->mIsReadOnly = true;
  627. localDef->mParamFailed = true;
  628. localDef->mReadFromId = 0;
  629. mModule->AddLocalVariableDef(localDef);
  630. }
  631. }
  632. else
  633. {
  634. mModule->Visit(varDecl);
  635. }
  636. }
  637. void Visit(BfExpressionStatement* exprStatement) override
  638. {
  639. VisitChild(exprStatement->mExpression);
  640. }
  641. // void Visit(BfIfStatement* ifStmt) override
  642. // {
  643. // mModule->DoIfStatement(ifStmt,
  644. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  645. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  646. // }
  647. void Visit(BfBlock* block) override
  648. {
  649. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  650. return;
  651. int appendAllocIdx = -1;
  652. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  653. {
  654. auto child = block->mChildArr.mVals[childIdx];
  655. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  656. {
  657. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  658. {
  659. auto emitChild = block->mChildArr.mVals[emitIdx];
  660. mModule->UpdateSrcPos(emitChild);
  661. VisitChild(emitChild);
  662. if ((mFailed) && (!mIsFirstConstPass))
  663. break;
  664. }
  665. break;
  666. }
  667. }
  668. }
  669. };
  670. //////////////////////////////////////////////////////////////////////////
  671. BfModule* gLastCreatedModule = NULL;
  672. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  673. {
  674. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  675. gLastCreatedModule = this;
  676. mContext = context;
  677. mModuleName = moduleName;
  678. if (!moduleName.empty())
  679. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  680. mAddedToCount = false;
  681. mParentModule = NULL;
  682. mNextAltModule = NULL;
  683. mBfIRBuilder = NULL;
  684. mWantsIRIgnoreWrites = false;
  685. mModuleOptions = NULL;
  686. mLastUsedRevision = -1;
  687. mUsedSlotCount = -1;
  688. mIsReified = true;
  689. mReifyQueued = false;
  690. mIsSpecialModule = false;
  691. mIsScratchModule = false;
  692. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  693. mHadBuildError = false;
  694. mHadBuildWarning = false;
  695. mIgnoreErrors = false;
  696. mIgnoreWarnings = false;
  697. mHadIgnoredError = false;
  698. mReportErrors = true;
  699. mIsInsideAutoComplete = false;
  700. mIsDeleting = false;
  701. mSkipInnerLookup = false;
  702. mIsHotModule = false;
  703. mSetIllegalSrcPosition = false;
  704. mNoResolveGenericParams = false;
  705. mWroteToLib = false;
  706. mContext = context;
  707. mCompiler = context->mCompiler;
  708. mSystem = mCompiler->mSystem;
  709. mProject = NULL;
  710. mCurMethodState = NULL;
  711. mAttributeState = NULL;
  712. mCurLocalMethodId = 0;
  713. mParentNodeEntry = NULL;
  714. mRevision = -1;
  715. mRebuildIdx = 0;
  716. mLastModuleWrittenRevision = 0;
  717. mIsModuleMutable = false;
  718. mExtensionCount = 0;
  719. mIncompleteMethodCount = 0;
  720. mOnDemandMethodCount = 0;
  721. mHasGenericMethods = false;
  722. mCurMethodInstance = NULL;
  723. mCurTypeInstance = NULL;
  724. mAwaitingInitFinish = false;
  725. mAwaitingFinish = false;
  726. mHasFullDebugInfo = false;
  727. mHadHotObjectWrites = false;
  728. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  729. mBuiltInFuncs[i] = BfIRFunction();
  730. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  731. }
  732. void BfReportMemory();
  733. BfModule::~BfModule()
  734. {
  735. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  736. if (!mIsDeleting)
  737. RemoveModuleData();
  738. }
  739. void BfModule::RemoveModuleData()
  740. {
  741. BF_ASSERT(!mIsDeleting);
  742. if (!mModuleName.empty())
  743. {
  744. // Note: module names not necessarily unique
  745. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  746. }
  747. CleanupFileInstances();
  748. delete mBfIRBuilder;
  749. mBfIRBuilder = NULL;
  750. //delete mCpu;
  751. for (auto prevModule : mPrevIRBuilders)
  752. delete prevModule;
  753. mPrevIRBuilders.Clear();
  754. for (auto& pairVal : mDeferredMethodCallData)
  755. delete pairVal.mValue;
  756. mDeferredMethodCallData.Clear();
  757. mDeferredMethodIds.Clear();
  758. for (auto& specModulePair : mSpecializedMethodModules)
  759. delete specModulePair.mValue;
  760. mSpecializedMethodModules.Clear();
  761. if (mNextAltModule != NULL)
  762. delete mNextAltModule;
  763. mNextAltModule = NULL;
  764. if (mModuleOptions != NULL)
  765. delete mModuleOptions;
  766. mModuleOptions = NULL;
  767. BfReportMemory();
  768. }
  769. void BfModule::Init(bool isFullRebuild)
  770. {
  771. mContext->mFinishedModuleWorkList.Remove(this);
  772. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  773. BF_ASSERT(mIsReified);
  774. if (!mIsScratchModule)
  775. {
  776. mCompiler->mStats.mModulesStarted++;
  777. if (mIsReified)
  778. mCompiler->mStats.mReifiedModuleCount++;
  779. mAddedToCount = true;
  780. }
  781. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  782. mFuncReferences.Clear();
  783. mClassVDataRefs.Clear();
  784. mClassVDataExtRefs.Clear();
  785. //mTypeDataRefs.Clear();
  786. mDbgRawAllocDataRefs.Clear();
  787. CleanupFileInstances();
  788. mStaticFieldRefs.Clear();
  789. //mInterfaceSlotRefs.Clear();
  790. // If we are just doing an extension then the ownede types aren't rebuilt.
  791. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  792. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  793. if (isFullRebuild)
  794. mRevision = mCompiler->mRevision;
  795. BF_ASSERT(mCurTypeInstance == NULL);
  796. mIsModuleMutable = true;
  797. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  798. #ifdef _DEBUG
  799. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  800. #else
  801. EnsureIRBuilder(false);
  802. #endif
  803. mCurMethodState = NULL;
  804. mAwaitingInitFinish = true;
  805. mOnDemandMethodCount = 0;
  806. mAwaitingFinish = false;
  807. mHasForceLinkMarker = false;
  808. mUsedSlotCount = -1;
  809. }
  810. bool BfModule::WantsFinishModule()
  811. {
  812. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  813. }
  814. void BfModule::FinishInit()
  815. {
  816. BF_ASSERT(mAwaitingInitFinish);
  817. auto moduleOptions = GetModuleOptions();
  818. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  819. #ifdef BF_PLATFORM_WINDOWS
  820. if (mCompiler->mOptions.mToolsetType == BfToolsetType_GNU)
  821. {
  822. if (mCompiler->mOptions.mMachineType == BfMachineType_x86)
  823. mBfIRBuilder->Module_SetTargetTriple("i686-pc-windows-gnu");
  824. else
  825. mBfIRBuilder->Module_SetTargetTriple("x86_64-pc-windows-gnu");
  826. }
  827. else //if (mCompiler->mOptions.mToolsetType == BfToolsetType_Microsoft)
  828. {
  829. if (mCompiler->mOptions.mMachineType == BfMachineType_x86)
  830. mBfIRBuilder->Module_SetTargetTriple("i686-pc-windows-msvc");
  831. else
  832. mBfIRBuilder->Module_SetTargetTriple("x86_64-pc-windows-msvc");
  833. }
  834. #elif defined BF_PLATFORM_LINUX
  835. if (mCompiler->mOptions.mMachineType == BfMachineType_x86)
  836. mBfIRBuilder->Module_SetTargetTriple("i686-unknown-linux-gnu");
  837. else
  838. mBfIRBuilder->Module_SetTargetTriple("x86_64-unknown-linux-gnu");
  839. #else
  840. // Leave it default
  841. mBfIRBuilder->Module_SetTargetTriple("");
  842. #endif
  843. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  844. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  845. {
  846. // Og+ requires debug info
  847. moduleOptions.mEmitDebugInfo = 1;
  848. }
  849. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  850. // We need to create DIBuilder for mIsSpecialModule so we have it around when we need it
  851. // if ((!mCompiler->mIsResolveOnly) && ((mIsScratchModule) || (moduleOptions.mEmitDebugInfo != 0)))
  852. // {
  853. // BF_ASSERT((!mBfIRBuilder->mIgnoreWrites) || (mIsScratchModule) || (!mIsReified));
  854. // mBfIRBuilder->DbgInit();
  855. // }
  856. // else
  857. // mHasFullDebugInfo = false;
  858. if ((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified))
  859. {
  860. mBfIRBuilder->DbgInit();
  861. }
  862. else
  863. mHasFullDebugInfo = false;
  864. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  865. ((moduleOptions.mEmitDebugInfo != 0)))
  866. {
  867. if (mCompiler->mOptions.IsCodeView())
  868. {
  869. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  870. }
  871. else
  872. {
  873. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  874. }
  875. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  876. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  877. }
  878. mAwaitingInitFinish = false;
  879. }
  880. void BfModule::ReifyModule()
  881. {
  882. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  883. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  884. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  885. mIsReified = true;
  886. mReifyQueued = false;
  887. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  888. mCompiler->mStats.mModulesReified++;
  889. }
  890. void BfModule::UnreifyModule()
  891. {
  892. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  893. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  894. mIsReified = false;
  895. mReifyQueued = false;
  896. StartNewRevision(RebuildKind_None, true);
  897. mCompiler->mStats.mModulesUnreified++;
  898. }
  899. void BfModule::CleanupFileInstances()
  900. {
  901. for (auto& itr : mNamedFileInstanceMap)
  902. {
  903. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  904. delete itr.mValue;
  905. }
  906. mCurFilePosition.mFileInstance = NULL;//
  907. mFileInstanceMap.Clear();
  908. mNamedFileInstanceMap.Clear();
  909. }
  910. void BfModule::Cleanup()
  911. {
  912. CleanupFileInstances();
  913. }
  914. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  915. {
  916. if (HasCompiledOutput())
  917. {
  918. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  919. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  920. {
  921. StartExtension();
  922. }
  923. }
  924. else
  925. {
  926. EnsureIRBuilder();
  927. }
  928. }
  929. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  930. {
  931. BF_ASSERT(!mIsDeleting);
  932. if (mBfIRBuilder == NULL)
  933. {
  934. if ((!mIsScratchModule) && (!mAddedToCount))
  935. {
  936. mCompiler->mStats.mModulesStarted++;
  937. mAddedToCount = true;
  938. }
  939. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  940. /*if (mCompiler->mIsResolveOnly)
  941. BF_ASSERT(mIsResolveOnly);*/
  942. mBfIRBuilder = new BfIRBuilder(this);
  943. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  944. if (mIsScratchModule)
  945. {
  946. mBfIRBuilder->mIgnoreWrites = true;
  947. BF_ASSERT(!dbgVerifyCodeGen);
  948. }
  949. #ifdef _DEBUG
  950. if (mCompiler->mIsResolveOnly)
  951. {
  952. // For "deep" verification testing
  953. /*if (!mIsSpecialModule)
  954. dbgVerifyCodeGen = true;*/
  955. // We only want to turn this off on smaller builds for testing
  956. mBfIRBuilder->mIgnoreWrites = true;
  957. if (dbgVerifyCodeGen)
  958. mBfIRBuilder->mIgnoreWrites = false;
  959. if (!mBfIRBuilder->mIgnoreWrites)
  960. {
  961. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  962. mBfIRBuilder->mDbgVerifyCodeGen = true;
  963. }
  964. }
  965. else if (!mIsReified)
  966. {
  967. mBfIRBuilder->mIgnoreWrites = true;
  968. }
  969. else
  970. {
  971. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  972. // code as we walk the AST
  973. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  974. if (
  975. (mModuleName == "Program")
  976. //|| (mModuleName == "System_Internal")
  977. //|| (mModuleName == "vdata")
  978. //|| (mModuleName == "Hey_Dude_Bro_TestClass")
  979. )
  980. mBfIRBuilder->mDbgVerifyCodeGen = true;
  981. // Just for testing!
  982. //mBfIRBuilder->mIgnoreWrites = true;
  983. }
  984. #else
  985. if (mCompiler->mIsResolveOnly)
  986. {
  987. // Always ignore writes in resolveOnly for release builds
  988. mBfIRBuilder->mIgnoreWrites = true;
  989. }
  990. else
  991. {
  992. // Just for memory testing! This breaks everything.
  993. //mBfIRBuilder->mIgnoreWrites = true;
  994. // For "deep" verification testing
  995. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  996. }
  997. #endif
  998. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  999. }
  1000. }
  1001. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1002. {
  1003. String name = "FORCELINKMOD_" + module->mModuleName;
  1004. if (outName != NULL)
  1005. *outName = name;
  1006. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1007. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1008. }
  1009. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1010. {
  1011. BP_ZONE("BfModule::StartNewRevision");
  1012. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1013. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1014. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1015. // Already on new revision?
  1016. if ((mRevision == mCompiler->mRevision) && (!force))
  1017. return;
  1018. mHadBuildError = false;
  1019. mHadBuildWarning = false;
  1020. mExtensionCount = 0;
  1021. mRevision = mCompiler->mRevision;
  1022. mRebuildIdx++;
  1023. ClearModuleData();
  1024. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1025. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1026. mStringPoolRefs.Clear();
  1027. mDllImportEntries.Clear();
  1028. mImportFileNames.Clear();
  1029. for (auto& pairVal : mDeferredMethodCallData)
  1030. delete pairVal.mValue;
  1031. mDeferredMethodCallData.Clear();
  1032. mDeferredMethodIds.Clear();
  1033. mModuleRefs.Clear();
  1034. mOutFileNames.Clear();
  1035. mTypeDataRefs.Clear();
  1036. mInterfaceSlotRefs.Clear();
  1037. if (rebuildKind == BfModule::RebuildKind_None)
  1038. {
  1039. for (auto& specPair : mSpecializedMethodModules)
  1040. {
  1041. auto specModule = specPair.mValue;
  1042. if (specModule->mIsReified != mIsReified)
  1043. {
  1044. if (mIsReified)
  1045. specModule->ReifyModule();
  1046. else
  1047. specModule->UnreifyModule();
  1048. }
  1049. }
  1050. }
  1051. else
  1052. {
  1053. for (auto& specPair : mSpecializedMethodModules)
  1054. {
  1055. auto specModule = specPair.mValue;
  1056. delete specModule;
  1057. }
  1058. }
  1059. mSpecializedMethodModules.Clear();
  1060. delete mNextAltModule;
  1061. mNextAltModule = NULL;
  1062. BF_ASSERT(mModuleOptions == NULL);
  1063. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1064. bool needsTypePopulated = false;
  1065. int oldOnDemandCount = 0;
  1066. // We don't have to rebuild types in the unspecialized module because there is no
  1067. // data that's needed -- their method instances are all NULL and the module
  1068. // doesn't get included in the build
  1069. if (this != mContext->mScratchModule)
  1070. {
  1071. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1072. {
  1073. auto typeInst = mOwnedTypeInstances[typeIdx];
  1074. if (!typeInst->IsDeleting())
  1075. {
  1076. typeInst->mIsReified = mIsReified;
  1077. if (rebuildKind != BfModule::RebuildKind_None)
  1078. {
  1079. if (typeInst->IsOnDemand())
  1080. {
  1081. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1082. if (rebuildKind == BfModule::RebuildKind_All)
  1083. mContext->DeleteType(typeInst);
  1084. else
  1085. {
  1086. RebuildMethods(typeInst);
  1087. }
  1088. }
  1089. else
  1090. mContext->RebuildType(typeInst, false, false, false);
  1091. }
  1092. else
  1093. {
  1094. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1095. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1096. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference))
  1097. {
  1098. oldOnDemandCount++;
  1099. }
  1100. }
  1101. if (typeInst->IsDeleting())
  1102. typeIdx--;
  1103. }
  1104. }
  1105. }
  1106. if (!mIsDeleting)
  1107. Init();
  1108. mOnDemandMethodCount += oldOnDemandCount;
  1109. }
  1110. void BfModule::StartExtension()
  1111. {
  1112. BF_ASSERT(!mIsModuleMutable);
  1113. BfLogSysM("Extension started of module %p\n", this);
  1114. mExtensionCount++;
  1115. if (mBfIRBuilder != NULL)
  1116. mPrevIRBuilders.push_back(mBfIRBuilder);
  1117. mBfIRBuilder = NULL;
  1118. mWantsIRIgnoreWrites = false;
  1119. mFuncReferences.Clear();
  1120. mClassVDataRefs.Clear();
  1121. mClassVDataExtRefs.Clear();
  1122. for (auto& kv : mTypeDataRefs)
  1123. kv.mValue = BfIRValue();
  1124. mDbgRawAllocDataRefs.Clear();
  1125. mStringCharPtrPool.Clear();
  1126. mStringObjectPool.Clear();
  1127. mStaticFieldRefs.Clear();
  1128. for (auto& kv : mInterfaceSlotRefs)
  1129. kv.mValue = BfIRValue();
  1130. mDeferredMethodCallData.Clear();
  1131. mDeferredMethodIds.Clear();
  1132. DisownMethods();
  1133. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1134. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1135. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1136. Init(false);
  1137. if (!wasAwaitingInitFinish)
  1138. FinishInit();
  1139. mOnDemandMethodCount = prevOnDemandMethodCount;
  1140. }
  1141. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1142. {
  1143. BfIRValue vDataValue;
  1144. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1145. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1146. else
  1147. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1148. typeValueParams.push_back(vDataValue);
  1149. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1150. {
  1151. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1152. typeValueParams.push_back(GetDefaultValue(primType));
  1153. }
  1154. }
  1155. BfIRValue BfModule::GetConstValue(int64 val)
  1156. {
  1157. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1158. }
  1159. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1160. {
  1161. BfType* checkType = type;
  1162. if (type->IsTypedPrimitive())
  1163. {
  1164. checkType = type->GetUnderlyingType();
  1165. }
  1166. if (checkType->IsPrimitiveType())
  1167. {
  1168. auto primType = (BfPrimitiveType*)checkType;
  1169. if (checkType->IsFloat())
  1170. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1171. else
  1172. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1173. }
  1174. return BfIRValue();
  1175. }
  1176. BfIRValue BfModule::GetConstValue8(int val)
  1177. {
  1178. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1179. }
  1180. BfIRValue BfModule::GetConstValue32(int32 val)
  1181. {
  1182. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1183. }
  1184. BfIRValue BfModule::GetConstValue64(int64 val)
  1185. {
  1186. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1187. }
  1188. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1189. {
  1190. PopulateType(type, BfPopulateType_Data);
  1191. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1192. if (type->IsTypedPrimitive())
  1193. {
  1194. auto underlyingType = type->GetUnderlyingType();
  1195. if (underlyingType == NULL)
  1196. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1197. return GetDefaultValue(type->GetUnderlyingType());
  1198. }
  1199. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1200. type->IsRetTypeType() || type->IsConcreteInterfaceType())
  1201. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1202. if ((type->IsIntegral()) || (type->IsBoolean()))
  1203. {
  1204. auto primType = (BfPrimitiveType*)type;
  1205. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1206. }
  1207. if (type->IsFloat())
  1208. {
  1209. auto primType = (BfPrimitiveType*)type;
  1210. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1211. }
  1212. if (type->IsVoid())
  1213. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1214. return mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(type));
  1215. }
  1216. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1217. {
  1218. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1219. if (type->mSize == 0)
  1220. return BfTypedValue(BfIRValue(), type);
  1221. else
  1222. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1223. }
  1224. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1225. {
  1226. PopulateType(type, BfPopulateType_Data);
  1227. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1228. if (defaultValueKind == BfDefaultValueKind_Undef)
  1229. {
  1230. auto primType = type->ToPrimitiveType();
  1231. if (primType != NULL)
  1232. {
  1233. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode), type);
  1234. }
  1235. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(type)), type);
  1236. }
  1237. BfTypedValue typedValue;
  1238. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1239. {
  1240. if (type->IsRef())
  1241. {
  1242. BfRefType* refType = (BfRefType*)type;
  1243. BfType* underlyingType = refType->GetUnderlyingType();
  1244. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1245. }
  1246. else
  1247. {
  1248. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1249. }
  1250. if (!mBfIRBuilder->mIgnoreWrites)
  1251. {
  1252. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1253. GetConstValue(type->mSize), type->mAlign);
  1254. }
  1255. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1256. typedValue = LoadValue(typedValue);
  1257. return typedValue;
  1258. }
  1259. if ((type->IsRef()) && (!allowRef))
  1260. {
  1261. BfRefType* refType = (BfRefType*)type;
  1262. BfType* underlyingType = refType->GetUnderlyingType();
  1263. if (underlyingType->IsValuelessType())
  1264. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1265. else
  1266. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1267. }
  1268. else
  1269. {
  1270. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1271. }
  1272. return typedValue;
  1273. }
  1274. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1275. {
  1276. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1277. BfIRType strCharType;
  1278. //
  1279. {
  1280. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites);
  1281. strCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Char8), (int)str.length() + 1);
  1282. }
  1283. BfIRValue strConstant;
  1284. if (define)
  1285. {
  1286. strConstant = mBfIRBuilder->CreateConstString(str);
  1287. }
  1288. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(strCharType,
  1289. true, BfIRLinkageType_External,
  1290. strConstant, stringDataName);
  1291. if (define)
  1292. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1293. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1294. }
  1295. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1296. {
  1297. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1298. mBfIRBuilder->PopulateType(stringTypeInst);
  1299. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1300. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1301. BfIRValue stringValData;
  1302. if (define)
  1303. {
  1304. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1305. mStringCharPtrPool[stringId] = stringCharsVal;
  1306. SizedArray<BfIRValue, 8> typeValueParams;
  1307. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1308. auto objData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1309. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1310. typeValueParams.clear();
  1311. typeValueParams.push_back(objData);
  1312. if (lenByteCount == 4)
  1313. {
  1314. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1315. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1316. }
  1317. else
  1318. {
  1319. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1320. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1321. }
  1322. typeValueParams.push_back(stringCharsVal); // mPtr
  1323. stringValData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1324. }
  1325. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1326. mBfIRBuilder->MapTypeInst(stringTypeInst),
  1327. true,
  1328. BfIRLinkageType_External,
  1329. define ? stringValData : BfIRValue(),
  1330. stringObjName);
  1331. auto stringVal = mBfIRBuilder->CreateBitCast(stringValLiteral, mBfIRBuilder->MapType(stringTypeInst, BfIRPopulateType_Full));
  1332. return stringVal;
  1333. }
  1334. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1335. {
  1336. BF_ASSERT(constantStr.IsConst());
  1337. if (constHolder == NULL)
  1338. constHolder = mBfIRBuilder;
  1339. auto constant = constHolder->GetConstant(constantStr);
  1340. if (constant->mTypeCode == BfTypeCode_Int32)
  1341. {
  1342. return constant->mInt32;
  1343. }
  1344. while (constant->mConstType == BfConstType_BitCast)
  1345. {
  1346. auto constBitCast = (BfConstantBitCast*)constant;
  1347. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1348. }
  1349. if (constant->mConstType == BfConstType_GEP32_2)
  1350. {
  1351. auto constGEP = (BfConstantGEP32_2*)constant;
  1352. constant = constHolder->GetConstantById(constGEP->mTarget);
  1353. }
  1354. if (constant->mConstType == BfConstType_GlobalVar)
  1355. {
  1356. auto constGV = (BfGlobalVar*)constant;
  1357. const char* strDataPrefix = "__bfStrData";
  1358. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1359. return atoi(constGV->mName + strlen(strDataPrefix));
  1360. const char* strObjPrefix = "__bfStrObj";
  1361. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1362. return atoi(constGV->mName + strlen(strObjPrefix));
  1363. }
  1364. return -1;
  1365. }
  1366. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1367. {
  1368. int strId = GetStringPoolIdx(constantStr, constHolder);
  1369. if (strId != -1)
  1370. {
  1371. auto& entry = mContext->mStringObjectIdMap[strId];
  1372. return &entry.mString;
  1373. }
  1374. return NULL;
  1375. }
  1376. BfIRValue BfModule::GetStringCharPtr(int stringId)
  1377. {
  1378. BfIRValue* irValue = NULL;
  1379. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1380. return *irValue;
  1381. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1382. if (!mStringObjectPool.ContainsKey(stringId))
  1383. mStringPoolRefs.Add(stringId);
  1384. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1385. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1386. *irValue = strCharPtrConst;
  1387. return strCharPtrConst;
  1388. }
  1389. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue)
  1390. {
  1391. if (strValue.IsConst())
  1392. {
  1393. int stringId = GetStringPoolIdx(strValue);
  1394. BF_ASSERT(stringId != -1);
  1395. return GetStringCharPtr(stringId);
  1396. }
  1397. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1398. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1399. return charPtr;
  1400. }
  1401. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str)
  1402. {
  1403. return GetStringCharPtr(GetStringObjectValue(str));
  1404. }
  1405. BfIRValue BfModule::GetStringObjectValue(int strId)
  1406. {
  1407. BfIRValue* objValue;
  1408. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1409. return *objValue;
  1410. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1411. return GetStringObjectValue(stringPoolEntry.mString, true);
  1412. }
  1413. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define)
  1414. {
  1415. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1416. mBfIRBuilder->PopulateType(stringType);
  1417. int strId = mContext->GetStringLiteralId(str);
  1418. BfIRValue* irValuePtr = NULL;
  1419. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1420. return *irValuePtr;
  1421. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1422. if (!mStringCharPtrPool.ContainsKey(strId))
  1423. mStringPoolRefs.Add(strId);
  1424. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1425. *irValuePtr = strObject;
  1426. mStringPoolRefs.Add(strId);
  1427. return strObject;
  1428. }
  1429. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1430. {
  1431. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1432. type,
  1433. true,
  1434. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1435. constant,
  1436. name.c_str());
  1437. return newConst;
  1438. }
  1439. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1440. {
  1441. auto curScope = mCurMethodState->mCurScope;
  1442. if (curScope->mLabelNode != NULL)
  1443. curScope->mLabelNode->ToString(curScope->mLabel);
  1444. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1445. {
  1446. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1447. while (checkScope != NULL)
  1448. {
  1449. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1450. {
  1451. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1452. if (errorNode != NULL)
  1453. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1454. break;
  1455. }
  1456. checkScope = checkScope->mPrevScope;
  1457. }
  1458. }
  1459. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1460. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1461. {
  1462. if (prevScope->mHadScopeValueRetain)
  1463. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1464. else
  1465. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1466. }
  1467. mCurMethodState->mBlockNestLevel++;
  1468. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1469. {
  1470. // DIScope could be NULL if we're in an unspecialized method (for example)
  1471. if (mCurMethodState->mCurScope->mDIScope)
  1472. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1473. }
  1474. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1475. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1476. }
  1477. void BfModule::RestoreScoreState_LocalVariables()
  1478. {
  1479. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1480. {
  1481. auto localVar = mCurMethodState->mLocals.back();
  1482. LocalVariableDone(localVar, false);
  1483. mCurMethodState->mLocals.pop_back();
  1484. if (localVar->mShadowedLocal != NULL)
  1485. {
  1486. BfLocalVarEntry* localVarEntryPtr;
  1487. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1488. {
  1489. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1490. }
  1491. }
  1492. else
  1493. {
  1494. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1495. }
  1496. delete localVar;
  1497. }
  1498. }
  1499. void BfModule::RestoreScopeState()
  1500. {
  1501. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1502. mCurMethodState->mBlockNestLevel--;
  1503. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1504. {
  1505. BfIRBlock afterEndBlock;
  1506. if (!mCurMethodState->mLeftBlockUncond)
  1507. {
  1508. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1509. mBfIRBuilder->CreateBr(afterEndBlock);
  1510. mBfIRBuilder->ClearDebugLocation_Last();
  1511. }
  1512. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1513. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1514. if (afterEndBlock)
  1515. {
  1516. mBfIRBuilder->AddBlock(afterEndBlock);
  1517. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1518. }
  1519. }
  1520. if (!mCurMethodState->mLeftBlockUncond)
  1521. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1522. RestoreScoreState_LocalVariables();
  1523. if (mCurMethodState->mCurScope->mValueScopeStart)
  1524. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1525. mCurMethodState->mCurScope = prevScopeData;
  1526. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1527. }
  1528. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1529. {
  1530. if (mBfIRBuilder->mIgnoreWrites)
  1531. return mBfIRBuilder->GetFakeVal();
  1532. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1533. mBfIRBuilder->PopulateType(type);
  1534. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1535. if (!mBfIRBuilder->mIgnoreWrites)
  1536. BF_ASSERT(!prevInsertBlock.IsFake());
  1537. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1538. BfIRValue allocaInst;
  1539. if (arraySize)
  1540. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1541. else
  1542. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1543. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1544. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1545. if (name != NULL)
  1546. mBfIRBuilder->SetName(allocaInst, name);
  1547. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1548. if ((addLifetime) && (WantsLifetimes()))
  1549. {
  1550. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1551. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1552. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1553. }
  1554. return allocaInst;
  1555. }
  1556. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1557. {
  1558. if (mBfIRBuilder->mIgnoreWrites)
  1559. return mBfIRBuilder->GetFakeVal();
  1560. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1561. mBfIRBuilder->PopulateType(typeInst);
  1562. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1563. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1564. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1565. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1566. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1567. if (name != NULL)
  1568. mBfIRBuilder->SetName(allocaInst, name);
  1569. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1570. if ((addLifetime) && (WantsLifetimes()))
  1571. {
  1572. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1573. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1574. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1575. }
  1576. return allocaInst;
  1577. }
  1578. void BfModule::AddStackAlloc(BfTypedValue val, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape)
  1579. {
  1580. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1581. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1582. /*if (mCurMethodState->mInHeadScope)
  1583. isScopeAlloc = true;*/
  1584. if (scopeData == NULL)
  1585. return;
  1586. auto checkBaseType = val.mType->ToTypeInstance();
  1587. if ((checkBaseType != NULL) && (checkBaseType->IsObject()))
  1588. {
  1589. bool hadDtorCall = false;
  1590. while (checkBaseType != NULL)
  1591. {
  1592. if ((checkBaseType->mTypeDef->mDtorDef != NULL) /*&& (checkBaseType != mContext->mBfObjectType)*/)
  1593. {
  1594. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1595. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  1596. BfIRValue useVal = val.mValue;
  1597. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1598. if (isDynAlloc)
  1599. {
  1600. //
  1601. }
  1602. else if (condAlloca)
  1603. {
  1604. BF_ASSERT(!IsTargetingBeefBackend());
  1605. BF_ASSERT(!isDynAlloc);
  1606. auto valPtr = CreateAlloca(checkBaseType);
  1607. mBfIRBuilder->CreateStore(useVal, valPtr);
  1608. useVal = valPtr;
  1609. }
  1610. SizedArray<BfIRValue, 1> llvmArgs;
  1611. llvmArgs.push_back(useVal);
  1612. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1613. if (deferredCall != NULL)
  1614. {
  1615. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1616. if (condAlloca)
  1617. deferredCall->mArgsNeedLoad = true;
  1618. }
  1619. hadDtorCall = true;
  1620. break;
  1621. }
  1622. checkBaseType = checkBaseType->mBaseType;
  1623. }
  1624. return;
  1625. }
  1626. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1627. if (mayEscape)
  1628. {
  1629. // Is this worth it?
  1630. // if ((!IsOptimized()) && (val.mType->IsComposite()) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1631. // {
  1632. // auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1633. // bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1634. // if (!isDyn)
  1635. // {
  1636. // int clearSize = val.mType->mSize;
  1637. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod("MemSet");
  1638. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1639. // SizedArray<BfIRValue, 1> llvmArgs;
  1640. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1641. // llvmArgs.push_back(GetConstValue8(0xDD));
  1642. // llvmArgs.push_back(GetConstValue(clearSize));
  1643. // llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1644. // llvmArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0));
  1645. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1646. // }
  1647. // else
  1648. // {
  1649. // const char* funcName = "SetDeleted1";
  1650. // if (val.mType->mSize >= 16)
  1651. // funcName = "SetDeleted16";
  1652. // else if (val.mType->mSize >= 8)
  1653. // funcName = "SetDeleted8";
  1654. // else if (val.mType->mSize >= 4)
  1655. // funcName = "SetDeleted4";
  1656. //
  1657. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1658. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1659. // SizedArray<BfIRValue, 1> llvmArgs;
  1660. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1661. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1662. // }
  1663. // }
  1664. }
  1665. }
  1666. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1667. {
  1668. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1669. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1670. return false;
  1671. auto checkTypeInstance = startTypeInstance;
  1672. while (checkTypeInstance != NULL)
  1673. {
  1674. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1675. {
  1676. if (fieldInstance.mMergedDataIdx != -1)
  1677. {
  1678. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1679. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1680. {
  1681. // For fields added in extensions, we automatically initialize those if necessary
  1682. auto fieldDef = fieldInstance.GetFieldDef();
  1683. if (!fieldDef->mDeclaringType->IsExtension())
  1684. return false;
  1685. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1686. {
  1687. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1688. mBfIRBuilder->SaveDebugLocation();
  1689. if (localVar->IsParam())
  1690. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1691. else
  1692. {
  1693. BF_ASSERT(localVar->mDeclBlock);
  1694. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1695. }
  1696. mBfIRBuilder->ClearDebugLocation();
  1697. BfIRValue curVal;
  1698. if (localVar->mIsThis)
  1699. curVal = mBfIRBuilder->GetArgument(0);
  1700. else
  1701. curVal = localVar->mAddr;
  1702. auto subTypeInstance = startTypeInstance;
  1703. while (subTypeInstance != checkTypeInstance)
  1704. {
  1705. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1706. subTypeInstance = subTypeInstance->mBaseType;
  1707. }
  1708. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1709. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1710. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1711. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1712. mBfIRBuilder->RestoreDebugLocation();
  1713. }
  1714. localVar->mUnassignedFieldFlags &= ~checkMask;
  1715. if (localVar->mUnassignedFieldFlags == 0)
  1716. localVar->mIsAssigned = true;
  1717. }
  1718. }
  1719. }
  1720. checkTypeInstance = checkTypeInstance->mBaseType;
  1721. }
  1722. return localVar->mIsAssigned;
  1723. }
  1724. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1725. {
  1726. //if (localVar->mAddr == NULL)
  1727. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1728. {
  1729. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1730. {
  1731. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1732. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1733. }
  1734. }*/
  1735. BfAstNode* localNameNode = localVar->mNameNode;
  1736. if (localVar->mIsThis)
  1737. {
  1738. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1739. }
  1740. if (localNameNode != NULL)
  1741. {
  1742. bool isOut = false;
  1743. if (localVar->mResolvedType->IsRef())
  1744. {
  1745. auto refType = (BfRefType*)localVar->mResolvedType;
  1746. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1747. }
  1748. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1749. {
  1750. if ((!localVar->mIsAssigned) & (localVar->IsParam()))
  1751. TryLocalVariableInit(localVar);
  1752. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1753. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1754. //bool deferFullAnalysis = true;
  1755. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1756. if (!localVar->mIsAssigned)
  1757. {
  1758. if (deferUsageWarning)
  1759. {
  1760. // Ignore
  1761. }
  1762. else if (localVar->mIsThis)
  1763. {
  1764. bool foundFields = false;
  1765. auto checkTypeInstance = mCurTypeInstance;
  1766. while (checkTypeInstance != NULL)
  1767. {
  1768. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1769. {
  1770. if (fieldInstance.mMergedDataIdx != -1)
  1771. {
  1772. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1773. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1774. {
  1775. auto fieldDef = fieldInstance.GetFieldDef();
  1776. if (fieldDef->mProtection != BfProtection_Hidden)
  1777. {
  1778. if (checkTypeInstance == mCurTypeInstance)
  1779. {
  1780. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  1781. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1782. }
  1783. else
  1784. {
  1785. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  1786. TypeToString(checkTypeInstance).c_str(),
  1787. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1788. }
  1789. }
  1790. foundFields = true;
  1791. }
  1792. }
  1793. }
  1794. checkTypeInstance = checkTypeInstance->mBaseType;
  1795. }
  1796. if (!foundFields)
  1797. {
  1798. if (mCurTypeInstance->mInstSize > 0)
  1799. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  1800. }
  1801. }
  1802. else if (localVar->IsParam())
  1803. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  1804. else if (!deferUsageWarning)
  1805. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1806. }
  1807. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  1808. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1809. }
  1810. }
  1811. }
  1812. void BfModule::MarkDynStack(BfScopeData* scopeData)
  1813. {
  1814. auto checkScope = mCurMethodState->mCurScope;
  1815. while (true)
  1816. {
  1817. if (checkScope == scopeData)
  1818. break;
  1819. checkScope->mHadOuterDynStack = true;
  1820. checkScope = checkScope->mPrevScope;
  1821. }
  1822. }
  1823. void BfModule::SaveStackState(BfScopeData* scopeData)
  1824. {
  1825. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  1826. // scopes within scopeData restore the stack
  1827. auto checkScope = mCurMethodState->mCurScope;
  1828. while (true)
  1829. {
  1830. if (checkScope == scopeData)
  1831. {
  1832. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  1833. {
  1834. if (mBfIRBuilder->mHasDebugInfo)
  1835. mBfIRBuilder->SaveDebugLocation();
  1836. auto prevPos = mBfIRBuilder->GetInsertBlock();
  1837. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  1838. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  1839. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  1840. mBfIRBuilder->SetInsertPoint(prevPos);
  1841. if (mBfIRBuilder->mHasDebugInfo)
  1842. mBfIRBuilder->RestoreDebugLocation();
  1843. }
  1844. break;
  1845. }
  1846. if (checkScope->mSavedStack)
  1847. {
  1848. for (auto usage : checkScope->mSavedStackUses)
  1849. mBfIRBuilder->EraseInstFromParent(usage);
  1850. checkScope->mSavedStackUses.Clear();
  1851. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  1852. checkScope->mSavedStack = BfIRValue();
  1853. }
  1854. checkScope = checkScope->mPrevScope;
  1855. }
  1856. }
  1857. BfIRValue BfModule::ValueScopeStart()
  1858. {
  1859. if (IsTargetingBeefBackend())
  1860. return mBfIRBuilder->CreateValueScopeStart();
  1861. return BfIRValue();
  1862. }
  1863. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  1864. {
  1865. if (valueScopeStart)
  1866. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  1867. }
  1868. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  1869. {
  1870. auto bfParser = astNode->GetSourceData()->ToParserData();
  1871. if (bfParser == NULL)
  1872. return NULL;
  1873. BfFileInstance** fileInstancePtr = NULL;
  1874. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  1875. {
  1876. return *fileInstancePtr;
  1877. }
  1878. else
  1879. {
  1880. // It's possible two parsers have the same file name (ie: mNextRevision)
  1881. BfFileInstance** namedFileInstancePtr = NULL;
  1882. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  1883. {
  1884. auto bfFileInstance = *namedFileInstancePtr;
  1885. *fileInstancePtr = bfFileInstance;
  1886. return bfFileInstance;
  1887. }
  1888. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  1889. auto bfFileInstance = new BfFileInstance();
  1890. *fileInstancePtr = bfFileInstance;
  1891. *namedFileInstancePtr = bfFileInstance;
  1892. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  1893. bfFileInstance->mParser = bfParser;
  1894. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  1895. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasInfo()))
  1896. {
  1897. String fileName = bfParser->mFileName;
  1898. for (int i = 0; i < (int)fileName.length(); i++)
  1899. {
  1900. if (fileName[i] == DIR_SEP_CHAR_ALT)
  1901. fileName[i] = DIR_SEP_CHAR;
  1902. }
  1903. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, slashPos));
  1904. }
  1905. return bfFileInstance;
  1906. }
  1907. }
  1908. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  1909. {
  1910. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  1911. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  1912. return;
  1913. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  1914. if (astNode == NULL)
  1915. return;
  1916. auto bfParser = astNode->GetSourceData()->ToParserData();
  1917. if (bfParser == NULL)
  1918. return;
  1919. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  1920. {
  1921. if (mCurFilePosition.mFileInstance != NULL)
  1922. {
  1923. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  1924. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  1925. }
  1926. auto bfFileInstance = GetFileFromNode(astNode);
  1927. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  1928. {
  1929. mCurFilePosition = bfFileInstance->mPrevPosition;
  1930. }
  1931. else
  1932. {
  1933. mCurFilePosition.mFileInstance = bfFileInstance;
  1934. mCurFilePosition.mCurLine = 0;
  1935. mCurFilePosition.mCurSrcPos = 0;
  1936. }
  1937. }
  1938. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  1939. BF_ASSERT(srcPos < bfParser->mSrcLength);
  1940. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  1941. if (jumpEntry->mCharIdx > srcPos)
  1942. jumpEntry--;
  1943. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  1944. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  1945. mCurFilePosition.mCurColumn = 0;
  1946. while (mCurFilePosition.mCurSrcPos < srcPos)
  1947. {
  1948. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  1949. {
  1950. mCurFilePosition.mCurLine++;
  1951. mCurFilePosition.mCurColumn = 0;
  1952. }
  1953. else
  1954. {
  1955. mCurFilePosition.mCurColumn++;
  1956. }
  1957. mCurFilePosition.mCurSrcPos++;
  1958. }
  1959. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  1960. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1961. {
  1962. int column = mCurFilePosition.mCurColumn + 1;
  1963. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  1964. {
  1965. // Set to illegal position
  1966. column = 0;
  1967. }
  1968. if (mSetIllegalSrcPosition)
  1969. column = 0;
  1970. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  1971. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  1972. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  1973. {
  1974. // This is from a different scope...
  1975. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  1976. {
  1977. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  1978. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  1979. }
  1980. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  1981. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  1982. }
  1983. else
  1984. {
  1985. if (mCurMethodState->mCurScope->mAltDIFile)
  1986. {
  1987. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  1988. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  1989. }
  1990. }
  1991. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  1992. if (mCurMethodState->mCrossingMixin)
  1993. inlineAt = BfIRMDNode();
  1994. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  1995. if ((flags & BfSrcPosFlag_Expression) == 0)
  1996. mBfIRBuilder->CreateStatementStart();
  1997. }
  1998. }
  1999. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2000. {
  2001. // We've turned off expr src pos (for now?)
  2002. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2003. }
  2004. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2005. {
  2006. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2007. }
  2008. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2009. {
  2010. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2011. {
  2012. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2013. {
  2014. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2015. mBfIRBuilder->SetCurrentDebugLocation(0, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2016. }
  2017. else
  2018. {
  2019. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2020. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2021. }
  2022. if ((flags & BfSrcPosFlag_Expression) == 0)
  2023. mBfIRBuilder->CreateStatementStart();
  2024. }
  2025. }
  2026. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2027. {
  2028. // We've turned off expr src pos (for now?)
  2029. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2030. }
  2031. bool BfModule::CheckProtection(BfProtection protection, bool allowProtected, bool allowPrivate)
  2032. {
  2033. if ((protection == BfProtection_Public) ||
  2034. ((protection == BfProtection_Protected) && (allowProtected)) ||
  2035. ((protection == BfProtection_Private) && (allowPrivate)))
  2036. return true;
  2037. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2038. return true;
  2039. return false;
  2040. }
  2041. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2042. {
  2043. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2044. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2045. {
  2046. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2047. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2048. }
  2049. allowProtected = allowPrivate;
  2050. }
  2051. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2052. {
  2053. if (memberProtection == BfProtection_Hidden)
  2054. return false;
  2055. if (memberProtection == BfProtection_Public)
  2056. return true;
  2057. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2058. {
  2059. BfTypeInstance* curCheckType = mCurTypeInstance;
  2060. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2061. {
  2062. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2063. curCheckType = mixinOwner;
  2064. }
  2065. bool allowPrivate = (memberOwner->mTypeDef == curCheckType->mTypeDef) || (IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef));
  2066. if (allowPrivate)
  2067. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2068. else
  2069. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2070. }
  2071. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2072. return true;
  2073. if (memberProtection == BfProtection_Protected)
  2074. {
  2075. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2076. {
  2077. bool allowProtected = false;
  2078. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2079. auto curCheckType = mCurTypeInstance;
  2080. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2081. {
  2082. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2083. curCheckType = mixinOwner;
  2084. }
  2085. auto lookupCheckType = lookupStartType;
  2086. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2087. {
  2088. if (lookupCheckType == curCheckType)
  2089. {
  2090. allowProtected = true;
  2091. break;
  2092. }
  2093. if (lookupCheckType == memberOwner)
  2094. break;
  2095. lookupCheckType = lookupCheckType->mBaseType;
  2096. if (lookupCheckType == NULL)
  2097. break;
  2098. }
  2099. if (!allowProtected)
  2100. {
  2101. // It's possible our outer type is derived from 'memberOwner'
  2102. while (curCheckType->mTypeDef->mNestDepth > 0)
  2103. {
  2104. curCheckType = GetOuterType(curCheckType);
  2105. if (curCheckType == NULL)
  2106. break;
  2107. auto lookupCheckType = lookupStartType;
  2108. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2109. {
  2110. if (lookupCheckType == curCheckType)
  2111. {
  2112. allowProtected = true;
  2113. break;
  2114. }
  2115. if (lookupCheckType == memberOwner)
  2116. break;
  2117. lookupCheckType = lookupCheckType->mBaseType;
  2118. if (lookupCheckType == NULL)
  2119. break;
  2120. }
  2121. }
  2122. }
  2123. if (allowProtected)
  2124. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2125. else
  2126. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2127. }
  2128. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2129. return true;
  2130. }
  2131. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2132. return true;
  2133. return false;
  2134. }
  2135. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2136. {
  2137. if ((mCompiler->mResolvePassData != NULL) &&
  2138. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2139. (astNode->IsFromParser( mCompiler->mResolvePassData->mParser)))
  2140. {
  2141. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2142. }
  2143. }
  2144. void BfModule::SetHadVarUsage()
  2145. {
  2146. mHadVarUsage = true;
  2147. mHadBuildError = true;
  2148. }
  2149. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent)
  2150. {
  2151. BP_ZONE("BfModule::Fail");
  2152. if (mIgnoreErrors)
  2153. {
  2154. mHadIgnoredError = true;
  2155. return NULL;
  2156. }
  2157. if (!mReportErrors)
  2158. {
  2159. mCompiler->mPassInstance->SilentFail();
  2160. return NULL;
  2161. }
  2162. if (refNode != NULL)
  2163. refNode = BfNodeToNonTemporary(refNode);
  2164. //BF_ASSERT(refNode != NULL);
  2165. if (mCurMethodInstance != NULL)
  2166. mCurMethodInstance->mHasFailed = true;
  2167. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2168. return NULL;
  2169. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecializedVariation))
  2170. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2171. if (!mHadBuildError)
  2172. mHadBuildError = true;
  2173. if (mParentModule != NULL)
  2174. mParentModule->mHadBuildError = true;
  2175. if (mCurTypeInstance != NULL)
  2176. AddFailType(mCurTypeInstance);
  2177. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2178. String errorString = error;
  2179. bool isWhileSpecializing = false;
  2180. bool isWhileSpecializingMethod = false;
  2181. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2182. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2183. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2184. errorString += StrFormat("\n while generating append size calculating method");
  2185. else if (refNode == NULL)
  2186. {
  2187. if (mCurTypeInstance != NULL)
  2188. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2189. else if (mProject != NULL)
  2190. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2191. }
  2192. if ((mCurTypeInstance != NULL) && (mCurMethodState != NULL))
  2193. {
  2194. auto checkMethodState = mCurMethodState;
  2195. while (checkMethodState != NULL)
  2196. {
  2197. auto methodInstance = checkMethodState->mMethodInstance;
  2198. if (methodInstance == NULL)
  2199. {
  2200. checkMethodState = checkMethodState->mPrevMethodState;
  2201. continue;
  2202. }
  2203. // Propogatea the fail all the way to the main method (assuming we're in a local method or lambda)
  2204. methodInstance->mHasFailed = true;
  2205. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2206. if (isSpecializedMethod)
  2207. {
  2208. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2209. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2210. if (unspecializedMethod->mHasFailed)
  2211. return NULL; // At least SOME error has already been reported
  2212. }
  2213. if (isSpecializedMethod)
  2214. {
  2215. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2216. isWhileSpecializing = true;
  2217. isWhileSpecializingMethod = true;
  2218. }
  2219. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2220. {
  2221. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2222. isWhileSpecializing = true;
  2223. isWhileSpecializingMethod = true;
  2224. }
  2225. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2226. {
  2227. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2228. isWhileSpecializing = true;
  2229. }
  2230. checkMethodState = checkMethodState->mPrevMethodState;
  2231. }
  2232. // Keep in mind that all method specializations with generic type instances as its method generic params
  2233. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2234. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2235. // those method specializations if that occurs
  2236. if (isWhileSpecializing)
  2237. {
  2238. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2239. if (bfError != NULL)
  2240. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2241. return bfError;
  2242. }
  2243. }
  2244. if (!mHadBuildError)
  2245. mHadBuildError = true;
  2246. // Check mixins
  2247. {
  2248. auto checkMethodInstance = mCurMethodState;
  2249. while (checkMethodInstance != NULL)
  2250. {
  2251. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2252. if (rootMixinState != NULL)
  2253. {
  2254. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2255. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2256. auto mixinState = checkMethodInstance->mMixinState;
  2257. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2258. {
  2259. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2260. mixinState = mixinState->mPrevMixinState;
  2261. }
  2262. return bfError;
  2263. }
  2264. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2265. }
  2266. }
  2267. BfError* bfError = NULL;
  2268. if (refNode == NULL)
  2269. bfError = mCompiler->mPassInstance->Fail(errorString);
  2270. else
  2271. {
  2272. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2273. }
  2274. if (bfError != NULL)
  2275. {
  2276. bfError->mIsPersistent = isPersistent;
  2277. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2278. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2279. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2280. }
  2281. return bfError;
  2282. }
  2283. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2284. {
  2285. if (mIgnoreErrors)
  2286. return NULL;
  2287. if (refNode != NULL)
  2288. refNode = BfNodeToNonTemporary(refNode);
  2289. mHadBuildError = true;
  2290. return mCompiler->mPassInstance->FailAfter(error, refNode);
  2291. }
  2292. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2293. {
  2294. if (mIgnoreErrors || mIgnoreWarnings)
  2295. return NULL;
  2296. if (!mReportErrors)
  2297. {
  2298. mCompiler->mPassInstance->SilentFail();
  2299. return NULL;
  2300. }
  2301. BfAstNode* unwarnNode = refNode;
  2302. //
  2303. {
  2304. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2305. while (parentNodeEntry != NULL)
  2306. {
  2307. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2308. break;
  2309. unwarnNode = parentNodeEntry->mNode;
  2310. parentNodeEntry = parentNodeEntry->mPrev;
  2311. }
  2312. }
  2313. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2314. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2315. {
  2316. return NULL;
  2317. }
  2318. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2319. if (mCurMethodInstance != NULL)
  2320. {
  2321. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2322. return NULL;
  2323. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2324. return NULL; // No ctorCalcAppend warnings
  2325. }
  2326. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2327. return NULL;
  2328. if (refNode != NULL)
  2329. refNode = BfNodeToNonTemporary(refNode);
  2330. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2331. {
  2332. // We used to bubble up warnings into the mixin injection site, BUT
  2333. // we are now assuming any relevant warnings will be given at the declaration site
  2334. return NULL;
  2335. // AddFailType(mCurTypeInstance);
  2336. //
  2337. // BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Warning while injecting mixin", mCurMethodState->mMixinState->GetRoot()->mSource);
  2338. // if (bfError == NULL)
  2339. // return NULL;
  2340. // mHadBuildWarning = true;
  2341. // return mCompiler->mPassInstance->MoreInfo(warning, refNode);
  2342. }
  2343. BfError* bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2344. if (bfError != NULL)
  2345. {
  2346. AddFailType(mCurTypeInstance);
  2347. mHadBuildWarning = true;
  2348. bfError->mIsPersistent = isPersistent;
  2349. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2350. {
  2351. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2352. if (parser != NULL)
  2353. {
  2354. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2355. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2356. }
  2357. }
  2358. }
  2359. return bfError;
  2360. }
  2361. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2362. {
  2363. if (mBfIRBuilder->mOpFailed)
  2364. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2365. }
  2366. void BfModule::NotImpl(BfAstNode* astNode)
  2367. {
  2368. Fail("INTERNAL ERROR: Not implemented", astNode);
  2369. }
  2370. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfType* memberType)
  2371. {
  2372. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2373. if (!allowPrivate)
  2374. allowPrivate |= memberType->IsInterface();
  2375. bool allowProtected = allowPrivate;// allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2376. if (!CheckProtection(protection, allowProtected, allowPrivate))
  2377. {
  2378. return false;
  2379. }
  2380. return true;
  2381. }
  2382. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2383. {
  2384. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2385. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2386. auto memberTypeInstance = memberType->ToTypeInstance();
  2387. if (memberTypeInstance == NULL)
  2388. {
  2389. auto underlyingType = memberType->GetUnderlyingType();
  2390. if (underlyingType != NULL)
  2391. return CheckDefineMemberProtection(protection, underlyingType);
  2392. return true;
  2393. }
  2394. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2395. return false;
  2396. if (memberTypeInstance->IsGenericTypeInstance())
  2397. {
  2398. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2399. auto genericTypeInstance = (BfGenericTypeInstance*) memberTypeInstance;
  2400. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  2401. {
  2402. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2403. return false;
  2404. }
  2405. }
  2406. return true;
  2407. }
  2408. void BfModule::AddDependency(BfType* usedType, BfType* usingType, BfDependencyMap::DependencyDependencyFlag flags)
  2409. {
  2410. if (usedType == usingType)
  2411. return;
  2412. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2413. return;
  2414. if (usedType->IsSpecializedByAutoCompleteMethod())
  2415. return;
  2416. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) &&
  2417. ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0))
  2418. {
  2419. bool addType = true;
  2420. auto checkType = usedType;
  2421. while (true)
  2422. {
  2423. if ((checkType->IsPointer()) || (checkType->IsRef()) || (checkType->IsSizedArray()))
  2424. checkType = checkType->GetUnderlyingType();
  2425. else if (checkType->IsArray())
  2426. {
  2427. checkType = ((BfGenericTypeInstance*)checkType)->mTypeGenericArguments[0];
  2428. }
  2429. else
  2430. break;
  2431. }
  2432. PopulateType(checkType, BfPopulateType_Data);
  2433. if (checkType->IsValuelessType())
  2434. addType = false;
  2435. else if (checkType->IsPrimitiveType())
  2436. addType = false;
  2437. else
  2438. {
  2439. auto checkTypeInst = checkType->ToTypeInstance();
  2440. if (checkTypeInst == NULL)
  2441. {
  2442. addType = false;
  2443. }
  2444. else
  2445. {
  2446. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2447. addType = false;
  2448. }
  2449. }
  2450. if (addType)
  2451. {
  2452. auto checkTypeInst = checkType->ToTypeInstance();
  2453. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2454. BF_ASSERT(hotTypeVersion != NULL);
  2455. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2456. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2457. (checkType->IsComposite()))
  2458. isAllocation = true;
  2459. if (isAllocation)
  2460. {
  2461. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2462. }
  2463. else
  2464. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2465. }
  2466. }
  2467. //BP_ZONE("BfModule::AddDependency");
  2468. /*if (usedType->IsMethodRef())
  2469. {
  2470. auto methodRefType = (BfMethodRefType*)usedType;
  2471. AddDependency(methodRefType->mMethodRef->GetOwner(), usingType, flags);
  2472. return;
  2473. }*/
  2474. // Why in the world were we doing this?
  2475. // This caused functions to get immediately deleted since they appear to have no references ever....
  2476. // if (usedType->IsFunction())
  2477. // {
  2478. // usedType = ResolveTypeDef(mCompiler->mFunctionTypeDef);
  2479. // }
  2480. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2481. {
  2482. auto usingModule = usingType->GetModule();
  2483. BfModule* usedModule;
  2484. if (usedType->IsFunction())
  2485. {
  2486. auto typeInst = usedType->ToTypeInstance();
  2487. if (typeInst->mBaseType == NULL)
  2488. PopulateType(typeInst);
  2489. usedModule = typeInst->mBaseType->GetModule();
  2490. }
  2491. else
  2492. usedModule = usedType->GetModule();
  2493. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2494. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2495. {
  2496. usingModule->mModuleRefs.Add(usedModule);
  2497. }
  2498. }
  2499. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2500. {
  2501. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2502. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2503. if (genericArg == usedType)
  2504. return;
  2505. }
  2506. auto underlyingType = usedType->GetUnderlyingType();
  2507. if (underlyingType != NULL) // Not really a "GenericArg", but... same purpose.
  2508. AddDependency(underlyingType, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2509. BfDependedType* checkDType = usedType->ToDependedType();
  2510. if (checkDType == NULL)
  2511. return;
  2512. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2513. mContext->MarkAsReferenced(checkDType);
  2514. checkDType->mDependencyMap.AddUsedBy(usingType, flags);
  2515. if (checkDType->IsGenericTypeInstance())
  2516. {
  2517. auto genericTypeInstance = (BfGenericTypeInstance*) checkDType;
  2518. for (auto genericArg : genericTypeInstance->mTypeGenericArguments)
  2519. {
  2520. AddDependency(genericArg, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2521. }
  2522. }
  2523. }
  2524. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  2525. {
  2526. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  2527. {
  2528. if (methodInstance->mHotMethod == NULL)
  2529. CheckHotMethod(methodInstance, "");
  2530. BF_ASSERT(methodInstance->mHotMethod != NULL);
  2531. if (devirtualized)
  2532. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  2533. else
  2534. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  2535. }
  2536. }
  2537. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  2538. {
  2539. auto checkTypeInst = typeInst;
  2540. while (checkTypeInst != NULL)
  2541. {
  2542. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  2543. return true;
  2544. checkTypeInst = checkTypeInst->mBaseType;
  2545. }
  2546. return false;
  2547. }
  2548. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  2549. {
  2550. if (mContext->mCurTypeState == NULL)
  2551. return;
  2552. BP_ZONE("PopulateGlobalContainersList");
  2553. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  2554. if (userTypeDef == NULL)
  2555. userTypeDef = mCurTypeInstance->mTypeDef;
  2556. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  2557. {
  2558. mContext->mCurTypeState->mGlobalContainers.Clear();
  2559. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  2560. {
  2561. BfAtomComposite findStr;
  2562. if (namespaceIdx != -1)
  2563. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  2564. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  2565. while (typeDefItr)
  2566. {
  2567. auto typeDef = *typeDefItr;
  2568. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  2569. {
  2570. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  2571. {
  2572. BfGlobalContainerEntry globalEntry;
  2573. globalEntry.mTypeDef = typeDef;
  2574. globalEntry.mTypeInst = NULL;
  2575. typeDef->PopulateMemberSets();
  2576. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  2577. }
  2578. }
  2579. else if (!typeDef->mIsPartial)
  2580. {
  2581. //break;
  2582. }
  2583. typeDefItr.MoveToNextHashMatch();
  2584. }
  2585. }
  2586. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  2587. }
  2588. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  2589. // reifing types
  2590. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  2591. {
  2592. if (globalEntry.mTypeInst == NULL)
  2593. {
  2594. bool include = false;
  2595. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  2596. include = true;
  2597. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  2598. {
  2599. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  2600. include = true;
  2601. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  2602. include = true;
  2603. }
  2604. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  2605. {
  2606. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  2607. include = true;
  2608. }
  2609. if (include)
  2610. {
  2611. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  2612. if (type != NULL)
  2613. globalEntry.mTypeInst = type->ToTypeInstance();
  2614. }
  2615. }
  2616. }
  2617. }
  2618. void PrintUsers(llvm::MDNode* md);
  2619. BfModuleOptions BfModule::GetModuleOptions()
  2620. {
  2621. if (mIsScratchModule)
  2622. return BfModuleOptions();
  2623. if (mModuleOptions != NULL)
  2624. return *mModuleOptions;
  2625. BfModuleOptions moduleOptions;
  2626. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  2627. if (mProject != NULL)
  2628. {
  2629. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  2630. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  2631. }
  2632. auto headModule = this;
  2633. while (headModule->mParentModule != NULL)
  2634. headModule = headModule->mParentModule;
  2635. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata"));
  2636. if (headModule->mOwnedTypeInstances.size() > 0)
  2637. {
  2638. auto typeInst = headModule->mOwnedTypeInstances[0];
  2639. PopulateType(typeInst);
  2640. if (typeInst->mTypeOptionsIdx != -1)
  2641. {
  2642. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  2643. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  2644. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  2645. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  2646. }
  2647. }
  2648. return moduleOptions;
  2649. }
  2650. BfCheckedKind BfModule::GetDefaultCheckedKind()
  2651. {
  2652. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  2653. auto typeOptions = GetTypeOptions();
  2654. if (typeOptions != NULL)
  2655. runtimeChecks = BfTypeOptions::Apply(runtimeChecks, typeOptions->mRuntimeChecks);
  2656. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  2657. }
  2658. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  2659. {
  2660. mContext->mFailTypes.Add(typeInstance);
  2661. }
  2662. void BfModule::CheckAddFailType()
  2663. {
  2664. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  2665. // but we still need to add the owning type to the FailTypes list
  2666. //.. OLD:
  2667. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  2668. /*if (mCurTypeInstance->mModule != this)
  2669. return;*/
  2670. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  2671. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  2672. // being recompiled. This forces types with warnings to be recompiled.
  2673. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  2674. // constantly warning-aware
  2675. if ((mHadBuildError) ||
  2676. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  2677. {
  2678. //mContext->mFailTypes.Add(mCurTypeInstance);
  2679. }
  2680. }
  2681. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  2682. {
  2683. if (!mCompiler->IsHotCompile())
  2684. return;
  2685. typeInst->mDirty = true;
  2686. for (auto& dep : typeInst->mDependencyMap)
  2687. {
  2688. auto depType = dep.mKey;
  2689. auto depFlags = dep.mValue.mFlags;
  2690. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  2691. {
  2692. MarkDerivedDirty(depType->ToTypeInstance());
  2693. }
  2694. }
  2695. }
  2696. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  2697. {
  2698. auto fieldType = fieldInstance->GetResolvedType();
  2699. auto field = fieldInstance->GetFieldDef();
  2700. if (fieldType->IsVar())
  2701. return;
  2702. BfIRValue initValue;
  2703. if (field->mIsConst)
  2704. {
  2705. if (fieldType->IsPointer())
  2706. fieldType = fieldType->GetUnderlyingType();
  2707. }
  2708. if (!field->mIsExtern)
  2709. initValue = GetDefaultValue(fieldType);
  2710. if (fieldInstance->mOwner->IsUnspecializedType())
  2711. {
  2712. // Placeholder
  2713. auto ptrVal = CreatePointerType(fieldType);
  2714. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  2715. }
  2716. else
  2717. {
  2718. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  2719. StringT<128> staticVarName;
  2720. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  2721. if (!fieldType->IsValuelessType())
  2722. {
  2723. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  2724. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  2725. false,
  2726. BfIRLinkageType_External,
  2727. initValue,
  2728. staticVarName,
  2729. isThreadLocal);
  2730. BF_ASSERT(globalVar);
  2731. mStaticFieldRefs[fieldInstance] = globalVar;
  2732. }
  2733. }
  2734. }
  2735. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  2736. {
  2737. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  2738. BfType* fieldType = NULL;
  2739. if (fieldInstance != NULL)
  2740. {
  2741. fieldType = fieldInstance->GetResolvedType();
  2742. if (fieldType == NULL)
  2743. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2744. }
  2745. else
  2746. {
  2747. BF_ASSERT(mCompiler->IsAutocomplete());
  2748. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2749. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  2750. {
  2751. fieldType = typeInstance;
  2752. }
  2753. else
  2754. {
  2755. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  2756. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  2757. if (isLet || isVar)
  2758. fieldType = GetPrimitiveType(BfTypeCode_Var);
  2759. else
  2760. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2761. if (fieldType == NULL)
  2762. fieldType = mContext->mBfObjectType;
  2763. }
  2764. }
  2765. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  2766. return;
  2767. if (mContext->mFieldResolveReentrys.size() > 1)
  2768. {
  2769. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2770. {
  2771. String failStr = "Circular data reference detected between the following fields:";
  2772. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2773. {
  2774. if (i > 1)
  2775. failStr += ",";
  2776. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  2777. }
  2778. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  2779. if (err)
  2780. err->mIsPersistent = true;
  2781. return;
  2782. }
  2783. }
  2784. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2785. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2786. if (fieldInstance == NULL)
  2787. popTypeResolveReentry.Pop();
  2788. auto typeDef = typeInstance->mTypeDef;
  2789. BfIRValue constValue;
  2790. if (fieldDef->mIsExtern)
  2791. {
  2792. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  2793. {
  2794. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  2795. }
  2796. if (fieldDef->mInitializer != NULL)
  2797. {
  2798. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  2799. }
  2800. }
  2801. else if (fieldDef->mInitializer == NULL)
  2802. {
  2803. if (fieldDef->IsEnumCaseEntry())
  2804. {
  2805. if (typeInstance->IsTypedPrimitive())
  2806. {
  2807. BfFieldInstance* prevFieldInstance = NULL;
  2808. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  2809. {
  2810. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  2811. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  2812. {
  2813. prevFieldInstance = checkFieldInst;
  2814. break;
  2815. }
  2816. }
  2817. if (prevFieldInstance == NULL)
  2818. constValue = GetConstValue(0, typeInstance);
  2819. else
  2820. {
  2821. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  2822. if (prevFieldInstance->mConstIdx == -1)
  2823. {
  2824. if (!mCompiler->IsAutocomplete())
  2825. AssertErrorState();
  2826. constValue = GetConstValue(0, typeInstance);
  2827. }
  2828. else
  2829. {
  2830. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  2831. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  2832. }
  2833. }
  2834. }
  2835. }
  2836. else
  2837. {
  2838. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  2839. }
  2840. }
  2841. else
  2842. {
  2843. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2844. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2845. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  2846. BfConstResolver constResolver(this);
  2847. BfMethodState methodState;
  2848. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2849. methodState.mTempKind = BfMethodState::TempKind_Static;
  2850. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2851. if (fieldType->IsVar())
  2852. {
  2853. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2854. if (!initValue)
  2855. {
  2856. AssertErrorState();
  2857. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  2858. }
  2859. if (fieldInstance != NULL)
  2860. {
  2861. fieldInstance->mResolvedType = initValue.mType;
  2862. }
  2863. constValue = initValue.mValue;
  2864. }
  2865. else
  2866. {
  2867. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2868. constValue = uncastedInitValue.mValue;
  2869. }
  2870. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2871. }
  2872. if (fieldInstance != NULL)
  2873. {
  2874. fieldType = fieldInstance->GetResolvedType();
  2875. if ((fieldType == NULL) || (fieldType->IsVar()))
  2876. {
  2877. AssertErrorState();
  2878. // Default const type is 'int'
  2879. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  2880. if (fieldInstance != NULL)
  2881. {
  2882. fieldInstance->mResolvedType = initValue.mType;
  2883. }
  2884. constValue = initValue.mValue;
  2885. }
  2886. if ((constValue) && (fieldInstance->mConstIdx == -1))
  2887. {
  2888. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2889. CurrentAddToConstHolder(constValue);
  2890. fieldInstance->mConstIdx = constValue.mId;
  2891. }
  2892. }
  2893. }
  2894. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  2895. {
  2896. bool isDeclType = BfNodeDynCastExact<BfDeclTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  2897. auto fieldType = fieldInstance->GetResolvedType();
  2898. if ((field->mIsConst) && (!isDeclType))
  2899. {
  2900. ResolveConstField(typeInstance, fieldInstance, field);
  2901. return fieldInstance->GetResolvedType();
  2902. }
  2903. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  2904. if (!fieldInstance->mIsInferredType)
  2905. return fieldType;
  2906. if (!fieldType->IsVar())
  2907. return fieldType;
  2908. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2909. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  2910. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mTypeInstance != typeInstance);
  2911. auto typeDef = typeInstance->mTypeDef;
  2912. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  2913. {
  2914. AssertErrorState();
  2915. SetHadVarUsage();
  2916. return GetPrimitiveType(BfTypeCode_Var);
  2917. }
  2918. bool hadInferenceCycle = false;
  2919. if (mContext->mFieldResolveReentrys.size() > 1)
  2920. {
  2921. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2922. {
  2923. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2924. {
  2925. auto fieldInst = mContext->mFieldResolveReentrys[i];
  2926. auto fieldDef = fieldInst->GetFieldDef();
  2927. auto fieldOwner = fieldInst->mOwner;
  2928. auto fieldModule = fieldOwner->mModule;
  2929. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  2930. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  2931. }
  2932. SetHadVarUsage();
  2933. return GetPrimitiveType(BfTypeCode_Var);
  2934. }
  2935. }
  2936. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2937. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2938. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  2939. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  2940. if ((field->mInitializer == NULL) && (!isDeclType))
  2941. {
  2942. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  2943. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  2944. SetHadVarUsage();
  2945. return GetPrimitiveType(BfTypeCode_Var);
  2946. }
  2947. BfType* resolvedType = NULL;
  2948. if (!hadInferenceCycle)
  2949. {
  2950. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2951. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  2952. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2953. BfMethodState methodState;
  2954. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2955. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  2956. if (!staticOnly)
  2957. {
  2958. //BfLocalVariable localVar;
  2959. //methodState.mLocals.push_back(localVar);
  2960. }
  2961. if (isDeclType)
  2962. {
  2963. auto fieldDef = fieldInstance->GetFieldDef();
  2964. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  2965. }
  2966. else
  2967. {
  2968. BfTypedValue valueFromExpr;
  2969. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  2970. FixIntUnknown(valueFromExpr);
  2971. resolvedType = valueFromExpr.mType;
  2972. }
  2973. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2974. }
  2975. if (resolvedType == NULL)
  2976. return GetPrimitiveType(BfTypeCode_Var);
  2977. fieldInstance->SetResolvedType(resolvedType);
  2978. if (field->mIsStatic)
  2979. {
  2980. }
  2981. else if (fieldInstance->mDataIdx <= 0)
  2982. {
  2983. }
  2984. else
  2985. {
  2986. BF_ASSERT(typeInstance->IsIncomplete());
  2987. }
  2988. return resolvedType;
  2989. }
  2990. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  2991. {
  2992. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  2993. auto fieldType = fieldInstance->GetResolvedType();
  2994. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  2995. {
  2996. int fieldDataCount = 1;
  2997. if (fieldType->IsStruct())
  2998. {
  2999. auto structTypeInst = fieldType->ToTypeInstance();
  3000. fieldDataCount = structTypeInst->mMergedFieldDataCount;
  3001. }
  3002. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3003. auto thisVariable = GetThisVariable();
  3004. if (thisVariable != NULL)
  3005. {
  3006. for (int i = 0; i < fieldDataCount; i++)
  3007. mCurMethodState->LocalDefined(thisVariable, fieldInstance->mMergedDataIdx + i);
  3008. }
  3009. }
  3010. }
  3011. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3012. {
  3013. if (fieldInstance->mCustomAttributes == NULL)
  3014. return false;
  3015. auto fieldDef = fieldInstance->GetFieldDef();
  3016. if (!fieldDef->mIsStatic)
  3017. return false;
  3018. bool isThreadLocal = false;
  3019. if (fieldInstance->mCustomAttributes != NULL)
  3020. {
  3021. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3022. {
  3023. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  3024. return true;
  3025. }
  3026. }
  3027. return false;
  3028. }
  3029. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType)
  3030. {
  3031. if (fieldDef == NULL)
  3032. fieldDef = fieldInstance->GetFieldDef();
  3033. if (fieldType == NULL)
  3034. fieldType = fieldInstance->GetResolvedType();
  3035. if (initializer == NULL)
  3036. {
  3037. if (fieldDef == NULL)
  3038. return BfTypedValue();
  3039. initializer = fieldDef->mInitializer;
  3040. }
  3041. BfTypedValue result;
  3042. if (initializer == NULL)
  3043. {
  3044. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3045. }
  3046. else
  3047. {
  3048. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3049. {
  3050. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3051. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3052. }
  3053. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3054. {
  3055. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3056. BfConstResolver constResolver(this);
  3057. constResolver.Resolve(initializer);
  3058. return GetDefaultTypedValue(fieldType);
  3059. }
  3060. else if (fieldDef->mIsConst)
  3061. {
  3062. BfTypeState typeState;
  3063. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3064. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3065. BfConstResolver constResolver(this);
  3066. if (fieldType->IsVar())
  3067. return constResolver.Resolve(initializer);
  3068. else
  3069. return constResolver.Resolve(initializer, fieldType);
  3070. }
  3071. if (fieldType->IsVar())
  3072. result = CreateValueFromExpression(initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3073. else
  3074. result = CreateValueFromExpression(initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3075. }
  3076. if (fieldInstance != NULL)
  3077. MarkFieldInitialized(fieldInstance);
  3078. return result;
  3079. }
  3080. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3081. {
  3082. }
  3083. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3084. {
  3085. PopulateType(classType);
  3086. if (isInterfacePass)
  3087. {
  3088. for (auto ifaceInst : classType->mInterfaces)
  3089. {
  3090. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3091. continue;
  3092. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3093. continue;
  3094. if (ifaceInst.mDeclaringType->IsExtension())
  3095. {
  3096. bool needsExCheck = false;
  3097. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3098. {
  3099. exChecks->push_back(ifaceInst.mInterfaceType);
  3100. continue;
  3101. }
  3102. }
  3103. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3104. }
  3105. }
  3106. else
  3107. {
  3108. outVals->push_back(classType->mTypeId);
  3109. }
  3110. if (classType->mBaseType != NULL)
  3111. {
  3112. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3113. }
  3114. }
  3115. void BfModule::CreateDynamicCastMethod()
  3116. {
  3117. auto objType = mContext->mBfObjectType;
  3118. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3119. {
  3120. // The main reason to punt on this method for ResolveOnly is because types can be created
  3121. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3122. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3123. // remove this punt when we recycle typeId's
  3124. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3125. mCurMethodState->mHadReturn = true;
  3126. return;
  3127. }
  3128. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3129. auto func = mCurMethodState->mIRFunction;
  3130. auto thisValue = mBfIRBuilder->GetArgument(0);
  3131. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3132. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3133. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3134. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3135. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3136. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3137. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3138. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3139. SizedArray<int, 8> typeMatches;
  3140. SizedArray<BfTypeInstance*, 8> exChecks;
  3141. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3142. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3143. {
  3144. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3145. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3146. BfTypeVector genericArgs;
  3147. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3148. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3149. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3150. typeMatches.push_back(unboundType->mTypeId);
  3151. }
  3152. if (mCurTypeInstance->IsBoxed())
  3153. {
  3154. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3155. BfTypeInstance* innerType = boxedType->mElementType;
  3156. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3157. if (innerType->IsTypedPrimitive())
  3158. {
  3159. auto underlyingType = innerType->GetUnderlyingType();
  3160. typeMatches.push_back(underlyingType->mTypeId);
  3161. }
  3162. auto innerTypeInst = innerType->ToTypeInstance();
  3163. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3164. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3165. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3166. {
  3167. PopulateType(innerTypeInst);
  3168. //TODO: What case was this supposed to handle?
  3169. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3170. }
  3171. }
  3172. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3173. BfIRValue vDataPtr;
  3174. if (!exChecks.empty())
  3175. {
  3176. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3177. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3178. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3179. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3180. }
  3181. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3182. for (auto typeMatch : typeMatches)
  3183. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3184. Array<BfIRValue> incomingFalses;
  3185. for (auto ifaceTypeInst : exChecks)
  3186. {
  3187. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3188. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3189. mBfIRBuilder->SetInsertPoint(nextBB);
  3190. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3191. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3192. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3193. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3194. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3195. incomingFalses.push_back(nextBB);
  3196. }
  3197. mBfIRBuilder->AddBlock(trueBB);
  3198. mBfIRBuilder->SetInsertPoint(trueBB);
  3199. mBfIRBuilder->CreateBr(exitBB);
  3200. mBfIRBuilder->AddBlock(exitBB);
  3201. mBfIRBuilder->SetInsertPoint(exitBB);
  3202. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3203. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3204. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3205. for (auto incomingFalseBlock : incomingFalses)
  3206. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3207. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3208. mBfIRBuilder->CreateRet(phi);
  3209. mCurMethodState->mHadReturn = true;
  3210. }
  3211. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB)
  3212. {
  3213. BfExprEvaluator exprEvaluator(this);
  3214. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3215. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, BfBinaryOp_Equality, NULL, BfBinOpFlag_None, leftValue, rightValue);
  3216. BfTypedValue result = exprEvaluator.GetResult();
  3217. if (result)
  3218. {
  3219. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3220. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3221. mBfIRBuilder->AddBlock(nextBB);
  3222. mBfIRBuilder->SetInsertPoint(nextBB);
  3223. }
  3224. }
  3225. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3226. {
  3227. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3228. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3229. SizedArray<BfIRType, 4> paramTypes;
  3230. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3231. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3232. mBfIRBuilder->SetActiveFunction(func);
  3233. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3234. mBfIRBuilder->SetInsertPoint(entryBlock);
  3235. SizedArray<BfIRValue, 8> args;
  3236. BfExprEvaluator exprEvaluator(this);
  3237. if (mCurMethodInstance->HasThis())
  3238. {
  3239. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true);
  3240. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3241. }
  3242. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3243. {
  3244. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3245. if (paramType->IsValuelessType())
  3246. continue;
  3247. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true), args);
  3248. }
  3249. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3250. mBfIRBuilder->CreateRetVoid();
  3251. }
  3252. void BfModule::CreateValueTypeEqualsMethod()
  3253. {
  3254. if (mCurMethodInstance->mIsUnspecialized)
  3255. return;
  3256. if (mCurTypeInstance->IsTypedPrimitive())
  3257. return;
  3258. if (mBfIRBuilder->mIgnoreWrites)
  3259. return;
  3260. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3261. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3262. bool isValid = true;
  3263. auto compareDType = compareType->ToDependedType();
  3264. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3265. if (compareTypeInst != NULL)
  3266. {
  3267. if (compareType->IsPrimitiveType())
  3268. compareTypeInst = GetWrappedStructType(compareType);
  3269. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3270. {
  3271. isValid = false;
  3272. }
  3273. mBfIRBuilder->PopulateType(compareTypeInst);
  3274. }
  3275. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3276. if (!isValid)
  3277. {
  3278. ClearLifetimeEnds();
  3279. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3280. return;
  3281. }
  3282. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3283. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3284. if (refNode == NULL)
  3285. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3286. UpdateSrcPos(refNode);
  3287. SetIllegalSrcPos();
  3288. auto resultVal = CreateAlloca(boolType);
  3289. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3290. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3291. if (compareType->IsSizedArray())
  3292. {
  3293. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3294. if (sizedArrayType->mElementCount > 6)
  3295. {
  3296. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3297. auto itr = CreateAlloca(intPtrType);
  3298. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3299. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3300. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  3301. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  3302. mBfIRBuilder->CreateBr(loopBB);
  3303. mBfIRBuilder->SetInsertPoint(loopBB);
  3304. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  3305. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  3306. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  3307. mBfIRBuilder->SetInsertPoint(bodyBB);
  3308. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3309. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3310. EmitEquals(leftValue, rightValue, exitBB);
  3311. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  3312. mBfIRBuilder->CreateStore(incValue, itr);
  3313. mBfIRBuilder->CreateBr(loopBB);
  3314. mBfIRBuilder->SetInsertPoint(doneBB);
  3315. }
  3316. else
  3317. {
  3318. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  3319. {
  3320. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3321. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3322. EmitEquals(leftValue, rightValue, exitBB);
  3323. }
  3324. }
  3325. }
  3326. else if (compareType->IsMethodRef())
  3327. {
  3328. auto methodRefType = (BfMethodRefType*)compareType;
  3329. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  3330. BfExprEvaluator exprEvaluator(this);
  3331. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3332. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3333. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  3334. // values for the same method reference -- they will always refer back to the same local variables.
  3335. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  3336. if (dataIdx != -1)
  3337. {
  3338. bool failed = false;
  3339. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  3340. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  3341. BF_ASSERT(!failed);
  3342. EmitEquals(leftValue, rightValue, exitBB);
  3343. }
  3344. }
  3345. else if (compareTypeInst->IsEnum())
  3346. {
  3347. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3348. BfExprEvaluator exprEvaluator(this);
  3349. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3350. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3351. auto dscrType = compareTypeInst->GetDiscriminatorType();
  3352. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  3353. leftValue = LoadValue(leftValue);
  3354. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  3355. rightValue = LoadValue(rightValue);
  3356. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  3357. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  3358. EmitEquals(leftValue, rightValue, exitBB);
  3359. int enumCount = 0;
  3360. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3361. {
  3362. BfFieldInstance* fieldInstance = &fieldRef;
  3363. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3364. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3365. {
  3366. enumCount = -fieldInstance->mDataIdx;
  3367. }
  3368. }
  3369. if (enumCount > 0)
  3370. {
  3371. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  3372. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  3373. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3374. {
  3375. BfFieldInstance* fieldInstance = &fieldRef;
  3376. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3377. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3378. {
  3379. int enumIdx = -fieldInstance->mDataIdx - 1;
  3380. if (fieldInstance->mResolvedType->mSize == 0)
  3381. {
  3382. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  3383. }
  3384. else
  3385. {
  3386. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  3387. mBfIRBuilder->SetInsertPoint(caseBlock);
  3388. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  3389. BfTypedValue leftTuple;
  3390. BfTypedValue rightTuple;
  3391. if (leftPayload.IsAddr())
  3392. {
  3393. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3394. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3395. }
  3396. else
  3397. {
  3398. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3399. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3400. }
  3401. EmitEquals(leftTuple, rightTuple, exitBB);
  3402. mBfIRBuilder->CreateBr(matchedBlock);
  3403. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  3404. }
  3405. }
  3406. }
  3407. mBfIRBuilder->AddBlock(matchedBlock);
  3408. mBfIRBuilder->SetInsertPoint(matchedBlock);
  3409. }
  3410. }
  3411. else if (compareTypeInst->IsUnion())
  3412. {
  3413. auto innerType = compareTypeInst->GetUnionInnerType();
  3414. if (!innerType->IsValuelessType())
  3415. {
  3416. BfExprEvaluator exprEvaluator(this);
  3417. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3418. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  3419. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3420. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  3421. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB);
  3422. }
  3423. }
  3424. else
  3425. {
  3426. BfExprEvaluator exprEvaluator(this);
  3427. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3428. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3429. bool hadComparison = false;
  3430. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3431. {
  3432. BfFieldInstance* fieldInstance = &fieldRef;
  3433. if (fieldInstance->mDataOffset == -1)
  3434. continue;
  3435. if (fieldInstance->mResolvedType->IsValuelessType())
  3436. continue;
  3437. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3438. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3439. if (!fieldInstance->mResolvedType->IsComposite())
  3440. {
  3441. leftValue = LoadValue(leftValue);
  3442. rightValue = LoadValue(rightValue);
  3443. }
  3444. EmitEquals(leftValue, rightValue, exitBB);
  3445. }
  3446. auto baseTypeInst = compareTypeInst->mBaseType;
  3447. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  3448. {
  3449. BfTypedValue leftOrigValue(mCurMethodState->mLocals[0]->mValue, compareTypeInst, true);
  3450. BfTypedValue rightOrigValue(mCurMethodState->mLocals[1]->mValue, compareTypeInst, true);
  3451. BfTypedValue leftValue = Cast(NULL, leftOrigValue, baseTypeInst);
  3452. BfTypedValue rightValue = Cast(NULL, rightOrigValue, baseTypeInst);
  3453. EmitEquals(leftValue, rightValue, exitBB);
  3454. }
  3455. }
  3456. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  3457. mBfIRBuilder->CreateBr(exitBB);
  3458. mBfIRBuilder->AddBlock(exitBB);
  3459. mBfIRBuilder->SetInsertPoint(exitBB);
  3460. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  3461. ClearLifetimeEnds();
  3462. mBfIRBuilder->CreateRet(loadedResult);
  3463. mCurMethodState->mHadReturn = true;
  3464. }
  3465. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  3466. {
  3467. if (mBfIRBuilder->mIgnoreWrites)
  3468. return mBfIRBuilder->GetFakeVal();
  3469. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3470. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3471. BfIRValue* globalVariablePtr = NULL;
  3472. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  3473. int numElements = 1;
  3474. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  3475. {
  3476. numElements += mCompiler->mMaxInterfaceSlots;
  3477. auto maxIFaceVirtIdx = 0;
  3478. if (!typeInstance->IsInterface())
  3479. {
  3480. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3481. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  3482. numElements += typeInstance->GetOrigVTableSize();
  3483. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  3484. if (typeInstance->mHotTypeData != NULL)
  3485. {
  3486. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  3487. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  3488. }
  3489. numElements += ifaceMethodLen;
  3490. }
  3491. if (outNumElements != NULL)
  3492. *outNumElements = numElements;
  3493. }
  3494. StringT<128> classVDataName;
  3495. String memberName = "sBfClassVData";
  3496. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  3497. {
  3498. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3499. memberName += "_";
  3500. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  3501. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  3502. }
  3503. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  3504. if (outMangledName != NULL)
  3505. *outMangledName = classVDataName;
  3506. /*if (itr != mClassVDataRefs.end())
  3507. {
  3508. globalVariable = itr->second;
  3509. }*/
  3510. BfIRValue globalVariable;
  3511. if (globalVariablePtr != NULL)
  3512. {
  3513. globalVariable = *globalVariablePtr;
  3514. }
  3515. else
  3516. {
  3517. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  3518. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3519. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  3520. arrayType,
  3521. true,
  3522. BfIRLinkageType_External,
  3523. BfIRValue(),
  3524. classVDataName);
  3525. mClassVDataRefs[typeInstance] = globalVariable;
  3526. }
  3527. return globalVariable;
  3528. }
  3529. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  3530. {
  3531. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3532. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  3533. }
  3534. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  3535. {
  3536. if (mBfIRBuilder->mIgnoreWrites)
  3537. return mBfIRBuilder->GetFakeVal();
  3538. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  3539. BF_ASSERT(numElements >= 0);
  3540. if (numElements <= 0)
  3541. return BfIRValue();
  3542. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  3543. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  3544. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  3545. BF_ASSERT(declTypeInst == implTypeInst);
  3546. else
  3547. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  3548. if (declTypeInst != implTypeInst)
  3549. {
  3550. BfTypeInstance* highestImpl = declTypeInst;
  3551. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3552. {
  3553. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3554. break; // Start of an ext entry for another type
  3555. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  3556. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  3557. highestImpl = checkImplTypeInst;
  3558. }
  3559. if (highestImpl != implTypeInst)
  3560. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  3561. }
  3562. BfVDataExtEntry mapEntry;
  3563. mapEntry.mDeclTypeInst = declTypeInst;
  3564. mapEntry.mImplTypeInst = implTypeInst;
  3565. BfIRValue* irValuePtr = NULL;
  3566. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  3567. return *irValuePtr;
  3568. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  3569. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  3570. StringT<128> classVDataName;
  3571. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  3572. if (declTypeInst != implTypeInst)
  3573. {
  3574. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  3575. }
  3576. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3577. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3578. SizedArray<BfIRValue, 32> vData;
  3579. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3580. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3581. {
  3582. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3583. break; // Start of an ext entry for another type
  3584. BfIRValue vValue;
  3585. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  3586. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  3587. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  3588. {
  3589. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  3590. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  3591. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  3592. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  3593. {
  3594. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  3595. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  3596. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  3597. vValue = funcPtr;
  3598. }
  3599. }
  3600. if (!vValue)
  3601. vValue = voidPtrNull;
  3602. vData.Add(vValue);
  3603. }
  3604. BF_ASSERT((int)vData.size() == numElements);
  3605. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  3606. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3607. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  3608. BfIRLinkageType_External, BfIRValue(), classVDataName);
  3609. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  3610. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, vData);
  3611. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  3612. mClassVDataExtRefs[mapEntry] = globalVariable;
  3613. return globalVariable;
  3614. }
  3615. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  3616. {
  3617. if (mBfIRBuilder->mIgnoreWrites)
  3618. {
  3619. return mBfIRBuilder->CreateTypeOf(type);
  3620. }
  3621. BfIRValue globalVariable;
  3622. BfIRValue* globalVariablePtr = NULL;
  3623. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  3624. {
  3625. globalVariable = *globalVariablePtr;
  3626. if (globalVariable)
  3627. return globalVariable;
  3628. }
  3629. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  3630. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  3631. auto typeInstance = type->ToTypeInstance();
  3632. StringT<128> typeDataName;
  3633. if (typeInstance != NULL)
  3634. {
  3635. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3636. }
  3637. else
  3638. {
  3639. typeDataName += "sBfTypeData.";
  3640. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type);
  3641. }
  3642. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  3643. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  3644. mTypeDataRefs[type] = globalVariable;
  3645. return globalVariable;
  3646. }
  3647. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  3648. {
  3649. if ((mCompiler->IsHotCompile()) && (!type->mDirty))
  3650. return BfIRValue();
  3651. BfIRValue* irValuePtr = NULL;
  3652. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  3653. {
  3654. return *irValuePtr;
  3655. }
  3656. BfTypeInstance* typeInstance = type->ToTypeInstance();
  3657. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  3658. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  3659. if (typeInstanceType == NULL)
  3660. {
  3661. AssertErrorState();
  3662. return BfIRValue();
  3663. }
  3664. BfIRValue typeTypeData;
  3665. int typeFlags = 0;
  3666. if (needsTypeData)
  3667. {
  3668. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  3669. BfTypeInstance* typeDataSource = NULL;
  3670. if (typeInstance != NULL)
  3671. {
  3672. if (typeInstance->IsUnspecializedType())
  3673. {
  3674. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  3675. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  3676. }
  3677. else if (typeInstance->IsArray())
  3678. {
  3679. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  3680. typeFlags |= BfTypeFlags_Array;
  3681. }
  3682. else if (typeInstance->IsGenericTypeInstance())
  3683. {
  3684. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  3685. typeFlags |= BfTypeFlags_SpecializedGeneric;
  3686. }
  3687. else
  3688. typeDataSource = typeInstanceTypeInstance;
  3689. }
  3690. else if (type->IsPointer())
  3691. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3692. else if (type->IsSizedArray())
  3693. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3694. else
  3695. typeDataSource = mContext->mBfTypeType;
  3696. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  3697. {
  3698. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  3699. }
  3700. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  3701. }
  3702. else
  3703. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  3704. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  3705. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  3706. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  3707. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  3708. BfType* typeIdType = intType;
  3709. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3710. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3711. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  3712. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3713. SizedArray<BfIRValue, 4> typeValueParams;
  3714. GetConstClassValueParam(typeTypeData, typeValueParams);
  3715. BfIRValue objectData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  3716. StringT<128> typeDataName;
  3717. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  3718. {
  3719. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3720. if (typeInstance->mTypeDef->IsGlobalsContainer())
  3721. typeDataName += "@" + typeInstance->mTypeDef->mProject->mName;
  3722. }
  3723. else
  3724. {
  3725. typeDataName += "sBfTypeData.";
  3726. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type);
  3727. }
  3728. int typeCode = BfTypeCode_None;
  3729. if (typeInstance != NULL)
  3730. {
  3731. typeCode = typeInstance->mTypeDef->mTypeCode;
  3732. }
  3733. else if (type->IsPrimitiveType())
  3734. {
  3735. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  3736. typeCode = primType->mTypeDef->mTypeCode;
  3737. }
  3738. else if (type->IsPointer())
  3739. {
  3740. typeCode = BfTypeCode_Pointer;
  3741. typeFlags |= BfTypeFlags_Pointer;
  3742. }
  3743. if (type->IsObject())
  3744. {
  3745. typeFlags |= BfTypeFlags_Object;
  3746. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  3747. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  3748. typeFlags |= BfTypeFlags_HasDestructor;
  3749. }
  3750. if (type->IsStruct())
  3751. typeFlags |= BfTypeFlags_Struct;
  3752. if (type->IsBoxed())
  3753. {
  3754. typeFlags |= BfTypeFlags_Boxed;
  3755. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  3756. typeFlags |= BfTypeFlags_Pointer;
  3757. }
  3758. if (type->IsPrimitiveType())
  3759. typeFlags |= BfTypeFlags_Primitive;
  3760. if (type->IsTypedPrimitive())
  3761. typeFlags |= BfTypeFlags_TypedPrimitive;
  3762. if (type->IsTuple())
  3763. typeFlags |= BfTypeFlags_Tuple;
  3764. if (type->IsNullable())
  3765. typeFlags |= BfTypeFlags_Nullable;
  3766. if (type->IsSizedArray())
  3767. typeFlags |= BfTypeFlags_SizedArray;
  3768. if (type->IsSplattable())
  3769. typeFlags |= BfTypeFlags_Splattable;
  3770. if (type->IsUnion())
  3771. typeFlags |= BfTypeFlags_Union;
  3772. if (type->IsDelegate())
  3773. typeFlags |= BfTypeFlags_Delegate;
  3774. if (type->WantsGCMarking())
  3775. typeFlags |= BfTypeFlags_WantsMarking;
  3776. int memberDataOffset = 0;
  3777. if (typeInstance != NULL)
  3778. {
  3779. for (auto& fieldInstance : typeInstance->mFieldInstances)
  3780. {
  3781. if (fieldInstance.mDataOffset != -1)
  3782. {
  3783. memberDataOffset = fieldInstance.mDataOffset;
  3784. break;
  3785. }
  3786. }
  3787. }
  3788. SizedArray<BfIRValue, 8> typeDataParams =
  3789. {
  3790. objectData,
  3791. GetConstValue(type->mSize, intType), // mSize
  3792. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  3793. GetConstValue(typeFlags, intType), // mTypeFlags
  3794. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  3795. GetConstValue(typeCode, byteType), // mTypeCode
  3796. GetConstValue(type->mAlign, byteType),
  3797. };
  3798. auto typeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  3799. if (typeInstance == NULL)
  3800. {
  3801. BfIRValue typeDataVar;
  3802. if (needsTypeData)
  3803. {
  3804. if (type->IsPointer())
  3805. {
  3806. auto pointerType = (BfPointerType*)type;
  3807. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  3808. {
  3809. typeData,
  3810. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  3811. };
  3812. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3813. auto pointerTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  3814. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  3815. BfIRLinkageType_External, pointerTypeData, typeDataName);
  3816. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3817. }
  3818. else if (type->IsSizedArray())
  3819. {
  3820. auto sizedArrayType = (BfSizedArrayType*)type;
  3821. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  3822. {
  3823. typeData,
  3824. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  3825. GetConstValue(sizedArrayType->mElementCount, intType)
  3826. };
  3827. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3828. auto sizedArrayTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  3829. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  3830. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  3831. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3832. }
  3833. else
  3834. {
  3835. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  3836. BfIRLinkageType_External, typeData, typeDataName);
  3837. }
  3838. }
  3839. else
  3840. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  3841. mTypeDataRefs[typeInstance] = typeDataVar;
  3842. return typeDataVar;
  3843. }
  3844. // Reserve position
  3845. mTypeDataRefs[typeInstance] = BfIRValue();
  3846. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3847. BfTypeDef* typeDef = typeInstance->mTypeDef;
  3848. StringT<128> mangledName;
  3849. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance);
  3850. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  3851. {
  3852. auto methodDef = typeDef->mMethods[methodIdx];
  3853. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  3854. if (methodInstance == NULL)
  3855. continue;
  3856. if (typeInstance->IsUnspecializedType())
  3857. continue;
  3858. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  3859. {
  3860. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  3861. {
  3862. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  3863. // We need to create an empty thunk for this chained method
  3864. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  3865. mBfIRBuilder->SetActiveFunction(func);
  3866. auto block = mBfIRBuilder->CreateBlock("entry", true);
  3867. mBfIRBuilder->SetInsertPoint(block);
  3868. mBfIRBuilder->CreateRetVoid();
  3869. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  3870. }
  3871. }
  3872. }
  3873. SizedArray<BfIRValue, 32> vData;
  3874. BfIRValue classVDataVar;
  3875. String classVDataName;
  3876. if (typeInstance->mSlotNum >= 0)
  3877. {
  3878. // For interfaces we ONLY emit the slot num
  3879. int virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  3880. StringT<128> slotVarName;
  3881. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  3882. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3883. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  3884. GetConstValue32(virtSlotIdx), slotVarName);
  3885. }
  3886. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  3887. {
  3888. int dynCastDataElems = 0;
  3889. int numElements = 1;
  3890. int vDataOfs = 1; // The number of intptrs before the iface slot map
  3891. numElements += mCompiler->mMaxInterfaceSlots;
  3892. if (!typeInstance->IsInterface())
  3893. {
  3894. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3895. numElements += mCompiler->GetDynCastVDataCount();
  3896. numElements += typeInstance->mVirtualMethodTableSize;
  3897. }
  3898. int expectNumElements = 0;
  3899. if (!typeDef->mIsStatic)
  3900. {
  3901. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  3902. }
  3903. vData.push_back(BfIRValue()); // Type*
  3904. SizedArray<BfIRValue, 1> extVTableData;
  3905. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  3906. if (!typeInstance->IsInterface())
  3907. {
  3908. Array<int32> dynCastData;
  3909. if (typeInstance->IsBoxed())
  3910. {
  3911. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  3912. dynCastData.Add(underlyingType->mInheritanceId);
  3913. }
  3914. else
  3915. dynCastData.Add(typeInstance->mInheritanceId);
  3916. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  3917. dynCastData.Add(0);
  3918. dynCastData.Add(0);
  3919. auto checkTypeInst = typeInstance;
  3920. while (checkTypeInst != NULL)
  3921. {
  3922. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3923. {
  3924. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  3925. {
  3926. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  3927. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  3928. }
  3929. }
  3930. checkTypeInst = checkTypeInst->GetImplBaseType();
  3931. }
  3932. if (mSystem->mPtrSize == 8)
  3933. {
  3934. int intPtrCount = (dynCastDataElems + 1) / 2;
  3935. vDataOfs += intPtrCount;
  3936. uint64* intPtrData = (uint64*)&dynCastData[0];
  3937. for (int i = 0; i < intPtrCount; i++)
  3938. {
  3939. uint64 val = intPtrData[i];
  3940. if (val == 0)
  3941. {
  3942. vData.push_back(voidPtrNull);
  3943. }
  3944. else
  3945. {
  3946. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  3947. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3948. }
  3949. }
  3950. }
  3951. else
  3952. {
  3953. int intPtrCount = dynCastDataElems;
  3954. vDataOfs += intPtrCount;
  3955. uint32* intPtrData = (uint32*)&dynCastData[0];
  3956. for (int i = 0; i < intPtrCount; i++)
  3957. {
  3958. uint32 val = intPtrData[i];
  3959. if (val == 0)
  3960. {
  3961. vData.push_back(voidPtrNull);
  3962. }
  3963. else
  3964. {
  3965. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  3966. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3967. }
  3968. }
  3969. }
  3970. }
  3971. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  3972. vData.push_back(voidPtrNull);
  3973. struct _InterfaceMatchEntry
  3974. {
  3975. BfTypeInterfaceEntry* mEntry;
  3976. BfTypeInstance* mEntrySource;
  3977. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  3978. };
  3979. int highestIFaceVirtIdx = 0;
  3980. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  3981. auto checkTypeInst = typeInstance;
  3982. bool forceInterfaceSet = false;
  3983. while (checkTypeInst != NULL)
  3984. {
  3985. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3986. {
  3987. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  3988. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject))
  3989. continue;
  3990. _InterfaceMatchEntry* matchEntry = NULL;
  3991. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  3992. {
  3993. auto prevEntry = matchEntry->mEntry;
  3994. bool isBetter = TypeIsSubTypeOf(checkTypeInst, matchEntry->mEntrySource);
  3995. bool isWorse = TypeIsSubTypeOf(matchEntry->mEntrySource, checkTypeInst);
  3996. if (forceInterfaceSet)
  3997. {
  3998. isBetter = true;
  3999. isWorse = false;
  4000. }
  4001. if (isBetter == isWorse)
  4002. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  4003. if (isBetter == isWorse)
  4004. {
  4005. if (matchEntry->mAmbiguousEntries.empty())
  4006. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  4007. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  4008. continue;
  4009. }
  4010. else if (isBetter)
  4011. {
  4012. matchEntry->mEntry = &interfaceEntry;
  4013. matchEntry->mEntrySource = checkTypeInst;
  4014. matchEntry->mAmbiguousEntries.Clear();
  4015. }
  4016. else
  4017. continue;
  4018. }
  4019. else
  4020. {
  4021. _InterfaceMatchEntry matchEntry;
  4022. matchEntry.mEntry = &interfaceEntry;
  4023. matchEntry.mEntrySource = checkTypeInst;
  4024. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  4025. }
  4026. }
  4027. checkTypeInst = checkTypeInst->GetImplBaseType();
  4028. }
  4029. for (auto interfacePair : interfaceMap)
  4030. {
  4031. auto& interfaceMatchEntry = interfacePair.mValue;
  4032. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  4033. {
  4034. auto error = Fail(StrFormat("Type '%s' has an ambiguous declaration for interface '%s'", TypeToString(typeInstance).c_str(), TypeToString(interfaceMatchEntry.mEntry->mInterfaceType).c_str()), interfaceMatchEntry.mEntry->mDeclaringType->GetRefNode());
  4035. if (error != NULL)
  4036. {
  4037. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  4038. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  4039. }
  4040. }
  4041. }
  4042. if ((!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4043. {
  4044. int startTabIdx = (int)vData.size();
  4045. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4046. BfTypeInstance* checkTypeInst = typeInstance;
  4047. while (checkTypeInst != NULL)
  4048. {
  4049. origVirtTypeStack.push_back(checkTypeInst);
  4050. checkTypeInst = checkTypeInst->GetImplBaseType();
  4051. }
  4052. Array<BfVirtualMethodEntry> origVTable;
  4053. int origVirtIdx = 0;
  4054. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4055. {
  4056. HashSet<String> reslotNames;
  4057. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4058. {
  4059. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4060. if (entry.mDeclaringMethod.mMethodNum == -1)
  4061. continue;
  4062. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4063. if ((methodInstance == NULL) || (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4064. {
  4065. if (origVTable.empty())
  4066. origVTable = typeInstance->mVirtualMethodTable;
  4067. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4068. if (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject))
  4069. {
  4070. // Prepare to reslot...
  4071. entry.mImplementingMethod = entry.mDeclaringMethod;
  4072. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4073. }
  4074. else
  4075. {
  4076. // Decl isn't accessible, null out entry
  4077. entry.mImplementingMethod = BfMethodRef();
  4078. }
  4079. }
  4080. }
  4081. if (!reslotNames.IsEmpty())
  4082. {
  4083. BfAmbiguityContext ambiguityContext;
  4084. ambiguityContext.mTypeInstance = typeInstance;
  4085. ambiguityContext.mModule = this;
  4086. ambiguityContext.mIsProjectSpecific = true;
  4087. ambiguityContext.mIsReslotting = true;
  4088. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4089. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4090. {
  4091. auto methodInstance = methodGroup.mDefault;
  4092. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4093. continue;
  4094. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4095. continue;
  4096. if (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))
  4097. continue;
  4098. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4099. continue;
  4100. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4101. }
  4102. ambiguityContext.Finish();
  4103. }
  4104. }
  4105. bool isInExts = false;
  4106. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4107. {
  4108. BfIRValue vValue = voidPtrNull;
  4109. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4110. BfModuleMethodInstance moduleMethodInst;
  4111. if (entry.mDeclaringMethod.mMethodNum == -1)
  4112. {
  4113. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4114. isInExts = true;
  4115. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4116. if (vExt)
  4117. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4118. }
  4119. else
  4120. {
  4121. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4122. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4123. {
  4124. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4125. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4126. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4127. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4128. {
  4129. BF_ASSERT(typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4130. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  4131. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4132. vValue = funcPtr;
  4133. }
  4134. }
  4135. }
  4136. while (origVirtTypeStack.size() != 0)
  4137. {
  4138. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4139. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4140. {
  4141. // Moved past current base vtable size
  4142. origVirtTypeStack.pop_back();
  4143. continue;
  4144. }
  4145. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4146. {
  4147. // We are within the original vtable size
  4148. int idx = startTabIdx + origVirtIdx;
  4149. origVirtIdx++;
  4150. vData.push_back(vValue);
  4151. }
  4152. else
  4153. {
  4154. // This is a new entry, it only gets added to the ext
  4155. BF_ASSERT(isInExts);
  4156. }
  4157. break;
  4158. }
  4159. }
  4160. if (!origVTable.empty())
  4161. typeInstance->mVirtualMethodTable = origVTable;
  4162. }
  4163. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4164. if (typeInstance->mHotTypeData != NULL)
  4165. {
  4166. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4167. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4168. }
  4169. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4170. int iFaceMethodStartIdx = (int)vData.size();
  4171. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4172. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4173. vData[i] = voidPtrNull;
  4174. if (expectNumElements != 0)
  4175. BF_ASSERT(expectNumElements == vData.size());
  4176. //BF_ASSERT(vData.size() == expectNumElements);
  4177. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4178. // ifaceMethodExtData.Add(voidPtrNull);
  4179. int ifaceEntryIdx = iFaceMethodStartIdx;
  4180. for (auto& interfacePair : interfaceMap)
  4181. {
  4182. auto interfaceEntry = interfacePair.mValue.mEntry;
  4183. bool makeEmpty = false;
  4184. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject))
  4185. makeEmpty = true;
  4186. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4187. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4188. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4189. {
  4190. BfIRValue pushValue;
  4191. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4192. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4193. continue;
  4194. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4195. continue;
  4196. if (makeEmpty)
  4197. {
  4198. pushValue = voidPtrNull;
  4199. }
  4200. else
  4201. {
  4202. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4203. auto methodInstance = (BfMethodInstance*)methodRef;
  4204. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4205. {
  4206. BF_ASSERT(methodInstance->mIsReified);
  4207. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4208. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4209. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4210. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4211. pushValue = funcPtr;
  4212. }
  4213. else
  4214. {
  4215. pushValue = voidPtrNull;
  4216. }
  4217. }
  4218. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4219. if (idx < ifaceMethodExtStart)
  4220. {
  4221. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  4222. vData[iFaceMethodStartIdx + idx] = pushValue;
  4223. }
  4224. else
  4225. {
  4226. BF_ASSERT(useExt);
  4227. int extIdx = idx - ifaceMethodExtStart;
  4228. while (extIdx >= ifaceMethodExtData.size())
  4229. ifaceMethodExtData.Add(voidPtrNull);
  4230. ifaceMethodExtData[extIdx] = pushValue;
  4231. }
  4232. }
  4233. }
  4234. if (typeInstance->IsBoxed())
  4235. {
  4236. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  4237. if (boxedType->IsBoxedStructPtr())
  4238. {
  4239. // Force override of GetHashCode so we use the pointer address as the hash code
  4240. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  4241. // Force override of GetHashCode so we use the pointer address as the hash code
  4242. for (auto& checkIFace : checkTypeInst->mInterfaces)
  4243. {
  4244. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4245. {
  4246. BfIRValue pushValue;
  4247. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4248. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4249. continue;
  4250. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4251. continue;
  4252. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4253. auto methodInstance = (BfMethodInstance*)methodRef;
  4254. BF_ASSERT(methodInstance->mIsReified);
  4255. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4256. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4257. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4258. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4259. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4260. vData[iFaceMethodStartIdx + idx] = funcPtr;
  4261. }
  4262. }
  4263. }
  4264. }
  4265. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic))
  4266. {
  4267. BfIRValue ifaceMethodExtVar;
  4268. if (!ifaceMethodExtData.IsEmpty())
  4269. {
  4270. StringT<128> classVDataName;
  4271. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  4272. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  4273. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4274. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4275. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  4276. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, ifaceMethodExtData);
  4277. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  4278. }
  4279. for (auto& ifaceInstPair : interfaceMap)
  4280. {
  4281. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  4282. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  4283. if (slotNum >= 0)
  4284. {
  4285. BfIRValue vtablePtr;
  4286. int idx = interfaceEntry->mStartVirtualIdx;
  4287. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4288. if (endVirtualIdx > ifaceMethodExtStart)
  4289. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  4290. else
  4291. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  4292. int slotVirtIdx = slotNum + vDataOfs;
  4293. if (vData[slotVirtIdx] == voidPtrNull)
  4294. {
  4295. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  4296. }
  4297. else
  4298. {
  4299. if (mCompiler->IsHotCompile())
  4300. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  4301. else
  4302. Fail("Interface slot collision error", typeDef->GetRefNode());
  4303. }
  4304. }
  4305. }
  4306. }
  4307. }
  4308. BfIRValue typeNameConst;
  4309. BfIRValue namespaceConst;
  4310. if (needsTypeNames)
  4311. {
  4312. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  4313. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  4314. }
  4315. else
  4316. {
  4317. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  4318. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4319. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4320. }
  4321. int baseTypeId = 0;
  4322. if (typeInstance->mBaseType != NULL)
  4323. {
  4324. baseTypeId = typeInstance->mBaseType->mTypeId;
  4325. }
  4326. SizedArray<BfIRValue, 16> customAttrs;
  4327. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  4328. BfIRValue castedClassVData;
  4329. if (classVDataVar)
  4330. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  4331. else
  4332. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  4333. bool freflectIncludeTypeData = false;
  4334. bool reflectIncludeAllFields = false;
  4335. bool reflectIncludeAllMethods = false;
  4336. if (TypeIsSubTypeOf(typeInstance, attributeType))
  4337. {
  4338. reflectIncludeAllFields = true;
  4339. reflectIncludeAllMethods = true;
  4340. }
  4341. enum ReflectKind
  4342. {
  4343. ReflectKind_None = 0,
  4344. ReflectKind_Type = 1,
  4345. ReflectKind_NonStaticFields = 2,
  4346. ReflectKind_StaticFields = 4,
  4347. ReflectKind_DefaultConstructor = 8,
  4348. ReflectKind_Constructors = 0x10,
  4349. ReflectKind_StaticMethods = 0x20,
  4350. ReflectKind_Methods = 0x40,
  4351. ReflectKind_User = 0x80,
  4352. ReflectKind_All = 0x7F,
  4353. ReflectKind_ApplyToInnerTypes = 0x80
  4354. };
  4355. ReflectKind reflectKind = ReflectKind_Type;
  4356. auto _GetReflectUser = [&](BfTypeInstance* attrType)
  4357. {
  4358. ReflectKind reflectKind = ReflectKind_None;
  4359. if (attrType->mCustomAttributes != NULL)
  4360. {
  4361. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  4362. {
  4363. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  4364. {
  4365. for (auto& prop : customAttr.mSetProperties)
  4366. {
  4367. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  4368. if (propDef->mName == "ReflectUser")
  4369. {
  4370. if (prop.mParam.mValue.IsConst())
  4371. {
  4372. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  4373. reflectKind = (ReflectKind)(reflectKind | (ReflectKind)constant->mInt32);
  4374. }
  4375. }
  4376. }
  4377. // Check for Flags arg
  4378. if (customAttr.mCtorArgs.size() < 2)
  4379. continue;
  4380. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  4381. if (constant == NULL)
  4382. continue;
  4383. if (constant->mTypeCode == BfTypeCode_Boolean)
  4384. continue;
  4385. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4386. reflectKind = (ReflectKind)(reflectKind | ReflectKind_User);
  4387. }
  4388. }
  4389. }
  4390. return reflectKind;
  4391. };
  4392. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  4393. {
  4394. ReflectKind reflectKind = ReflectKind_None;
  4395. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  4396. if (customAttrs != NULL)
  4397. {
  4398. for (auto& attr : customAttrs->mAttributes)
  4399. {
  4400. reflectKind = (ReflectKind)(reflectKind | _GetReflectUser(attr.mType));
  4401. }
  4402. }
  4403. return reflectKind;
  4404. };
  4405. //
  4406. {
  4407. auto checkTypeInstance = typeInstance;
  4408. while (checkTypeInstance != NULL)
  4409. {
  4410. if (checkTypeInstance->mCustomAttributes != NULL)
  4411. {
  4412. auto checkReflectKind = ReflectKind_None;
  4413. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  4414. {
  4415. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4416. {
  4417. if (customAttr.mCtorArgs.size() > 0)
  4418. {
  4419. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  4420. checkReflectKind = (ReflectKind)((int)checkReflectKind | constant->mInt32);
  4421. }
  4422. else
  4423. {
  4424. checkReflectKind = ReflectKind_All;
  4425. }
  4426. }
  4427. else
  4428. {
  4429. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4430. checkReflectKind = (ReflectKind)(checkReflectKind | userReflectKind);
  4431. }
  4432. }
  4433. if ((checkTypeInstance == typeInstance) ||
  4434. ((checkReflectKind & ReflectKind_ApplyToInnerTypes) != 0))
  4435. {
  4436. reflectKind = (ReflectKind)(reflectKind | checkReflectKind);
  4437. }
  4438. }
  4439. checkTypeInstance = GetOuterType(checkTypeInstance);
  4440. }
  4441. }
  4442. // Fields
  4443. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  4444. BfIRValue emptyValueType = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  4445. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  4446. {
  4447. if (customAttributes == NULL)
  4448. return -1;
  4449. Array<BfCustomAttribute*> reflectAttributes;
  4450. for (auto& attr : customAttributes->mAttributes)
  4451. {
  4452. bool wantAttribute = false;
  4453. if (attr.mType->mCustomAttributes != NULL)
  4454. {
  4455. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  4456. if (usageAttribute != NULL)
  4457. {
  4458. // Check for Flags arg
  4459. if (usageAttribute->mCtorArgs.size() < 2)
  4460. continue;
  4461. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  4462. if (constant == NULL)
  4463. continue;
  4464. if (constant->mTypeCode == BfTypeCode_Boolean)
  4465. continue;
  4466. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4467. wantAttribute = true;
  4468. }
  4469. }
  4470. if ((wantAttribute) && (attr.mType->mIsReified))
  4471. {
  4472. reflectAttributes.Add(&attr);
  4473. }
  4474. }
  4475. if (reflectAttributes.size() == 0)
  4476. return -1;
  4477. #define PUSH_INT8(val) data.push_back((uint8)val)
  4478. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4479. #define PUSH_INT32(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); data.push_back((val >> 16) & 0xFF); data.push_back((val >> 24) & 0xFF); }
  4480. #define PUSH_INT64(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); data.push_back((val >> 16) & 0xFF); data.push_back((val >> 24) & 0xFF); \
  4481. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4482. SizedArray<uint8, 16> data;
  4483. int customAttrIdx = (int)customAttrs.size();
  4484. data.push_back((uint8)reflectAttributes.size());
  4485. for (auto attr : reflectAttributes)
  4486. {
  4487. // Size prefix
  4488. int sizeIdx = (int)data.size();
  4489. PUSH_INT16(0); // mSize
  4490. PUSH_INT32(attr->mType->mTypeId); // mType
  4491. PUSH_INT16(attr->mCtor->mIdx);
  4492. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  4493. int argIdx = 0;
  4494. for (auto arg : attr->mCtorArgs)
  4495. {
  4496. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4497. bool handled = false;
  4498. if (constant != NULL)
  4499. {
  4500. auto argType = ctorMethodInstance->GetParamType(argIdx);
  4501. if (argType->IsObject())
  4502. {
  4503. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  4504. int stringId = constant->mInt32;
  4505. int* orderedIdPtr;
  4506. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4507. {
  4508. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4509. }
  4510. GetStringObjectValue(stringId);
  4511. PUSH_INT8(0xFF); // String
  4512. PUSH_INT32(*orderedIdPtr);
  4513. continue;
  4514. }
  4515. PUSH_INT8(constant->mTypeCode);
  4516. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4517. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4518. (constant->mTypeCode == BfTypeCode_Double))
  4519. {
  4520. PUSH_INT64(constant->mInt64);
  4521. }
  4522. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4523. (constant->mTypeCode == BfTypeCode_UInt32))
  4524. {
  4525. PUSH_INT32(constant->mInt32);
  4526. }
  4527. else if (constant->mTypeCode == BfTypeCode_Single)
  4528. {
  4529. float val = (float)constant->mDouble;
  4530. PUSH_INT32(*(int*)&val);
  4531. }
  4532. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4533. (constant->mTypeCode == BfTypeCode_UInt16))
  4534. {
  4535. PUSH_INT16(constant->mInt16);
  4536. }
  4537. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4538. (constant->mTypeCode == BfTypeCode_UInt8))
  4539. {
  4540. PUSH_INT8(constant->mInt8);
  4541. }
  4542. else if (constant->mTypeCode == BfTypeCode_Object)
  4543. {
  4544. BF_FATAL("Unhandled");
  4545. }
  4546. else
  4547. {
  4548. BF_FATAL("Unhandled");
  4549. }
  4550. }
  4551. else if (!handled)
  4552. {
  4553. BF_FATAL("Unhandled");
  4554. }
  4555. argIdx++;
  4556. }
  4557. int size = (int)data.size() - sizeIdx;
  4558. *((uint16*)&data[sizeIdx]) = size;
  4559. }
  4560. #undef PUSH_INT8
  4561. #undef PUSH_INT16
  4562. #undef PUSH_INT32
  4563. SizedArray<BfIRValue, 16> dataValues;
  4564. for (uint8 val : data)
  4565. dataValues.push_back(GetConstValue8(val));
  4566. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  4567. auto customAttrConst = mBfIRBuilder->CreateConstArray(dataArrayType, dataValues);
  4568. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  4569. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  4570. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  4571. customAttrs.push_back(customAttrArrayPtr);
  4572. return customAttrIdx;
  4573. };
  4574. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  4575. SizedArray<int, 16> reflectFieldIndices;
  4576. for (int pass = 0; pass < 2; pass++)
  4577. {
  4578. bool skippedField = false;
  4579. reflectFieldIndices.clear();
  4580. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  4581. {
  4582. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4583. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4584. if (fieldDef == NULL)
  4585. continue;
  4586. auto fieldReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4587. bool includeField = reflectIncludeAllFields;
  4588. if (fieldInstance->mCustomAttributes != NULL)
  4589. {
  4590. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4591. {
  4592. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4593. {
  4594. includeField = true;
  4595. }
  4596. else
  4597. {
  4598. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4599. fieldReflectKind = (ReflectKind)(fieldReflectKind | userReflectKind);
  4600. }
  4601. }
  4602. }
  4603. if ((fieldReflectKind & ReflectKind_User) != 0)
  4604. includeField = true;
  4605. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_NonStaticFields) != 0))
  4606. includeField = true;
  4607. if ((fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_StaticFields) != 0))
  4608. includeField = true;
  4609. includeField |= forceReflectFields;
  4610. if (!includeField)
  4611. {
  4612. skippedField = true;
  4613. continue;
  4614. }
  4615. reflectFieldIndices.Add(fieldIdx);
  4616. }
  4617. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  4618. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  4619. // possible because we write out a SplatData structure containing just TypeIds in that case
  4620. if (pass == 0)
  4621. {
  4622. if (!typeInstance->IsSplattable())
  4623. break;
  4624. if (!skippedField)
  4625. break;
  4626. if (reflectFieldIndices.size() == 0)
  4627. break;
  4628. }
  4629. }
  4630. SizedArray<BfIRValue, 16> fieldTypes;
  4631. enum FieldFlags
  4632. {
  4633. FieldFlags_Protected = 3,
  4634. FieldFlags_Public = 6,
  4635. FieldFlags_Static = 0x10,
  4636. FieldFlags_Const = 0x40,
  4637. FieldFlags_SpecialName = 0x80,
  4638. FieldFlags_EnumPayload = 0x100,
  4639. FieldFlags_EnumDiscriminator = 0x200
  4640. };
  4641. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  4642. {
  4643. BfType* payloadType = typeInstance->GetUnionInnerType();
  4644. if (!payloadType->IsValuelessType())
  4645. {
  4646. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  4647. SizedArray<BfIRValue, 8> payloadFieldVals =
  4648. {
  4649. emptyValueType,
  4650. payloadNameConst, // mName
  4651. GetConstValue(0, longType), // mConstValue
  4652. GetConstValue(0, intType), // mDataOffset
  4653. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  4654. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  4655. GetConstValue(-1, intType), // mCustomAttributesIdx
  4656. };
  4657. auto payloadFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  4658. fieldTypes.push_back(payloadFieldData);
  4659. }
  4660. BfType* dscrType = typeInstance->GetDiscriminatorType();
  4661. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  4662. SizedArray<BfIRValue, 8> dscrFieldVals =
  4663. {
  4664. emptyValueType,
  4665. dscrNameConst, // mName
  4666. GetConstValue(0, longType), // mConstValue
  4667. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intType), // mDataOffset
  4668. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  4669. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  4670. GetConstValue(-1, intType), // mCustomAttributesIdx
  4671. };
  4672. auto dscrFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  4673. fieldTypes.push_back(dscrFieldData);
  4674. }
  4675. for (auto fieldIdx : reflectFieldIndices)
  4676. {
  4677. if (!needsTypeData)
  4678. break;
  4679. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4680. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4681. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  4682. int typeId = 0;
  4683. auto fieldType = fieldInstance->GetResolvedType();
  4684. if (fieldType->IsGenericParam())
  4685. {
  4686. //TODO:
  4687. }
  4688. else
  4689. typeId = fieldType->mTypeId;
  4690. FieldFlags fieldFlags = (FieldFlags)0;
  4691. if (fieldDef->mProtection == BfProtection_Protected)
  4692. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  4693. if (fieldDef->mProtection == BfProtection_Public)
  4694. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  4695. if (fieldDef->mIsStatic)
  4696. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  4697. if (fieldDef->mIsConst)
  4698. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  4699. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  4700. BfIRValue constValue = GetConstValue(0, longType);
  4701. if (fieldInstance->GetFieldDef()->mIsConst)
  4702. {
  4703. if (fieldInstance->mConstIdx != -1)
  4704. {
  4705. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4706. constValue = mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constant->mUInt64);
  4707. }
  4708. }
  4709. SizedArray<BfIRValue, 8> fieldVals =
  4710. {
  4711. emptyValueType,
  4712. fieldNameConst, // mName
  4713. constValue, // mConstValue
  4714. GetConstValue(fieldInstance->mDataOffset, intType), // mDataOffset
  4715. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4716. GetConstValue(fieldFlags, shortType), // mFlags
  4717. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  4718. };
  4719. auto fieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  4720. fieldTypes.push_back(fieldData);
  4721. }
  4722. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  4723. BfIRValue fieldDataPtr;
  4724. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  4725. if (fieldTypes.size() == 0)
  4726. {
  4727. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()))
  4728. {
  4729. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  4730. SizedArray<BfIRValue, 3> splatTypes;
  4731. SizedArray<BfIRValue, 3> splatOffsets;
  4732. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  4733. {
  4734. auto checkTypeInstance = checkType->ToTypeInstance();
  4735. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  4736. PopulateType(checkTypeInstance);
  4737. if (checkType->IsStruct())
  4738. {
  4739. int dataEnd = offset;
  4740. if (checkTypeInstance->mBaseType != NULL)
  4741. _CheckSplat(checkTypeInstance->mBaseType, offset);
  4742. if (checkTypeInstance->mIsUnion)
  4743. {
  4744. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  4745. _CheckSplat(unionInnerType, offset);
  4746. }
  4747. else
  4748. {
  4749. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  4750. {
  4751. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  4752. if (fieldInstance->mDataIdx >= 0)
  4753. {
  4754. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  4755. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  4756. }
  4757. }
  4758. }
  4759. if (checkTypeInstance->IsEnum())
  4760. {
  4761. // Add discriminator
  4762. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  4763. if (!checkTypeInstance->mIsPacked)
  4764. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  4765. _CheckSplat(dscrType, dataEnd);
  4766. }
  4767. }
  4768. else if (checkType->IsMethodRef())
  4769. {
  4770. // auto methodRefType = (BfMethodRefType*)checkType;
  4771. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  4772. // {
  4773. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  4774. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  4775. // else
  4776. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  4777. // }
  4778. }
  4779. else if (!checkType->IsValuelessType())
  4780. {
  4781. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  4782. splatOffsets.Add(GetConstValue(offset, intType));
  4783. }
  4784. };
  4785. _CheckSplat(type, 0);
  4786. while (splatTypes.size() < 3)
  4787. {
  4788. splatTypes.Add(GetConstValue(0, typeIdType));
  4789. splatOffsets.Add(GetConstValue(0, intType));
  4790. }
  4791. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  4792. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  4793. SizedArray<BfIRValue, 8> splatVals =
  4794. {
  4795. emptyValueType,
  4796. splatTypesConst,
  4797. splatOffsetsConst
  4798. };
  4799. auto fieldSplatData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  4800. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  4801. fieldSplatData, typeDataName + ".splats");
  4802. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4803. }
  4804. else
  4805. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  4806. }
  4807. else
  4808. {
  4809. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  4810. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstArray(fieldDataConstType, fieldTypes);
  4811. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  4812. fieldDataConst, "fields." + typeDataName);
  4813. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4814. }
  4815. /// Methods
  4816. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  4817. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  4818. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  4819. SizedArray<BfIRValue, 16> methodTypes;
  4820. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4821. {
  4822. if (!needsTypeData)
  4823. break;
  4824. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  4825. if (!methodInstanceGroup->IsImplemented())
  4826. continue;
  4827. auto methodDef = typeDef->mMethods[methodIdx];
  4828. if (methodDef->mNoReflect)
  4829. continue;
  4830. auto defaultMethod = methodInstanceGroup->mDefault;
  4831. if (defaultMethod == NULL)
  4832. continue;
  4833. if (defaultMethod->mIsUnspecialized)
  4834. continue;
  4835. if (!defaultMethod->mIsReified)
  4836. continue;
  4837. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  4838. continue;
  4839. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  4840. continue;
  4841. auto methodReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4842. bool includeMethod = reflectIncludeAllMethods;
  4843. BfCustomAttributes* methodCustomAttributes = NULL;
  4844. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  4845. {
  4846. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  4847. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  4848. {
  4849. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4850. {
  4851. includeMethod = true;
  4852. }
  4853. else
  4854. {
  4855. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4856. methodReflectKind = (ReflectKind)(methodReflectKind | userReflectKind);
  4857. }
  4858. }
  4859. }
  4860. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4861. continue;
  4862. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  4863. {
  4864. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  4865. {
  4866. if (paramDecl->mAttributes != NULL)
  4867. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  4868. }
  4869. if (methodDeclaration->mReturnAttributes != NULL)
  4870. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(methodDeclaration->mReturnAttributes, BfAttributeTargets_ReturnValue));
  4871. }
  4872. if ((methodReflectKind & (ReflectKind_Methods | ReflectKind_User)) != 0)
  4873. includeMethod = true;
  4874. if ((methodDef->mIsStatic) && ((methodReflectKind & ReflectKind_StaticMethods) != 0))
  4875. includeMethod = true;
  4876. if (!includeMethod)
  4877. continue;
  4878. BfModuleMethodInstance moduleMethodInstance;
  4879. BfIRValue funcVal = voidPtrNull;
  4880. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  4881. (!typeInstance->IsUnspecializedType()) &&
  4882. (methodDef->mMethodType != BfMethodType_Ignore) &&
  4883. (methodDef->mMethodType != BfMethodType_Mixin) &&
  4884. (!methodDef->mIsAbstract) &&
  4885. (methodDef->mGenericParams.size() == 0))
  4886. {
  4887. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx);
  4888. if (moduleMethodInstance.mFunc)
  4889. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  4890. }
  4891. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  4892. enum MethodFlags
  4893. {
  4894. MethodFlags_Protected = 3,
  4895. MethodFlags_Public = 6,
  4896. MethodFlags_Static = 0x10,
  4897. MethodFlags_Virtual = 0x40,
  4898. MethodFlags_StdCall = 0x1000,
  4899. MethodFlags_FastCall = 0x2000,
  4900. MethodFlags_Mutating = 0x4000,
  4901. };
  4902. MethodFlags methodFlags = (MethodFlags)0;
  4903. if (methodDef->mProtection == BfProtection_Protected)
  4904. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Protected);
  4905. if (methodDef->mProtection == BfProtection_Public)
  4906. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Public);
  4907. if (methodDef->mIsStatic)
  4908. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Static);
  4909. if (methodDef->mIsVirtual)
  4910. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Virtual);
  4911. if (methodDef->mCallingConvention == BfCallingConvention_Fastcall)
  4912. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  4913. if (methodDef->mIsMutating)
  4914. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Mutating);
  4915. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  4916. enum ParamFlags
  4917. {
  4918. ParamFlag_None = 0,
  4919. ParamFlag_Splat = 1,
  4920. ParamFlag_Implicit = 2,
  4921. };
  4922. SizedArray<BfIRValue, 8> paramVals;
  4923. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  4924. {
  4925. String paramName = defaultMethod->GetParamName(paramIdx);
  4926. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  4927. ParamFlags paramFlags = ParamFlag_None;
  4928. if (defaultMethod->GetParamIsSplat(paramIdx))
  4929. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  4930. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  4931. SizedArray<BfIRValue, 8> paramDataVals =
  4932. {
  4933. emptyValueType,
  4934. paramNameConst,
  4935. GetConstValue(paramType->mTypeId, typeIdType),
  4936. GetConstValue((int32)paramFlags, shortType),
  4937. GetConstValue(customAttrIdx, intType) // defaultIdx
  4938. };
  4939. auto paramData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  4940. paramVals.Add(paramData);
  4941. }
  4942. BfIRValue paramsVal;
  4943. if (paramVals.size() > 0)
  4944. {
  4945. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  4946. BfIRValue paramDataConst = mBfIRBuilder->CreateConstArray(paramDataArrayType, paramVals);
  4947. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  4948. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  4949. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  4950. }
  4951. else
  4952. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  4953. int vDataVal = -1;
  4954. if (defaultMethod->mVirtualTableIdx != -1)
  4955. {
  4956. int vDataIdx = -1;
  4957. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  4958. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  4959. {
  4960. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  4961. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  4962. if (extMethodIdx >= 0)
  4963. {
  4964. // Extension?
  4965. int vExtOfs = typeInst->GetOrigBaseVTableSize();
  4966. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  4967. }
  4968. else
  4969. {
  4970. // Map this new virtual index back to the original index
  4971. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  4972. }
  4973. }
  4974. else
  4975. {
  4976. vDataIdx += defaultMethod->mVirtualTableIdx;
  4977. }
  4978. if (vDataVal == -1)
  4979. vDataVal = vDataIdx * mSystem->mPtrSize;
  4980. }
  4981. SizedArray<BfIRValue, 8> methodDataVals =
  4982. {
  4983. emptyValueType,
  4984. methodNameConst, // mName
  4985. funcVal, // mFuncPtr
  4986. paramsVal,
  4987. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  4988. GetConstValue((int)paramVals.size(), shortType),
  4989. GetConstValue(methodFlags, shortType),
  4990. GetConstValue(vDataVal, intType),
  4991. GetConstValue(-1, intType),
  4992. };
  4993. auto methodData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  4994. methodTypes.push_back(methodData);
  4995. }
  4996. BfIRValue methodDataPtr;
  4997. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  4998. if (methodTypes.size() == 0)
  4999. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  5000. else
  5001. {
  5002. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  5003. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methodTypes);
  5004. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  5005. methodDataConst, "methods." + typeDataName);
  5006. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  5007. }
  5008. /////
  5009. int underlyingType = 0;
  5010. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  5011. {
  5012. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  5013. }
  5014. int outerTypeId = 0;
  5015. auto outerType = GetOuterType(typeInstance);
  5016. if (outerType != NULL)
  5017. outerTypeId = outerType->mTypeId;
  5018. BfIRValue customAttrDataPtr;
  5019. if (customAttrs.size() > 0)
  5020. {
  5021. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  5022. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstArray(customAttrsArrayType, customAttrs);
  5023. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  5024. customAttrsConst, "customAttrs." + typeDataName);
  5025. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  5026. }
  5027. else
  5028. {
  5029. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  5030. }
  5031. SizedArray<BfIRValue, 32> typeDataVals =
  5032. {
  5033. typeData,
  5034. castedClassVData, // mTypeClassVData
  5035. typeNameConst, // mName
  5036. namespaceConst, // mNamespace
  5037. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  5038. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  5039. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  5040. GetConstValue(baseTypeId, typeIdType), // mBaseType
  5041. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  5042. GetConstValue(outerTypeId, typeIdType), // mOuterType
  5043. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  5044. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  5045. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  5046. GetConstValue(0, byteType), // mInterfaceCount
  5047. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  5048. GetConstValue(0, shortType), // mPropertyDataCount
  5049. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  5050. GetConstValue(0, shortType), // mConstructorDataCount
  5051. voidPtrNull, // mInterfaceDataPtr
  5052. methodDataPtr, // mMethodDataPtr
  5053. voidPtrNull, // mPropertyDataPtr
  5054. fieldDataPtr, // mFieldDataPtr
  5055. voidPtrNull, // mConstructorDataPtr
  5056. customAttrDataPtr, // mCustomAttrDataPtr
  5057. };
  5058. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5059. auto typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, typeDataVals);
  5060. if (!needsTypeData)
  5061. {
  5062. // No need for anything beyond typeInstanceData
  5063. }
  5064. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5065. {
  5066. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5067. SizedArray<BfIRValue, 4> unspecializedData =
  5068. {
  5069. typeInstanceData,
  5070. GetConstValue((int)genericTypeInstance->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5071. };
  5072. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5073. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5074. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, unspecializedData);
  5075. }
  5076. else if (typeInstance->IsGenericTypeInstance())
  5077. {
  5078. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5079. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5080. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5081. SizedArray<BfIRValue, 4> resolvedTypes;
  5082. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  5083. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5084. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5085. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5086. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5087. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstArray(genericArrayType, resolvedTypes);
  5088. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5089. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5090. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5091. SizedArray<BfIRValue, 3> specGenericData =
  5092. {
  5093. typeInstanceData,
  5094. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5095. resovledTypesPtr, // mFieldDataPtr
  5096. };
  5097. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5098. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, specGenericData);
  5099. if (typeInstance->IsArray())
  5100. {
  5101. auto arrayType = (BfArrayType*)typeInstance;
  5102. BfType* elementType = genericTypeInstance->mTypeGenericArguments[0];
  5103. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5104. SizedArray<BfIRValue, 4> arrayData =
  5105. {
  5106. typeInstanceData,
  5107. GetConstValue(elementType->mSize, intType), // mElementSize
  5108. GetConstValue(1, byteType), // mRank
  5109. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5110. };
  5111. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5112. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5113. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, arrayData);
  5114. }
  5115. }
  5116. BfIRValue typeDataVar;
  5117. if (needsTypeData)
  5118. {
  5119. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5120. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5121. if (mBfIRBuilder->DbgHasInfo())
  5122. {
  5123. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, NULL, 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5124. }
  5125. }
  5126. else
  5127. {
  5128. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5129. }
  5130. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5131. mTypeDataRefs[typeInstance] = typeDataVar;
  5132. if (classVDataVar)
  5133. {
  5134. BF_ASSERT(!classVDataName.IsEmpty());
  5135. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5136. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5137. auto classVDataConstData = mBfIRBuilder->CreateConstArray(classVDataConstDataType, vData);
  5138. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5139. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5140. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5141. else
  5142. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5143. if (mBfIRBuilder->DbgHasInfo())
  5144. {
  5145. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5146. BfType* voidPtrType = CreatePointerType(voidType);
  5147. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5148. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5149. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, NULL, 0, arrayType, false, classVDataVar);
  5150. }
  5151. }
  5152. return typeDataVar;
  5153. }
  5154. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5155. {
  5156. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  5157. return value;
  5158. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5159. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5160. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5161. }
  5162. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5163. {
  5164. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5165. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  5166. // When we access classes with static constructors FROM a static constructor,
  5167. // we call that other class's static constructor first. Recursion cannot occur, since
  5168. // we simply ignore subsequent attempts to re-enter the constructor
  5169. if (!typeInstance->mHasStaticInitMethod)
  5170. return;
  5171. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  5172. return;
  5173. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  5174. return;
  5175. auto checkTypeDef = typeInstance->mTypeDef;
  5176. checkTypeDef->PopulateMemberSets();
  5177. BfMethodDef* nextMethodDef = NULL;
  5178. BfMemberSetEntry* entry;
  5179. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  5180. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5181. while (nextMethodDef != NULL)
  5182. {
  5183. auto checkMethod = nextMethodDef;
  5184. nextMethodDef = nextMethodDef->mNextWithSameName;
  5185. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  5186. if (methodModule)
  5187. {
  5188. auto methodInstance = methodModule.mMethodInstance;
  5189. if ((methodInstance != NULL) &&
  5190. (methodInstance->mMethodDef->mIsStatic) &&
  5191. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  5192. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  5193. {
  5194. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  5195. break;
  5196. }
  5197. }
  5198. }
  5199. }
  5200. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  5201. {
  5202. auto methodOwner = methodInstance->GetOwner();
  5203. auto methodDef = methodInstance->mMethodDef;
  5204. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5205. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  5206. if (!hasExternSpecifier)
  5207. return BfIRFunction();
  5208. if (methodInstance->GetCustomAttributes() == NULL)
  5209. return BfIRFunction();
  5210. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  5211. {
  5212. String typeName = TypeToString(customAttribute.mType);
  5213. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  5214. {
  5215. methodInstance->mIsIntrinsic = true;
  5216. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  5217. String error;
  5218. if ((constant != NULL) && (BfIRConstHolder::IsInt(constant->mTypeCode)))
  5219. {
  5220. int stringId = constant->mInt32;
  5221. auto entry = mContext->mStringObjectIdMap[stringId];
  5222. int intrinId = BfIRCodeGen::GetIntrinsicId(entry.mString);
  5223. if (intrinId != -1)
  5224. {
  5225. if (intrinId == BfIRIntrinsic_Malloc)
  5226. {
  5227. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  5228. }
  5229. else if (intrinId == BfIRIntrinsic_Free)
  5230. {
  5231. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  5232. }
  5233. SizedArray<BfIRType, 2> paramTypes;
  5234. for (auto& param : methodInstance->mParams)
  5235. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5236. return mBfIRBuilder->GetIntrinsic(intrinId, paramTypes);
  5237. }
  5238. else if (reportFailure)
  5239. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  5240. }
  5241. else if (reportFailure)
  5242. error = "Intrinsic name must be a constant string";
  5243. if (reportFailure)
  5244. {
  5245. BfAstNode* ref = methodDeclaration->mAttributes;
  5246. Fail(error, ref);
  5247. }
  5248. }
  5249. }
  5250. return BfIRFunction();
  5251. }
  5252. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  5253. {
  5254. if (mBfIRBuilder->mIgnoreWrites)
  5255. return mBfIRBuilder->GetFakeFunction();
  5256. if (!mBuiltInFuncs[(int)funcTypeId])
  5257. {
  5258. SizedArray<BfIRType, 4> paramTypes;
  5259. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  5260. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5261. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  5262. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5263. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  5264. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  5265. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  5266. BfIRFunctionType funcType;
  5267. BfIRFunction func;
  5268. switch (funcTypeId)
  5269. {
  5270. case BfBuiltInFuncType_PrintF:
  5271. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  5272. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  5273. break;
  5274. case BfBuiltInFuncType_Malloc:
  5275. {
  5276. if (mCompiler->mOptions.mDebugAlloc)
  5277. {
  5278. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  5279. }
  5280. else
  5281. {
  5282. String funcName = mCompiler->mOptions.mMallocLinkName;
  5283. if (funcName.IsEmpty())
  5284. funcName = "malloc";
  5285. func = mBfIRBuilder->GetFunction(funcName);
  5286. if (!func)
  5287. {
  5288. paramTypes.clear();
  5289. paramTypes.push_back(intType);
  5290. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  5291. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5292. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  5293. }
  5294. }
  5295. }
  5296. break;
  5297. case BfBuiltInFuncType_Free:
  5298. {
  5299. if (mCompiler->mOptions.mDebugAlloc)
  5300. {
  5301. func = GetInternalMethod("Dbg_RawFree").mFunc;
  5302. }
  5303. else
  5304. {
  5305. String funcName = mCompiler->mOptions.mFreeLinkName;
  5306. if (funcName.IsEmpty())
  5307. funcName = "free";
  5308. func = mBfIRBuilder->GetFunction(funcName);
  5309. if (!func)
  5310. {
  5311. paramTypes.clear();
  5312. paramTypes.push_back(nullPtrType);
  5313. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5314. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5315. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  5316. }
  5317. }
  5318. }
  5319. break;
  5320. case BfBuiltInFuncType_LoadSharedLibraries:
  5321. paramTypes.clear();
  5322. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5323. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  5324. break;
  5325. default: break;
  5326. }
  5327. mBuiltInFuncs[(int)funcTypeId] = func;
  5328. return func;
  5329. }
  5330. return mBuiltInFuncs[(int)funcTypeId];
  5331. }
  5332. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, const Array<BfGenericParamDef*>& genericParamDefs, int genericParamIdx)
  5333. {
  5334. BfGenericParamDef* genericParamDef = genericParamDefs[genericParamIdx];
  5335. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  5336. BfAutoComplete* bfAutocomplete = NULL;
  5337. if (mCompiler->mResolvePassData != NULL)
  5338. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  5339. if (bfAutocomplete != NULL)
  5340. {
  5341. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  5342. {
  5343. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  5344. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  5345. {
  5346. String filter = nameNode->ToString();
  5347. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  5348. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  5349. if (nameIdx != 0)
  5350. {
  5351. for (auto checkGenericParam : genericParamDefs)
  5352. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", checkGenericParam->mName.c_str()), filter);
  5353. }
  5354. }
  5355. }
  5356. }
  5357. for (auto constraintTypeRef : genericParamDef->mInterfaceConstraints)
  5358. {
  5359. if (bfAutocomplete != NULL)
  5360. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  5361. //TODO: Constraints may refer to other generic params (of either type or method)
  5362. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  5363. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  5364. if (constraintType != NULL)
  5365. {
  5366. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5367. {
  5368. bool isValidTypeCode = false;
  5369. BfTypeCode typeCode = BfTypeCode_None;
  5370. if (constraintType->IsTypedPrimitive())
  5371. {
  5372. auto underlyingType = constraintType->GetUnderlyingType();
  5373. if (underlyingType->IsPrimitiveType())
  5374. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  5375. }
  5376. if (constraintType->IsPrimitiveType())
  5377. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  5378. switch (typeCode)
  5379. {
  5380. case BfTypeCode_Int8:
  5381. case BfTypeCode_UInt8:
  5382. case BfTypeCode_Int16:
  5383. case BfTypeCode_UInt16:
  5384. case BfTypeCode_Int32:
  5385. case BfTypeCode_UInt32:
  5386. case BfTypeCode_Int64:
  5387. case BfTypeCode_UInt64:
  5388. case BfTypeCode_IntPtr:
  5389. case BfTypeCode_UIntPtr:
  5390. case BfTypeCode_IntUnknown:
  5391. case BfTypeCode_UIntUnknown:
  5392. case BfTypeCode_Single:
  5393. case BfTypeCode_Double:
  5394. case BfTypeCode_Char8:
  5395. case BfTypeCode_Char16:
  5396. case BfTypeCode_Char32:
  5397. isValidTypeCode = true;
  5398. break;
  5399. default: break;
  5400. }
  5401. if (isValidTypeCode)
  5402. {
  5403. genericParamInstance->mTypeConstraint = constraintType;
  5404. }
  5405. else
  5406. {
  5407. Fail("Const constraint must be a primitive type", constraintTypeRef);
  5408. }
  5409. }
  5410. else
  5411. {
  5412. if (constraintType->IsPrimitiveType())
  5413. {
  5414. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  5415. continue;
  5416. }
  5417. if (constraintType->IsArray())
  5418. {
  5419. Fail("Array constraints are not allowed. If a constant-sized array was intended, an type parameterized by a const generic param can be used (ie: where T : int[T2] where T2 : const int)", constraintTypeRef);
  5420. continue;
  5421. }
  5422. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  5423. {
  5424. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  5425. continue;
  5426. }
  5427. if (constraintType->IsInterface())
  5428. {
  5429. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  5430. }
  5431. else
  5432. {
  5433. auto constraintTypeInst = constraintType->ToTypeInstance();
  5434. if (genericParamInstance->mTypeConstraint != NULL)
  5435. {
  5436. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  5437. {
  5438. // Allow more specific type
  5439. genericParamInstance->mTypeConstraint = constraintTypeInst;
  5440. }
  5441. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  5442. {
  5443. // Silently ignore less-specific type
  5444. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  5445. {
  5446. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  5447. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  5448. }
  5449. }
  5450. else
  5451. {
  5452. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  5453. return;
  5454. }
  5455. }
  5456. else
  5457. genericParamInstance->mTypeConstraint = constraintType;
  5458. }
  5459. }
  5460. }
  5461. }
  5462. if (((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  5463. (genericParamInstance->mTypeConstraint == NULL))
  5464. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  5465. }
  5466. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  5467. {
  5468. if (genericParamSource.mMethodInstance != NULL)
  5469. {
  5470. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance);
  5471. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  5472. return MethodToString(methodInst);
  5473. }
  5474. else
  5475. {
  5476. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  5477. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  5478. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  5479. return TypeToString(typeInst);
  5480. }
  5481. }
  5482. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  5483. {
  5484. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  5485. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  5486. BfType* origCheckArgType = checkArgType;
  5487. if (origCheckArgType->IsRef())
  5488. origCheckArgType = origCheckArgType->GetUnderlyingType();
  5489. bool argMayBeReferenceType = false;
  5490. int checkGenericParamFlags = 0;
  5491. if (checkArgType->IsGenericParam())
  5492. {
  5493. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  5494. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  5495. if (checkGenericParamInst->mTypeConstraint != NULL)
  5496. checkArgType = checkGenericParamInst->mTypeConstraint;
  5497. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  5498. {
  5499. argMayBeReferenceType = false;
  5500. }
  5501. else
  5502. {
  5503. argMayBeReferenceType = true;
  5504. }
  5505. }
  5506. if (checkArgType->IsObjectOrInterface())
  5507. argMayBeReferenceType = true;
  5508. BfTypeInstance* typeConstraintInst = NULL;
  5509. if (genericParamInst->mTypeConstraint != NULL)
  5510. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  5511. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  5512. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  5513. {
  5514. if (!ignoreErrors)
  5515. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  5516. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5517. return false;
  5518. }
  5519. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  5520. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  5521. {
  5522. if (!ignoreErrors)
  5523. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  5524. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5525. return false;
  5526. }
  5527. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  5528. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  5529. {
  5530. if (!ignoreErrors)
  5531. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  5532. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5533. return false;
  5534. }
  5535. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5536. {
  5537. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  5538. {
  5539. if (!ignoreErrors)
  5540. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  5541. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5542. return false;
  5543. }
  5544. }
  5545. else
  5546. {
  5547. if (checkArgType->IsConstExprValue())
  5548. {
  5549. if (!ignoreErrors)
  5550. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  5551. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5552. return false;
  5553. }
  5554. }
  5555. if ((genericParamInst->mInterfaceConstraints.size() == 0) && (genericParamInst->mTypeConstraint == NULL))
  5556. return true;
  5557. if (checkArgType->IsPointer())
  5558. {
  5559. auto ptrType = (BfPointerType*)checkArgType;
  5560. checkArgType = ptrType->mElementType;
  5561. }
  5562. if (genericParamInst->mTypeConstraint != NULL)
  5563. {
  5564. bool constraintMatched = false;
  5565. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5566. {
  5567. if (checkArgType->IsConstExprValue())
  5568. {
  5569. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  5570. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  5571. {
  5572. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  5573. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  5574. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  5575. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  5576. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  5577. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  5578. {
  5579. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  5580. {
  5581. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5582. {
  5583. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  5584. {
  5585. if (!ignoreErrors)
  5586. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5587. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5588. return false;
  5589. }
  5590. }
  5591. else
  5592. {
  5593. if (!ignoreErrors)
  5594. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with integer const '%lld', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5595. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5596. return false;
  5597. }
  5598. }
  5599. else
  5600. {
  5601. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5602. {
  5603. char valStr[64];
  5604. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  5605. if (!ignoreErrors)
  5606. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with floating point const '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5607. valStr, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5608. return false;
  5609. }
  5610. }
  5611. }
  5612. }
  5613. }
  5614. }
  5615. else
  5616. {
  5617. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  5618. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  5619. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5620. if ((checkArgType->IsMethodRef()) && (convCheckConstraint->IsDelegate()))
  5621. {
  5622. auto methodRefType = (BfMethodRefType*)checkArgType;
  5623. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  5624. BfExprEvaluator exprEvaluator(this);
  5625. if (exprEvaluator.IsExactMethodMatch(methodRefType->mMethodRef, invokeMethod))
  5626. constraintMatched = true;
  5627. }
  5628. else if (CanImplicitlyCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  5629. {
  5630. constraintMatched = true;
  5631. }
  5632. else if (origCheckArgType->IsWrappableType())
  5633. {
  5634. if (origCheckArgType->IsSizedArray())
  5635. {
  5636. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  5637. if (convCheckConstraint->IsGenericTypeInstance())
  5638. {
  5639. auto convCheckConstraintInst = (BfGenericTypeInstance*)convCheckConstraint;
  5640. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  5641. {
  5642. if (convCheckConstraintInst->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  5643. {
  5644. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mTypeGenericArguments[1];
  5645. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  5646. constraintMatched = true;
  5647. }
  5648. }
  5649. }
  5650. }
  5651. if (!constraintMatched)
  5652. {
  5653. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5654. if (CanImplicitlyCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  5655. constraintMatched = true;
  5656. }
  5657. }
  5658. if (!constraintMatched)
  5659. {
  5660. if (!ignoreErrors)
  5661. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5662. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  5663. TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  5664. return false;
  5665. }
  5666. }
  5667. }
  5668. if ((genericParamInst->mInterfaceConstraints.size() > 0) && (origCheckArgType->IsInterface()))
  5669. {
  5670. PopulateType(origCheckArgType);
  5671. auto checkTypeInst = origCheckArgType->ToTypeInstance();
  5672. if (checkTypeInst->mTypeDef->mIsConcrete)
  5673. {
  5674. if (!ignoreErrors)
  5675. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be concrete interface '%s' for '%s', must be a concrete type", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5676. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5677. return false;
  5678. }
  5679. }
  5680. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  5681. {
  5682. BfType* convCheckConstraint = checkConstraint;
  5683. if (convCheckConstraint->IsUnspecializedType())
  5684. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5685. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  5686. bool implementsInterface = false;
  5687. if (origCheckArgType != checkArgType)
  5688. {
  5689. implementsInterface = CanImplicitlyCast(origCheckArgType, convCheckConstraint);
  5690. }
  5691. if (!implementsInterface)
  5692. implementsInterface = CanImplicitlyCast(checkArgType, convCheckConstraint);
  5693. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  5694. {
  5695. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5696. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5697. implementsInterface = true;
  5698. }
  5699. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  5700. {
  5701. auto underlyingType = origCheckArgType->GetUnderlyingType();
  5702. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  5703. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5704. implementsInterface = true;
  5705. }
  5706. if (!implementsInterface)
  5707. {
  5708. if (!ignoreErrors)
  5709. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5710. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  5711. return false;
  5712. }
  5713. }
  5714. return true;
  5715. }
  5716. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  5717. {
  5718. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  5719. {
  5720. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  5721. return genericParamType;
  5722. }
  5723. auto genericParamType = new BfGenericParamType();
  5724. genericParamType->mContext = mContext;
  5725. genericParamType->mGenericParamKind = paramKind;
  5726. genericParamType->mGenericParamIdx = paramIdx;
  5727. PopulateType(genericParamType);
  5728. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  5729. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  5730. BfResolvedTypeSet::LookupContext lookupCtx;
  5731. lookupCtx.mModule = this;
  5732. BfResolvedTypeSet::Entry* typeEntry = NULL;
  5733. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  5734. BF_ASSERT(inserted);
  5735. typeEntry->mValue = genericParamType;
  5736. return genericParamType;
  5737. }
  5738. static int sValueFromExprIdx = 0;
  5739. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  5740. {
  5741. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  5742. if ((result) && (!ignoreNullable))
  5743. {
  5744. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  5745. //TODO: Make this work, needed for 'void' and such
  5746. BfType* nullableType = NULL;
  5747. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  5748. {
  5749. BfTypeVector typeVec;
  5750. typeVec.push_back(result.mType);
  5751. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  5752. BF_ASSERT(nullableType != NULL);
  5753. }
  5754. // Go back to start and do any setup we need
  5755. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5756. BfTypedValue nullableTypedValue;
  5757. if (nullableType != NULL)
  5758. {
  5759. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  5760. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  5761. GetConstValue(nullableType->mSize), nullableType->mAlign);
  5762. }
  5763. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5764. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  5765. mBfIRBuilder->SetInsertPoint(notNullBB);
  5766. result = LoadValue(result);
  5767. if (nullableTypedValue)
  5768. {
  5769. auto elementType = nullableType->GetUnderlyingType();
  5770. if (elementType->IsValuelessType())
  5771. {
  5772. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  5773. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5774. result = nullableTypedValue;
  5775. }
  5776. else
  5777. {
  5778. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  5779. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  5780. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  5781. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5782. result = nullableTypedValue;
  5783. }
  5784. }
  5785. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5786. AddBasicBlock(pendingNullCond->mDoneBB);
  5787. if (nullableType == NULL)
  5788. {
  5789. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 2);
  5790. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  5791. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  5792. result.mValue = phi;
  5793. }
  5794. }
  5795. else
  5796. {
  5797. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5798. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5799. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5800. AddBasicBlock(pendingNullCond->mDoneBB);
  5801. }
  5802. delete mCurMethodState->mPendingNullConditional;
  5803. mCurMethodState->mPendingNullConditional = NULL;
  5804. return result;
  5805. }
  5806. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  5807. {
  5808. BfScopeData newScope;
  5809. newScope.mOuterIsConditional = true;
  5810. newScope.mAllowTargeting = false;
  5811. mCurMethodState->AddScope(&newScope);
  5812. NewScopeState();
  5813. exprEvaluator.mBfEvalExprFlags = flags;
  5814. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5815. RestoreScopeState();
  5816. }
  5817. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5818. {
  5819. //
  5820. {
  5821. BP_ZONE("CreateValueFromExpression:CheckStack");
  5822. StackHelper stackHelper;
  5823. if (!stackHelper.CanStackExpand(64 * 1024))
  5824. {
  5825. BfTypedValue result;
  5826. if (!stackHelper.Execute([&]()
  5827. {
  5828. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5829. }))
  5830. {
  5831. Fail("Expression too complex to compile", expr);
  5832. }
  5833. return result;
  5834. }
  5835. }
  5836. BP_ZONE("BfModule::CreateValueFromExpression");
  5837. if (outOrigType != NULL)
  5838. *outOrigType = NULL;
  5839. exprEvaluator.mExpectingType = wantTypeRef;
  5840. exprEvaluator.mBfEvalExprFlags = flags;
  5841. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  5842. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  5843. {
  5844. EvaluateWithNewScope(exprEvaluator, expr, flags);
  5845. }
  5846. else
  5847. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5848. if (!exprEvaluator.mResult)
  5849. {
  5850. if (!mCompiler->mPassInstance->HasFailed())
  5851. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  5852. return BfTypedValue();
  5853. }
  5854. auto typedVal = exprEvaluator.mResult;
  5855. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  5856. {
  5857. BF_ASSERT(typedVal.mType->IsGenericParam());
  5858. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  5859. bool handled = false;
  5860. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5861. {
  5862. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  5863. if (genericTypeConstraint != NULL)
  5864. {
  5865. auto primType = genericTypeConstraint->ToPrimitiveType();
  5866. if (primType != NULL)
  5867. {
  5868. BfTypedValue result;
  5869. result.mKind = BfTypedValueKind_Value;
  5870. result.mType = genericTypeConstraint;
  5871. result.mValue = mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode);
  5872. typedVal = result;
  5873. handled = true;
  5874. }
  5875. }
  5876. }
  5877. if (!handled)
  5878. {
  5879. //Fail("Only const generic parameters can be used as values", expr);
  5880. AssertErrorState();
  5881. return BfTypedValue();
  5882. }
  5883. }
  5884. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  5885. FixIntUnknown(typedVal);
  5886. exprEvaluator.CheckResultForReading(typedVal);
  5887. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  5888. {
  5889. if ((flags & BfEvalExprFlags_NoCast) == 0)
  5890. {
  5891. // Only allow a 'ref' type if we have an explicit 'ref' operator
  5892. bool allowRef = false;
  5893. BfExpression* checkExpr = expr;
  5894. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  5895. checkExpr = parenExpr->mExpression;
  5896. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  5897. {
  5898. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  5899. allowRef = true;
  5900. }
  5901. if (!allowRef)
  5902. typedVal = RemoveRef(typedVal);
  5903. }
  5904. }
  5905. if (!typedVal.mType->IsComposite()) // Load non-structs by default
  5906. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5907. if (wantTypeRef != NULL)
  5908. {
  5909. if (outOrigType != NULL)
  5910. *outOrigType = typedVal.mType;
  5911. if ((flags & BfEvalExprFlags_NoCast) == 0)
  5912. {
  5913. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  5914. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  5915. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  5916. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  5917. if (!typedVal)
  5918. return typedVal;
  5919. }
  5920. //WTF- why did we have this?
  5921. /*if ((flags & BfEvalExprFlags_ExplicitCast) == 0)
  5922. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);*/
  5923. if (exprEvaluator.mIsVolatileReference)
  5924. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5925. }
  5926. // if ((typedVal.IsSplat()) && ((flags & BfEvalExprFlags_AllowSplat) == 0))
  5927. // typedVal = MakeAddressable(typedVal);
  5928. //typedVal = AggregateSplat(typedVal);
  5929. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  5930. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5931. return typedVal;
  5932. }
  5933. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5934. {
  5935. BfExprEvaluator exprEvaluator(this);
  5936. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5937. }
  5938. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  5939. {
  5940. BfExprEvaluator exprEvaluator(this);
  5941. exprEvaluator.Evaluate(expr);
  5942. if (!exprEvaluator.mResult)
  5943. {
  5944. Fail("Invalid expression type", expr);
  5945. return BfTypedValue();
  5946. }
  5947. if (!exprEvaluator.mResult.IsAddr())
  5948. {
  5949. Fail("Cannot assign to value", expr);
  5950. return BfTypedValue();
  5951. }
  5952. return exprEvaluator.mResult;
  5953. }
  5954. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  5955. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  5956. {
  5957. auto typeInstance = typedValue.mType->ToTypeInstance();
  5958. if (zeroMemory)
  5959. {
  5960. int zeroAlign = typedValue.mType->mAlign;
  5961. if (typeInstance != NULL)
  5962. zeroAlign = typeInstance->mInstAlign;
  5963. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  5964. }
  5965. if (!typedValue.mType->IsObject())
  5966. {
  5967. return;
  5968. }
  5969. if ((scopeData == NULL) && (mCurMethodState != NULL))
  5970. return; // Handled in heap alloc funcs
  5971. auto typeDef = typeInstance->mTypeDef;
  5972. mBfIRBuilder->PopulateType(typedValue.mType);
  5973. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  5974. bool isAutocomplete = mCompiler->IsAutocomplete();
  5975. BfIRValue vDataRef;
  5976. if (!isAutocomplete)
  5977. {
  5978. vDataRef = GetClassVDataPtr(typeInstance);
  5979. }
  5980. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  5981. auto ptrType = CreatePointerType(i8Type);
  5982. auto ptrPtrType = CreatePointerType(ptrType);
  5983. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  5984. PopulateType(ptrType, BfPopulateType_Declaration);
  5985. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  5986. if (!isAutocomplete)
  5987. {
  5988. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5989. {
  5990. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  5991. SizedArray<BfIRValue, 4> llvmArgs;
  5992. llvmArgs.push_back(objectPtr);
  5993. llvmArgs.push_back(vDataRef);
  5994. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  5995. if (objectStackInitMethod)
  5996. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  5997. }
  5998. else
  5999. {
  6000. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  6001. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  6002. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6003. }
  6004. }
  6005. }
  6006. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  6007. {
  6008. BfIRValue result;
  6009. BfType* ptrType;
  6010. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  6011. ptrType = type;
  6012. else
  6013. ptrType = CreatePointerType(type);
  6014. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  6015. {
  6016. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6017. SizedArray<BfExpression*, 2> argExprs;
  6018. BfTypedValueExpression typedValueExpr;
  6019. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  6020. typedValueExpr.mRefNode = refNode;
  6021. argExprs.push_back(&typedValueExpr);
  6022. BfTypedValueExpression appendSizeValueExpr;
  6023. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  6024. appendSizeValueExpr.mRefNode = refNode;
  6025. argExprs.push_back(&appendSizeValueExpr);
  6026. BfExprEvaluator exprEvaluator(this);
  6027. BfTypedValue allocResult;
  6028. if (allocTarget.mScopedInvocationTarget != NULL)
  6029. {
  6030. SizedArray<BfTypeReference*, 2> genericArgs;
  6031. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  6032. allocResult = LoadValue(exprEvaluator.mResult);
  6033. }
  6034. else if (allocTarget.mCustomAllocator)
  6035. {
  6036. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6037. if (customTypeInst != NULL)
  6038. {
  6039. BfTypedValueExpression typeValueExpr;
  6040. String allocMethodName = "Alloc";
  6041. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  6042. {
  6043. allocMethodName = "AllocTyped";
  6044. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  6045. auto typeRefVal = CreateTypeDataRef(type);
  6046. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  6047. typeValueExpr.mRefNode = refNode;
  6048. argExprs.Insert(0, &typeValueExpr);
  6049. }
  6050. if (HasMixin(customTypeInst, allocMethodName, 2))
  6051. {
  6052. BfSizedArray<BfExpression*> argExprArr;
  6053. argExprArr.mSize = (int)argExprs.size();
  6054. argExprArr.mVals = &argExprs[0];
  6055. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  6056. allocResult = exprEvaluator.GetResult();
  6057. }
  6058. else
  6059. {
  6060. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6061. BfResolvedArgs argValues(&sizedArgExprs);
  6062. exprEvaluator.ResolveArgValues(argValues);
  6063. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  6064. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  6065. }
  6066. }
  6067. }
  6068. if (allocResult)
  6069. {
  6070. if (allocResult.mType->IsVoidPtr())
  6071. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  6072. else
  6073. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  6074. return result;
  6075. }
  6076. }
  6077. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  6078. return result;
  6079. if (mCompiler->mOptions.mDebugAlloc)
  6080. {
  6081. BfIRValue allocData = GetDbgRawAllocData(type);
  6082. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  6083. SizedArray<BfIRValue, 2> llvmArgs;
  6084. llvmArgs.push_back(sizeValue);
  6085. llvmArgs.push_back(allocData);
  6086. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  6087. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6088. }
  6089. BfModuleMethodInstance moduleMethodInstance;
  6090. moduleMethodInstance = GetInternalMethod("Malloc");
  6091. SizedArray<BfIRValue, 1> llvmArgs;
  6092. llvmArgs.push_back(sizeValue);
  6093. auto func = moduleMethodInstance.mFunc;
  6094. if ((!func) || (func.IsFake()))
  6095. {
  6096. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  6097. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  6098. }
  6099. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  6100. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  6101. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  6102. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6103. return result;
  6104. }
  6105. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  6106. {
  6107. if (type->IsStruct())
  6108. {
  6109. auto typeInstance = type->ToTypeInstance();
  6110. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  6111. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6112. }
  6113. else if (type->IsObjectOrInterface())
  6114. {
  6115. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6116. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  6117. BF_ASSERT(moduleMethodInst.mFunc);
  6118. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6119. }
  6120. else
  6121. {
  6122. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6123. BfExprEvaluator exprEvaluator(this);
  6124. SizedArray<BfResolvedArg, 1> resolvedArgs;
  6125. BfResolvedArg resolvedArg;
  6126. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  6127. resolvedArgs.Add(resolvedArg);
  6128. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  6129. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  6130. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  6131. BF_ASSERT(moduleMethodInst.mFunc);
  6132. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6133. }
  6134. return BfIRValue();
  6135. }
  6136. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  6137. {
  6138. BfIRValue allocDataValue;
  6139. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  6140. return allocDataValue;
  6141. BfIRValue markFuncPtr;
  6142. if (type->WantsGCMarking())
  6143. markFuncPtr = GetMarkFuncPtr(type);
  6144. else
  6145. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6146. BfIRValue typeDataRef = CreateTypeDataRef(type);
  6147. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  6148. BfTypeInstance* typeInstance = type->ToTypeInstance();
  6149. if (typeInstance == NULL)
  6150. {
  6151. typeInstance = GetWrappedStructType(type);
  6152. if (typeInstance != NULL)
  6153. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6154. }
  6155. if (typeInstance != NULL)
  6156. PopulateType(typeInstance);
  6157. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6158. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  6159. {
  6160. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6161. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6162. }
  6163. SizedArray<BfIRValue, 2> dataValues;
  6164. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  6165. dataValues.Add(typeDataRef);
  6166. dataValues.Add(markFuncPtr);
  6167. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  6168. BfIRValue dataStruct = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  6169. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  6170. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  6171. return allocDataValue;
  6172. }
  6173. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  6174. {
  6175. BP_ZONE("AllocFromType");
  6176. BfScopeData* scopeData = allocTarget.mScopeData;
  6177. auto typeInstance = type->ToTypeInstance();
  6178. if ((typeInstance == NULL) && (type->IsGenericParam()))
  6179. typeInstance = mContext->mBfObjectType;
  6180. bool isHeapAlloc = scopeData == NULL;
  6181. bool isScopeAlloc = scopeData != NULL;
  6182. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  6183. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  6184. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  6185. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  6186. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  6187. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  6188. {
  6189. BfPointerType* ptrType = CreatePointerType(type);
  6190. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  6191. return val;
  6192. }
  6193. if (typeInstance != NULL)
  6194. mBfIRBuilder->PopulateType(typeInstance);
  6195. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  6196. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  6197. {
  6198. if (arraySize)
  6199. {
  6200. if (isRawArrayAlloc)
  6201. {
  6202. BfPointerType* ptrType = CreatePointerType(type);
  6203. return GetDefaultValue(ptrType);
  6204. }
  6205. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6206. return GetDefaultValue(arrayType);
  6207. }
  6208. if (type->IsValueType())
  6209. {
  6210. BfPointerType* ptrType = CreatePointerType(type);
  6211. return GetDefaultValue(ptrType);
  6212. }
  6213. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  6214. }
  6215. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6216. BfIRValue sizeValue;
  6217. BfIRType allocType = mBfIRBuilder->MapType(type);
  6218. int allocSize = type->mSize;
  6219. int allocAlign = type->mAlign;
  6220. if (typeInstance != NULL)
  6221. {
  6222. if (!mBfIRBuilder->mIgnoreWrites)
  6223. typeInstance->mHasBeenInstantiated = true;
  6224. allocSize = typeInstance->mInstSize;
  6225. allocAlign = typeInstance->mInstAlign;
  6226. //if (typeInstance->IsEnum())
  6227. //allocType = typeInstance->mIRType;
  6228. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  6229. }
  6230. if (alignOverride != -1)
  6231. allocAlign = alignOverride;
  6232. // The "dynSize" cases:
  6233. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  6234. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  6235. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  6236. // though we'd expect their stack space to be released
  6237. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  6238. {
  6239. MarkDynStack(scopeData);
  6240. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6241. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  6242. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6243. BfType* voidPtrType = CreatePointerType(voidType);
  6244. if (!mCurMethodState->mDynStackRevIdx)
  6245. {
  6246. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  6247. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6248. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6249. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  6250. mBfIRBuilder->ClearDebugLocation(storeInst);
  6251. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6252. }
  6253. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  6254. auto bytePtrType = CreatePointerType(byteType);
  6255. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  6256. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  6257. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6258. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6259. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  6260. mBfIRBuilder->ClearDebugLocation(storeInst);
  6261. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  6262. mBfIRBuilder->ClearDebugLocation(storeInst);
  6263. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6264. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  6265. if (IsTargetingBeefBackend())
  6266. {
  6267. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  6268. // to ensure there isn't any register collision during looping is just to not allow it to
  6269. // bind to a register at all
  6270. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  6271. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  6272. }
  6273. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  6274. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  6275. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  6276. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  6277. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  6278. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  6279. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  6280. mBfIRBuilder->AddBlock(verCheckBB);
  6281. mBfIRBuilder->SetInsertPoint(verCheckBB);
  6282. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  6283. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  6284. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  6285. mBfIRBuilder->AddBlock(resizeBB);
  6286. mBfIRBuilder->SetInsertPoint(resizeBB);
  6287. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6288. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  6289. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  6290. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  6291. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  6292. mBfIRBuilder->CreateBr(endBB);
  6293. mBfIRBuilder->AddBlock(endBB);
  6294. mBfIRBuilder->SetInsertPoint(endBB);
  6295. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  6296. };
  6297. if (isScopeAlloc)
  6298. {
  6299. if (arraySize)
  6300. {
  6301. bool isConstantArraySize = arraySize.IsConst();
  6302. if (isRawArrayAlloc)
  6303. {
  6304. BfPointerType* ptrType = CreatePointerType(type);
  6305. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6306. {
  6307. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6308. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  6309. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  6310. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  6311. }
  6312. else
  6313. {
  6314. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6315. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  6316. if (!isDynAlloc)
  6317. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6318. else
  6319. {
  6320. MarkDynStack(scopeData);
  6321. SaveStackState(scopeData);
  6322. }
  6323. int typeSize = type->GetStride();
  6324. BfIRValue allocaInst;
  6325. BfIRValue result;
  6326. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  6327. {
  6328. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6329. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  6330. result = allocaInst;
  6331. }
  6332. else
  6333. {
  6334. if (typeInstance->IsStruct())
  6335. typeSize = typeInstance->GetInstStride();
  6336. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  6337. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6338. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6339. auto ptrType = CreatePointerType(typeInstance);
  6340. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  6341. if (!isDynAlloc)
  6342. mBfIRBuilder->ClearDebugLocation(result);
  6343. }
  6344. if (!isDynAlloc)
  6345. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6346. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  6347. if (!isDynAlloc)
  6348. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6349. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  6350. if (arraySize.IsConst())
  6351. {
  6352. auto constant = mBfIRBuilder->GetConstant(arraySize);
  6353. if (constant->mInt64 == 0)
  6354. noDtorCall = true;
  6355. }
  6356. if (!noDtorCall)
  6357. {
  6358. bool isConstSize = arraySize.IsConst();
  6359. BfIRBlock clearBlock;
  6360. BfIRBlock contBlock;
  6361. if (!isConstSize)
  6362. {
  6363. clearBlock = mBfIRBuilder->CreateBlock("clear");
  6364. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  6365. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  6366. mBfIRBuilder->AddBlock(clearBlock);
  6367. mBfIRBuilder->SetInsertPoint(clearBlock);
  6368. }
  6369. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6370. if (!isConstSize)
  6371. {
  6372. mBfIRBuilder->CreateBr(contBlock);
  6373. mBfIRBuilder->AddBlock(contBlock);
  6374. mBfIRBuilder->SetInsertPoint(contBlock);
  6375. }
  6376. }
  6377. //InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6378. return result;
  6379. }
  6380. }
  6381. else
  6382. {
  6383. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6384. {
  6385. // Generate and check new size
  6386. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6387. auto firstElementField = &arrayType->mFieldInstances.back();
  6388. int arrayClassSize = firstElementField->mDataOffset;
  6389. sizeValue = GetConstValue(arrayClassSize);
  6390. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6391. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6392. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  6393. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  6394. if (!noDtorCall)
  6395. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6396. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6397. return typedVal.mValue;
  6398. }
  6399. else
  6400. {
  6401. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6402. auto firstElementField = &arrayType->mFieldInstances.back();
  6403. int arrayClassSize = firstElementField->mDataOffset;
  6404. sizeValue = GetConstValue(arrayClassSize);
  6405. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6406. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6407. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6408. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6409. if (!isDynAlloc)
  6410. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6411. else
  6412. {
  6413. MarkDynStack(scopeData);
  6414. SaveStackState(scopeData);
  6415. }
  6416. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  6417. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6418. if (!isDynAlloc)
  6419. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6420. mBfIRBuilder->SetAllocaAlignment(allocaInst, arrayType->mAlign);
  6421. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  6422. mBfIRBuilder->ClearDebugLocation_Last();
  6423. if (!isDynAlloc)
  6424. mBfIRBuilder->SetInsertPoint(prevBlock);
  6425. if (!noDtorCall)
  6426. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6427. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6428. return typedVal.mValue;
  6429. }
  6430. }
  6431. }
  6432. else if (appendSizeValue)
  6433. {
  6434. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  6435. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  6436. // use the "dynSize" version conservatively
  6437. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6438. {
  6439. // Generate and check new size
  6440. sizeValue = GetConstValue(typeInstance->mInstSize);
  6441. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6442. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  6443. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  6444. if (!noDtorCall)
  6445. AddStackAlloc(typedVal, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  6446. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6447. return typedVal.mValue;
  6448. }
  6449. else // stack alloc, unlooped, with append
  6450. {
  6451. sizeValue = GetConstValue(typeInstance->mInstSize);
  6452. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6453. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6454. bool wasDynAlloc = isDynAlloc;
  6455. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6456. if (!isDynAlloc)
  6457. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6458. else
  6459. {
  6460. MarkDynStack(scopeData);
  6461. SaveStackState(scopeData);
  6462. }
  6463. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  6464. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  6465. if (!isDynAlloc)
  6466. {
  6467. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6468. }
  6469. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6470. bool mayBeLarge = false;
  6471. if (sizeValue.IsConst())
  6472. {
  6473. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  6474. if (constantInt->mInt64 >= 4096)
  6475. mayBeLarge = true;
  6476. }
  6477. else
  6478. mayBeLarge = true;
  6479. if (((type->IsObject() && (!mayBeLarge))) ||
  6480. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6481. ((zeroMemory) && (!mayBeLarge)))
  6482. {
  6483. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6484. }
  6485. BfIRValue castedVal;
  6486. if (!isDynAlloc)
  6487. {
  6488. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6489. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6490. mBfIRBuilder->ClearDebugLocation(castedVal);
  6491. mBfIRBuilder->SetInsertPoint(prevBlock);
  6492. if (WantsLifetimes())
  6493. {
  6494. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6495. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6496. }
  6497. }
  6498. else
  6499. {
  6500. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6501. }
  6502. auto typedVal = BfTypedValue(castedVal, typeInstance);
  6503. if (!noDtorCall)
  6504. {
  6505. bool doCondAlloca = false;
  6506. if (!IsTargetingBeefBackend())
  6507. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  6508. AddStackAlloc(typedVal, NULL, scopeData, doCondAlloca, true);
  6509. }
  6510. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6511. return typedVal.mValue;
  6512. }
  6513. }
  6514. else // "Normal" stack alloc
  6515. {
  6516. BF_ASSERT(!sizeValue);
  6517. //TODO: If sizeValue is a constant then do this in the head IR builder
  6518. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6519. if (!isLoopedAlloc)
  6520. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6521. else
  6522. {
  6523. MarkDynStack(scopeData);
  6524. SaveStackState(scopeData);
  6525. }
  6526. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  6527. if (!isLoopedAlloc)
  6528. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6529. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6530. bool mayBeLarge = allocSize >= 4096;
  6531. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  6532. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6533. ((zeroMemory) && (!mayBeLarge)))
  6534. {
  6535. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  6536. // and memset is always safe
  6537. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6538. }
  6539. auto typedVal = BfTypedValue(allocaInst, type);
  6540. if (!isLoopedAlloc)
  6541. {
  6542. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6543. mBfIRBuilder->SetInsertPoint(prevBlock);
  6544. if (WantsLifetimes())
  6545. {
  6546. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6547. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6548. }
  6549. }
  6550. if (!noDtorCall)
  6551. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6552. if (typeInstance != NULL)
  6553. {
  6554. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  6555. }
  6556. else
  6557. {
  6558. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  6559. }
  6560. return allocaInst;
  6561. }
  6562. }
  6563. else if (arraySize)
  6564. {
  6565. if (isRawArrayAlloc)
  6566. {
  6567. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6568. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  6569. }
  6570. else
  6571. {
  6572. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6573. typeInstance = arrayType;
  6574. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6575. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6576. appendSizeValue = elementDataSize;
  6577. if (!type->IsSizeAligned())
  6578. {
  6579. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  6580. }
  6581. }
  6582. }
  6583. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  6584. {
  6585. auto vDataRef = GetClassVDataPtr(typeInstance);
  6586. BfIRValue result;
  6587. bool isResultInitialized = false;
  6588. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6589. if (typeInstance->mTypeOptionsIdx != -1)
  6590. {
  6591. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6592. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6593. }
  6594. if (!sizeValue)
  6595. sizeValue = GetConstValue(typeInstance->mInstSize);
  6596. if (appendSizeValue)
  6597. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6598. BfIRValue origSizeValue = sizeValue;
  6599. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  6600. if (isAllocEx)
  6601. {
  6602. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  6603. if (prepareStackTraceMethod)
  6604. {
  6605. SizedArray<BfIRValue, 2> irArgs;
  6606. irArgs.Add(sizeValue);
  6607. irArgs.Add(GetConstValue(stackCount));
  6608. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  6609. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  6610. }
  6611. }
  6612. if (allocTarget.mCustomAllocator)
  6613. {
  6614. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6615. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  6616. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  6617. {
  6618. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6619. mBfIRBuilder->PopulateType(classVDataType);
  6620. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6621. mBfIRBuilder->PopulateType(typeInstType);
  6622. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  6623. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  6624. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  6625. BfTypedValueExpression typedValueExpr;
  6626. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  6627. typedValueExpr.mRefNode = allocTarget.mRefNode;
  6628. BfExprEvaluator exprEvaluator(this);
  6629. SizedArray<BfExpression*, 2> argExprs;
  6630. argExprs.push_back(&typedValueExpr);
  6631. BfTypedValueExpression sizeValueExpr;
  6632. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  6633. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  6634. argExprs.push_back(&sizeValueExpr);
  6635. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6636. BfResolvedArgs argValues(&sizedArgExprs);
  6637. exprEvaluator.ResolveArgValues(argValues);
  6638. exprEvaluator.mNoBind = true;
  6639. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  6640. if (allocResult)
  6641. {
  6642. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  6643. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  6644. else
  6645. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  6646. isResultInitialized = true;
  6647. }
  6648. }
  6649. }
  6650. if (!result)
  6651. {
  6652. if (hasCustomAllocator)
  6653. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  6654. }
  6655. if (result)
  6656. {
  6657. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6658. {
  6659. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  6660. SizedArray<BfIRValue, 4> llvmArgs;
  6661. llvmArgs.push_back(objectPtr);
  6662. llvmArgs.push_back(origSizeValue);
  6663. llvmArgs.push_back(vDataRef);
  6664. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  6665. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  6666. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  6667. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  6668. }
  6669. else
  6670. {
  6671. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  6672. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6673. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  6674. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  6675. }
  6676. }
  6677. else
  6678. {
  6679. if ((mBfIRBuilder->mIgnoreWrites) || (mCompiler->mIsResolveOnly))
  6680. return GetDefaultValue(typeInstance);
  6681. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6682. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  6683. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6684. {
  6685. SizedArray<BfIRValue, 4> llvmArgs;
  6686. llvmArgs.push_back(vData);
  6687. llvmArgs.push_back(sizeValue);
  6688. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  6689. llvmArgs.push_back(GetConstValue(stackCount));
  6690. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  6691. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  6692. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6693. }
  6694. else
  6695. {
  6696. SizedArray<BfIRValue, 4> llvmArgs;
  6697. llvmArgs.push_back(sizeValue);
  6698. BfIRFunction irFunc;
  6699. if (mCompiler->mOptions.mDebugAlloc)
  6700. {
  6701. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  6702. irFunc = moduleMethodInstance.mFunc;
  6703. }
  6704. if (!irFunc)
  6705. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6706. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  6707. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  6708. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  6709. mBfIRBuilder->CreateStore(vData, vdataPtr);
  6710. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6711. }
  6712. }
  6713. if ((zeroMemory) && (arraySize))
  6714. {
  6715. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6716. typeInstance = arrayType;
  6717. auto firstElementField = &arrayType->mFieldInstances.back();
  6718. int arrayClassSize = firstElementField->mDataOffset;
  6719. BfIRValue elementDataSize;
  6720. bool skipZero = false;
  6721. if (arraySize.IsConst())
  6722. {
  6723. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6724. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6725. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  6726. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  6727. if (constVal->mInt64 <= 0)
  6728. skipZero = true;
  6729. }
  6730. else
  6731. {
  6732. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  6733. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6734. }
  6735. if (!skipZero)
  6736. {
  6737. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6738. auto ptrType = CreatePointerType(i8Type);
  6739. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  6740. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  6741. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  6742. appendSizeValue = elementDataSize;
  6743. }
  6744. }
  6745. return result;
  6746. }
  6747. else
  6748. {
  6749. if (!sizeValue)
  6750. sizeValue = GetConstValue(allocSize);
  6751. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  6752. }
  6753. }
  6754. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  6755. {
  6756. if ((type == NULL) || (refNode == NULL))
  6757. return;
  6758. auto typeInstance = type->ToTypeInstance();
  6759. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  6760. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  6761. }
  6762. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  6763. {
  6764. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6765. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6766. }
  6767. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  6768. {
  6769. if (sizeMultiple == 0)
  6770. sizeMultiple = align;
  6771. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  6772. {
  6773. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  6774. {
  6775. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6776. BF_ASSERT(localVar->mName == "appendIdx");
  6777. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  6778. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6779. if (align > 1)
  6780. {
  6781. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6782. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6783. }
  6784. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  6785. }
  6786. else
  6787. {
  6788. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  6789. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  6790. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  6791. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6792. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6793. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  6794. }
  6795. }
  6796. if (mCurMethodState->mCurAppendAlign == 0)
  6797. mCurMethodState->mCurAppendAlign = sizeMultiple;
  6798. else
  6799. {
  6800. if (sizeMultiple % align == 0)
  6801. mCurMethodState->mCurAppendAlign = align;
  6802. else
  6803. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  6804. }
  6805. }
  6806. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  6807. {
  6808. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6809. BF_ASSERT(localVar->mName == "appendIdx");
  6810. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  6811. BfIRValue retValue;
  6812. BfTypeInstance* retTypeInstance = NULL;
  6813. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  6814. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  6815. if (arraySize)
  6816. {
  6817. if (isRawArrayAlloc)
  6818. {
  6819. EmitAppendAlign(type->mAlign);
  6820. BfPointerType* ptrType = CreatePointerType(type);
  6821. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6822. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6823. if (mSystem->mPtrSize != 4)
  6824. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6825. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6826. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6827. if (zeroMemory)
  6828. {
  6829. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  6830. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  6831. }
  6832. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  6833. }
  6834. else
  6835. {
  6836. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6837. EmitAppendAlign(arrayType->mAlign, type->mSize);
  6838. auto firstElementField = &arrayType->mFieldInstances.back();
  6839. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  6840. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  6841. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6842. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6843. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6844. if (mSystem->mPtrSize != 4)
  6845. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6846. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6847. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6848. if (zeroMemory)
  6849. {
  6850. // Only zero out the actual elements
  6851. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  6852. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  6853. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  6854. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  6855. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  6856. }
  6857. retTypeInstance = arrayType;
  6858. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  6859. }
  6860. }
  6861. else
  6862. {
  6863. auto typeInst = type->ToTypeInstance();
  6864. BfIRValue sizeValue;
  6865. BfIRType toType;
  6866. if (typeInst != NULL)
  6867. {
  6868. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  6869. sizeValue = GetConstValue(typeInst->mInstSize);
  6870. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  6871. }
  6872. else
  6873. {
  6874. EmitAppendAlign(type->mAlign, type->mSize);
  6875. sizeValue = GetConstValue(type->mSize);
  6876. auto toPtrType = CreatePointerType(type);
  6877. toType = mBfIRBuilder->MapType(toPtrType);
  6878. }
  6879. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6880. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6881. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6882. retTypeInstance = typeInst;
  6883. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  6884. }
  6885. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  6886. {
  6887. mBfIRBuilder->PopulateType(retTypeInstance);
  6888. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  6889. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  6890. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  6891. auto curThis = GetThis();
  6892. BfIRValue newFlags;
  6893. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6894. {
  6895. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  6896. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  6897. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  6898. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  6899. }
  6900. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  6901. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  6902. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  6903. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6904. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6905. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6906. {
  6907. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  6908. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  6909. }
  6910. }
  6911. if (appendSizeValue)
  6912. {
  6913. EmitAppendAlign(appendAllocAlign);
  6914. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6915. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  6916. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6917. }
  6918. return retValue;
  6919. }
  6920. bool BfModule::IsOptimized()
  6921. {
  6922. if (mProject == NULL)
  6923. return false;
  6924. int optLevel = GetModuleOptions().mOptLevel;
  6925. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  6926. }
  6927. bool BfModule::IsTargetingBeefBackend()
  6928. {
  6929. if (mProject == NULL)
  6930. return false;
  6931. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  6932. }
  6933. bool BfModule::WantsLifetimes()
  6934. {
  6935. if (mProject == NULL)
  6936. return false;
  6937. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  6938. }
  6939. bool BfModule::HasCompiledOutput()
  6940. {
  6941. return (!mSystem->mIsResolveOnly) && (mIsReified);
  6942. }
  6943. // We will skip the object access check for any occurances of this value
  6944. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  6945. {
  6946. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  6947. return;
  6948. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  6949. return;
  6950. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  6951. return;
  6952. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  6953. }
  6954. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  6955. {
  6956. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  6957. return;
  6958. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  6959. return;
  6960. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  6961. auto typeOptions = GetTypeOptions();
  6962. if (typeOptions != NULL)
  6963. emitObjectAccessCheck = BfTypeOptions::Apply(emitObjectAccessCheck, typeOptions->mEmitObjectAccessCheck);
  6964. if (!emitObjectAccessCheck)
  6965. return;
  6966. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  6967. {
  6968. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  6969. return;
  6970. }
  6971. if (typedVal.IsAddr())
  6972. typedVal = LoadValue(typedVal);
  6973. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  6974. }
  6975. void BfModule::EmitEnsureInstructionAt()
  6976. {
  6977. if (mProject == NULL)
  6978. return;
  6979. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  6980. return;
  6981. mBfIRBuilder->CreateEnsureInstructionAt();
  6982. }
  6983. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  6984. {
  6985. if (mBfIRBuilder->mIgnoreWrites)
  6986. return; // Nothing needed here
  6987. auto irb = mBfIRBuilder;
  6988. auto checkBB = irb->CreateBlock("as.check");
  6989. auto isNull = irb->CreateIsNull(targetValue.mValue);
  6990. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  6991. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6992. auto intPtrType = CreatePointerType(intType);
  6993. auto intPtrPtrType = CreatePointerType(intPtrType);
  6994. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  6995. auto int32PtrType = CreatePointerType(int32Type);
  6996. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6997. if (mCompiler->mOptions.mAllowHotSwapping)
  6998. {
  6999. BfExprEvaluator exprEvaluator(this);
  7000. AddBasicBlock(checkBB);
  7001. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7002. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  7003. SizedArray<BfIRValue, 4> irArgs;
  7004. irArgs.push_back(objectParam);
  7005. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  7006. auto callResult = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  7007. auto resultType = ResolveTypeDef(mSystem->mTypeBool);
  7008. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  7009. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7010. }
  7011. else
  7012. {
  7013. AddBasicBlock(checkBB);
  7014. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  7015. vDataPtr = irb->CreateLoad(vDataPtr);
  7016. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7017. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  7018. if (targetType->IsInterface())
  7019. {
  7020. auto targetTypeInst = targetType->ToTypeInstance();
  7021. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7022. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  7023. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  7024. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7025. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  7026. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  7027. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  7028. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  7029. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  7030. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7031. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  7032. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  7033. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7034. }
  7035. else
  7036. {
  7037. if (!targetType->IsTypeInstance())
  7038. targetType = GetWrappedStructType(targetType);
  7039. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7040. int inheritanceIdOfs = mSystem->mPtrSize;
  7041. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7042. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7043. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  7044. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  7045. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  7046. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  7047. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  7048. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7049. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  7050. fieldInst = &typeTypeInstance->mFieldInstances[10];
  7051. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  7052. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7053. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  7054. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  7055. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  7056. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7057. }
  7058. }
  7059. }
  7060. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  7061. {
  7062. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  7063. auto typeOptions = GetTypeOptions();
  7064. if (typeOptions != NULL)
  7065. emitDynamicCastCheck = BfTypeOptions::Apply(emitDynamicCastCheck, typeOptions->mEmitDynamicCastCheck);
  7066. if (emitDynamicCastCheck)
  7067. {
  7068. int wantTypeId = 0;
  7069. if (!type->IsGenericParam())
  7070. wantTypeId = type->mTypeId;
  7071. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  7072. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  7073. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  7074. AddBasicBlock(failBlock);
  7075. SizedArray<BfIRValue, 8> llvmArgs;
  7076. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7077. llvmArgs.push_back(bitAddr);
  7078. llvmArgs.push_back(GetConstValue32(wantTypeId));
  7079. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  7080. BF_ASSERT(objDynCheck);
  7081. if (objDynCheck)
  7082. {
  7083. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  7084. }
  7085. mBfIRBuilder->CreateBr(endBlock);
  7086. AddBasicBlock(endBlock);
  7087. }
  7088. }
  7089. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  7090. {
  7091. BP_ZONE("BoxValue");
  7092. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  7093. if (typedVal.mType->IsNullable())
  7094. {
  7095. typedVal = MakeAddressable(typedVal);
  7096. auto innerType = typedVal.mType->GetUnderlyingType();
  7097. if (!innerType->IsValueType())
  7098. {
  7099. Fail("Only value types can be boxed", srcNode);
  7100. return BfTypedValue();
  7101. }
  7102. auto prevBB = mBfIRBuilder->GetInsertBlock();
  7103. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  7104. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  7105. mBfIRBuilder->PopulateType(typedVal.mType);
  7106. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  7107. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  7108. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  7109. auto boxedType = CreateBoxedType(innerType);
  7110. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7111. auto resultType = toType;
  7112. if (resultType == NULL)
  7113. resultType = boxedType;
  7114. mBfIRBuilder->AddBlock(boxBB);
  7115. mBfIRBuilder->SetInsertPoint(boxBB);
  7116. BfScopeData newScope;
  7117. newScope.mOuterIsConditional = true;
  7118. mCurMethodState->AddScope(&newScope);
  7119. NewScopeState();
  7120. BfIRValue nullableValueAddr;
  7121. BfIRValue loadedVal;
  7122. if (innerType->IsValuelessType())
  7123. {
  7124. loadedVal = mBfIRBuilder->GetFakeVal();
  7125. }
  7126. else
  7127. {
  7128. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  7129. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  7130. }
  7131. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  7132. RestoreScopeState();
  7133. if (!boxedVal)
  7134. return BfTypedValue();
  7135. mBfIRBuilder->CreateBr(endBB);
  7136. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  7137. mBfIRBuilder->AddBlock(endBB);
  7138. mBfIRBuilder->SetInsertPoint(endBB);
  7139. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  7140. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  7141. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  7142. return BfTypedValue(phi, resultType);
  7143. }
  7144. bool alreadyCheckedCast = false;
  7145. BfTypeInstance* toTypeInstance = NULL;
  7146. if (toType != NULL)
  7147. toTypeInstance = toType->ToTypeInstance();
  7148. bool isStructPtr = typedVal.mType->IsStructPtr();
  7149. if (fromStructTypeInstance == NULL)
  7150. {
  7151. auto primType = (BfPrimitiveType*)typedVal.mType;
  7152. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  7153. if (isStructPtr)
  7154. {
  7155. if ((toTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7156. alreadyCheckedCast = true;
  7157. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  7158. }
  7159. }
  7160. if (fromStructTypeInstance == NULL)
  7161. return BfTypedValue();
  7162. // Need to box it
  7163. auto boxedType = CreateBoxedType(typedVal.mType);
  7164. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed()) && (boxedType == toType);
  7165. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7166. {
  7167. if (typedVal.mType->IsPointer())
  7168. {
  7169. NOP;
  7170. }
  7171. mBfIRBuilder->PopulateType(boxedType);
  7172. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7173. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  7174. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  7175. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  7176. if (boxedType->IsUnspecializedType())
  7177. {
  7178. BF_ASSERT(mCurMethodInstance->mIsUnspecialized);
  7179. }
  7180. else
  7181. {
  7182. PopulateType(fromStructTypeInstance);
  7183. if (!fromStructTypeInstance->IsValuelessType())
  7184. {
  7185. typedVal = LoadValue(typedVal);
  7186. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  7187. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  7188. {
  7189. auto ptrType = CreatePointerType(typedVal.mType);
  7190. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  7191. }
  7192. if (typedVal.IsSplat())
  7193. {
  7194. AggregateSplatIntoAddr(typedVal, valPtr);
  7195. }
  7196. else
  7197. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  7198. }
  7199. }
  7200. if (toType == NULL)
  7201. {
  7202. return BfTypedValue(allocaInst, boxedType);
  7203. }
  7204. else
  7205. {
  7206. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  7207. return BfTypedValue(castedValue, toType);
  7208. }
  7209. }
  7210. return BfTypedValue();
  7211. }
  7212. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  7213. {
  7214. BfTypeInstance* checkTypeInst = typeInst;
  7215. while (checkTypeInst != NULL)
  7216. {
  7217. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  7218. {
  7219. if (checkProp->mName == propDef->mName)
  7220. {
  7221. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  7222. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  7223. {
  7224. propDef = checkProp;
  7225. typeInst = checkTypeInst;
  7226. return true;
  7227. }
  7228. }
  7229. }
  7230. checkTypeInst = checkTypeInst->mBaseType;
  7231. }
  7232. return false;
  7233. }
  7234. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7235. {
  7236. if (!typeInstance->mResolvingVarField)
  7237. {
  7238. if (typeInstance->IsIncomplete())
  7239. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7240. }
  7241. else
  7242. {
  7243. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  7244. {
  7245. AssertErrorState();
  7246. return NULL;
  7247. }
  7248. }
  7249. if (assertName != NULL)
  7250. {
  7251. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7252. }
  7253. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  7254. if (methodGroup.mDefault == NULL)
  7255. {
  7256. if (!mCompiler->mIsResolveOnly)
  7257. {
  7258. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl));
  7259. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  7260. // Get it from the owning module so we don't create a reference prematurely...
  7261. auto declModule = typeInstance->mModule;
  7262. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified)).mMethodInstance;
  7263. }
  7264. else
  7265. {
  7266. auto declModule = typeInstance->mModule;
  7267. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass)).mMethodInstance;
  7268. }
  7269. }
  7270. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7271. //TODO: Why did we have this adding methods to the work list? This should only happen if we actually attempt to USE the method, which should
  7272. // be from a call to the NON-raw version
  7273. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  7274. // {
  7275. // methodInstance->mIsReified = mIsReified;
  7276. // if (methodInstance->mMethodProcessRequest == NULL)
  7277. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  7278. // }
  7279. return methodInstance;
  7280. }
  7281. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  7282. {
  7283. if (methodDef->mIsLocalMethod)
  7284. {
  7285. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  7286. }
  7287. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7288. }
  7289. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  7290. {
  7291. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7292. while (typeInstance != NULL)
  7293. {
  7294. typeInstance->mTypeDef->PopulateMemberSets();
  7295. BfMemberSetEntry* entry = NULL;
  7296. BfMethodDef* methodDef = NULL;
  7297. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7298. methodDef = (BfMethodDef*)entry->mMemberDef;
  7299. while (methodDef != NULL)
  7300. {
  7301. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  7302. (methodDef->mGenericParams.size() == 0) &&
  7303. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7304. return GetRawMethodInstance(typeInstance, methodDef);
  7305. methodDef = methodDef->mNextWithSameName;
  7306. }
  7307. if (!checkBase)
  7308. break;
  7309. typeInstance = typeInstance->mBaseType;
  7310. }
  7311. return NULL;
  7312. }
  7313. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance)
  7314. {
  7315. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7316. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  7317. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  7318. if (!owner->IsGenericTypeInstance())
  7319. return methodInstance;
  7320. auto genericType = (BfGenericTypeInstance*)owner;
  7321. if (genericType->IsUnspecializedType())
  7322. return methodInstance;
  7323. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  7324. if (unspecializedType == NULL)
  7325. {
  7326. AssertErrorState();
  7327. return methodInstance;
  7328. }
  7329. if (unspecializedType == NULL)
  7330. return methodInstance;
  7331. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  7332. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  7333. }
  7334. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  7335. {
  7336. int genericCount = 0;
  7337. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  7338. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  7339. {
  7340. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  7341. if (param->IsGenericParam())
  7342. genericCount++;
  7343. }
  7344. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  7345. genericCount++;
  7346. return genericCount;
  7347. }
  7348. BfModule* BfModule::GetSpecializedMethodModule(const Array<BfProject*>& projectList)
  7349. {
  7350. BF_ASSERT(!mIsScratchModule);
  7351. BF_ASSERT(mIsReified);
  7352. BfModule* mainModule = this;
  7353. if (mParentModule != NULL)
  7354. mainModule = mParentModule;
  7355. BfModule* specModule = NULL;
  7356. BfModule** specModulePtr = NULL;
  7357. if (mainModule->mSpecializedMethodModules.TryGetValue(projectList, &specModulePtr))
  7358. {
  7359. return *specModulePtr;
  7360. }
  7361. else
  7362. {
  7363. String specModuleName = mModuleName;
  7364. for (auto bfProject : projectList)
  7365. specModuleName += StrFormat("@%s", bfProject->mName.c_str());
  7366. specModule = new BfModule(mContext, specModuleName);
  7367. specModule->mProject = mainModule->mProject;
  7368. specModule->mParentModule = mainModule;
  7369. specModule->mIsSpecializedMethodModuleRoot = true;
  7370. specModule->Init();
  7371. mainModule->mSpecializedMethodModules[projectList] = specModule;
  7372. }
  7373. return specModule;
  7374. }
  7375. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  7376. {
  7377. if (mCompiler->IsSkippingExtraResolveChecks())
  7378. return BfIRValue();
  7379. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  7380. {
  7381. //BF_ASSERT(!methodInstance->mIRFunction);
  7382. return BfIRValue();
  7383. }
  7384. auto methodDef = methodInstance->mMethodDef;
  7385. StringT<128> methodName;
  7386. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  7387. if (isInlined != methodInstance->mAlwaysInline)
  7388. {
  7389. if (isInlined)
  7390. methodName += "__INLINE";
  7391. else
  7392. methodName += "__NOINLINE";
  7393. }
  7394. if (tryExisting)
  7395. {
  7396. auto func = mBfIRBuilder->GetFunction(methodName);
  7397. if (func)
  7398. return func;
  7399. }
  7400. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  7401. {
  7402. if (methodDeclaration->mExternSpecifier != NULL)
  7403. {
  7404. auto intrinsic = GetIntrinsic(methodInstance);
  7405. if (intrinsic)
  7406. return intrinsic;
  7407. // If we have multiple entries with the same name, they could have different arguments and will generate other errors...
  7408. /*auto func = mBfIRBuilder->GetFunction(methodName);
  7409. if (func)
  7410. return func;*/
  7411. }
  7412. }
  7413. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  7414. {
  7415. return CreateDllImportGlobalVar(methodInstance, false);
  7416. }
  7417. BfIRType returnType;
  7418. SizedArray<BfIRType, 8> paramTypes;
  7419. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  7420. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes);
  7421. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  7422. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  7423. if (callingConv != BfIRCallingConv_CDecl)
  7424. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  7425. SetupIRMethod(methodInstance, func, isInlined);
  7426. // auto srcModule = methodInstance->GetOwner()->GetModule();
  7427. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  7428. // {
  7429. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  7430. // {
  7431. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  7432. // }
  7433. // }
  7434. return func;
  7435. }
  7436. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7437. {
  7438. if (assertName != NULL)
  7439. {
  7440. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7441. }
  7442. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7443. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7444. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  7445. {
  7446. // Can't use it, not reified
  7447. methodInstance = NULL;
  7448. }
  7449. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  7450. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  7451. {
  7452. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  7453. return BfModuleMethodInstance(methodInstance, func);
  7454. }
  7455. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector());
  7456. }
  7457. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7458. {
  7459. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7460. while (typeInstance != NULL)
  7461. {
  7462. typeInstance->mTypeDef->PopulateMemberSets();
  7463. BfMemberSetEntry* entry = NULL;
  7464. BfMethodDef* methodDef = NULL;
  7465. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7466. methodDef = (BfMethodDef*)entry->mMemberDef;
  7467. while (methodDef != NULL)
  7468. {
  7469. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7470. (methodDef->mGenericParams.size() == 0) &&
  7471. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7472. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7473. methodDef = methodDef->mNextWithSameName;
  7474. }
  7475. if (!checkBase)
  7476. break;
  7477. typeInstance = typeInstance->mBaseType;
  7478. }
  7479. return BfModuleMethodInstance();
  7480. }
  7481. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  7482. {
  7483. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7484. while (typeInstance != NULL)
  7485. {
  7486. typeInstance->mTypeDef->PopulateMemberSets();
  7487. BfMemberSetEntry* entry = NULL;
  7488. BfMethodDef* methodDef = NULL;
  7489. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7490. methodDef = (BfMethodDef*)entry->mMemberDef;
  7491. while (methodDef != NULL)
  7492. {
  7493. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7494. (methodDef->mGenericParams.size() == 0) &&
  7495. (paramTypes.size() == methodDef->mParams.size()))
  7496. {
  7497. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7498. if (moduleMethodInstance.mMethodInstance != NULL)
  7499. {
  7500. bool matches = true;
  7501. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  7502. {
  7503. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  7504. matches = false;
  7505. }
  7506. if (matches)
  7507. return moduleMethodInstance;
  7508. }
  7509. }
  7510. methodDef = methodDef->mNextWithSameName;
  7511. }
  7512. if (!checkBase)
  7513. break;
  7514. typeInstance = typeInstance->mBaseType;
  7515. }
  7516. return BfModuleMethodInstance();
  7517. }
  7518. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  7519. {
  7520. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  7521. PopulateType(internalType);
  7522. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  7523. if (!moduleMethodInstance)
  7524. {
  7525. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  7526. }
  7527. return moduleMethodInstance;
  7528. }
  7529. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7530. {
  7531. while (typeInstance != NULL)
  7532. {
  7533. typeInstance->mTypeDef->PopulateMemberSets();
  7534. BfMemberSetEntry* entry = NULL;
  7535. BfMethodDef* methodDef = NULL;
  7536. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7537. methodDef = (BfMethodDef*)entry->mMemberDef;
  7538. while (methodDef != NULL)
  7539. {
  7540. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7541. (methodDef->mGenericParams.size() == 0) &&
  7542. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7543. {
  7544. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  7545. if (!methodInstanceGroup.IsImplemented())
  7546. return false;
  7547. if (methodInstanceGroup.mDefault == NULL)
  7548. return false;
  7549. return methodInstanceGroup.mDefault->mIsReified;
  7550. }
  7551. methodDef = methodDef->mNextWithSameName;
  7552. }
  7553. if (!checkBase)
  7554. break;
  7555. typeInstance = typeInstance->mBaseType;
  7556. }
  7557. return false;
  7558. }
  7559. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7560. {
  7561. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7562. while (typeInstance != NULL)
  7563. {
  7564. typeInstance->mTypeDef->PopulateMemberSets();
  7565. BfMemberSetEntry* entry = NULL;
  7566. BfMethodDef* methodDef = NULL;
  7567. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7568. methodDef = (BfMethodDef*)entry->mMemberDef;
  7569. while (methodDef != NULL)
  7570. {
  7571. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  7572. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7573. return true;
  7574. methodDef = methodDef->mNextWithSameName;
  7575. }
  7576. if (!checkBase)
  7577. break;
  7578. typeInstance = typeInstance->mBaseType;
  7579. }
  7580. return BfModuleMethodInstance();
  7581. }
  7582. BfFieldInstance* BfModule::GetFieldByName(BfTypeInstance* typeInstance, const StringImpl& fieldName)
  7583. {
  7584. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7585. typeInstance->mTypeDef->PopulateMemberSets();
  7586. BfMemberSetEntry* entry = NULL;
  7587. BfFieldDef* fieldDef = NULL;
  7588. if (typeInstance->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  7589. {
  7590. fieldDef = (BfFieldDef*)entry->mMemberDef;
  7591. return &typeInstance->mFieldInstances[fieldDef->mIdx];
  7592. }
  7593. // for (auto& fieldInst : typeInstance->mFieldInstances)
  7594. // {
  7595. // auto fieldDef = fieldInst.GetFieldDef();
  7596. // if ((fieldDef != NULL) && (fieldDef->mName == fieldName))
  7597. // return &fieldInst;
  7598. // }
  7599. return NULL;
  7600. }
  7601. String BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* methodGenericArgs)
  7602. {
  7603. auto methodDef = methodInst->mMethodDef;
  7604. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  7605. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7606. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  7607. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7608. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  7609. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7610. type = ResolveGenericType(type, *methodGenericArgs);
  7611. String methodName;
  7612. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  7613. {
  7614. methodName = TypeToString(type, typeNameFlags);
  7615. if (methodName == "$")
  7616. methodName = "";
  7617. else
  7618. methodName += ".";
  7619. }
  7620. String accessorString;
  7621. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  7622. if (methodInst->mMethodDef->mIsLocalMethod)
  7623. {
  7624. int atPos = (int)methodDefName.IndexOf('$');
  7625. methodDefName.RemoveToEnd(atPos);
  7626. methodDefName.Replace("@", ".");
  7627. }
  7628. else
  7629. {
  7630. int atPos = (int)methodDefName.IndexOf('$');
  7631. if (atPos != -1)
  7632. {
  7633. accessorString = methodDefName.Substring(0, atPos);
  7634. if ((accessorString == "get") || (accessorString == "set"))
  7635. {
  7636. methodDefName = methodDefName.Substring(atPos + 1);
  7637. }
  7638. else
  7639. accessorString = "";
  7640. }
  7641. }
  7642. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  7643. {
  7644. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7645. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7646. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7647. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  7648. methodName += ".";
  7649. }
  7650. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  7651. {
  7652. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7653. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7654. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7655. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  7656. methodName += ".";
  7657. }
  7658. if (methodDef->mMethodType == BfMethodType_Operator)
  7659. {
  7660. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  7661. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  7662. {
  7663. // Don't add explicit/implicit part, since that's not available in GCC mangling
  7664. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  7665. {
  7666. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7667. methodName += "explicit ";
  7668. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7669. methodName += "explicit ";
  7670. }*/
  7671. methodName += "operator ";
  7672. if (methodInst->mReturnType != NULL)
  7673. methodName += TypeToString(methodInst->mReturnType);
  7674. }
  7675. else
  7676. {
  7677. methodName += "operator";
  7678. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  7679. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  7680. }
  7681. }
  7682. else if (methodDef->mMethodType == BfMethodType_Ctor)
  7683. {
  7684. if (methodDef->mIsStatic)
  7685. methodName += "__BfStaticCtor";
  7686. else
  7687. methodName += "this";
  7688. accessorString = "";
  7689. }
  7690. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  7691. {
  7692. methodDef->GetRefNode()->ToString(methodName);
  7693. methodName += " get accessor";
  7694. return methodName;
  7695. }
  7696. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  7697. {
  7698. methodDef->GetRefNode()->ToString(methodName);
  7699. methodName += " set accessor";
  7700. return methodName;
  7701. }
  7702. else
  7703. methodName += methodDefName;
  7704. BfTypeVector newMethodGenericArgs;
  7705. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7706. {
  7707. methodName += "<";
  7708. for (int i = 0; i < (int) methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  7709. {
  7710. if (i > 0)
  7711. methodName += ", ";
  7712. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7713. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  7714. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7715. if (allowResolveGenericParamNames)
  7716. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7717. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  7718. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7719. {
  7720. bool hasEmpty = false;
  7721. for (auto arg : *methodGenericArgs)
  7722. {
  7723. if (arg == NULL)
  7724. hasEmpty = true;
  7725. }
  7726. if (hasEmpty)
  7727. {
  7728. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  7729. {
  7730. auto arg = (*methodGenericArgs)[genericIdx];
  7731. if (arg != NULL)
  7732. newMethodGenericArgs.push_back(arg);
  7733. else
  7734. {
  7735. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  7736. if (genericParamInst->mTypeConstraint != NULL)
  7737. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  7738. else
  7739. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  7740. }
  7741. }
  7742. methodGenericArgs = &newMethodGenericArgs;
  7743. }
  7744. if (type->IsUnspecializedType())
  7745. type = ResolveGenericType(type, *methodGenericArgs);
  7746. }
  7747. methodName += TypeToString(type, typeNameFlags);
  7748. }
  7749. methodName += ">";
  7750. }
  7751. if (accessorString.length() == 0)
  7752. {
  7753. int dispParamIdx = 0;
  7754. methodName += "(";
  7755. for (int paramIdx = 0; paramIdx < (int) methodInst->GetParamCount(); paramIdx++)
  7756. {
  7757. int paramKind = methodInst->GetParamKind(paramIdx);
  7758. if (paramKind == BfParamKind_ImplicitCapture)
  7759. continue;
  7760. if (dispParamIdx > 0)
  7761. methodName += ", ";
  7762. if (paramKind == BfParamKind_Params)
  7763. methodName += "params ";
  7764. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7765. BfType* type = methodInst->GetParamType(paramIdx);
  7766. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7767. type = ResolveGenericType(type, *methodGenericArgs);
  7768. methodName += TypeToString(type, typeNameFlags);
  7769. methodName += " ";
  7770. methodName += methodInst->GetParamName(paramIdx);
  7771. dispParamIdx++;
  7772. }
  7773. methodName += ")";
  7774. }
  7775. if (accessorString.length() != 0)
  7776. {
  7777. methodName += " " + accessorString;
  7778. }
  7779. return methodName;
  7780. }
  7781. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  7782. {
  7783. if ((flagsLeft & checkFlag) == 0)
  7784. return;
  7785. if (!str.empty())
  7786. {
  7787. if (flagsLeft == checkFlag)
  7788. {
  7789. if ((int)str.IndexOf(',') != -1)
  7790. str += ", and ";
  7791. else
  7792. str += " and ";
  7793. }
  7794. else
  7795. str += ", ";
  7796. }
  7797. str += addString;
  7798. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  7799. }
  7800. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  7801. {
  7802. String resultStr;
  7803. auto flagsLeft = attrTarget;
  7804. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  7805. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  7806. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  7807. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  7808. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  7809. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  7810. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  7811. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  7812. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  7813. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  7814. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  7815. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  7816. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  7817. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  7818. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  7819. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  7820. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  7821. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  7822. if (resultStr.IsEmpty())
  7823. return "<nothing>";
  7824. return resultStr;
  7825. }
  7826. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  7827. {
  7828. auto constant = mBfIRBuilder->GetConstant(irVal);
  7829. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  7830. if (stringPoolIdx != -1)
  7831. {
  7832. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_Int32, stringPoolIdx);
  7833. return;
  7834. }
  7835. if (constant->mConstType == BfConstType_Array)
  7836. {
  7837. auto constArray = (BfConstantArray*)constant;
  7838. SizedArray<BfIRValue, 8> newVals;
  7839. for (auto val : constArray->mValues)
  7840. {
  7841. auto newVal = val;
  7842. CurrentAddToConstHolder(newVal);
  7843. newVals.push_back(newVal);
  7844. }
  7845. irVal = mCurTypeInstance->mConstHolder->CreateConstArray(constArray->mType, newVals);
  7846. return;
  7847. }
  7848. auto origConst = irVal;
  7849. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  7850. {
  7851. auto bitcast = (BfConstantBitCast*)constant;
  7852. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  7853. }
  7854. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  7855. }
  7856. void BfModule::ClearConstData()
  7857. {
  7858. mBfIRBuilder->ClearConstData();
  7859. mStringObjectPool.Clear();
  7860. mStringCharPtrPool.Clear();
  7861. mStringPoolRefs.Clear();
  7862. }
  7863. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  7864. {
  7865. bool isString = false;
  7866. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  7867. if (wantType->IsPointer())
  7868. isString = true;
  7869. if (!isString)
  7870. {
  7871. switch (constant->mTypeCode)
  7872. {
  7873. case BfTypeCode_Boolean:
  7874. case BfTypeCode_Int8:
  7875. case BfTypeCode_UInt8:
  7876. case BfTypeCode_Int16:
  7877. case BfTypeCode_UInt16:
  7878. case BfTypeCode_Int32:
  7879. case BfTypeCode_UInt32:
  7880. case BfTypeCode_Int64:
  7881. case BfTypeCode_UInt64:
  7882. case BfTypeCode_IntPtr:
  7883. case BfTypeCode_UIntPtr:
  7884. case BfTypeCode_IntUnknown:
  7885. case BfTypeCode_UIntUnknown:
  7886. case BfTypeCode_Char8:
  7887. case BfTypeCode_Char16:
  7888. case BfTypeCode_Char32:
  7889. case BfTypeCode_Single:
  7890. case BfTypeCode_Double:
  7891. {
  7892. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  7893. auto typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  7894. if (typedValue.mType == wantType)
  7895. return typedValue;
  7896. if (wantType->IsTypedPrimitive())
  7897. {
  7898. if (typedValue.mType == wantType->GetUnderlyingType())
  7899. {
  7900. typedValue.mType = wantType;
  7901. return typedValue;
  7902. }
  7903. }
  7904. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  7905. BF_ASSERT(castedTypedValue);
  7906. return castedTypedValue;
  7907. }
  7908. break;
  7909. default: break;
  7910. }
  7911. }
  7912. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  7913. BF_ASSERT(irValue);
  7914. if (!irValue)
  7915. return BfTypedValue();
  7916. return BfTypedValue(irValue, wantType, false);
  7917. }
  7918. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  7919. {
  7920. if (constant->mTypeCode == BfTypeCode_NullPtr)
  7921. {
  7922. return GetDefaultValue(wantType);
  7923. }
  7924. bool isString = false;
  7925. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  7926. if (((wantType->IsPointer()) || (isString)) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  7927. {
  7928. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  7929. BfIRValue stringObjConst = GetStringObjectValue(str);
  7930. if (wantType->IsObject())
  7931. return stringObjConst;
  7932. return GetStringCharPtr(stringObjConst);
  7933. }
  7934. if (constant->mConstType == BfConstType_Array)
  7935. {
  7936. auto elementType = wantType->GetUnderlyingType();
  7937. auto constArray = (BfConstantArray*)constant;
  7938. SizedArray<BfIRValue, 8> newVals;
  7939. for (auto val : constArray->mValues)
  7940. {
  7941. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  7942. }
  7943. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  7944. }
  7945. return mBfIRBuilder->CreateConst(constant, constHolder);
  7946. }
  7947. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  7948. {
  7949. if (attrTarget == BfAttributeTargets_SkipValidate)
  7950. return;
  7951. for (auto& customAttribute : customAttributes->mAttributes)
  7952. {
  7953. if (!customAttribute.mAwaitingValidation)
  7954. continue;
  7955. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  7956. {
  7957. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  7958. customAttribute.mRef->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  7959. }
  7960. customAttribute.mAwaitingValidation = false;
  7961. }
  7962. }
  7963. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  7964. {
  7965. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  7966. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  7967. {
  7968. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  7969. }
  7970. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  7971. if (mCompiler->IsAutocomplete())
  7972. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  7973. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  7974. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  7975. BfAutoComplete* autoComplete = NULL;
  7976. if (mCompiler->mResolvePassData != NULL)
  7977. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  7978. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  7979. {
  7980. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  7981. BfCustomAttribute customAttribute;
  7982. customAttribute.mAwaitingValidation = true;
  7983. customAttribute.mRef = attributesDirective;
  7984. if (attributesDirective->mAttrOpenToken != NULL)
  7985. targetOverride = (BfAttributeTargets)0;
  7986. if (attributesDirective->mAttributeTypeRef == NULL)
  7987. {
  7988. AssertErrorState();
  7989. continue;
  7990. }
  7991. String attrName = attributesDirective->mAttributeTypeRef->ToString();
  7992. BfType* attrType = NULL;
  7993. BfAtomComposite nameComposite;
  7994. BfTypeDef* attrTypeDef = NULL;
  7995. if (mSystem->ParseAtomComposite(attrName + "Attribute", nameComposite))
  7996. {
  7997. BfTypeLookupError error;
  7998. error.mRefNode = attributesDirective->mAttributeTypeRef;
  7999. attrTypeDef = FindTypeDefRaw(nameComposite, 0, mCurTypeInstance, GetActiveTypeDef(NULL, true), &error);
  8000. }
  8001. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  8002. {
  8003. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  8004. if (attrTypeDef != NULL)
  8005. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  8006. }
  8007. if (attrTypeDef == NULL)
  8008. {
  8009. TypeRefNotFound(attributesDirective->mAttributeTypeRef, "Attribute");
  8010. continue;
  8011. }
  8012. bool isBypassedAttr = false;
  8013. if (attrTypeDef != NULL)
  8014. {
  8015. attrType = mContext->mUnreifiedModule->ResolveTypeDef(attrTypeDef, BfPopulateType_Identity);
  8016. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  8017. // We solve it by having a 'bypass' for known attributes that Object depends on
  8018. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  8019. {
  8020. if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  8021. {
  8022. BfTypeInstance* attrTypeInst = attrType->ToTypeInstance();
  8023. for (auto methodDef : attrTypeDef->mMethods)
  8024. {
  8025. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  8026. {
  8027. customAttribute.mType = attrType->ToTypeInstance();
  8028. customAttribute.mCtor = methodDef;
  8029. isBypassedAttr = true;
  8030. break;
  8031. }
  8032. }
  8033. }
  8034. }
  8035. if (isBypassedAttr)
  8036. {
  8037. customAttribute.mAwaitingValidation = false;
  8038. customAttributes->mAttributes.push_back(customAttribute);
  8039. continue;
  8040. }
  8041. if (mContext->mCurTypeState != NULL)
  8042. {
  8043. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8044. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8045. }
  8046. else
  8047. {
  8048. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8049. }
  8050. }
  8051. // Don't allow this
  8052. /*else if (mContext->mCurTypeState != NULL)
  8053. {
  8054. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8055. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_DataAndMethods);
  8056. }
  8057. else
  8058. {
  8059. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef);
  8060. }*/
  8061. BfTypeInstance* attrTypeInst = NULL;
  8062. if (attrType == NULL)
  8063. continue;
  8064. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  8065. attrTypeInst = attrType->ToTypeInstance();
  8066. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  8067. {
  8068. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  8069. continue;
  8070. }
  8071. if (mCurTypeInstance != NULL)
  8072. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8073. customAttribute.mType = attrTypeInst;
  8074. BfConstResolver constResolver(this);
  8075. bool inPropSet = false;
  8076. SizedArray<BfResolvedArg, 2> argValues;
  8077. for (BfExpression* arg : attributesDirective->mArguments)
  8078. {
  8079. if (arg == NULL)
  8080. {
  8081. continue;
  8082. }
  8083. if (autoComplete != NULL)
  8084. autoComplete->mShowAttributeProperties = attrTypeInst;
  8085. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  8086. {
  8087. inPropSet = true;
  8088. if (autoComplete != NULL)
  8089. autoComplete->CheckNode(assignExpr->mLeft);
  8090. String findName = assignExpr->mLeft->ToString();
  8091. BfPropertyDef* bestProp = NULL;
  8092. BfTypeInstance* bestPropTypeInst = NULL;
  8093. BfFieldDef* bestField = NULL;
  8094. BfTypeInstance* bestFieldTypeInst = NULL;
  8095. auto checkTypeInst = attrTypeInst;
  8096. while (checkTypeInst != NULL)
  8097. {
  8098. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  8099. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  8100. {
  8101. if (prop->mName == findName)
  8102. {
  8103. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  8104. {
  8105. bestProp = prop;
  8106. bestPropTypeInst = checkTypeInst;
  8107. }
  8108. }
  8109. }
  8110. for (auto field : checkTypeInst->mTypeDef->mFields)
  8111. {
  8112. if (field->mName == findName)
  8113. {
  8114. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  8115. {
  8116. bestField = field;
  8117. bestFieldTypeInst = checkTypeInst;
  8118. }
  8119. }
  8120. }
  8121. if ((bestProp != NULL) || (bestField != NULL))
  8122. break;
  8123. checkTypeInst = checkTypeInst->mBaseType;
  8124. }
  8125. bool handledExpr = false;
  8126. if (bestField != NULL)
  8127. {
  8128. handledExpr = true;
  8129. if (mCompiler->mResolvePassData != NULL)
  8130. {
  8131. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  8132. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8133. {
  8134. autoComplete->mDefField = bestField;
  8135. autoComplete->mDefType = attrTypeDef;
  8136. }
  8137. }
  8138. if (bestField->mProtection != BfProtection_Public)
  8139. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8140. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8141. BfCustomAttributeSetField setField;
  8142. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  8143. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  8144. if (assignExpr->mRight != NULL)
  8145. {
  8146. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  8147. if (result)
  8148. {
  8149. CurrentAddToConstHolder(result.mValue);
  8150. setField.mParam = result;
  8151. customAttribute.mSetField.push_back(setField);
  8152. }
  8153. }
  8154. }
  8155. else if (bestProp == NULL)
  8156. {
  8157. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  8158. }
  8159. else
  8160. {
  8161. BfMethodDef* setMethod = NULL;
  8162. for (auto methodDef : bestProp->mMethods)
  8163. {
  8164. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8165. {
  8166. setMethod = methodDef;
  8167. break;
  8168. }
  8169. }
  8170. if (setMethod == NULL)
  8171. {
  8172. Fail("Property has no setter", assignExpr->mLeft);
  8173. }
  8174. else
  8175. {
  8176. if (mCompiler->mResolvePassData != NULL)
  8177. {
  8178. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  8179. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8180. {
  8181. autoComplete->mDefProp = bestProp;
  8182. autoComplete->mDefType = attrTypeDef;
  8183. }
  8184. }
  8185. handledExpr = true;
  8186. if (bestProp->mProtection != BfProtection_Public)
  8187. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8188. BfResolvedArg resolvedArg;
  8189. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8190. BfCustomAttributeSetProperty setProperty;
  8191. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  8192. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  8193. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  8194. if (methodInstance.mMethodInstance != NULL)
  8195. {
  8196. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  8197. if (assignExpr->mRight != NULL)
  8198. {
  8199. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  8200. if (result)
  8201. {
  8202. BF_ASSERT(result.mType == propType);
  8203. CurrentAddToConstHolder(result.mValue);
  8204. setProperty.mParam = result;
  8205. customAttribute.mSetProperties.push_back(setProperty);
  8206. }
  8207. }
  8208. }
  8209. }
  8210. }
  8211. if ((!handledExpr) && (assignExpr->mRight != NULL))
  8212. constResolver.Resolve(assignExpr->mRight);
  8213. }
  8214. else
  8215. {
  8216. if (inPropSet)
  8217. {
  8218. Fail("Named attribute argument expected", arg); // CS1016
  8219. }
  8220. BfDeferEvalChecker deferEvalChecker;
  8221. arg->Accept(&deferEvalChecker);
  8222. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  8223. BfResolvedArg resolvedArg;
  8224. resolvedArg.mExpression = arg;
  8225. if (deferParamEval)
  8226. {
  8227. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  8228. }
  8229. else
  8230. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  8231. if (!inPropSet)
  8232. argValues.push_back(resolvedArg);
  8233. }
  8234. if (autoComplete != NULL)
  8235. autoComplete->mShowAttributeProperties = NULL;
  8236. }
  8237. auto wasCapturingMethodInfo = false;
  8238. if (autoComplete != NULL)
  8239. {
  8240. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8241. if (attributesDirective->mCtorOpenParen != NULL)
  8242. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  8243. }
  8244. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  8245. attrTypeDef = attrTypeInst->mTypeDef;
  8246. bool success = true;
  8247. bool isFailurePass = false;
  8248. for (int pass = 0; pass < 2; pass++)
  8249. {
  8250. bool isFailurePass = pass == 1;
  8251. for (auto checkMethod : attrTypeDef->mMethods)
  8252. {
  8253. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  8254. continue; // Don't match private default ctor if there's a user-defined one
  8255. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  8256. continue;
  8257. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, false, false)))
  8258. continue;
  8259. methodMatcher.CheckMethod(attrTypeInst, checkMethod, isFailurePass);
  8260. }
  8261. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8262. break;
  8263. }
  8264. if (autoComplete != NULL)
  8265. {
  8266. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  8267. {
  8268. autoComplete->mIsCapturingMethodMatchInfo = true;
  8269. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  8270. }
  8271. else
  8272. autoComplete->mIsCapturingMethodMatchInfo = false;
  8273. }
  8274. if (methodMatcher.mBestMethodDef == NULL)
  8275. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8276. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8277. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  8278. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  8279. {
  8280. Fail("Custom attribute circular reference", attributesDirective);
  8281. }
  8282. if (mCurTypeInstance != NULL)
  8283. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8284. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  8285. success = false;
  8286. for (auto& arg : argValues)
  8287. {
  8288. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  8289. {
  8290. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  8291. constResolver.Resolve(expr);
  8292. }
  8293. }
  8294. // Move all those to the constHolder
  8295. for (auto& ctorArg : customAttribute.mCtorArgs)
  8296. {
  8297. CurrentAddToConstHolder(ctorArg);
  8298. }
  8299. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  8300. {
  8301. targetOverride = BfAttributeTargets_ReturnValue;
  8302. if (attrTarget != BfAttributeTargets_Method)
  8303. {
  8304. Fail(StrFormat("'%s' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are '%s'. All attributes in this block will be ignored.",
  8305. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  8306. }
  8307. success = false;
  8308. }
  8309. if ((success) && (targetOverride != (BfAttributeTargets)0))
  8310. {
  8311. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  8312. {
  8313. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  8314. if (methodInfoEx->mMethodCustomAttributes == NULL)
  8315. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  8316. if (success)
  8317. {
  8318. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  8319. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  8320. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  8321. }
  8322. }
  8323. else
  8324. {
  8325. // Failed - ignore
  8326. success = false;
  8327. }
  8328. }
  8329. if (success)
  8330. {
  8331. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  8332. {
  8333. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  8334. {
  8335. if (prevCustomAttribute.mType == attrTypeInst)
  8336. {
  8337. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  8338. }
  8339. }
  8340. }
  8341. }
  8342. if (success)
  8343. {
  8344. customAttributes->mAttributes.push_back(customAttribute);
  8345. }
  8346. }
  8347. ValidateCustomAttributes(customAttributes, attrTarget);
  8348. }
  8349. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType)
  8350. {
  8351. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  8352. GetCustomAttributes(customAttributes, attributesDirective, attrType);
  8353. return customAttributes;
  8354. }
  8355. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered)
  8356. {
  8357. if (mCurTypeInstance->mCustomAttributes != NULL)
  8358. {
  8359. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8360. {
  8361. String typeName = TypeToString(customAttribute.mType);
  8362. if (typeName == "System.PackedAttribute")
  8363. {
  8364. isPacked = true;
  8365. }
  8366. else if (typeName == "System.UnionAttribute")
  8367. {
  8368. isUnion = true;
  8369. }
  8370. else if (typeName == "System.CReprAttribute")
  8371. {
  8372. isCRepr = true;
  8373. isOrdered = true;
  8374. }
  8375. else if (typeName == "System.OrderedAttribute")
  8376. {
  8377. isOrdered = true;
  8378. }
  8379. else if (typeName == "System.AlwaysIncludeAttribute")
  8380. {
  8381. for (auto setProp : customAttribute.mSetProperties)
  8382. {
  8383. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  8384. if (propertyDef->mName == "AssumeInstantiated")
  8385. {
  8386. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8387. if ((constant != NULL) && (constant->mBool))
  8388. mCurTypeInstance->mHasBeenInstantiated = true;
  8389. }
  8390. }
  8391. }
  8392. }
  8393. }
  8394. }
  8395. // Checking to see if we're an attribute or not
  8396. void BfModule::ProcessCustomAttributeData()
  8397. {
  8398. bool isAttribute = false;
  8399. auto checkTypeInst = mCurTypeInstance->mBaseType;
  8400. while (checkTypeInst != NULL)
  8401. {
  8402. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  8403. isAttribute = true;
  8404. checkTypeInst = checkTypeInst->mBaseType;
  8405. }
  8406. if (!isAttribute)
  8407. return;
  8408. auto attributeData = new BfAttributeData();
  8409. bool hasCustomAttribute = false;
  8410. if (mCurTypeInstance->mCustomAttributes != NULL)
  8411. {
  8412. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8413. {
  8414. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  8415. {
  8416. if (customAttribute.mCtorArgs.size() > 0)
  8417. {
  8418. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  8419. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8420. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8421. }
  8422. for (auto& setProp : customAttribute.mSetProperties)
  8423. {
  8424. BfPropertyDef* propDef = setProp.mPropertyRef;
  8425. if (propDef->mName == "AllowMultiple")
  8426. {
  8427. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8428. if (constant != NULL)
  8429. attributeData->mAllowMultiple = constant->mBool;
  8430. }
  8431. else if (propDef->mName == "Inherited")
  8432. {
  8433. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8434. if (constant != NULL)
  8435. attributeData->mInherited = constant->mBool;
  8436. }
  8437. else if (propDef->mName == "ValidOn")
  8438. {
  8439. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8440. if (constant != NULL)
  8441. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8442. }
  8443. }
  8444. hasCustomAttribute = true;
  8445. }
  8446. }
  8447. }
  8448. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  8449. {
  8450. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  8451. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  8452. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  8453. }
  8454. mCurTypeInstance->mAttributeData = attributeData;
  8455. }
  8456. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  8457. {
  8458. auto constant = constHolder->GetConstant(irValue);
  8459. if (constant == NULL)
  8460. return false;
  8461. if (!BfIRConstHolder::IsInt(constant->mTypeCode))
  8462. return false;
  8463. int stringId = constant->mInt32;
  8464. BfStringPoolEntry* entry = NULL;
  8465. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  8466. {
  8467. str = entry->mString;
  8468. }
  8469. else
  8470. {
  8471. BF_DBG_FATAL("Failed to find string by id");
  8472. }
  8473. return true;
  8474. }
  8475. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  8476. {
  8477. BfVariant variant;
  8478. variant.mTypeCode = BfTypeCode_None;
  8479. BfType* primType = NULL;
  8480. if (value.mType->IsPrimitiveType())
  8481. primType = (BfPrimitiveType*)value.mType;
  8482. else if (value.mType->IsTypedPrimitive())
  8483. primType = value.mType->GetUnderlyingType();
  8484. if (primType)
  8485. {
  8486. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  8487. if (constant != NULL)
  8488. {
  8489. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  8490. {
  8491. variant.mTypeCode = BfTypeCode_Let;
  8492. return variant;
  8493. }
  8494. switch (constant->mTypeCode)
  8495. {
  8496. case BfTypeCode_Int8:
  8497. case BfTypeCode_UInt8:
  8498. case BfTypeCode_Int16:
  8499. case BfTypeCode_UInt16:
  8500. case BfTypeCode_Int32:
  8501. case BfTypeCode_UInt32:
  8502. case BfTypeCode_Int64:
  8503. case BfTypeCode_UInt64:
  8504. case BfTypeCode_IntPtr:
  8505. case BfTypeCode_UIntPtr:
  8506. case BfTypeCode_IntUnknown:
  8507. case BfTypeCode_UIntUnknown:
  8508. case BfTypeCode_Single:
  8509. case BfTypeCode_Double:
  8510. case BfTypeCode_Char8:
  8511. case BfTypeCode_Char16:
  8512. case BfTypeCode_Char32:
  8513. variant.mTypeCode = constant->mTypeCode;
  8514. variant.mInt64 = constant->mInt64;
  8515. break;
  8516. default:
  8517. if (refNode != NULL)
  8518. Fail("Invalid const expression type", refNode);
  8519. break;
  8520. }
  8521. }
  8522. }
  8523. return variant;
  8524. }
  8525. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  8526. {
  8527. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  8528. {
  8529. auto elementType = typedValue.mType->GetUnderlyingType();
  8530. if (typedValue.IsAddr())
  8531. {
  8532. if (elementType->IsValuelessType())
  8533. {
  8534. BF_ASSERT(!typedValue.mValue);
  8535. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8536. }
  8537. else
  8538. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  8539. }
  8540. else
  8541. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8542. if (typedValue.mType->IsValuelessType())
  8543. {
  8544. BF_ASSERT(typedValue.mValue.IsFake());
  8545. }
  8546. }
  8547. return typedValue;
  8548. }
  8549. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  8550. {
  8551. if (!typedValue.IsAddr())
  8552. return typedValue;
  8553. if (typedValue.mType->IsValuelessType())
  8554. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  8555. BfIRValue loadedVal = typedValue.mValue;
  8556. if (loadedVal)
  8557. {
  8558. /*if (isVolatile)
  8559. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  8560. PopulateType(typedValue.mType, BfPopulateType_Data);
  8561. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  8562. }
  8563. return BfTypedValue(loadedVal, typedValue.mType, false);
  8564. }
  8565. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  8566. {
  8567. if (typedValue.IsSplat())
  8568. return AggregateSplat(typedValue);
  8569. if (typedValue.IsAddr())
  8570. return LoadValue(typedValue);
  8571. return typedValue;
  8572. }
  8573. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  8574. {
  8575. if (!typedValue.IsSplat())
  8576. return typedValue;
  8577. if (typedValue.mType->IsValuelessType())
  8578. return typedValue;
  8579. int elementIdx = 0;
  8580. auto _ExtractValue = [&](BfType* checkType)
  8581. {
  8582. if (valueArrPtr != NULL)
  8583. return valueArrPtr[elementIdx++];
  8584. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  8585. };
  8586. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8587. {
  8588. if (checkType->IsStruct())
  8589. {
  8590. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8591. auto checkTypeInstance = checkType->ToTypeInstance();
  8592. if (checkTypeInstance->mBaseType != NULL)
  8593. {
  8594. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  8595. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  8596. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  8597. }
  8598. if (checkTypeInstance->mIsUnion)
  8599. {
  8600. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8601. if (!unionInnerType->IsValuelessType())
  8602. {
  8603. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  8604. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  8605. }
  8606. if (checkTypeInstance->IsEnum())
  8607. {
  8608. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8609. BfIRValue fieldValue = checkTypeLambda(dscrType);
  8610. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  8611. }
  8612. }
  8613. else
  8614. {
  8615. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8616. {
  8617. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8618. if (fieldInstance->mDataIdx >= 0)
  8619. {
  8620. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  8621. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  8622. }
  8623. }
  8624. }
  8625. return curValue;
  8626. }
  8627. else if (checkType->IsMethodRef())
  8628. {
  8629. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8630. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8631. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8632. {
  8633. BfIRValue fieldValue;
  8634. auto checkType = methodRefType->GetCaptureType(dataIdx);
  8635. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8636. {
  8637. fieldValue = checkTypeLambda(checkType);
  8638. }
  8639. else
  8640. {
  8641. fieldValue = _ExtractValue(checkType);
  8642. }
  8643. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  8644. }
  8645. return curValue;
  8646. }
  8647. else if (!checkType->IsValuelessType())
  8648. {
  8649. return _ExtractValue(checkType);
  8650. }
  8651. return BfIRValue();
  8652. };
  8653. BfIRValue value = checkTypeLambda(typedValue.mType);
  8654. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  8655. }
  8656. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  8657. {
  8658. if (!typedValue.IsSplat())
  8659. return;
  8660. if (typedValue.mType->IsValuelessType())
  8661. return;
  8662. /*static int sCallIdx = 0;
  8663. if (!mCompiler->mIsResolveOnly)
  8664. sCallIdx++;
  8665. int callIdx = sCallIdx;*/
  8666. int elementIdx = 0;
  8667. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  8668. {
  8669. if (checkType->IsStruct())
  8670. {
  8671. auto checkTypeInstance = checkType->ToTypeInstance();
  8672. if (checkTypeInstance->mBaseType != NULL)
  8673. {
  8674. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  8675. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  8676. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  8677. }
  8678. if (checkTypeInstance->mIsUnion)
  8679. {
  8680. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8681. if (!unionInnerType->IsValuelessType())
  8682. {
  8683. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  8684. checkTypeLambda(unionInnerType, fieldAddrVal);
  8685. }
  8686. if (checkTypeInstance->IsEnum())
  8687. {
  8688. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8689. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  8690. checkTypeLambda(dscrType, fieldAddrVal);
  8691. }
  8692. }
  8693. else
  8694. {
  8695. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8696. {
  8697. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8698. if (fieldInstance->mDataIdx >= 0)
  8699. {
  8700. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  8701. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  8702. }
  8703. }
  8704. }
  8705. }
  8706. else if (checkType->IsMethodRef())
  8707. {
  8708. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8709. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8710. {
  8711. auto dataType = methodRefType->GetCaptureType(dataIdx);
  8712. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  8713. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8714. {
  8715. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  8716. }
  8717. else
  8718. {
  8719. // static int sItrCount = 0;
  8720. // sItrCount++;
  8721. // int curItr = sItrCount;
  8722. // if (curItr == 1)
  8723. // {
  8724. // NOP;
  8725. // }
  8726. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  8727. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  8728. }
  8729. }
  8730. }
  8731. else if (!checkType->IsValuelessType())
  8732. {
  8733. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  8734. mBfIRBuilder->CreateStore(val, curAddrVal);
  8735. }
  8736. };
  8737. checkTypeLambda(typedValue.mType, addrVal);
  8738. }
  8739. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  8740. {
  8741. bool wasReadOnly = typedVal.IsReadOnly();
  8742. if ((typedVal.mType->IsValueType()) &&
  8743. (!typedVal.mType->IsValuelessType()))
  8744. {
  8745. wasReadOnly = true; // Any non-addr is implicitly read-only
  8746. //static int gCallIdx = 0;
  8747. if (typedVal.IsAddr())
  8748. return typedVal;
  8749. BfType* type = typedVal.mType;
  8750. PopulateType(type);
  8751. auto tempVar = CreateAlloca(type);
  8752. if (typedVal.IsSplat())
  8753. AggregateSplatIntoAddr(typedVal, tempVar);
  8754. else
  8755. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  8756. return BfTypedValue(tempVar, type,
  8757. typedVal.IsThis() ?
  8758. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  8759. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  8760. }
  8761. return LoadValue(typedVal);
  8762. }
  8763. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  8764. {
  8765. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  8766. typedValue.mKind = BfTypedValueKind_Addr;
  8767. return typedValue;
  8768. }
  8769. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  8770. {
  8771. BfIRValue val;
  8772. if (typedValue.mValue.IsArg())
  8773. {
  8774. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  8775. if (isAddr != NULL)
  8776. {
  8777. if (wantType != NULL)
  8778. *isAddr = wantType->IsComposite();
  8779. else
  8780. *isAddr = false;
  8781. }
  8782. else if (wantType->IsComposite())
  8783. val = mBfIRBuilder->CreateLoad(val);
  8784. }
  8785. if (!val)
  8786. {
  8787. auto checkMethodState = mCurMethodState;
  8788. while (checkMethodState != NULL)
  8789. {
  8790. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  8791. {
  8792. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  8793. if (decompAddr == typedValue.mValue)
  8794. {
  8795. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  8796. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  8797. {
  8798. // This is really backing for a POINTER to a composite inside a methodRef
  8799. val = mBfIRBuilder->CreateLoad(val);
  8800. }
  8801. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  8802. {
  8803. *isAddr = true;
  8804. return val;
  8805. }
  8806. else
  8807. {
  8808. val = mBfIRBuilder->CreateLoad(val);
  8809. break;
  8810. }
  8811. }
  8812. }
  8813. if (val)
  8814. break;
  8815. checkMethodState = checkMethodState->mPrevMethodState;
  8816. }
  8817. }
  8818. if (val)
  8819. {
  8820. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  8821. {
  8822. BF_ASSERT(wantType != NULL);
  8823. if (wantType != NULL)
  8824. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  8825. }
  8826. return val;
  8827. }
  8828. BF_FATAL("Splat not found");
  8829. return BfIRValue();
  8830. }
  8831. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  8832. {
  8833. int useFieldIdx = fieldIdx;
  8834. BfType* fieldType = NULL;
  8835. if (fieldInstance != NULL)
  8836. {
  8837. fieldType = fieldInstance->mResolvedType;
  8838. if (typedValue.mType->IsUnion())
  8839. {
  8840. if (fieldIdx == 1)
  8841. {
  8842. if (typedValue.IsSplat())
  8843. {
  8844. BfTypedValue innerVal = typedValue;
  8845. innerVal.mType = fieldType;
  8846. return innerVal;
  8847. }
  8848. }
  8849. }
  8850. }
  8851. else
  8852. {
  8853. if (typedValue.mType->IsPayloadEnum())
  8854. {
  8855. auto typeInst = typedValue.mType->ToTypeInstance();
  8856. if (fieldIdx == 1)
  8857. fieldType = typeInst->GetUnionInnerType();
  8858. else if (fieldIdx == 2)
  8859. {
  8860. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  8861. }
  8862. }
  8863. else if (typedValue.mType->IsUnion())
  8864. {
  8865. if (fieldIdx == 1)
  8866. {
  8867. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  8868. if (typedValue.IsSplat())
  8869. {
  8870. BfTypedValue innerVal = typedValue;
  8871. innerVal.mType = fieldType;
  8872. return innerVal;
  8873. }
  8874. }
  8875. }
  8876. }
  8877. BF_ASSERT(typedValue.mType->IsStruct());
  8878. if (typedValue.IsSplat())
  8879. {
  8880. if (typedValue.mType->IsPayloadEnum())
  8881. {
  8882. if (fieldIdx == 1)
  8883. {
  8884. // Payload
  8885. auto typeInst = typedValue.mType->ToTypeInstance();
  8886. auto unionInnerType = typeInst->GetUnionInnerType();
  8887. bool isAddr = false;
  8888. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  8889. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  8890. }
  8891. if (fieldIdx == 2)
  8892. {
  8893. // Discriminator
  8894. auto typeInst = typedValue.mType->ToTypeInstance();
  8895. auto unionInnerType = typeInst->GetUnionInnerType();
  8896. auto dscrType = typeInst->GetDiscriminatorType();
  8897. int argIdx = typedValue.mValue.mId;
  8898. int componentIdx = 0;
  8899. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  8900. bool isAddr;
  8901. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  8902. return BfTypedValue(irVal, dscrType, isAddr);
  8903. }
  8904. }
  8905. int componentIdx = 0;
  8906. BfTypedValue retVal;
  8907. BfFieldInstance* wantFieldInstance = fieldInstance;
  8908. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8909. {
  8910. if (checkType->IsStruct())
  8911. {
  8912. auto checkTypeInstance = checkType->ToTypeInstance();
  8913. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  8914. {
  8915. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  8916. fieldType = checkTypeInstance->GetUnionInnerType();
  8917. checkTypeLambda(fieldType);
  8918. if (checkType->IsEnum())
  8919. {
  8920. // Past discriminator...
  8921. componentIdx++;
  8922. }
  8923. return;
  8924. }
  8925. if (checkTypeInstance->mBaseType != NULL)
  8926. checkTypeLambda(checkTypeInstance->mBaseType);
  8927. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8928. {
  8929. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8930. if (fieldInstance == wantFieldInstance)
  8931. {
  8932. bool isAddr = false;
  8933. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  8934. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  8935. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  8936. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  8937. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  8938. {
  8939. retVal = LoadValue(retVal);
  8940. }
  8941. break;
  8942. }
  8943. if (fieldInstance->mDataIdx >= 0)
  8944. checkTypeLambda(fieldInstance->GetResolvedType());
  8945. }
  8946. }
  8947. else if (!checkType->IsValuelessType())
  8948. {
  8949. componentIdx++;
  8950. //argIdx++;
  8951. }
  8952. };
  8953. checkTypeLambda(typedValue.mType);
  8954. BF_ASSERT(retVal);
  8955. return retVal;
  8956. }
  8957. if (typedValue.IsAddr())
  8958. {
  8959. BF_ASSERT(fieldType != NULL);
  8960. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  8961. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  8962. }
  8963. else
  8964. {
  8965. BF_ASSERT(fieldType != NULL);
  8966. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  8967. }
  8968. }
  8969. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  8970. {
  8971. if (typedValue.IsAddr())
  8972. {
  8973. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  8974. return mBfIRBuilder->CreateLoad(addrVal);
  8975. }
  8976. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  8977. }
  8978. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  8979. {
  8980. if (elementType->IsSizeAligned())
  8981. {
  8982. if (isElementIndex)
  8983. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  8984. else
  8985. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  8986. }
  8987. auto ptrType = CreatePointerType(elementType);
  8988. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  8989. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  8990. auto intVal = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  8991. auto newIntVal = mBfIRBuilder->CreateAdd(intVal, ofsScaledVal);
  8992. return mBfIRBuilder->CreateIntToPtr(newIntVal, mBfIRBuilder->MapType(ptrType));
  8993. }
  8994. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  8995. {
  8996. if (elementType->IsSizeAligned())
  8997. {
  8998. if (isElementIndex)
  8999. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  9000. else
  9001. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  9002. }
  9003. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  9004. }
  9005. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  9006. {
  9007. if (modifyType == NULL)
  9008. modifyType = "modify";
  9009. if (typedValue.mType->IsVar())
  9010. return true;
  9011. if (typedValue.IsReadOnly())
  9012. {
  9013. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  9014. return false;
  9015. }
  9016. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  9017. {
  9018. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  9019. return false;
  9020. }
  9021. if (typedValue.mKind == BfTypedValueKind_TempAddr)
  9022. {
  9023. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  9024. return false;
  9025. }
  9026. return true;
  9027. }
  9028. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  9029. {
  9030. if (methodA->mMethodDef->mIsLocalMethod)
  9031. {
  9032. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  9033. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  9034. if (sepPosA != sepPosB)
  9035. return false;
  9036. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  9037. return false;
  9038. }
  9039. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  9040. return false;
  9041. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  9042. return false;
  9043. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  9044. {
  9045. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  9046. return false;
  9047. }
  9048. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  9049. {
  9050. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  9051. return false;
  9052. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  9053. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  9054. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  9055. return false;
  9056. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  9057. return false;
  9058. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  9059. {
  9060. if (methodA->mReturnType != methodB->mReturnType)
  9061. return false;
  9062. }
  9063. }
  9064. int implicitParamCountA = methodA->GetImplicitParamCount();
  9065. int implicitParamCountB = methodB->GetImplicitParamCount();
  9066. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  9067. return false;
  9068. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  9069. return false;
  9070. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  9071. {
  9072. if ((methodA->GetParamType(paramIdx + implicitParamCountA) != methodB->GetParamType(paramIdx + implicitParamCountB)) ||
  9073. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  9074. return false;
  9075. }
  9076. // Compare generic params. Generic params are part of the method signature here
  9077. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  9078. return false;
  9079. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  9080. {
  9081. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  9082. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  9083. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  9084. return false;
  9085. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  9086. return false;
  9087. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  9088. return false;
  9089. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  9090. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  9091. return false;
  9092. }
  9093. return true;
  9094. }
  9095. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  9096. {
  9097. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  9098. return false;
  9099. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  9100. return false;
  9101. if (iMethodInst->mMethodDef->mIsOperator)
  9102. {
  9103. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  9104. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  9105. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  9106. return false;
  9107. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  9108. return false;
  9109. }
  9110. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  9111. return false;
  9112. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  9113. {
  9114. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  9115. return false;
  9116. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  9117. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  9118. if (iParamType->IsSelf())
  9119. {
  9120. if (methodParamType != methodInstance->GetOwner())
  9121. return false;
  9122. }
  9123. else if (!iParamType->IsGenericParam())
  9124. {
  9125. if (methodParamType != iParamType)
  9126. return false;
  9127. }
  9128. else
  9129. {
  9130. if (!methodParamType->IsGenericParam())
  9131. return false;
  9132. auto genericParamType = (BfGenericParamType*)methodParamType;
  9133. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  9134. return false;
  9135. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  9136. bool hadInterface = false;
  9137. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  9138. if (interfaceConstraint == iParamType)
  9139. hadInterface = true;
  9140. if (!hadInterface)
  9141. return false;
  9142. }
  9143. }
  9144. return true;
  9145. }
  9146. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  9147. {
  9148. BfMethodInstance* methodInstance = methodRef;
  9149. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  9150. {
  9151. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  9152. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  9153. {
  9154. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  9155. BfMethodRef methodRef = methodInstance;
  9156. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  9157. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  9158. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  9159. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  9160. (mIsReified))
  9161. {
  9162. specializedMethodRefInfo->mHasReifiedRef = true;
  9163. }
  9164. }
  9165. }
  9166. }
  9167. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9168. {
  9169. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  9170. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9171. if (mBfIRBuilder == NULL)
  9172. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9173. if (methodInstance->GetOwner()->IsFunction())
  9174. {
  9175. // No actual ref needed- not an actual generated function
  9176. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9177. }
  9178. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  9179. if (!isGenFunction)
  9180. AddMethodReference(methodInstance, flags);
  9181. if (mBfIRBuilder->mIgnoreWrites)
  9182. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  9183. if (mCompiler->IsSkippingExtraResolveChecks())
  9184. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9185. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  9186. {
  9187. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9188. }
  9189. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9190. BfMethodRef methodRef = methodInstance;
  9191. if (isInlined)
  9192. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  9193. else
  9194. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  9195. if (!isGenFunction)
  9196. {
  9197. BfIRValue* irFuncPtr = NULL;
  9198. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  9199. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  9200. }
  9201. if (mAwaitingInitFinish)
  9202. FinishInit();
  9203. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  9204. if (!isGenFunction)
  9205. mFuncReferences[methodRef] = func;
  9206. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  9207. if ((isInlined) && (!mIsScratchModule))
  9208. {
  9209. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  9210. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  9211. // type instance
  9212. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  9213. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  9214. for (auto ownedTypeInst : mOwnedTypeInstances)
  9215. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  9216. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  9217. {
  9218. mIncompleteMethodCount++;
  9219. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9220. inlineMethodRequest->mType = methodInstance->GetOwner();
  9221. inlineMethodRequest->mFromModule = this;
  9222. inlineMethodRequest->mFunc = func;
  9223. inlineMethodRequest->mFromModuleRevision = mRevision;
  9224. inlineMethodRequest->mMethodInstance = methodInstance;
  9225. BF_ASSERT(mIsModuleMutable);
  9226. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9227. }
  9228. }
  9229. return BfModuleMethodInstance(methodInstance, func);
  9230. }
  9231. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  9232. {
  9233. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  9234. if (mBfIRBuilder == NULL)
  9235. {
  9236. // To allow for custom attribute data
  9237. PrepareForIRWriting(typeInst);
  9238. }
  9239. BfModule* declareModule = this;
  9240. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  9241. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  9242. declareModule = declareModule->mParentModule;
  9243. // Check for attributes
  9244. if (typeInst == mContext->mBfObjectType)
  9245. {
  9246. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  9247. if (methodDecl != NULL)
  9248. {
  9249. auto attributesDirective = methodDecl->mAttributes;
  9250. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9251. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9252. {
  9253. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9254. }
  9255. }
  9256. }
  9257. else
  9258. {
  9259. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  9260. GetMethodCustomAttributes(methodInstance);
  9261. }
  9262. BF_ASSERT(mModuleOptions == NULL);
  9263. if (methodInstance->GetCustomAttributes() != NULL)
  9264. {
  9265. auto project = typeInst->mTypeDef->mProject;
  9266. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  9267. BfModuleOptions wantOptions = moduleOptions;
  9268. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  9269. if (typeOptions != NULL)
  9270. {
  9271. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  9272. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  9273. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  9274. }
  9275. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  9276. {
  9277. StringT<128> attrName;
  9278. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  9279. {
  9280. attrName.Clear();
  9281. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  9282. Array<int>* arrPtr;
  9283. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  9284. {
  9285. for (auto optionsIdx : *arrPtr)
  9286. {
  9287. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  9288. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  9289. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  9290. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  9291. }
  9292. }
  9293. }
  9294. }
  9295. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  9296. {
  9297. auto lastCheckModule = this;
  9298. auto checkModule = this->mNextAltModule;
  9299. while (checkModule != NULL)
  9300. {
  9301. if (*checkModule->mModuleOptions == wantOptions)
  9302. {
  9303. declareModule = checkModule;
  9304. break;
  9305. }
  9306. lastCheckModule = checkModule;
  9307. checkModule = checkModule->mNextAltModule;
  9308. }
  9309. // Not found?
  9310. if (declareModule == this)
  9311. {
  9312. String specModuleName = mModuleName + "@@";
  9313. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  9314. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  9315. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  9316. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  9317. declareModule = new BfModule(mContext, specModuleName);
  9318. declareModule->mProject = project;
  9319. declareModule->mModuleOptions = new BfModuleOptions();
  9320. *declareModule->mModuleOptions = wantOptions;
  9321. declareModule->mParentModule = lastCheckModule;
  9322. declareModule->Init();
  9323. lastCheckModule->mNextAltModule = declareModule;
  9324. }
  9325. }
  9326. }
  9327. declareModule->PrepareForIRWriting(typeInst);
  9328. return declareModule;
  9329. }
  9330. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  9331. {
  9332. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  9333. {
  9334. // Don't bother inlining for resolve-only
  9335. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9336. }
  9337. bool processNow = false;
  9338. bool keepInCurrentModule = false;
  9339. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  9340. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  9341. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  9342. {
  9343. return BfModuleMethodInstance();
  9344. }
  9345. if (methodDef->mIsLocalMethod)
  9346. {
  9347. auto rootMethodState = mCurMethodState->GetRootMethodState();
  9348. BfLocalMethod* localMethod;
  9349. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  9350. {
  9351. // Handle the def in the correct method state
  9352. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  9353. }
  9354. BF_FATAL("Cannot find local method");
  9355. return BfModuleMethodInstance();
  9356. }
  9357. #ifdef _DEBUG
  9358. for (auto arg : methodGenericArguments)
  9359. BF_ASSERT(!arg->IsVar());
  9360. #endif
  9361. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  9362. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  9363. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  9364. // a FinishInit
  9365. if ((typeInst->IsIncomplete()) &&
  9366. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  9367. {
  9368. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  9369. // for resolve-only because we don't differentiate between reified/unreified there
  9370. PopulateType(typeInst, BfPopulateType_Full);
  9371. }
  9372. bool tryModuleMethodLookup = false;
  9373. BfModuleMethodInstance moduleMethodInst;
  9374. BfModule* instModule = typeInst->mModule;
  9375. if (keepInCurrentModule)
  9376. {
  9377. // Stay here
  9378. instModule = this;
  9379. }
  9380. if (this == mContext->mUnreifiedModule)
  9381. {
  9382. // Stay in this 'resolve only' module here
  9383. }
  9384. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  9385. {
  9386. BF_ASSERT(this == mContext->mUnreifiedModule);
  9387. }
  9388. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  9389. {
  9390. BF_ASSERT(instModule == mParentModule);
  9391. }
  9392. else if (instModule != this)
  9393. {
  9394. if ((!mIsReified) && (instModule->mIsReified))
  9395. {
  9396. BF_ASSERT(!mCompiler->mIsResolveOnly);
  9397. // A resolve-only module is specializing a method from a type in a reified module,
  9398. // we need to take care that this doesn't cause anything new to become reified
  9399. return mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  9400. }
  9401. else
  9402. {
  9403. if ((mIsReified) && (!instModule->mIsReified))
  9404. {
  9405. if (!instModule->mReifyQueued)
  9406. {
  9407. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  9408. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  9409. mContext->mReifyModuleWorkList.Add(instModule);
  9410. instModule->mReifyQueued = true;
  9411. }
  9412. // This ensures that the method will actually be created when it gets reified
  9413. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  9414. specializationRequest->mFromModule = typeInst->mModule;
  9415. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  9416. specializationRequest->mMethodDef = methodDef;
  9417. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  9418. specializationRequest->mType = typeInst;
  9419. }
  9420. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9421. // Not extern
  9422. // Create the instance in the proper module and then create a reference in this one
  9423. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  9424. tryModuleMethodLookup = true;
  9425. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  9426. {
  9427. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  9428. }
  9429. }
  9430. }
  9431. if (tryModuleMethodLookup)
  9432. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  9433. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  9434. {
  9435. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  9436. if (moduleMethodInstance)
  9437. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  9438. return moduleMethodInst;
  9439. }
  9440. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  9441. bool hadConcreteInterfaceGenericArgument = false;
  9442. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  9443. isReified = false;
  9444. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  9445. {
  9446. isReified = false;
  9447. }
  9448. BfTypeVector sanitizedMethodGenericArguments;
  9449. Array<BfProject*> projectList;
  9450. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  9451. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  9452. isUnspecializedPass = false;
  9453. // Check for whether we are an extension method from a project that does not hold the root type, AND that isn't already the project for this type
  9454. bool isExternalExtensionMethod = false;
  9455. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  9456. {
  9457. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  9458. {
  9459. auto specProject = methodDef->mDeclaringType->mProject;
  9460. isExternalExtensionMethod = true;
  9461. if (typeInst->IsGenericTypeInstance())
  9462. {
  9463. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9464. if (genericTypeInst->mProjectsReferenced.empty())
  9465. genericTypeInst->GenerateProjectsReferenced();
  9466. if (genericTypeInst->mProjectsReferenced.Contains(specProject))
  9467. {
  9468. // This is a generic type where a generic param is already confined to the project in question
  9469. isExternalExtensionMethod = false;
  9470. }
  9471. }
  9472. if (isExternalExtensionMethod)
  9473. {
  9474. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  9475. projectList.push_back(methodDef->mDeclaringType->mProject);
  9476. }
  9477. }
  9478. }
  9479. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  9480. {
  9481. int typeProjectsCounts = 0;
  9482. if (typeInst->IsGenericTypeInstance())
  9483. {
  9484. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9485. if (genericTypeInst->mProjectsReferenced.empty())
  9486. genericTypeInst->GenerateProjectsReferenced();
  9487. typeProjectsCounts = (int)genericTypeInst->mProjectsReferenced.size();
  9488. projectList.Insert(0, &genericTypeInst->mProjectsReferenced[0], genericTypeInst->mProjectsReferenced.size());
  9489. }
  9490. else
  9491. {
  9492. typeProjectsCounts = 1;
  9493. projectList.Insert(0, typeInst->mTypeDef->mProject);
  9494. }
  9495. isUnspecializedPass = true;
  9496. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  9497. {
  9498. auto genericArgType = methodGenericArguments[genericArgIdx];
  9499. //BF_ASSERT(!genericArgType->IsRef());
  9500. if (genericArgType->IsConcreteInterfaceType())
  9501. {
  9502. hadConcreteInterfaceGenericArgument = true;
  9503. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  9504. genericArgType = concreteInterfaceType->mInterface;
  9505. }
  9506. if (genericArgType->IsGenericParam())
  9507. {
  9508. auto genericParam = (BfGenericParamType*) genericArgType;
  9509. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  9510. isUnspecializedPass = false;
  9511. }
  9512. else
  9513. {
  9514. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  9515. isUnspecializedPass = false;
  9516. }
  9517. sanitizedMethodGenericArguments.push_back(genericArgType);
  9518. }
  9519. if ((int)projectList.size() > typeProjectsCounts)
  9520. {
  9521. // Just leave the new items
  9522. projectList.RemoveRange(0, typeProjectsCounts);
  9523. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  9524. {
  9525. return lhs->mName < rhs->mName;
  9526. });
  9527. }
  9528. else
  9529. {
  9530. projectList.Clear();
  9531. }
  9532. }
  9533. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  9534. BfMethodInstanceGroup* methodInstGroup = NULL;
  9535. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9536. {
  9537. BF_ASSERT(!typeInst->IsInterface());
  9538. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  9539. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  9540. {
  9541. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  9542. // if (checkGroup.mDefault == NULL)
  9543. // {
  9544. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  9545. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  9546. // methodInstGroup = &checkGroup;
  9547. // break;
  9548. // }
  9549. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  9550. {
  9551. methodInstGroup = &checkGroup;
  9552. break;
  9553. }
  9554. }
  9555. if (methodInstGroup == NULL)
  9556. {
  9557. // Allocate a new entry
  9558. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  9559. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  9560. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  9561. methodInstGroup->mOwner = typeInst;
  9562. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9563. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9564. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  9565. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9566. else
  9567. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9568. }
  9569. }
  9570. else
  9571. {
  9572. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  9573. }
  9574. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9575. {
  9576. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  9577. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9578. }
  9579. BfIRFunction prevIRFunc;
  9580. bool doingRedeclare = false;
  9581. BfMethodInstance* methodInstance = NULL;
  9582. auto _SetReified = [&]()
  9583. {
  9584. methodInstance->mIsReified = true;
  9585. };
  9586. if (lookupMethodGenericArguments.size() == 0)
  9587. {
  9588. methodInstance = methodInstGroup->mDefault;
  9589. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  9590. {
  9591. MarkDerivedDirty(typeInst);
  9592. if (mIsScratchModule)
  9593. {
  9594. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  9595. _SetReified();
  9596. CheckHotMethod(methodInstance, "");
  9597. }
  9598. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  9599. {
  9600. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  9601. // the specializations to handle that for us
  9602. return BfModuleMethodInstance(methodInstance);
  9603. }
  9604. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  9605. {
  9606. if (methodDef->mIsAbstract)
  9607. {
  9608. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9609. _SetReified();
  9610. }
  9611. else
  9612. {
  9613. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9614. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9615. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  9616. doingRedeclare = true;
  9617. mOnDemandMethodCount++;
  9618. }
  9619. }
  9620. else
  9621. {
  9622. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  9623. // We haven't processed it yet
  9624. _SetReified();
  9625. CheckHotMethod(methodInstance, "");
  9626. if (methodInstance->mDeclModule == this)
  9627. {
  9628. if (methodInstance->mMethodProcessRequest != NULL)
  9629. {
  9630. // Disconnect method process request
  9631. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  9632. }
  9633. }
  9634. else
  9635. {
  9636. if (methodInstance->mMethodProcessRequest != NULL)
  9637. {
  9638. // Disconnect method process request
  9639. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == mContext->mUnreifiedModule);
  9640. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  9641. methodInstance->mMethodProcessRequest = NULL;
  9642. }
  9643. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  9644. {
  9645. // Add new request in proper module
  9646. methodInstance->mDeclModule = this;
  9647. }
  9648. else
  9649. {
  9650. if (methodInstance->mDeclModule == NULL)
  9651. {
  9652. //
  9653. }
  9654. else if (methodInstance->mDeclModule != this)
  9655. {
  9656. // Is from specialized module?
  9657. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  9658. }
  9659. }
  9660. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9661. {
  9662. methodInstance->mIRFunction = BfIRFunction();
  9663. if (!mIsModuleMutable)
  9664. StartExtension();
  9665. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  9666. {
  9667. StringT<128> mangledName;
  9668. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  9669. bool isIntrinsic = false;
  9670. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  9671. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  9672. }
  9673. }
  9674. AddMethodToWorkList(methodInstance);
  9675. }
  9676. }
  9677. }
  9678. }
  9679. else
  9680. {
  9681. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  9682. if (methodInstGroup->mMethodSpecializationMap == NULL)
  9683. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  9684. BfMethodInstance** methodInstancePtr = NULL;
  9685. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  9686. {
  9687. methodInstance = *methodInstancePtr;
  9688. if ((isReified) && (!methodInstance->mIsReified))
  9689. {
  9690. MarkDerivedDirty(typeInst);
  9691. if (methodInstance->mHasBeenProcessed)
  9692. {
  9693. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  9694. delete methodInstance;
  9695. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9696. methodInstance = NULL;
  9697. }
  9698. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9699. {
  9700. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  9701. delete methodInstance;
  9702. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9703. methodInstance = NULL;
  9704. }
  9705. else
  9706. {
  9707. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  9708. // We haven't processed it yet
  9709. _SetReified();
  9710. CheckHotMethod(methodInstance, "");
  9711. }
  9712. }
  9713. }
  9714. }
  9715. if ((methodInstance != NULL) && (!doingRedeclare))
  9716. {
  9717. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  9718. {
  9719. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  9720. BF_ASSERT(!methodInstance->mIsReified);*/
  9721. if (methodInstance->mIsReified != isReified)
  9722. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  9723. if ((!isReified) &&
  9724. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  9725. {
  9726. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  9727. methodInstance->mIRFunction = BfIRFunction();
  9728. }
  9729. methodInstance->mIsReified = isReified;
  9730. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  9731. {
  9732. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  9733. }
  9734. if (!methodInstance->mMethodDef->mIsAbstract)
  9735. {
  9736. AddMethodToWorkList(methodInstance);
  9737. }
  9738. else
  9739. {
  9740. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  9741. }
  9742. }
  9743. if (mExtensionCount > 0)
  9744. {
  9745. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  9746. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  9747. {
  9748. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  9749. if (mAwaitingInitFinish)
  9750. FinishInit();
  9751. // We need to refer to a function that was defined in a prior module
  9752. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9753. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  9754. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  9755. methodInstance->mDeclModule = this;
  9756. // Add this inlined def to ourselves
  9757. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized))
  9758. {
  9759. mIncompleteMethodCount++;
  9760. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9761. inlineMethodRequest->mType = typeInst;
  9762. inlineMethodRequest->mFromModule = this;
  9763. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  9764. inlineMethodRequest->mFromModuleRevision = mRevision;
  9765. inlineMethodRequest->mMethodInstance = methodInstance;
  9766. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9767. BF_ASSERT(mIsModuleMutable);
  9768. }
  9769. }
  9770. }
  9771. if (mCompiler->IsSkippingExtraResolveChecks())
  9772. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9773. else
  9774. {
  9775. if (methodInstance->mDeclModule != this)
  9776. return ReferenceExternalMethodInstance(methodInstance, flags);
  9777. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  9778. {
  9779. auto importKind = methodInstance->GetImportCallKind();
  9780. if (importKind != BfImportCallKind_None)
  9781. {
  9782. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  9783. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  9784. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  9785. }
  9786. }
  9787. return BfModuleMethodInstance(methodInstance);
  9788. }
  9789. }
  9790. if (!doingRedeclare)
  9791. {
  9792. BfModule* specModule = NULL;
  9793. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  9794. {
  9795. specModule = GetSpecializedMethodModule(projectList);
  9796. }
  9797. if ((specModule != NULL) && (specModule != this))
  9798. {
  9799. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  9800. if (mAwaitingInitFinish)
  9801. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  9802. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  9803. }
  9804. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  9805. {
  9806. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  9807. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  9808. }
  9809. }
  9810. if (methodInstance == NULL)
  9811. {
  9812. if (lookupMethodGenericArguments.size() == 0)
  9813. {
  9814. BF_ASSERT(methodInstGroup->mDefault == NULL);
  9815. methodInstance = new BfMethodInstance();
  9816. methodInstGroup->mDefault = methodInstance;
  9817. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  9818. }
  9819. else
  9820. {
  9821. BfMethodInstance** methodInstancePtr = NULL;
  9822. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  9823. BF_ASSERT(added);
  9824. methodInstance = new BfMethodInstance();
  9825. *methodInstancePtr = methodInstance;
  9826. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  9827. }
  9828. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  9829. methodInstance->mIRFunction = prevIRFunc; // Take it over
  9830. }
  9831. /*// 24 bits for typeid, 20 for method id, 20 for specialization index
  9832. methodInstance->mMethodId = ((int64)typeInst->mTypeId) + ((int64)methodInstGroup->mMethodIdx << 24);
  9833. if (methodInstGroup->mMethodSpecializationMap != NULL)
  9834. methodInstance->mMethodId += ((int64)methodInstGroup->mMethodSpecializationMap->size() << 44);*/
  9835. methodInstance->mMethodDef = methodDef;
  9836. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  9837. methodInstance->mMethodInstanceGroup = methodInstGroup;
  9838. methodInstance->mIsReified = isReified;
  9839. SetupMethodIdHash(methodInstance);
  9840. if (hadConcreteInterfaceGenericArgument)
  9841. methodInstance->mIgnoreBody = true;
  9842. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9843. {
  9844. methodInstance->mIsForeignMethodDef = true;
  9845. BF_ASSERT(foreignType != NULL);
  9846. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  9847. }
  9848. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  9849. {
  9850. if (!lookupMethodGenericArguments.empty())
  9851. {
  9852. auto compareType = lookupMethodGenericArguments[0];
  9853. PopulateType(compareType, BfPopulateType_Data);
  9854. if (compareType->IsSplattable())
  9855. methodInstance->mAlwaysInline = true;
  9856. }
  9857. }
  9858. if (methodDef->mDeclaringType->mTypeDeclaration != typeInst->mTypeDef->mTypeDeclaration)
  9859. {
  9860. // With extensions we can have multiple definitions of the same method
  9861. //methodInstance->mMangleWithIdx = true;
  9862. }
  9863. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  9864. BF_ASSERT(typeInst == methodInstance->GetOwner());
  9865. auto methodDeclaration = methodDef->GetMethodDeclaration();
  9866. if (isUnspecializedPass)
  9867. {
  9868. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  9869. {
  9870. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  9871. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  9872. }
  9873. }
  9874. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  9875. {
  9876. if (!sanitizedMethodGenericArguments.IsEmpty())
  9877. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  9878. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  9879. {
  9880. Fail("Internal error");
  9881. BF_FATAL("Generic method argument counts mismatch");
  9882. return NULL;
  9883. }
  9884. for (auto genericArg : sanitizedMethodGenericArguments)
  9885. {
  9886. if (genericArg->IsPrimitiveType())
  9887. genericArg = GetWrappedStructType(genericArg);
  9888. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  9889. if (genericArg->IsMethodRef())
  9890. {
  9891. auto methodRefType = (BfMethodRefType*)genericArg;
  9892. //AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_);
  9893. }
  9894. }
  9895. }
  9896. // Generic constraints
  9897. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  9898. {
  9899. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  9900. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  9901. }
  9902. bool addToWorkList = !processNow;
  9903. if (mCompiler->GetAutoComplete() != NULL)
  9904. {
  9905. if (typeInst->IsSpecializedByAutoCompleteMethod())
  9906. addToWorkList = false;
  9907. }
  9908. BF_ASSERT(declareModule != NULL);
  9909. methodInstance->mDeclModule = declareModule;
  9910. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  9911. {
  9912. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  9913. // of a reified module -
  9914. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  9915. // BUT if we don't reify it then we have to remove the body after processing.
  9916. // But if we declare it in the unreified module module and then end up needing to reify it then we need to re-declare it in
  9917. // the proper reified module.
  9918. declareModule = mContext->mUnreifiedModule;
  9919. }
  9920. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  9921. {
  9922. BF_ASSERT(!methodInstance->mIsReified);
  9923. declareModule = mContext->mUnreifiedModule;
  9924. }
  9925. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  9926. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  9927. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  9928. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  9929. if (processNow)
  9930. {
  9931. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  9932. ProcessMethod(methodInstance);
  9933. }
  9934. if (mCompiler->IsSkippingExtraResolveChecks())
  9935. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9936. return BfModuleMethodInstance(methodInstance);
  9937. }
  9938. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9939. {
  9940. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  9941. if (methodInstance->mIsForeignMethodDef)
  9942. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  9943. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  9944. }
  9945. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  9946. {
  9947. if (!methodInstance->mMethodDef->mIsLocalMethod)
  9948. return NULL;
  9949. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  9950. if (outerLocal == NULL)
  9951. return NULL;
  9952. BfTypeVector genericArgs;
  9953. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  9954. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  9955. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  9956. }
  9957. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  9958. {
  9959. HashContext hashCtx;
  9960. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  9961. {
  9962. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  9963. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  9964. if (methodInstance->GetNumGenericArguments() != 0)
  9965. {
  9966. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  9967. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  9968. hashCtx.Mixin(methodGenericArg->mTypeId);
  9969. }
  9970. };
  9971. _MixinMethodInstance(methodInstance);
  9972. if (methodInstance->mMethodDef->mIsLocalMethod)
  9973. {
  9974. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  9975. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  9976. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  9977. }
  9978. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  9979. }
  9980. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  9981. {
  9982. BfIRValue globalValue;
  9983. BfIRValue* globalValuePtr = NULL;
  9984. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  9985. {
  9986. globalValue = *globalValuePtr;
  9987. }
  9988. if (!globalValue)
  9989. {
  9990. // This is necessary to reify the interface type
  9991. PopulateType(ifaceType);
  9992. StringT<128> slotVarName;
  9993. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  9994. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  9995. BfIRValue value;
  9996. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  9997. {
  9998. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  9999. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  10000. int virtSlotIdx = ifaceType->mSlotNum + 1;
  10001. value = GetConstValue32(virtSlotIdx);*/
  10002. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  10003. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  10004. }
  10005. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  10006. mInterfaceSlotRefs[ifaceType] = globalValue;
  10007. }
  10008. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  10009. }
  10010. void BfModule::HadSlotCountDependency()
  10011. {
  10012. if (mCompiler->mIsResolveOnly)
  10013. return;
  10014. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  10015. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  10016. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  10017. }
  10018. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  10019. {
  10020. if (mIsScratchModule)
  10021. {
  10022. // Just fake it for the extern and unspecialized modules
  10023. auto ptrType = CreatePointerType(fieldInstance->GetResolvedType());
  10024. return BfTypedValue(GetDefaultValue(ptrType), fieldInstance->GetResolvedType(), true);
  10025. }
  10026. BfIRValue globalValue;
  10027. auto fieldDef = fieldInstance->GetFieldDef();
  10028. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  10029. {
  10030. if (fieldInstance->mConstIdx != -1)
  10031. {
  10032. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  10033. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  10034. }
  10035. else
  10036. {
  10037. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  10038. }
  10039. }
  10040. BfIRValue* globalValuePtr = NULL;
  10041. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  10042. {
  10043. globalValue = *globalValuePtr;
  10044. BF_ASSERT(globalValue);
  10045. }
  10046. else
  10047. {
  10048. StringT<128> staticVarName;
  10049. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  10050. auto typeType = fieldInstance->GetResolvedType();
  10051. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  10052. {
  10053. typeType = typeType->GetUnderlyingType();
  10054. }
  10055. PopulateType(typeType);
  10056. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  10057. {
  10058. globalValue = mBfIRBuilder->CreateGlobalVariable(
  10059. mBfIRBuilder->MapType(typeType),
  10060. false,
  10061. BfIRLinkageType_External,
  10062. BfIRValue(),
  10063. staticVarName,
  10064. IsThreadLocal(fieldInstance));
  10065. if (!mBfIRBuilder->mIgnoreWrites)
  10066. {
  10067. // Only store this if we actually did the creation
  10068. BF_ASSERT(globalValue);
  10069. mStaticFieldRefs[fieldInstance] = globalValue;
  10070. }
  10071. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  10072. }
  10073. }
  10074. auto type = fieldInstance->GetResolvedType();
  10075. if (type->IsValuelessType())
  10076. return BfTypedValue(globalValue, type);
  10077. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  10078. }
  10079. BfTypedValue BfModule::GetThis()
  10080. {
  10081. auto useMethodState = mCurMethodState;
  10082. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  10083. {
  10084. useMethodState = useMethodState->mPrevMethodState;
  10085. }
  10086. if (useMethodState != NULL)
  10087. {
  10088. // Fake a 'this' for var field resolution
  10089. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  10090. {
  10091. auto thisType = mCurTypeInstance;
  10092. if (thisType->IsValueType())
  10093. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  10094. else
  10095. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  10096. }
  10097. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  10098. {
  10099. return BfTypedValue();
  10100. }
  10101. }
  10102. else
  10103. {
  10104. //TODO: Do we allow useMethodState to be NULL anymore?
  10105. return BfTypedValue();
  10106. }
  10107. // if (useMethodState->HasNonStaticMixin())
  10108. // {
  10109. // auto checkMethodState = useMethodState;
  10110. // while (checkMethodState != NULL)
  10111. // {
  10112. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10113. // {
  10114. // auto varDecl = checkMethodState->mLocals[localIdx];
  10115. // if (varDecl->mName == "this")
  10116. // {
  10117. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10118. // if (varDecl->mIsSplat)
  10119. // {
  10120. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10121. // }
  10122. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  10123. // {
  10124. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  10125. // }
  10126. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  10127. // }
  10128. // }
  10129. //
  10130. // checkMethodState = checkMethodState->mPrevMethodState;
  10131. // }
  10132. // }
  10133. // Check mixin state for 'this'
  10134. {
  10135. auto checkMethodState = useMethodState;
  10136. while (checkMethodState != NULL)
  10137. {
  10138. if (checkMethodState->mMixinState != NULL)
  10139. {
  10140. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  10141. if (thisValue)
  10142. {
  10143. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10144. if (!thisValue.mType->IsValueType())
  10145. thisValue = LoadValue(thisValue);
  10146. return thisValue;
  10147. }
  10148. }
  10149. checkMethodState = checkMethodState->mPrevMethodState;
  10150. }
  10151. }
  10152. auto curMethodInstance = mCurMethodInstance;
  10153. if (useMethodState->mMethodInstance != NULL)
  10154. curMethodInstance = useMethodState->mMethodInstance;
  10155. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  10156. {
  10157. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  10158. {
  10159. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  10160. if (constLocal.mIsThis)
  10161. {
  10162. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  10163. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  10164. }
  10165. }
  10166. return BfTypedValue();
  10167. }
  10168. bool preferValue = !IsTargetingBeefBackend();
  10169. if (useMethodState->mLocals.IsEmpty())
  10170. {
  10171. // This can happen in rare non-capture cases, such as when we need to do a const expression resolve for a sized-array return type on a local method
  10172. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  10173. return BfTypedValue();
  10174. }
  10175. auto thisLocal = useMethodState->mLocals[0];
  10176. BF_ASSERT(thisLocal->mIsThis);
  10177. BfIRValue thisValue;
  10178. if ((preferValue) || (!thisLocal->mAddr) /*|| (thisLocal->mIsSplat)*/)
  10179. thisValue = thisLocal->mValue;
  10180. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  10181. thisValue = thisLocal->mAddr;
  10182. else
  10183. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  10184. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10185. if (useMethodState->mClosureState != NULL)
  10186. {
  10187. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  10188. if (closureTypeInst != NULL)
  10189. {
  10190. if (closureTypeInst->mFieldInstances.size() > 0)
  10191. {
  10192. auto& field = closureTypeInst->mFieldInstances[0];
  10193. auto fieldDef = field.GetFieldDef();
  10194. if (fieldDef->mName == "__this")
  10195. {
  10196. if (mCurMethodState->mClosureState->mCapturing)
  10197. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  10198. // This is a captured 'this'
  10199. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  10200. if (field.mResolvedType->IsRef())
  10201. {
  10202. auto refType = (BfRefType*)field.mResolvedType;
  10203. auto underlyingType = refType->GetUnderlyingType();
  10204. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  10205. }
  10206. if (field.mResolvedType->IsObject())
  10207. {
  10208. result = LoadValue(result);
  10209. result.mKind = BfTypedValueKind_ThisValue;
  10210. }
  10211. else
  10212. {
  10213. if (fieldDef->mIsReadOnly)
  10214. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  10215. else
  10216. result.mKind = BfTypedValueKind_ThisAddr;
  10217. }
  10218. return result;
  10219. }
  10220. }
  10221. return BfTypedValue();
  10222. }
  10223. if (useMethodState->mClosureState->mCapturing)
  10224. {
  10225. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  10226. if (thisType->IsValueType())
  10227. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  10228. else
  10229. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  10230. }
  10231. }
  10232. auto localDef = useMethodState->mLocals[0];
  10233. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  10234. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  10235. {
  10236. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  10237. {
  10238. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  10239. }
  10240. if (localDef->mIsSplat)
  10241. {
  10242. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10243. }
  10244. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  10245. }
  10246. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  10247. }
  10248. BfLocalVariable* BfModule::GetThisVariable()
  10249. {
  10250. if (mCurMethodState == NULL)
  10251. return NULL;
  10252. auto methodState = mCurMethodState->GetNonCaptureState();
  10253. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  10254. return methodState->mLocals[0];
  10255. return NULL;
  10256. }
  10257. bool BfModule::IsInGeneric()
  10258. {
  10259. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10260. }
  10261. bool BfModule::IsInSpecializedGeneric()
  10262. {
  10263. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  10264. return false;
  10265. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10266. }
  10267. bool BfModule::IsInSpecializedSection()
  10268. {
  10269. return IsInSpecializedGeneric() ||
  10270. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  10271. }
  10272. bool BfModule::IsInUnspecializedGeneric()
  10273. {
  10274. if (mCurMethodInstance != NULL)
  10275. return mCurMethodInstance->mIsUnspecialized;
  10276. return false;
  10277. }
  10278. //////////////////////////////////////////////////////////////////////////
  10279. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  10280. {
  10281. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  10282. if (type->IsValuelessType())
  10283. return mBfIRBuilder->GetFakeVal();
  10284. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  10285. if ((!doLifetimeEnd) && (WantsLifetimes()))
  10286. {
  10287. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  10288. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  10289. }
  10290. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  10291. auto typeOptions = GetTypeOptions();
  10292. if (typeOptions != NULL)
  10293. initLocalVariables = BfTypeOptions::Apply(initLocalVariables, typeOptions->mInitLocalVariables);
  10294. // Local variable inits are implicitly handled in the Beef Backend
  10295. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  10296. {
  10297. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10298. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10299. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  10300. mBfIRBuilder->ClearDebugLocation(storeInst);
  10301. mBfIRBuilder->SetInsertPoint(prevBlock);
  10302. }
  10303. return allocaInst;
  10304. }
  10305. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  10306. {
  10307. if (localVar->mResolvedType->IsVar())
  10308. {
  10309. BF_ASSERT((mCurMethodInstance->mIsUnspecialized) || (mCurMethodState->mClosureState != NULL) || (mHadVarUsage));
  10310. }
  10311. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  10312. mCurMethodState->mLocals.push_back(localVar);
  10313. BfLocalVarEntry* localVarEntryPtr;
  10314. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  10315. {
  10316. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  10317. localVarEntryPtr->mLocalVar = localVar;
  10318. }
  10319. }
  10320. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  10321. {
  10322. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()))
  10323. {
  10324. if ((!localVarDef->mValue.IsConst()) && (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  10325. {
  10326. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  10327. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  10328. }
  10329. }
  10330. if ((addDebugInfo) && (mBfIRBuilder->DbgHasInfo()) &&
  10331. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  10332. (mHasFullDebugInfo) &&
  10333. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  10334. {
  10335. auto varType = localVarDef->mResolvedType;
  10336. if (localVarDef->mResolvedType->IsValuelessType())
  10337. {
  10338. }
  10339. else
  10340. {
  10341. bool isByAddr = false;
  10342. auto diValue = localVarDef->mValue;
  10343. if (localVarDef->mConstValue)
  10344. diValue = localVarDef->mConstValue;
  10345. else if (localVarDef->mAddr)
  10346. {
  10347. diValue = localVarDef->mAddr;
  10348. isByAddr = true;
  10349. }
  10350. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  10351. bool didConstToMem = false;
  10352. bool isConstant = false;
  10353. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  10354. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10355. else if (localVarDef->mConstValue)
  10356. {
  10357. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  10358. isConstant =
  10359. (constant->mConstType < BfConstType_GlobalVar) ||
  10360. (constant->mConstType == BfConstType_AggZero) ||
  10361. (constant->mConstType == BfConstType_Array);
  10362. if (isConstant)
  10363. {
  10364. if (localVarDef->mResolvedType->IsComposite())
  10365. {
  10366. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  10367. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  10368. if (IsTargetingBeefBackend())
  10369. {
  10370. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  10371. didConstToMem = true;
  10372. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10373. }
  10374. else
  10375. {
  10376. isByAddr = true;
  10377. mBfIRBuilder->SaveDebugLocation();
  10378. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10379. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10380. mBfIRBuilder->ClearDebugLocation();
  10381. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  10382. auto addrVal = CreateAlloca(ptrType);
  10383. mBfIRBuilder->CreateStore(constMem, addrVal);
  10384. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10385. diValue = addrVal;
  10386. didConstToMem = true;
  10387. mBfIRBuilder->SetInsertPoint(prevBlock);
  10388. mBfIRBuilder->RestoreDebugLocation();
  10389. }
  10390. }
  10391. if (mCompiler->mOptions.IsCodeView())
  10392. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10393. }
  10394. }
  10395. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10396. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  10397. localVarDef->mDbgVarInst = diVariable;
  10398. if (mBfIRBuilder->HasDebugLocation())
  10399. {
  10400. if ((isConstant) && (!didConstToMem))
  10401. {
  10402. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  10403. }
  10404. else
  10405. {
  10406. if ((IsTargetingBeefBackend()) && (doAliasValue))
  10407. {
  10408. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  10409. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  10410. }
  10411. if (isByAddr)
  10412. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  10413. else if (diValue)
  10414. {
  10415. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  10416. }
  10417. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  10418. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  10419. }
  10420. }
  10421. }
  10422. }
  10423. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  10424. DoAddLocalVariable(localVarDef);
  10425. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10426. if (localVarDef->mLocalVarId == -1)
  10427. {
  10428. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  10429. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  10430. }
  10431. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10432. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  10433. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  10434. {
  10435. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  10436. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  10437. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  10438. }
  10439. return localVarDef;
  10440. }
  10441. void BfModule::CreateDIRetVal()
  10442. {
  10443. if (!WantsDebugInfo())
  10444. return;
  10445. /*if (!mCurMethodState->mRetVal)
  10446. {
  10447. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  10448. return;
  10449. }*/
  10450. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  10451. {
  10452. BF_ASSERT((!mBfIRBuilder->mIgnoreWrites) || (mHadVarUsage));
  10453. BfType* dbgType = mCurMethodInstance->mReturnType;
  10454. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  10455. if (mCurMethodInstance->HasStructRet())
  10456. {
  10457. BF_ASSERT(mCurMethodState->mRetValAddr);
  10458. dbgType = CreatePointerType(dbgType);
  10459. dbgValue = mCurMethodState->mRetValAddr;
  10460. }
  10461. else
  10462. {
  10463. BF_ASSERT(!mCurMethodState->mRetValAddr);
  10464. }
  10465. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10466. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  10467. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  10468. }
  10469. }
  10470. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  10471. {
  10472. BfLocalVarEntry* localVarEntryPtr = NULL;
  10473. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  10474. {
  10475. auto checkLocal = localVarEntryPtr->mLocalVar;
  10476. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  10477. {
  10478. BfError* error;
  10479. if (checkLocal->mIsImplicitParam)
  10480. return; // Ignore 'redefinition'
  10481. if (checkLocal->IsParam())
  10482. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  10483. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  10484. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10485. else
  10486. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10487. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  10488. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  10489. return;
  10490. }
  10491. }
  10492. }
  10493. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  10494. {
  10495. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  10496. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  10497. {
  10498. if (tokenNode->GetToken() == BfToken_Colon)
  10499. {
  10500. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  10501. {
  10502. Fail("Cannot access method scope across deferred block boundary", scopeName);
  10503. return NULL;
  10504. }
  10505. return &mCurMethodState->mHeadScope;
  10506. }
  10507. else if (tokenNode->GetToken() == BfToken_Mixin)
  10508. {
  10509. if (fromMixinState == NULL)
  10510. {
  10511. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  10512. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  10513. return mCurMethodState->mCurScope;
  10514. }
  10515. fromMixinState->mUsedInvocationScope = true;
  10516. return fromMixinState->mTargetScope;
  10517. }
  10518. else if (tokenNode->GetToken() == BfToken_New)
  10519. return NULL;
  10520. }
  10521. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  10522. {
  10523. auto findLabel = scopeName->ToString();
  10524. bool crossedDeferredBlock = false;
  10525. auto checkScope = mCurMethodState->mCurScope;
  10526. while (checkScope != NULL)
  10527. {
  10528. if (checkScope->mIsDeferredBlock)
  10529. crossedDeferredBlock = true;
  10530. if (checkScope->mLabel == findLabel)
  10531. {
  10532. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  10533. {
  10534. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  10535. return NULL;
  10536. }
  10537. return checkScope;
  10538. }
  10539. checkScope = checkScope->mPrevScope;
  10540. }
  10541. if (!inMixinDecl)
  10542. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  10543. }
  10544. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  10545. {
  10546. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  10547. }
  10548. return mCurMethodState->mCurScope;
  10549. }
  10550. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  10551. {
  10552. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  10553. }
  10554. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  10555. {
  10556. auto scopeData = FindScope(scopeName, false);
  10557. if (scopeData == NULL)
  10558. return NULL;
  10559. int scopeDepth = scopeData->GetDepth();
  10560. // Find the first break data that is at or below the depth of our requested scope
  10561. auto breakData = mCurMethodState->mBreakData;
  10562. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  10563. {
  10564. if (breakData->mScope->mIsConditional)
  10565. return NULL;
  10566. breakData = breakData->mPrevBreakData;
  10567. }
  10568. return breakData;
  10569. }
  10570. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  10571. {
  10572. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  10573. if (!IsTargetingBeefBackend())
  10574. return;
  10575. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  10576. {
  10577. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10578. }
  10579. }
  10580. void BfModule::ClearLifetimeEnds()
  10581. {
  10582. auto scopeData = mCurMethodState->mCurScope;
  10583. while (scopeData != NULL)
  10584. {
  10585. scopeData->mDeferredLifetimeEnds.Clear();
  10586. scopeData = scopeData->mPrevScope;
  10587. }
  10588. }
  10589. bool BfModule::WantsDebugInfo()
  10590. {
  10591. if ((mCurMethodInstance != NULL) &&
  10592. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  10593. return false;
  10594. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  10595. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  10596. }
  10597. BfTypeOptions* BfModule::GetTypeOptions()
  10598. {
  10599. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  10600. return mCurMethodState->mMethodTypeOptions;
  10601. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  10602. }
  10603. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  10604. {
  10605. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10606. while (checkScope != NULL)
  10607. {
  10608. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  10609. return true;
  10610. if (checkScope == scope)
  10611. break;
  10612. checkScope = checkScope->mPrevScope;
  10613. }
  10614. return false;
  10615. }
  10616. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  10617. {
  10618. // Is there anything we need to do here?
  10619. if (mBfIRBuilder->mIgnoreWrites)
  10620. {
  10621. // Just visit deferred blocks
  10622. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10623. while (checkScope != NULL)
  10624. {
  10625. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10626. while (deferredCallEntry != NULL)
  10627. {
  10628. if (deferredCallEntry->mDeferredBlock != NULL)
  10629. {
  10630. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  10631. }
  10632. deferredCallEntry = deferredCallEntry->mNext;
  10633. }
  10634. if (checkScope == scopeData)
  10635. break;
  10636. checkScope = checkScope->mPrevScope;
  10637. }
  10638. return;
  10639. }
  10640. // Why did we want to do SetIllegalSrcPos here?
  10641. // Don't we always want to step onto these instances?
  10642. // Find a case where we don't and perhaps only do it there.
  10643. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  10644. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  10645. //SetIllegalSrcPos();
  10646. bool setSrcPos = false;
  10647. bool wantsNop = true;
  10648. BfAstNode* deferCloseNode = NULL;
  10649. if (mCurMethodState->mInPostReturn)
  10650. {
  10651. // These won't get used, they are post-return
  10652. return;
  10653. }
  10654. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  10655. BfScopeData* scopeJumpBlock = NULL;
  10656. bool hadExtraDeferredLifetimeEnds = false;
  10657. auto _FlushLifetimeEnds = [&]()
  10658. {
  10659. for (auto lifetimeEnd : deferredLifetimeEnds)
  10660. {
  10661. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10662. mBfIRBuilder->ClearDebugLocation_Last();
  10663. }
  10664. deferredLifetimeEnds.clear();
  10665. };
  10666. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10667. while (checkScope != NULL)
  10668. {
  10669. if (checkScope->mCloseNode != NULL)
  10670. deferCloseNode = checkScope->mCloseNode;
  10671. if (doneBlock)
  10672. {
  10673. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  10674. for (auto& checkHandler : checkScope->mDeferredHandlers)
  10675. {
  10676. if (checkHandler.mDoneBlock == doneBlock)
  10677. {
  10678. scopeJumpBlock = checkScope;
  10679. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  10680. mBfIRBuilder->ClearDebugLocation_Last();
  10681. _FlushLifetimeEnds();
  10682. break;
  10683. }
  10684. }
  10685. if (scopeJumpBlock != NULL)
  10686. break;
  10687. }
  10688. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  10689. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  10690. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  10691. if (hasWork)
  10692. {
  10693. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  10694. if (deferCloseNode != NULL)
  10695. {
  10696. UpdateSrcPos(deferCloseNode);
  10697. }
  10698. if (doneBlock)
  10699. {
  10700. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  10701. String blockName = "deferredCalls";
  10702. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  10703. BfDeferredHandler deferredHandler;
  10704. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  10705. {
  10706. mBfIRBuilder->SaveDebugLocation();
  10707. mBfIRBuilder->ClearDebugLocation();
  10708. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  10709. mBfIRBuilder->RestoreDebugLocation();
  10710. }
  10711. else
  10712. {
  10713. // Definitely chain
  10714. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  10715. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  10716. mBfIRBuilder->ClearDebugLocation_Last();
  10717. _FlushLifetimeEnds();
  10718. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  10719. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  10720. }
  10721. deferredHandler.mDoneBlock = doneBlock;
  10722. if (!mBfIRBuilder->mIgnoreWrites)
  10723. checkScope->mDeferredHandlers.push_back(deferredHandler);
  10724. if (checkScope == &mCurMethodState->mHeadScope)
  10725. {
  10726. if (!mCurMethodState->mDIRetVal)
  10727. {
  10728. // Weird case- if we have a return from a mixin, we need the DbgLoc to be for the mixin but we need the DIRetVal to
  10729. // be scoped to the physical method
  10730. /*if (deferCloseNode != NULL)
  10731. {
  10732. UpdateSrcPos(deferCloseNode);
  10733. }*/
  10734. CreateDIRetVal();
  10735. }
  10736. }
  10737. if (checkScope != mCurMethodState->mTailScope)
  10738. {
  10739. if (deferredHandler.mHandlerBlock.IsFake())
  10740. {
  10741. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  10742. }
  10743. if (!mBfIRBuilder->mIgnoreWrites)
  10744. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  10745. }
  10746. }
  10747. std::unordered_set<BfDeferredCallEntry*> handledSet;
  10748. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10749. while (deferredCallEntry != NULL)
  10750. {
  10751. BfDeferredCallEmitState deferredCallEmitState;
  10752. deferredCallEmitState.mCloseNode = deferCloseNode;
  10753. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  10754. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  10755. if (deferCloseNode != NULL)
  10756. {
  10757. UpdateSrcPos(deferCloseNode);
  10758. }
  10759. if (wantsNop)
  10760. EmitEnsureInstructionAt();
  10761. wantsNop = false;
  10762. if (deferredCallEntry->mDeferredBlock != NULL)
  10763. {
  10764. auto itr = handledSet.insert(deferredCallEntry);
  10765. if (!itr.second)
  10766. {
  10767. // Already handled, can happen if we defer again within the block
  10768. deferredCallEntry = deferredCallEntry->mNext;
  10769. continue;
  10770. }
  10771. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  10772. EmitDeferredCall(*deferredCallEntry);
  10773. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  10774. {
  10775. // The list changed, start over and ignore anything we've already handled
  10776. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10777. }
  10778. else
  10779. deferredCallEntry = deferredCallEntry->mNext;
  10780. }
  10781. else
  10782. {
  10783. EmitDeferredCall(*deferredCallEntry);
  10784. deferredCallEntry = deferredCallEntry->mNext;
  10785. }
  10786. }
  10787. if (checkScope->mSavedStack)
  10788. {
  10789. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  10790. if (mCurMethodState->mDynStackRevIdx)
  10791. {
  10792. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  10793. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  10794. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  10795. }
  10796. }
  10797. }
  10798. if (!checkScope->mIsScopeHead)
  10799. {
  10800. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  10801. if (!IsTargetingBeefBackend())
  10802. {
  10803. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10804. {
  10805. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10806. }
  10807. }
  10808. else
  10809. {
  10810. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10811. {
  10812. deferredLifetimeEnds.Add(lifetimeEnd);
  10813. }
  10814. }
  10815. }
  10816. if (checkScope == scopeData)
  10817. break;
  10818. checkScope = checkScope->mPrevScope;
  10819. }
  10820. if ((doneBlock) && (scopeJumpBlock == NULL))
  10821. {
  10822. mBfIRBuilder->CreateBr(doneBlock);
  10823. mBfIRBuilder->ClearDebugLocation_Last();
  10824. }
  10825. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  10826. // may have been created when other scope lifetimes were available
  10827. _FlushLifetimeEnds();
  10828. // Emit lifetimeEnds after the branch for Beef
  10829. /*if (IsTargetingBeefBackend())
  10830. {
  10831. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  10832. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10833. while (checkScope != NULL)
  10834. {
  10835. if (checkScope == scopeJumpBlock)
  10836. break;
  10837. if (!checkScope->mIsScopeHead)
  10838. {
  10839. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10840. {
  10841. if (needsEnsureInst)
  10842. {
  10843. needsEnsureInst = false;
  10844. }
  10845. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10846. }
  10847. }
  10848. if (checkScope == scopeData)
  10849. break;
  10850. checkScope = checkScope->mPrevScope;
  10851. }
  10852. }*/
  10853. }
  10854. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  10855. {
  10856. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  10857. {
  10858. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  10859. while (deferredLocalAssignData != NULL)
  10860. {
  10861. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  10862. break;
  10863. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  10864. deferredLocalAssignData->mIsUnconditional = false;
  10865. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  10866. }
  10867. }
  10868. //for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  10869. // We mark all unassigned variables as assigned now, for avoiding "may be unassigned" usage cases like:
  10870. // int b;
  10871. // if (cond) return;
  10872. // else b = 1;
  10873. // Use(b);
  10874. for (int localIdx = 0; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  10875. {
  10876. auto localDef = mCurMethodState->mLocals[localIdx];
  10877. if ((!localDef->mIsAssigned) && (!localDef->IsParam()))
  10878. mCurMethodState->LocalDefined(localDef);
  10879. }
  10880. }
  10881. void BfModule::CreateReturn(BfIRValue val)
  10882. {
  10883. if (mCurMethodInstance->mReturnType->IsComposite())
  10884. {
  10885. // Store to sret
  10886. BF_ASSERT(val);
  10887. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(0));
  10888. mBfIRBuilder->CreateRetVoid();
  10889. }
  10890. else
  10891. {
  10892. if (mCurMethodInstance->mReturnType->IsValuelessType())
  10893. {
  10894. mBfIRBuilder->CreateRetVoid();
  10895. }
  10896. else
  10897. {
  10898. BF_ASSERT(val);
  10899. mBfIRBuilder->CreateRet(val);
  10900. }
  10901. }
  10902. }
  10903. void BfModule::EmitReturn(BfIRValue val)
  10904. {
  10905. if (mCurMethodState->mIRExitBlock)
  10906. {
  10907. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  10908. {
  10909. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  10910. {
  10911. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  10912. if (!mCurMethodState->mRetVal)
  10913. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  10914. mBfIRBuilder->CreateStore(val, retVal);
  10915. }
  10916. }
  10917. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  10918. }
  10919. else
  10920. {
  10921. EmitDeferredScopeCalls(false, NULL);
  10922. if (mCurMethodInstance->mReturnType->IsValuelessType())
  10923. mBfIRBuilder->CreateRetVoid();
  10924. else
  10925. mBfIRBuilder->CreateRet(val);
  10926. }
  10927. mCurMethodState->SetHadReturn(true);
  10928. mCurMethodState->mLeftBlockUncond = true;
  10929. }
  10930. void BfModule::EmitDefaultReturn()
  10931. {
  10932. if (mCurMethodState->mInDeferredBlock)
  10933. return;
  10934. if (mCurMethodState->mIRExitBlock)
  10935. {
  10936. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  10937. }
  10938. else
  10939. {
  10940. if (mCurMethodInstance->mReturnType->IsVoid())
  10941. mBfIRBuilder->CreateRetVoid();
  10942. else
  10943. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  10944. }
  10945. mCurMethodState->SetHadReturn(true);
  10946. mCurMethodState->mLeftBlockUncond = true;
  10947. }
  10948. void BfModule::AssertErrorState()
  10949. {
  10950. if (mIgnoreErrors)
  10951. return;
  10952. if (mHadBuildError)
  10953. return;
  10954. if (mCurTypeInstance != NULL)
  10955. {
  10956. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  10957. return;
  10958. }
  10959. if (mCurMethodInstance != NULL)
  10960. {
  10961. if (mCurMethodInstance->mIsUnspecializedVariation)
  10962. return;
  10963. }
  10964. // We want the module to be marked as failed even if it's just an error in the parser
  10965. if (mCurMethodInstance != NULL)
  10966. mCurMethodInstance->mHasFailed = true;
  10967. mHadBuildError = true;
  10968. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  10969. if (mCurTypeInstance != NULL)
  10970. {
  10971. if (mCurTypeInstance->mTypeFailed)
  10972. return;
  10973. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  10974. return;
  10975. }
  10976. if (mCurMethodInstance != NULL)
  10977. {
  10978. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  10979. return;
  10980. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  10981. return;
  10982. }
  10983. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  10984. }
  10985. void BfModule::AssertParseErrorState()
  10986. {
  10987. if (mCompiler->mRevision == 1)
  10988. AssertErrorState();
  10989. }
  10990. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  10991. {
  10992. BF_ASSERT(delegateType->IsDelegate());
  10993. auto typeInst = delegateType->ToTypeInstance();
  10994. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  10995. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  10996. return invokeMethodInstance->mReturnType;
  10997. }
  10998. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  10999. {
  11000. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  11001. }
  11002. void BfModule::CreateDelegateInvokeMethod()
  11003. {
  11004. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  11005. //mBfIRBuilder->ClearDebugLocation();
  11006. SetIllegalSrcPos();
  11007. auto typeInstance = mCurTypeInstance;
  11008. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  11009. SizedArray<BfIRType, 4> staticParamTypes;
  11010. SizedArray<BfIRValue, 4> staticFuncArgs;
  11011. SizedArray<BfIRValue, 4> memberFuncArgs;
  11012. auto multicastDelegateType = typeInstance->mBaseType;
  11013. if (multicastDelegateType->mFieldInstances.size() != 2)
  11014. {
  11015. AssertErrorState();
  11016. return;
  11017. }
  11018. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  11019. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  11020. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  11021. BfExprEvaluator exprEvaluator(this);
  11022. SizedArray<BfIRType, 8> origParamTypes;
  11023. BfIRType origReturnType;
  11024. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  11025. if (mCurMethodInstance->mReturnType->IsValueType())
  11026. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  11027. int thisIdx = 0;
  11028. if (mCurMethodInstance->HasStructRet())
  11029. {
  11030. thisIdx = 1;
  11031. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11032. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11033. }
  11034. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  11035. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  11036. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  11037. {
  11038. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  11039. exprEvaluator.PushArg(localVal, staticFuncArgs);
  11040. exprEvaluator.PushArg(localVal, memberFuncArgs);
  11041. }
  11042. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  11043. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  11044. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  11045. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  11046. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  11047. auto doneBB = mBfIRBuilder->CreateBlock("done");
  11048. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  11049. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  11050. BfIRValue nonStaticResult;
  11051. BfIRValue staticResult;
  11052. auto callingConv = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11053. /// Non-static invocation
  11054. {
  11055. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11056. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  11057. mBfIRBuilder->SetInsertPoint(trueBB);
  11058. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  11059. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11060. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  11061. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11062. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  11063. if (callingConv != BfIRCallingConv_CDecl)
  11064. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  11065. mCurMethodState->SetHadReturn(false);
  11066. mCurMethodState->mLeftBlockUncond = false;
  11067. mCurMethodState->mLeftBlockCond = false;
  11068. mBfIRBuilder->CreateBr(doneBB);
  11069. }
  11070. // Static invocation
  11071. {
  11072. mBfIRBuilder->AddBlock(falseBB);
  11073. mBfIRBuilder->SetInsertPoint(falseBB);
  11074. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11075. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  11076. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11077. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  11078. if (callingConv == BfIRCallingConv_ThisCall)
  11079. callingConv = BfIRCallingConv_CDecl;
  11080. if (callingConv != BfIRCallingConv_CDecl)
  11081. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  11082. // if (!mSystem->IsCompatibleCallingConvention(BfCallingConvention_Unspecified, mCurMethodInstance->mMethodDef->mCallingConvention))
  11083. // {
  11084. // if (mCurMethodInstance->mMethodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11085. //
  11086. // }
  11087. mCurMethodState->SetHadReturn(false);
  11088. mCurMethodState->mLeftBlockUncond = false;
  11089. mCurMethodState->mLeftBlockCond = false;
  11090. mBfIRBuilder->CreateBr(doneBB);
  11091. }
  11092. mBfIRBuilder->AddBlock(doneBB);
  11093. mBfIRBuilder->SetInsertPoint(doneBB);
  11094. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->HasStructRet()))
  11095. {
  11096. mBfIRBuilder->CreateRetVoid();
  11097. }
  11098. else
  11099. {
  11100. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(mCurMethodInstance->mReturnType), 2);
  11101. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  11102. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  11103. mBfIRBuilder->CreateRet(phi);
  11104. }
  11105. }
  11106. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  11107. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  11108. {
  11109. auto typeDef = typeInstance->mTypeDef;
  11110. auto methodDeclaration = methodDef->mMethodDeclaration;
  11111. if (!mCompiler->mIsResolveOnly)
  11112. return true;
  11113. if (typeInstance->IsGenericTypeInstance())
  11114. {
  11115. // We only really want to process the unspecialized type for autocompletion
  11116. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  11117. return false;
  11118. }
  11119. BfAstNode* checkNode = methodDeclaration;
  11120. if (methodDeclaration == NULL)
  11121. checkNode = methodDef->mBody;
  11122. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  11123. {
  11124. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  11125. return true;
  11126. }
  11127. return false;
  11128. }
  11129. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  11130. {
  11131. methodInst->mAppendAllocAlign = 1;
  11132. }
  11133. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  11134. {
  11135. BP_ZONE("BfModule::TryConstCalcAppend");
  11136. if (mCompiler->mIsResolveOnly)
  11137. return BfTypedValue();
  11138. // We want to regenerate all ctor calls when the method internals change
  11139. {
  11140. auto checkTypeInst = methodInst->GetOwner();
  11141. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  11142. {
  11143. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  11144. checkTypeInst = GetBaseType(checkTypeInst);
  11145. }
  11146. }
  11147. if (!methodInst->mMayBeConst)
  11148. return BfTypedValue();
  11149. // Do we need to iterate in order to resolve mAppendAllocAlign?
  11150. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  11151. bool wasAllConst = true;
  11152. int argIdx = 0;
  11153. int paramIdx = 0;
  11154. while (true)
  11155. {
  11156. if (argIdx >= (int)args.size())
  11157. break;
  11158. auto paramType = methodInst->GetParamType(paramIdx);
  11159. PopulateType(paramType);
  11160. int argCount = 0;
  11161. if (!paramType->IsValuelessType())
  11162. {
  11163. if (methodInst->GetParamIsSplat(paramIdx))
  11164. argCount = paramType->GetSplatCount();
  11165. else
  11166. argCount = 1;
  11167. for (int argOfs = 0; argOfs < argCount; argOfs++)
  11168. {
  11169. auto arg = args[argIdx + argOfs];
  11170. if (!arg.IsConst())
  11171. {
  11172. wasAllConst = false;
  11173. if (!isFirstRun)
  11174. {
  11175. auto& param = methodInst->mParams[argIdx];
  11176. if (param.mReferencedInConstPass)
  11177. {
  11178. // If this param is required as part of the const calculation then
  11179. // we require that it be const...
  11180. return BfTypedValue();
  11181. }
  11182. }
  11183. }
  11184. }
  11185. }
  11186. paramIdx++;
  11187. argIdx += argCount;
  11188. }
  11189. auto methodDef = methodInst->mMethodDef;
  11190. auto methodDecl = methodDef->GetMethodDeclaration();
  11191. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11192. if (methodDeclBlock == NULL)
  11193. return BfTypedValue();
  11194. BfTypedValue constValue;
  11195. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11196. auto checkState = mCurMethodState->mConstResolveState;
  11197. while (checkState != NULL)
  11198. {
  11199. if (checkState->mMethodInstance == methodInst)
  11200. {
  11201. return BfTypedValue();
  11202. }
  11203. checkState = checkState->mPrevConstResolveState;
  11204. }
  11205. //auto accumValue = GetConstValue(0);
  11206. bool failed = false;
  11207. //
  11208. {
  11209. BfConstResolveState constResolveState;
  11210. constResolveState.mMethodInstance = methodInst;
  11211. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  11212. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11213. BfMethodState methodState;
  11214. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  11215. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  11216. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  11217. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  11218. methodState.mConstResolveState = &constResolveState;
  11219. int argIdx = 0;
  11220. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11221. {
  11222. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  11223. continue;
  11224. auto paramType = methodInst->GetParamType(paramIdx);
  11225. // Fix this after we allow structs to be consts
  11226. //BF_ASSERT(!paramType->IsSplattable());
  11227. BfLocalVariable* localVar = new BfLocalVariable();
  11228. localVar->mName = methodInst->GetParamName(paramIdx);
  11229. localVar->mResolvedType = paramType;
  11230. localVar->mConstValue = args[argIdx];
  11231. localVar->mParamIdx = paramIdx;
  11232. AddLocalVariableDef(localVar);
  11233. argIdx++;
  11234. }
  11235. AppendAllocVisitor appendAllocVisitor;
  11236. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  11237. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  11238. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  11239. if (baseCtorAppendValue)
  11240. {
  11241. if (baseCtorAppendValue.mValue.IsFake())
  11242. appendAllocVisitor.mFailed = true;
  11243. else
  11244. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  11245. }
  11246. appendAllocVisitor.mModule = this;
  11247. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11248. if (!appendAllocVisitor.mFailed)
  11249. constValue = appendAllocVisitor.mConstAccum;
  11250. if (isFirstRun)
  11251. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  11252. if (isFirstRun)
  11253. {
  11254. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11255. {
  11256. auto localVar = mCurMethodState->mLocals[paramIdx];
  11257. if (localVar->mReadFromId != -1)
  11258. {
  11259. auto& param = methodInst->mParams[paramIdx];
  11260. param.mReferencedInConstPass = true;
  11261. }
  11262. }
  11263. }
  11264. }
  11265. mBfIRBuilder->SetInsertPoint(prevBlock);
  11266. if (!constValue)
  11267. {
  11268. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  11269. // all-const args
  11270. if (wasAllConst)
  11271. {
  11272. methodInst->mMayBeConst = false;
  11273. }
  11274. }
  11275. return constValue;
  11276. }
  11277. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  11278. {
  11279. // Any errors should only be shown in the actual CTOR call
  11280. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  11281. auto methodDef = mCurMethodInstance->mMethodDef;
  11282. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  11283. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11284. BfTypeInstance* targetType = NULL;
  11285. if (ctorDeclaration->mInitializer != NULL)
  11286. {
  11287. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11288. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11289. }
  11290. else
  11291. targetType = mCurTypeInstance->mBaseType;
  11292. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  11293. return NULL;
  11294. auto targetRefNode = methodDef->GetRefNode();
  11295. BfType* targetThisType = targetType;
  11296. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  11297. BfExprEvaluator exprEvaluator(this);
  11298. BfResolvedArgs argValues;
  11299. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11300. {
  11301. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11302. }
  11303. //
  11304. {
  11305. }
  11306. BfFunctionBindResult bindResult;
  11307. bindResult.mSkipThis = true;
  11308. bindResult.mWantsArgs = true;
  11309. {
  11310. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11311. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11312. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11313. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11314. }
  11315. if (bindResult.mMethodInstance == NULL)
  11316. {
  11317. AssertErrorState();
  11318. return BfTypedValue();
  11319. }
  11320. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  11321. {
  11322. return BfTypedValue();
  11323. }
  11324. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11325. bindResult.mIRArgs.RemoveAt(0);
  11326. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  11327. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  11328. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  11329. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  11330. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  11331. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  11332. if (appendSizeTypedValue)
  11333. return appendSizeTypedValue;
  11334. if (constOnly)
  11335. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  11336. bool needsRecalc = false;
  11337. for (auto irArg : bindResult.mIRArgs)
  11338. {
  11339. if (irArg.IsFake())
  11340. needsRecalc = true;
  11341. }
  11342. auto calcAppendArgs = bindResult.mIRArgs;
  11343. if (needsRecalc)
  11344. {
  11345. // Do it again, but without mIgnoreWrites set
  11346. BfResolvedArgs argValues;
  11347. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11348. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11349. BfFunctionBindResult bindResult;
  11350. bindResult.mSkipThis = true;
  11351. bindResult.mWantsArgs = true;
  11352. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11353. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11354. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11355. bindResult.mIRArgs.RemoveAt(0);
  11356. calcAppendArgs = bindResult.mIRArgs;
  11357. }
  11358. BF_ASSERT(calcAppendMethodModule.mFunc);
  11359. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  11360. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  11361. return appendSizeTypedValue;
  11362. }
  11363. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  11364. void BfModule::EmitCtorCalcAppend()
  11365. {
  11366. if (mCompiler->mIsResolveOnly)
  11367. return;
  11368. auto methodDef = mCurMethodInstance->mMethodDef;
  11369. auto methodDecl = methodDef->GetMethodDeclaration();
  11370. Array<BfAstNode*> deferredNodeList;
  11371. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11372. if (methodDeclBlock == NULL)
  11373. return;
  11374. AppendAllocVisitor appendAllocVisitor;
  11375. auto baseCalcAppend = CallBaseCtorCalc(false);
  11376. if (baseCalcAppend)
  11377. {
  11378. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  11379. }
  11380. appendAllocVisitor.mModule = this;
  11381. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11382. }
  11383. void BfModule::CreateStaticCtor()
  11384. {
  11385. auto typeDef = mCurTypeInstance->mTypeDef;
  11386. auto methodDef = mCurMethodInstance->mMethodDef;
  11387. BfIRBlock exitBB;
  11388. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  11389. {
  11390. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  11391. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  11392. mBfIRBuilder->MapType(boolType),
  11393. false,
  11394. BfIRLinkageType_Internal,
  11395. GetDefaultValue(boolType),
  11396. "didStaticInit");
  11397. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  11398. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  11399. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  11400. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  11401. mBfIRBuilder->SetInsertPoint(initBB);
  11402. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  11403. }
  11404. // Do DLL imports
  11405. if (!mDllImportEntries.empty())
  11406. {
  11407. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  11408. PopulateType(internalType);
  11409. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  11410. if (!getSharedProcAddressInstance)
  11411. {
  11412. if (!mCompiler->mPassInstance->HasFailed())
  11413. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  11414. }
  11415. }
  11416. // Fill in initializer values
  11417. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11418. {
  11419. for (auto fieldDef : typeDef->mFields)
  11420. {
  11421. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  11422. {
  11423. // For extensions, only handle these fields in the appropriate extension
  11424. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  11425. continue;
  11426. UpdateSrcPos(fieldDef->mInitializer);
  11427. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  11428. if (!fieldInst->mFieldIncluded)
  11429. continue;
  11430. if (fieldInst->mResolvedType->IsVar())
  11431. {
  11432. BF_ASSERT(mHadVarUsage);
  11433. continue;
  11434. }
  11435. auto assignValue = GetFieldInitializerValue(fieldInst);
  11436. if (assignValue)
  11437. {
  11438. assignValue = LoadValue(assignValue);
  11439. if (!assignValue.mType->IsValuelessType())
  11440. {
  11441. auto staticVarRef = ReferenceStaticField(fieldInst).mValue;
  11442. mBfIRBuilder->CreateStore(assignValue.mValue, staticVarRef);
  11443. }
  11444. }
  11445. }
  11446. }
  11447. }
  11448. else
  11449. {
  11450. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11451. {
  11452. if (tempTypeDef->mFullName == typeDef->mFullName)
  11453. {
  11454. for (auto fieldDef : tempTypeDef->mFields)
  11455. {
  11456. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  11457. {
  11458. if (fieldDef->mInitializer != NULL)
  11459. {
  11460. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  11461. {
  11462. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  11463. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  11464. }
  11465. BfType* wantType = NULL;
  11466. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  11467. {
  11468. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  11469. }
  11470. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  11471. }
  11472. }
  11473. }
  11474. }
  11475. }
  11476. }
  11477. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11478. CallChainedMethods(mCurMethodInstance, false);
  11479. }
  11480. void BfModule::EmitDtorBody()
  11481. {
  11482. if (mCurTypeInstance->IsClosure())
  11483. {
  11484. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  11485. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  11486. auto thisVal = GetThis();
  11487. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  11488. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  11489. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11490. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  11491. SizedArray<BfIRValue, 1> args;
  11492. args.push_back(thisVal.mValue);
  11493. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  11494. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11495. // Fall through to Object::~this call
  11496. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  11497. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  11498. SizedArray<BfIRValue, 1> vals = { basePtr };
  11499. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  11500. mBfIRBuilder->SetCallCallingConv(result, GetCallingConvention(dtorFunc.mMethodInstance));
  11501. mBfIRBuilder->SetTailCall(result);
  11502. return;
  11503. }
  11504. auto typeDef = mCurTypeInstance->mTypeDef;
  11505. auto methodDef = mCurMethodInstance->mMethodDef;
  11506. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11507. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11508. CallChainedMethods(mCurMethodInstance, true);
  11509. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11510. {
  11511. VisitCodeBlock(bodyBlock);
  11512. if (bodyBlock->mCloseBrace != NULL)
  11513. {
  11514. UpdateSrcPos(bodyBlock->mCloseBrace);
  11515. }
  11516. }
  11517. else
  11518. {
  11519. if (methodDeclaration != NULL)
  11520. UpdateSrcPos(methodDeclaration);
  11521. else if (typeDef->mTypeDeclaration != NULL)
  11522. UpdateSrcPos(typeDef->mTypeDeclaration);
  11523. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  11524. {
  11525. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken);
  11526. }
  11527. }
  11528. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11529. {
  11530. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  11531. {
  11532. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  11533. auto fieldDef = fieldInst->GetFieldDef();
  11534. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  11535. {
  11536. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  11537. {
  11538. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken);
  11539. }
  11540. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  11541. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11542. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  11543. continue;
  11544. UpdateSrcPos(fieldDtor);
  11545. BfScopeData scopeData;
  11546. mCurMethodState->AddScope(&scopeData);
  11547. NewScopeState();
  11548. UpdateSrcPos(fieldDtor);
  11549. bool hasDbgInfo = (!fieldDef->mIsConst);
  11550. if (hasDbgInfo)
  11551. {
  11552. mBfIRBuilder->SaveDebugLocation();
  11553. mBfIRBuilder->ClearDebugLocation();
  11554. }
  11555. BfIRValue value;
  11556. if (fieldDef->mIsStatic)
  11557. {
  11558. value = ReferenceStaticField(fieldInst).mValue;
  11559. }
  11560. else
  11561. {
  11562. if (!mCurTypeInstance->IsValueType())
  11563. {
  11564. auto thisValue = GetThis();
  11565. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  11566. }
  11567. else
  11568. {
  11569. AssertErrorState();
  11570. value = mBfIRBuilder->CreateConstNull(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInst->mResolvedType)));
  11571. }
  11572. }
  11573. BfIRValue staticVal;
  11574. if (hasDbgInfo)
  11575. {
  11576. BfIRValue dbgShowValue = value;
  11577. BfLocalVariable* localDef = new BfLocalVariable();
  11578. localDef->mName = "_";
  11579. localDef->mResolvedType = fieldInst->mResolvedType;
  11580. localDef->mAddr = value;
  11581. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  11582. {
  11583. // Create another pointer indirection, a ref to the gep
  11584. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  11585. auto allocaInst = CreateAlloca(refFieldType);
  11586. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  11587. localDef->mResolvedType = refFieldType;
  11588. localDef->mAddr = allocaInst;
  11589. }
  11590. mBfIRBuilder->RestoreDebugLocation();
  11591. auto defLocalVar = AddLocalVariableDef(localDef, true);
  11592. // Put back so we actually modify the correct value*/
  11593. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  11594. defLocalVar->mAddr = value;
  11595. }
  11596. while (fieldDtor != NULL)
  11597. {
  11598. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11599. {
  11600. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11601. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11602. }
  11603. UpdateSrcPos(fieldDtor);
  11604. VisitEmbeddedStatement(fieldDtor->mBody);
  11605. fieldDtor = fieldDtor->mNextFieldDtor;
  11606. }
  11607. RestoreScopeState();
  11608. }
  11609. }
  11610. if (!methodDef->mIsStatic)
  11611. {
  11612. auto checkBaseType = mCurTypeInstance->mBaseType;
  11613. while (checkBaseType != NULL)
  11614. {
  11615. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11616. {
  11617. if (bodyBlock->mCloseBrace != NULL)
  11618. UpdateSrcPos(bodyBlock->mCloseBrace);
  11619. }
  11620. else
  11621. {
  11622. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  11623. }
  11624. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  11625. {
  11626. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  11627. if (mCompiler->IsSkippingExtraResolveChecks())
  11628. {
  11629. // Nothing
  11630. }
  11631. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  11632. {
  11633. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  11634. {
  11635. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  11636. SizedArray<BfIRValue, 1> vals = { basePtr };
  11637. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  11638. mBfIRBuilder->SetCallCallingConv(callInst, GetCallingConvention(dtorMethodInstance.mMethodInstance));
  11639. }
  11640. }
  11641. else
  11642. {
  11643. // Invalid base dtor declaration
  11644. AssertErrorState();
  11645. }
  11646. break;
  11647. }
  11648. checkBaseType = checkBaseType->mBaseType;
  11649. }
  11650. }
  11651. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  11652. }
  11653. else
  11654. {
  11655. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  11656. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  11657. // resolve pass, NOT the autocomplete expression
  11658. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11659. {
  11660. if (tempTypeDef->mFullName == typeDef->mFullName)
  11661. {
  11662. for (auto fieldDef : tempTypeDef->mFields)
  11663. {
  11664. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  11665. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11666. {
  11667. BfType* fieldType = NULL;
  11668. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  11669. {
  11670. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  11671. auto curFieldDef = curFieldInstance->GetFieldDef();
  11672. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  11673. fieldType = curFieldInstance->GetResolvedType();
  11674. }
  11675. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11676. BfScopeData scopeData;
  11677. mCurMethodState->AddScope(&scopeData);
  11678. NewScopeState();
  11679. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  11680. if (fieldType != NULL)
  11681. {
  11682. BfLocalVariable* localDef = new BfLocalVariable();
  11683. localDef->mName = "_";
  11684. localDef->mResolvedType = fieldType;
  11685. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  11686. localDef->mIsAssigned = true;
  11687. AddLocalVariableDef(localDef);
  11688. }
  11689. while (fieldDtor != NULL)
  11690. {
  11691. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11692. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11693. UpdateSrcPos(fieldDtor);
  11694. VisitEmbeddedStatement(fieldDtor->mBody);
  11695. fieldDtor = fieldDtor->mNextFieldDtor;
  11696. }
  11697. RestoreScopeState();
  11698. }
  11699. }
  11700. }
  11701. }
  11702. }
  11703. }
  11704. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  11705. {
  11706. auto typeInstance = methodInstance->GetOwner();
  11707. bool foundDllImportAttr = false;
  11708. BfCallingConvention callingConvention = methodInstance->mMethodDef->mCallingConvention;
  11709. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  11710. {
  11711. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  11712. {
  11713. foundDllImportAttr = true;
  11714. }
  11715. }
  11716. if (!foundDllImportAttr)
  11717. {
  11718. AssertErrorState();
  11719. return BfIRValue();
  11720. }
  11721. String name = "bf_hs_preserve@";
  11722. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  11723. name += "__imp";
  11724. BfIRType returnType;
  11725. SizedArray<BfIRType, 8> paramTypes;
  11726. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11727. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11728. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  11729. BfIRValue initVal;
  11730. if (define)
  11731. {
  11732. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  11733. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  11734. }
  11735. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  11736. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  11737. {
  11738. auto voidType = GetPrimitiveType(BfTypeCode_None);
  11739. auto ptrType = CreatePointerType(voidType);
  11740. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  11741. }
  11742. return globalVar;
  11743. }
  11744. void BfModule::CreateDllImportMethod()
  11745. {
  11746. if (mBfIRBuilder->mIgnoreWrites)
  11747. return;
  11748. auto globalVar = mFuncReferences[mCurMethodInstance];
  11749. if (!globalVar)
  11750. return;
  11751. bool allowTailCall = true;
  11752. mBfIRBuilder->ClearDebugLocation();
  11753. bool isHotCompile = mCompiler->IsHotCompile();
  11754. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  11755. if (isHotCompile)
  11756. {
  11757. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  11758. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  11759. }
  11760. auto callingConvention = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11761. BfIRType returnType;
  11762. SizedArray<BfIRType, 8> paramTypes;
  11763. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11764. SizedArray<BfIRValue, 8> args;
  11765. for (int i = 0; i < (int)paramTypes.size(); i++)
  11766. args.push_back(mBfIRBuilder->GetArgument(i));
  11767. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11768. if (isHotCompile)
  11769. {
  11770. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  11771. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  11772. if (callingConvention == BfIRCallingConv_StdCall)
  11773. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  11774. else
  11775. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11776. if (allowTailCall)
  11777. mBfIRBuilder->SetTailCall(result);
  11778. CreateReturn(result);
  11779. mCurMethodState->mHadReturn = true;
  11780. }
  11781. if (HasCompiledOutput())
  11782. {
  11783. BfDllImportEntry dllImportEntry;
  11784. dllImportEntry.mFuncVar = globalVar;
  11785. dllImportEntry.mMethodInstance = mCurMethodInstance;
  11786. mDllImportEntries.push_back(dllImportEntry);
  11787. }
  11788. }
  11789. BfIRCallingConv BfModule::GetCallingConvention(BfTypeInstance* typeInst, BfMethodDef* methodDef)
  11790. {
  11791. if (mSystem->mPtrSize == 8)
  11792. return BfIRCallingConv_CDecl;
  11793. if (methodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11794. return BfIRCallingConv_StdCall;
  11795. if ((!methodDef->mIsStatic) && (!typeInst->IsValuelessType()) &&
  11796. ((!typeInst->IsSplattable()) || (methodDef->HasNoThisSplat())))
  11797. return BfIRCallingConv_ThisCall;
  11798. return BfIRCallingConv_CDecl;
  11799. }
  11800. BfIRCallingConv BfModule::GetCallingConvention(BfMethodInstance* methodInstance)
  11801. {
  11802. return GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  11803. }
  11804. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  11805. {
  11806. BfMethodDef* methodDef = NULL;
  11807. if (methodInstance != NULL)
  11808. methodDef = methodInstance->mMethodDef;
  11809. if (!func)
  11810. return;
  11811. if (mCompiler->mOptions.mNoFramePointerElim)
  11812. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  11813. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  11814. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  11815. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  11816. if (methodInstance == NULL)
  11817. return;
  11818. if (methodDef->mImportKind == BfImportKind_Export)
  11819. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  11820. if (methodDef->mNoReturn)
  11821. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  11822. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  11823. if (callingConv != BfIRCallingConv_CDecl)
  11824. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  11825. if (isInlined)
  11826. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  11827. int argIdx = 0;
  11828. int paramIdx = 0;
  11829. if (methodInstance->HasThis())
  11830. {
  11831. paramIdx = -1;
  11832. }
  11833. int argCount = methodInstance->GetIRFunctionParamCount(this);
  11834. if (methodInstance->HasStructRet())
  11835. {
  11836. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  11837. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  11838. argIdx++;
  11839. }
  11840. while (argIdx < argCount)
  11841. {
  11842. while ((paramIdx != -1) && (methodInstance->IsParamSkipped(paramIdx)))
  11843. paramIdx++;
  11844. BfType* resolvedTypeRef = NULL;
  11845. String paramName;
  11846. bool isSplattable = false;
  11847. bool isThis = paramIdx == -1;
  11848. if (isThis)
  11849. {
  11850. paramName = "this";
  11851. if (methodInstance->mIsClosure)
  11852. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  11853. else
  11854. resolvedTypeRef = methodInstance->GetOwner();
  11855. isSplattable = (resolvedTypeRef->IsSplattable()) && (!methodDef->HasNoThisSplat());
  11856. }
  11857. else if (!methodDef->mNoSplat)
  11858. {
  11859. paramName = methodInstance->GetParamName(paramIdx);
  11860. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  11861. if (resolvedTypeRef->IsMethodRef())
  11862. isSplattable = true;
  11863. else if (resolvedTypeRef->IsSplattable())
  11864. {
  11865. if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  11866. isSplattable = true;
  11867. }
  11868. }
  11869. //
  11870. {
  11871. auto loweredTypeCode = resolvedTypeRef->GetLoweredType();
  11872. if (loweredTypeCode != BfTypeCode_None)
  11873. resolvedTypeRef = GetPrimitiveType(loweredTypeCode);
  11874. }
  11875. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  11876. {
  11877. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  11878. int addDeref = -1;
  11879. if (resolvedTypeRef->IsRef())
  11880. {
  11881. auto refType = (BfRefType*)resolvedTypeRef;
  11882. auto elementType = refType->mElementType;
  11883. PopulateType(elementType, BfPopulateType_Data);
  11884. addDeref = elementType->mSize;
  11885. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  11886. AssertErrorState();
  11887. }
  11888. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  11889. {
  11890. if (mCompiler->mOptions.mAllowStructByVal)
  11891. {
  11892. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal);
  11893. }
  11894. else
  11895. {
  11896. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  11897. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  11898. addDeref = resolvedTypeRef->mSize;
  11899. }
  11900. }
  11901. else if (resolvedTypeRef->IsPrimitiveType())
  11902. {
  11903. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  11904. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  11905. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  11906. }
  11907. if (addDeref >= 0)
  11908. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  11909. argIdx++;
  11910. };
  11911. if (isSplattable)
  11912. {
  11913. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  11914. {
  11915. if (checkType->IsStruct())
  11916. {
  11917. auto checkTypeInstance = checkType->ToTypeInstance();
  11918. if (checkTypeInstance->mBaseType != NULL)
  11919. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  11920. if (checkTypeInstance->mIsUnion)
  11921. {
  11922. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  11923. checkTypeLambda(unionInnerType, curName + "_data");
  11924. }
  11925. else
  11926. {
  11927. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11928. {
  11929. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11930. auto fieldDef = fieldInstance->GetFieldDef();
  11931. if (fieldInstance->mDataIdx >= 0)
  11932. {
  11933. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  11934. }
  11935. }
  11936. }
  11937. if (checkTypeInstance->IsEnum())
  11938. {
  11939. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  11940. argIdx++;
  11941. }
  11942. }
  11943. else if (checkType->IsMethodRef())
  11944. {
  11945. auto methodRefType = (BfMethodRefType*)checkType;
  11946. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  11947. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  11948. {
  11949. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  11950. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11951. {
  11952. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  11953. }
  11954. else
  11955. {
  11956. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  11957. }
  11958. }
  11959. }
  11960. else if (!checkType->IsValuelessType())
  11961. {
  11962. _SetupParam(curName, checkType);
  11963. }
  11964. };
  11965. checkTypeLambda(resolvedTypeRef, paramName);
  11966. paramIdx++;
  11967. continue;
  11968. }
  11969. _SetupParam(paramName, resolvedTypeRef);
  11970. //argIdx++;
  11971. paramIdx++;
  11972. }
  11973. }
  11974. void BfModule::EmitCtorBody(bool& skipBody)
  11975. {
  11976. auto methodInstance = mCurMethodInstance;
  11977. auto methodDef = methodInstance->mMethodDef;
  11978. auto methodDeclaration = methodDef->mMethodDeclaration;
  11979. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11980. auto typeDef = mCurTypeInstance->mTypeDef;
  11981. // Prologue
  11982. mBfIRBuilder->ClearDebugLocation();
  11983. bool hadThisInitializer = false;
  11984. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11985. {
  11986. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11987. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11988. if (targetToken->GetToken() == BfToken_This)
  11989. {
  11990. hadThisInitializer = true;
  11991. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  11992. mCurMethodState->LocalDefined(GetThisVariable());
  11993. }
  11994. }
  11995. // Zero out memory for default ctor
  11996. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  11997. {
  11998. if (mCurTypeInstance->IsTypedPrimitive())
  11999. {
  12000. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12001. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  12002. }
  12003. else if (mCurTypeInstance->mInstSize > 0)
  12004. {
  12005. BfIRValue fillValue = GetConstValue8(0);
  12006. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  12007. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12008. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12009. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  12010. }
  12011. }
  12012. BfAstNode* baseCtorNode = NULL;
  12013. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL) && (ctorDeclaration->mInitializer->mTarget != NULL))
  12014. baseCtorNode = ctorDeclaration->mInitializer->mTarget;
  12015. else if (methodDef->mBody != NULL)
  12016. baseCtorNode = methodDef->mBody;
  12017. else if (ctorDeclaration != NULL)
  12018. baseCtorNode = ctorDeclaration;
  12019. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  12020. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  12021. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  12022. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  12023. else
  12024. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  12025. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor))
  12026. {
  12027. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  12028. if (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension)
  12029. {
  12030. BfMethodDef* defaultCtor = NULL;
  12031. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  12032. {
  12033. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  12034. {
  12035. defaultCtor = methodDef;
  12036. }
  12037. }
  12038. if (defaultCtor != NULL)
  12039. {
  12040. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  12041. SetIllegalSrcPos();
  12042. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  12043. BfExprEvaluator exprEvaluator(this);
  12044. SizedArray<BfIRValue, 1> irArgs;
  12045. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  12046. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  12047. }
  12048. }
  12049. }
  12050. // Initialize fields (if applicable)
  12051. if (mCurTypeInstance->IsBoxed())
  12052. {
  12053. skipBody = true;
  12054. }
  12055. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  12056. {
  12057. // Field initializers occur in CtorNoBody methods for extensions
  12058. }
  12059. else if (!hadThisInitializer)
  12060. {
  12061. // If we had a 'this' initializer, that other ctor will have initialized our fields
  12062. if ((!mCompiler->mIsResolveOnly) ||
  12063. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  12064. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  12065. {
  12066. bool hadInlineInitBlock = false;
  12067. BfScopeData scopeData;
  12068. for (auto fieldDef : typeDef->mFields)
  12069. {
  12070. // For extensions, only handle these fields in the appropriate extension
  12071. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12072. continue;
  12073. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  12074. {
  12075. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12076. if (!fieldInst->mFieldIncluded)
  12077. continue;
  12078. if (fieldInst->mDataIdx < 0)
  12079. continue;
  12080. if (fieldDef->mInitializer == NULL)
  12081. {
  12082. if (fieldDef->mProtection != BfProtection_Hidden)
  12083. continue;
  12084. if (mCurTypeInstance->IsObject()) // Already zeroed out
  12085. continue;
  12086. }
  12087. if (fieldInst->mResolvedType == NULL)
  12088. {
  12089. BF_ASSERT(mHadBuildError);
  12090. continue;
  12091. }
  12092. if (fieldDef->mInitializer != NULL)
  12093. {
  12094. if (!hadInlineInitBlock)
  12095. {
  12096. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  12097. {
  12098. UpdateSrcPos(baseCtorNode);
  12099. // NOP so we step onto the open paren of the method so we can choose to set into the field initializers or step over them
  12100. EmitEnsureInstructionAt();
  12101. BfType* thisType = mCurTypeInstance;
  12102. if (thisType->IsValueType())
  12103. thisType = CreateRefType(thisType);
  12104. SizedArray<BfIRMDNode, 1> diParamTypes;
  12105. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  12106. mCurMethodState->AddScope(&scopeData);
  12107. NewScopeState();
  12108. int flags = 0;
  12109. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  12110. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  12111. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  12112. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  12113. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  12114. UpdateSrcPos(fieldDef->mInitializer);
  12115. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12116. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  12117. //
  12118. {
  12119. auto loadedThis = GetThis();
  12120. // LLVM can't handle two variables pointing to the same value
  12121. BfIRValue copiedThisPtr;
  12122. copiedThisPtr = CreateAlloca(thisType);
  12123. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  12124. mBfIRBuilder->ClearDebugLocation(storeInst);
  12125. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  12126. }
  12127. hadInlineInitBlock = true;
  12128. }
  12129. }
  12130. UpdateSrcPos(fieldDef->mInitializer);
  12131. }
  12132. BfIRValue fieldAddr;
  12133. if (!mCurTypeInstance->IsTypedPrimitive())
  12134. {
  12135. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  12136. }
  12137. else
  12138. {
  12139. AssertErrorState();
  12140. }
  12141. auto assignValue = GetFieldInitializerValue(fieldInst);
  12142. if ((fieldAddr) && (assignValue))
  12143. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  12144. }
  12145. }
  12146. if (hadInlineInitBlock)
  12147. {
  12148. RestoreScopeState();
  12149. // This gets set to false because of AddScope but we actually are still in the head block
  12150. mCurMethodState->mInHeadScope = true;
  12151. }
  12152. }
  12153. else // Autocomplete case
  12154. {
  12155. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  12156. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  12157. // resolve pass, NOT the autocomplete expression
  12158. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12159. {
  12160. if (tempTypeDef->mFullName == typeDef->mFullName)
  12161. {
  12162. for (auto fieldDef : tempTypeDef->mFields)
  12163. {
  12164. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12165. {
  12166. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12167. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12168. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12169. if ((wantType != NULL) &&
  12170. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  12171. wantType = NULL;
  12172. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12173. }
  12174. }
  12175. }
  12176. }
  12177. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  12178. for (auto fieldDef : typeDef->mFields)
  12179. {
  12180. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12181. {
  12182. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12183. if (fieldDef->mInitializer != NULL)
  12184. MarkFieldInitialized(fieldInst);
  12185. }
  12186. }
  12187. }
  12188. }
  12189. // Call base ctor (if applicable)
  12190. BfTypeInstance* targetType = NULL;
  12191. BfAstNode* targetRefNode = NULL;
  12192. if (ctorDeclaration != NULL)
  12193. targetRefNode = ctorDeclaration->mInitializer;
  12194. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  12195. targetRefNode = invocationExpr->mTarget;
  12196. if (baseCtorNode != NULL)
  12197. {
  12198. UpdateSrcPos(baseCtorNode);
  12199. }
  12200. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12201. {
  12202. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12203. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12204. }
  12205. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  12206. {
  12207. auto baseType = mCurTypeInstance->mBaseType;
  12208. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  12209. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  12210. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  12211. {
  12212. // Try to find a ctor without any params first
  12213. bool foundBaseCtor = false;
  12214. bool hadCtorWithAllDefaults = false;
  12215. for (int pass = 0; pass < 2; pass++)
  12216. {
  12217. for (auto checkMethodDef : baseType->mTypeDef->mMethods)
  12218. {
  12219. bool allowPriv = checkMethodDef->mProtection != BfProtection_Private;
  12220. // Allow calling of the default base ctor if it is implicitly defined
  12221. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  12222. allowPriv = true;
  12223. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowPriv))
  12224. {
  12225. if (checkMethodDef->mParams.size() == 0)
  12226. {
  12227. foundBaseCtor = true;
  12228. if (HasCompiledOutput())
  12229. {
  12230. SizedArray<BfIRValue, 1> args;
  12231. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, checkMethodDef, BfTypeVector());
  12232. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12233. {
  12234. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  12235. args.push_back(basePtr);
  12236. }
  12237. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  12238. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  12239. auto callingConv = GetCallingConvention(ctorBodyMethodInstance.mMethodInstance->GetOwner(), ctorBodyMethodInstance.mMethodInstance->mMethodDef);
  12240. if (callingConv != BfIRCallingConv_CDecl)
  12241. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  12242. // if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12243. // mBfIRBuilder->SetCallCallingConv(callInst, BfIRCallingConv_ThisCall);
  12244. break;
  12245. }
  12246. }
  12247. else if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  12248. hadCtorWithAllDefaults = true;
  12249. }
  12250. }
  12251. if (foundBaseCtor)
  12252. break;
  12253. }
  12254. if (!foundBaseCtor)
  12255. {
  12256. targetType = mCurTypeInstance->mBaseType;
  12257. if (ctorDeclaration != NULL)
  12258. targetRefNode = ctorDeclaration->mThisToken;
  12259. else if (typeDef->mTypeDeclaration != NULL)
  12260. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  12261. }
  12262. }
  12263. }
  12264. if (methodDef->mHasAppend)
  12265. {
  12266. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  12267. }
  12268. if (targetType != NULL)
  12269. {
  12270. auto autoComplete = mCompiler->GetAutoComplete();
  12271. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  12272. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12273. {
  12274. auto invocationExpr = ctorDeclaration->mInitializer;
  12275. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  12276. }
  12277. BfType* targetThisType = targetType;
  12278. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  12279. BfExprEvaluator exprEvaluator(this);
  12280. BfResolvedArgs argValues;
  12281. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12282. {
  12283. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  12284. if (gDebugStuff)
  12285. {
  12286. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  12287. }
  12288. }
  12289. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12290. BfTypedValue appendIdxVal;
  12291. if (methodDef->mHasAppend)
  12292. {
  12293. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  12294. BF_ASSERT(localVar->mName == "appendIdx");
  12295. auto intRefType = CreateRefType(localVar->mResolvedType);
  12296. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  12297. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  12298. }
  12299. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  12300. if (autoComplete != NULL)
  12301. {
  12302. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  12303. {
  12304. if (autoComplete->mMethodMatchInfo != NULL)
  12305. autoComplete->mIsCapturingMethodMatchInfo = true;
  12306. else
  12307. autoComplete->mIsCapturingMethodMatchInfo = false;
  12308. }
  12309. else
  12310. autoComplete->mIsCapturingMethodMatchInfo = false;
  12311. }
  12312. }
  12313. }
  12314. void BfModule::EmitEnumToStringBody()
  12315. {
  12316. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12317. auto strVal = CreateAlloca(stringType);
  12318. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  12319. BfExprEvaluator exprEvaluator(this);
  12320. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12321. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  12322. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  12323. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  12324. BfType* discriminatorType = NULL;
  12325. BfTypedValue rawPayload;
  12326. BfIRValue enumVal;
  12327. if (mCurTypeInstance->IsPayloadEnum())
  12328. {
  12329. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  12330. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  12331. enumTypedValue = LoadValue(enumTypedValue);
  12332. enumVal = enumTypedValue.mValue;
  12333. rawPayload = ExtractValue(GetThis(), NULL, 1);
  12334. }
  12335. else
  12336. enumVal = mBfIRBuilder->GetArgument(0);
  12337. Array<BfType*> paramTypes;
  12338. paramTypes.Add(stringType);
  12339. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12340. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  12341. HashSet<int64> handledCases;
  12342. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12343. {
  12344. if (fieldInstance.mIsEnumPayloadCase)
  12345. {
  12346. int tagId = -fieldInstance.mDataIdx - 1;
  12347. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12348. mBfIRBuilder->AddBlock(caseBlock);
  12349. mBfIRBuilder->SetInsertPoint(caseBlock);
  12350. BF_ASSERT(discriminatorType->IsPrimitiveType());
  12351. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  12352. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12353. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12354. auto stringDestVal = LoadValue(stringDestAddr);
  12355. SizedArray<BfIRValue, 2> args;
  12356. args.Add(stringDestVal.mValue);
  12357. args.Add(caseStr);
  12358. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12359. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  12360. BF_ASSERT(payloadType->IsTuple());
  12361. if (payloadType->mFieldInstances.size() != 0)
  12362. {
  12363. auto payload = rawPayload;
  12364. if (payload.mType != payloadType)
  12365. {
  12366. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  12367. }
  12368. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  12369. SizedArray<BfIRValue, 2> irArgs;
  12370. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  12371. stringDestVal = LoadValue(stringDestAddr);
  12372. irArgs.Add(stringDestVal.mValue);
  12373. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  12374. }
  12375. mBfIRBuilder->CreateBr(endBlock);
  12376. continue;
  12377. }
  12378. if (fieldInstance.mConstIdx == -1)
  12379. continue;
  12380. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  12381. if (!handledCases.TryAdd(constant->mInt64, NULL))
  12382. {
  12383. // Duplicate
  12384. continue;
  12385. }
  12386. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12387. mBfIRBuilder->AddBlock(caseBlock);
  12388. mBfIRBuilder->SetInsertPoint(caseBlock);
  12389. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  12390. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12391. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12392. mBfIRBuilder->CreateStore(caseStr, strVal);
  12393. mBfIRBuilder->CreateBr(appendBlock);
  12394. }
  12395. mBfIRBuilder->AddBlock(appendBlock);
  12396. mBfIRBuilder->SetInsertPoint(appendBlock);
  12397. SizedArray<BfIRValue, 2> args;
  12398. auto stringDestVal = LoadValue(stringDestAddr);
  12399. args.Add(stringDestVal.mValue);
  12400. args.Add(mBfIRBuilder->CreateLoad(strVal));
  12401. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12402. mBfIRBuilder->CreateBr(endBlock);
  12403. mBfIRBuilder->AddBlock(noMatchBlock);
  12404. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  12405. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  12406. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  12407. args.clear();
  12408. args.Add(int64Val);
  12409. stringDestVal = LoadValue(stringDestAddr);
  12410. args.Add(stringDestVal.mValue);
  12411. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  12412. mBfIRBuilder->CreateBr(endBlock);
  12413. mBfIRBuilder->AddBlock(endBlock);
  12414. mBfIRBuilder->SetInsertPoint(endBlock);
  12415. }
  12416. void BfModule::EmitTupleToStringBody()
  12417. {
  12418. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12419. BfExprEvaluator exprEvaluator(this);
  12420. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12421. Array<BfType*> paramTypes;
  12422. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  12423. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12424. paramTypes.Clear();
  12425. paramTypes.Add(stringType);
  12426. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12427. auto _AppendChar = [&](char c)
  12428. {
  12429. SizedArray<BfIRValue, 2> args;
  12430. auto stringDestVal = LoadValue(stringDestRef);
  12431. args.Add(stringDestVal.mValue);
  12432. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  12433. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  12434. };
  12435. int fieldIdx = 0;
  12436. auto thisValue = GetThis();
  12437. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  12438. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  12439. BfIRValue commaStr;
  12440. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  12441. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  12442. _AppendChar('(');
  12443. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12444. {
  12445. if (fieldInstance.mDataIdx == -1)
  12446. continue;
  12447. if (fieldIdx > 0)
  12448. {
  12449. if (!commaStr)
  12450. commaStr = GetStringObjectValue(", ");
  12451. SizedArray<BfIRValue, 2> args;
  12452. auto stringDestVal = LoadValue(stringDestRef);
  12453. args.Add(stringDestVal.mValue);
  12454. args.Add(commaStr);
  12455. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12456. }
  12457. fieldIdx++;
  12458. if (fieldInstance.mResolvedType->IsValuelessType())
  12459. continue;
  12460. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  12461. if (fieldValue.mType->IsPrimitiveType())
  12462. {
  12463. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  12464. }
  12465. auto typeInstance = fieldValue.mType->ToTypeInstance();
  12466. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  12467. {
  12468. BfExprEvaluator exprEvaluator(this);
  12469. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12470. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  12471. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  12472. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  12473. methodMatcher.TryDevirtualizeCall(fieldValue);
  12474. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12475. BfResolvedArg resolvedArg;
  12476. auto stringDestVal = LoadValue(stringDestRef);
  12477. resolvedArg.mTypedValue = stringDestVal;
  12478. resolvedArg.mResolvedType = stringDestVal.mType;
  12479. resolvedArgs.Add(resolvedArg);
  12480. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12481. continue;
  12482. }
  12483. if (fieldValue.mType->IsObjectOrInterface())
  12484. {
  12485. BF_ASSERT(!fieldValue.IsAddr());
  12486. SizedArray<BfIRValue, 2> args;
  12487. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  12488. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12489. stringDestVal = LoadValue(stringDestVal);
  12490. args.Add(stringDestVal.mValue);
  12491. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  12492. continue;
  12493. }
  12494. BfExprEvaluator exprEvaluator(this);
  12495. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12496. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  12497. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  12498. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  12499. methodMatcher.TryDevirtualizeCall(fieldValue);
  12500. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  12501. {
  12502. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  12503. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12504. // Just append the type name
  12505. String typeName = TypeToString(fieldInstance.mResolvedType);
  12506. auto strVal = GetStringObjectValue(typeName);
  12507. SizedArray<BfIRValue, 2> args;
  12508. auto stringDestVal = LoadValue(stringDestRef);
  12509. args.Add(stringDestVal.mValue);
  12510. args.Add(strVal);
  12511. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12512. continue;
  12513. }
  12514. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12515. BfResolvedArg resolvedArg;
  12516. auto stringDestVal = LoadValue(stringDestRef);
  12517. resolvedArg.mTypedValue = stringDestVal;
  12518. resolvedArg.mResolvedType = stringDestVal.mType;
  12519. resolvedArgs.Add(resolvedArg);
  12520. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12521. }
  12522. _AppendChar(')');
  12523. }
  12524. void BfModule::EmitIteratorBlock(bool& skipBody)
  12525. {
  12526. auto methodInstance = mCurMethodInstance;
  12527. auto methodDef = methodInstance->mMethodDef;
  12528. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12529. auto typeDef = mCurTypeInstance->mTypeDef;
  12530. BfType* innerRetType = NULL;
  12531. BfTypeInstance* usingInterface = NULL;
  12532. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  12533. if (retTypeInst != NULL)
  12534. {
  12535. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  12536. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  12537. {
  12538. innerRetType = retTypeInst->mTypeGenericArguments[0];
  12539. }
  12540. }
  12541. if (innerRetType == NULL)
  12542. {
  12543. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  12544. return;
  12545. }
  12546. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  12547. if (blockBody == NULL)
  12548. return;
  12549. }
  12550. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  12551. {
  12552. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  12553. if (fieldTypeInst == NULL)
  12554. return;
  12555. if (!markVal.mType->IsComposite())
  12556. markVal = LoadValue(markVal);
  12557. BfExprEvaluator exprEvaluator(this);
  12558. PopulateType(markVal.mType, BfPopulateType_Data);
  12559. if (markVal.mType->IsObjectOrInterface())
  12560. {
  12561. BfIRValue val = markVal.mValue;
  12562. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  12563. SizedArray<BfIRValue, 1> args;
  12564. args.push_back(val);
  12565. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  12566. }
  12567. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  12568. {
  12569. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  12570. if (markMemberMethodInstance)
  12571. {
  12572. SizedArray<BfIRValue, 1> args;
  12573. //(1, markVal.mValue);
  12574. //exprEvaluator.PushArg(markVal, args);
  12575. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  12576. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  12577. }
  12578. }
  12579. }
  12580. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  12581. {
  12582. Array<BfMethodInstance*> methodInstances;
  12583. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  12584. {
  12585. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  12586. auto chainedMethodInst = methodInstGroup.mDefault;
  12587. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  12588. {
  12589. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  12590. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  12591. {
  12592. methodInstances.push_back(chainedMethodInst);
  12593. }
  12594. }
  12595. }
  12596. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  12597. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  12598. {
  12599. bool isBetter;
  12600. bool isWorse;
  12601. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  12602. if (isBetter == isWorse)
  12603. {
  12604. return false;
  12605. }
  12606. return isWorse;
  12607. });
  12608. if (reverse)
  12609. std::reverse(methodInstances.begin(), methodInstances.end());
  12610. for (auto chainedMethodInst : methodInstances)
  12611. {
  12612. auto declModule = this;
  12613. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  12614. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  12615. BfExprEvaluator exprEvaluator(this);
  12616. SizedArray<BfIRValue, 1> args;
  12617. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  12618. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  12619. }
  12620. }
  12621. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  12622. {
  12623. BF_ASSERT(mCurMethodInstance->mIsReified);
  12624. if (mCurTypeInstance->mHotTypeData == NULL)
  12625. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  12626. auto hotMethod = mCurMethodInstance->mHotMethod;
  12627. for (auto depData : hotMethod->mReferences)
  12628. {
  12629. // Only virtual decls are allowed to already be there
  12630. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  12631. }
  12632. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  12633. int prevSize = (int)hotMethod->mReferences.size();
  12634. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  12635. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12636. refCount++;
  12637. hotMethod->mReferences.Reserve(refCount);
  12638. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12639. {
  12640. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  12641. hotThis->mRefCount++;
  12642. hotMethod->mReferences.Insert(0, hotThis);
  12643. prevSize++;
  12644. }
  12645. for (auto val : builder->mAllocatedData)
  12646. {
  12647. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  12648. hotMethod->mReferences.Add(hotAllocation);
  12649. }
  12650. for (auto val : builder->mUsedData)
  12651. hotMethod->mReferences.Add(val);
  12652. for (auto val : builder->mCalledMethods)
  12653. hotMethod->mReferences.Add(val);
  12654. for (auto val : builder->mDevirtualizedCalledMethods)
  12655. {
  12656. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  12657. hotMethod->mReferences.Add(devirtualizedMethod);
  12658. }
  12659. for (auto val : builder->mFunctionPtrs)
  12660. {
  12661. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  12662. hotMethod->mReferences.Add(funcRef);
  12663. }
  12664. for (auto val : builder->mInnerMethods)
  12665. {
  12666. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  12667. hotMethod->mReferences.Add(innerMethod);
  12668. }
  12669. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  12670. {
  12671. auto depData = hotMethod->mReferences[refIdx];
  12672. BF_ASSERT(depData != NULL);
  12673. depData->mRefCount++;
  12674. }
  12675. //hotMethod->mReferences.Sort([](BfHotDepData* lhs, BfHotDepData* rhs) { return lhs < rhs; });
  12676. }
  12677. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  12678. {
  12679. auto methodDef = methodInstance->mMethodDef;
  12680. auto methodDeclaration = methodDef->mMethodDeclaration;
  12681. bool isThisStruct = false;
  12682. if (thisType != NULL)
  12683. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  12684. int argIdx = 0;
  12685. if (methodInstance->HasStructRet())
  12686. argIdx++;
  12687. if (!methodDef->mIsStatic)
  12688. {
  12689. BfLocalVariable* paramVar = new BfLocalVariable();
  12690. paramVar->mResolvedType = thisType;
  12691. paramVar->mName = "this";
  12692. if (!thisType->IsValuelessType())
  12693. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12694. else
  12695. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12696. if ((thisType->IsComposite()) && (!methodDef->HasNoThisSplat()))
  12697. {
  12698. if (thisType->IsSplattable())
  12699. paramVar->mIsSplat = true;
  12700. else
  12701. paramVar->mIsLowered = thisType->GetLoweredType() != BfTypeCode_None;
  12702. }
  12703. auto thisTypeInst = thisType->ToTypeInstance();
  12704. paramVar->mIsStruct = isThisStruct;
  12705. paramVar->mAddr = BfIRValue();
  12706. paramVar->mIsThis = true;
  12707. paramVar->mParamIdx = -1;
  12708. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  12709. {
  12710. paramVar->mIsAssigned = false;
  12711. }
  12712. else
  12713. {
  12714. paramVar->mIsAssigned = true;
  12715. }
  12716. paramVar->mReadFromId = -1;
  12717. paramVar->Init();
  12718. if (methodDeclaration == NULL)
  12719. UseDefaultSrcPos();
  12720. AddLocalVariableDef(paramVar);
  12721. if (!thisType->IsValuelessType())
  12722. {
  12723. if (wantsDIData)
  12724. {
  12725. BfType* thisPtrType = thisType;
  12726. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  12727. if (!thisType->IsValueType())
  12728. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  12729. diParams->push_back(diType);
  12730. }
  12731. if (paramVar->mIsSplat)
  12732. {
  12733. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12734. }
  12735. else
  12736. {
  12737. argIdx++;
  12738. }
  12739. }
  12740. }
  12741. bool hadParams = false;
  12742. bool hasDefault = false;
  12743. int compositeVariableIdx = -1;
  12744. int paramIdx = 0;
  12745. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12746. {
  12747. // We already issues a type error for this param if we had one in declaration processing
  12748. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  12749. BfLocalVariable* paramVar = new BfLocalVariable();
  12750. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  12751. BfType* unresolvedType = methodInstance->GetParamType(paramIdx, false);
  12752. if (unresolvedType == NULL)
  12753. {
  12754. AssertErrorState();
  12755. unresolvedType = mContext->mBfObjectType;
  12756. paramVar->mParamFailed = true;
  12757. }
  12758. auto resolvedType = methodInstance->GetParamType(paramIdx, true);
  12759. prevIgnoreErrors.Restore();
  12760. PopulateType(resolvedType, BfPopulateType_Declaration);
  12761. paramVar->mResolvedType = resolvedType;
  12762. paramVar->mName = methodInstance->GetParamName(paramIdx);
  12763. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  12764. if (!isParamSkipped)
  12765. {
  12766. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12767. if (resolvedType->IsMethodRef())
  12768. {
  12769. paramVar->mIsSplat = true;
  12770. }
  12771. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  12772. {
  12773. int splatCount = resolvedType->GetSplatCount();
  12774. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  12775. paramVar->mIsSplat = true;
  12776. }
  12777. }
  12778. else
  12779. {
  12780. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  12781. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12782. }
  12783. paramVar->mIsLowered = resolvedType->GetLoweredType() != BfTypeCode_None;
  12784. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  12785. paramVar->mParamIdx = paramIdx;
  12786. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  12787. paramVar->mReadFromId = 0;
  12788. if (resolvedType->IsRef())
  12789. {
  12790. auto refType = (BfRefType*)resolvedType;
  12791. paramVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  12792. }
  12793. else
  12794. {
  12795. paramVar->mIsAssigned = true;
  12796. if (methodDef->mMethodType != BfMethodType_Mixin)
  12797. paramVar->mIsReadOnly = true;
  12798. }
  12799. if (paramVar->mResolvedType->IsGenericParam())
  12800. {
  12801. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  12802. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  12803. {
  12804. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  12805. paramVar->mResolvedType = typedVal.mType;
  12806. paramVar->mConstValue = typedVal.mValue;
  12807. }
  12808. }
  12809. if (paramVar->mResolvedType->IsConstExprValue())
  12810. {
  12811. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  12812. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  12813. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  12814. BF_ASSERT(unspecParamType->IsGenericParam());
  12815. if (unspecParamType->IsGenericParam())
  12816. {
  12817. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  12818. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  12819. {
  12820. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12821. if (genericParamInst->mTypeConstraint != NULL)
  12822. {
  12823. BfExprEvaluator exprEvaluator(this);
  12824. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  12825. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  12826. auto checkType = genericParamInst->mTypeConstraint;
  12827. if (checkType->IsTypedPrimitive())
  12828. checkType = checkType->GetUnderlyingType();
  12829. if (exprEvaluator.mResult.mType == checkType)
  12830. {
  12831. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12832. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  12833. BF_ASSERT(paramVar->mConstValue.IsConst());
  12834. }
  12835. else
  12836. {
  12837. AssertErrorState();
  12838. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12839. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  12840. }
  12841. }
  12842. }
  12843. }
  12844. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  12845. if (paramVar->mResolvedType->IsConstExprValue())
  12846. {
  12847. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  12848. //AssertErrorState();
  12849. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  12850. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  12851. }
  12852. }
  12853. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  12854. {
  12855. if (compositeVariableIdx == -1)
  12856. {
  12857. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  12858. BfLocalVariable* localVar = new BfLocalVariable();
  12859. auto paramInst = &methodInstance->mParams[paramIdx];
  12860. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  12861. localVar->mName = paramDef->mName;
  12862. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12863. localVar->mCompositeCount = 0;
  12864. DoAddLocalVariable(localVar);
  12865. }
  12866. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  12867. }
  12868. CheckVariableDef(paramVar);
  12869. paramVar->Init();
  12870. AddLocalVariableDef(paramVar);
  12871. if (!isParamSkipped)
  12872. {
  12873. if (wantsDIData)
  12874. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  12875. if (paramVar->mIsSplat)
  12876. {
  12877. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12878. }
  12879. else
  12880. {
  12881. argIdx++;
  12882. }
  12883. }
  12884. }
  12885. // Try to find an ending delegate params composite
  12886. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  12887. {
  12888. auto paramDef = methodDef->mParams.back();
  12889. if (paramDef->mParamKind == BfParamKind_Params)
  12890. {
  12891. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12892. if (paramsType == NULL)
  12893. {
  12894. AssertErrorState();
  12895. }
  12896. else if (paramsType->IsGenericParam())
  12897. {
  12898. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  12899. if (genericParamInstance->mTypeConstraint != NULL)
  12900. {
  12901. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  12902. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  12903. ((typeInstConstraint != NULL) &&
  12904. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  12905. {
  12906. BfLocalVariable* localVar = new BfLocalVariable();
  12907. localVar->mName = paramDef->mName;
  12908. localVar->mResolvedType = paramsType;
  12909. localVar->mCompositeCount = 0;
  12910. DoAddLocalVariable(localVar);
  12911. }
  12912. }
  12913. }
  12914. else if (paramsType->IsDelegate())
  12915. {
  12916. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  12917. if (invokeMethodInstance != NULL)
  12918. {
  12919. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  12920. // and wasn't cleared by the preceding loop
  12921. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  12922. BfLocalVariable* localVar = new BfLocalVariable();
  12923. localVar->mName = paramDef->mName;
  12924. localVar->mResolvedType = paramsType;
  12925. localVar->mCompositeCount = 0;
  12926. DoAddLocalVariable(localVar);
  12927. }
  12928. }
  12929. }
  12930. }
  12931. }
  12932. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  12933. {
  12934. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  12935. // return;
  12936. auto _ClearState = [&]()
  12937. {
  12938. mCurMethodState->mLocalMethods.Clear();
  12939. for (auto& local : mCurMethodState->mLocals)
  12940. delete local;
  12941. mCurMethodState->mLocals.Clear();
  12942. mCurMethodState->mLocalVarSet.Clear();
  12943. };
  12944. // Don't process local methods if we had a build error - this isn't just an optimization, it keeps us from showing the same error twice since
  12945. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  12946. // however (compiler bug), so this is the safest way
  12947. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  12948. {
  12949. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  12950. {
  12951. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  12952. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  12953. if (!mHadBuildError)
  12954. {
  12955. // Process as a closure - that allows us to look back and see the const locals and stuff
  12956. BfClosureState closureState;
  12957. mCurMethodState->mClosureState = &closureState;
  12958. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  12959. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  12960. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  12961. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  12962. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  12963. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  12964. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  12965. _ClearState();
  12966. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  12967. {
  12968. auto localVar = new BfLocalVariable();
  12969. *localVar = constLocal;
  12970. DoAddLocalVariable(localVar);
  12971. }
  12972. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  12973. bool doProcess = !mCompiler->mCanceling;
  12974. if (doProcess)
  12975. {
  12976. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  12977. ProcessMethod(deferredLocalMethod->mMethodInstance);
  12978. }
  12979. }
  12980. delete deferredLocalMethod;
  12981. mSystem->CheckLockYield();
  12982. }
  12983. }
  12984. for (auto& kv : mCurMethodState->mLocalMethodCache)
  12985. {
  12986. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  12987. }
  12988. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  12989. {
  12990. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  12991. {
  12992. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  12993. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  12994. BfClosureState closureState;
  12995. mCurMethodState->mClosureState = &closureState;
  12996. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  12997. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  12998. if (lambdaInstance->mClosureTypeInstance != NULL)
  12999. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  13000. else
  13001. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  13002. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13003. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  13004. _ClearState();
  13005. for (auto& constLocal : lambdaInstance->mConstLocals)
  13006. {
  13007. //if (constLocal.mIsThis)
  13008. {
  13009. // Valueless 'this'
  13010. closureState.mConstLocals.Add(constLocal);
  13011. }
  13012. /*else
  13013. {
  13014. auto localVar = new BfLocalVariable();
  13015. *localVar = constLocal;
  13016. DoAddLocalVariable(localVar);
  13017. }*/
  13018. }
  13019. BfMethodInstanceGroup methodInstanceGroup;
  13020. methodInstanceGroup.mOwner = mCurTypeInstance;
  13021. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  13022. bool doProcess = !mCompiler->mCanceling;
  13023. if (doProcess)
  13024. {
  13025. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  13026. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13027. ProcessMethod(lambdaInstance->mMethodInstance);
  13028. if (lambdaInstance->mDtorMethodInstance != NULL)
  13029. {
  13030. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13031. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  13032. }
  13033. }
  13034. }
  13035. mSystem->CheckLockYield();
  13036. }
  13037. }
  13038. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  13039. {
  13040. if (checkType->IsComposite())
  13041. PopulateType(checkType, BfPopulateType_Data);
  13042. if (!checkType->WantsGCMarking())
  13043. return;
  13044. auto typeInstance = checkType->ToTypeInstance();
  13045. bool callMarkMethod = false;
  13046. // Call the actual marking method
  13047. if (memberDepth == 0)
  13048. {
  13049. // Don't call marking method on self
  13050. }
  13051. else if (checkType->IsObjectOrInterface())
  13052. {
  13053. if (!objectOffsets.Add(curOffset))
  13054. {
  13055. return;
  13056. }
  13057. callMarkMethod = true;
  13058. }
  13059. else if (checkType->IsSizedArray())
  13060. {
  13061. callMarkMethod = true;
  13062. }
  13063. else if (typeInstance != NULL)
  13064. {
  13065. typeInstance->mTypeDef->PopulateMemberSets();
  13066. BfMemberSetEntry* entry = NULL;
  13067. BfMethodDef* methodDef = NULL;
  13068. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  13069. {
  13070. methodDef = (BfMethodDef*)entry->mMemberDef;
  13071. if (methodDef->HasBody())
  13072. {
  13073. callMarkMethod = true;
  13074. }
  13075. }
  13076. }
  13077. if (callMarkMethod)
  13078. {
  13079. BfTypedValue markValue;
  13080. auto memberType = checkType;
  13081. if (memberType->IsObjectOrInterface())
  13082. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  13083. auto memberPtrType = CreatePointerType(memberType);
  13084. if (curOffset == 0)
  13085. {
  13086. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13087. }
  13088. else
  13089. {
  13090. if (!thisValue.mType->IsPointer())
  13091. {
  13092. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  13093. auto int8PtrType = CreatePointerType(int8Type);
  13094. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  13095. }
  13096. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  13097. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13098. }
  13099. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13100. return;
  13101. }
  13102. auto methodDef = mCurMethodInstance->mMethodDef;
  13103. if (checkType->IsPayloadEnum())
  13104. {
  13105. for (auto& fieldInst : typeInstance->mFieldInstances)
  13106. {
  13107. if (!fieldInst.mIsEnumPayloadCase)
  13108. continue;
  13109. auto fieldDef = fieldInst.GetFieldDef();
  13110. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13111. }
  13112. return;
  13113. }
  13114. if (typeInstance == NULL)
  13115. return;
  13116. for (auto& fieldInst : typeInstance->mFieldInstances)
  13117. {
  13118. auto fieldDef = fieldInst.GetFieldDef();
  13119. if (fieldDef == NULL)
  13120. continue;
  13121. if (fieldDef->mIsStatic)
  13122. continue;
  13123. if (typeInstance == mCurTypeInstance)
  13124. {
  13125. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  13126. // we may be marking member values that can never contain a value anyway, but this is benign
  13127. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13128. continue;
  13129. }
  13130. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  13131. }
  13132. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  13133. {
  13134. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13135. }
  13136. }
  13137. void BfModule::EmitGCMarkMembers()
  13138. {
  13139. auto methodDef = mCurMethodInstance->mMethodDef;
  13140. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  13141. BfModuleMethodInstance markFromGCThreadMethodInstance;
  13142. if (gcType != NULL)
  13143. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  13144. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  13145. {
  13146. if (mCurTypeInstance->IsBoxed())
  13147. {
  13148. // This already gets filled in by the normal boxed forwarding
  13149. }
  13150. else
  13151. {
  13152. auto thisValue = GetThis();
  13153. if (thisValue.IsSplat())
  13154. {
  13155. BfIRFunction func = mCurMethodInstance->mIRFunction;
  13156. int argIdx = 0;
  13157. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  13158. {
  13159. if (checkType->IsStruct())
  13160. {
  13161. auto checkTypeInstance = checkType->ToTypeInstance();
  13162. if (checkTypeInstance->mBaseType != NULL)
  13163. checkTypeLambda(checkTypeInstance->mBaseType);
  13164. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13165. {
  13166. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13167. if (fieldInstance->mDataIdx >= 0)
  13168. checkTypeLambda(fieldInstance->GetResolvedType());
  13169. }
  13170. }
  13171. else if (checkType->IsMethodRef())
  13172. {
  13173. BF_FATAL("Not handled");
  13174. }
  13175. else if (checkType->WantsGCMarking())
  13176. {
  13177. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  13178. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13179. argIdx++;
  13180. }
  13181. };
  13182. checkTypeLambda(thisValue.mType);
  13183. }
  13184. else if (!methodDef->mIsStatic)
  13185. {
  13186. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  13187. {
  13188. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  13189. if (moduleMethodInst)
  13190. {
  13191. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  13192. if (methodBaseType != mContext->mBfObjectType)
  13193. {
  13194. auto thisValue = GetThis();
  13195. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  13196. SizedArray<BfIRValue, 1> args;
  13197. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  13198. {
  13199. BfExprEvaluator exprEvaluator(this);
  13200. exprEvaluator.SplatArgs(baseValue, args);
  13201. }
  13202. else
  13203. {
  13204. args.push_back(baseValue.mValue);
  13205. }
  13206. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  13207. }
  13208. }
  13209. }
  13210. }
  13211. if (!methodDef->mIsStatic)
  13212. {
  13213. HashSet<int> objectOffsets;
  13214. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  13215. }
  13216. else
  13217. {
  13218. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13219. {
  13220. if (thisValue.IsSplat())
  13221. break;
  13222. auto fieldDef = fieldInst.GetFieldDef();
  13223. if (fieldDef == NULL)
  13224. continue;
  13225. if (fieldInst.mIsThreadLocal)
  13226. continue;
  13227. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  13228. {
  13229. // For extensions, only handle these fields in the appropriate extension
  13230. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13231. continue;
  13232. if (!fieldInst.mFieldIncluded)
  13233. continue;
  13234. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  13235. if (fieldTypeInst != NULL)
  13236. {
  13237. auto fieldDef = fieldInst.GetFieldDef();
  13238. BfTypedValue markVal;
  13239. if (fieldDef->mIsConst)
  13240. continue;
  13241. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  13242. continue;
  13243. mBfIRBuilder->PopulateType(fieldTypeInst);
  13244. if (fieldTypeInst->IsValuelessType())
  13245. continue;
  13246. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  13247. {
  13248. markVal = ReferenceStaticField(&fieldInst);
  13249. }
  13250. else if (!fieldDef->mIsStatic)
  13251. {
  13252. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  13253. }
  13254. if (markVal)
  13255. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  13256. }
  13257. }
  13258. }
  13259. }
  13260. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13261. CallChainedMethods(mCurMethodInstance, false);
  13262. }
  13263. }
  13264. }
  13265. void BfModule::EmitGCFindTLSMembers()
  13266. {
  13267. auto methodDef = mCurMethodInstance->mMethodDef;
  13268. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  13269. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  13270. BF_ASSERT(reportTLSMark);
  13271. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13272. {
  13273. auto fieldDef = fieldInst.GetFieldDef();
  13274. if (fieldDef == NULL)
  13275. continue;
  13276. if (!fieldInst.mIsThreadLocal)
  13277. continue;
  13278. // For extensions, only handle these fields in the appropriate extension
  13279. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13280. continue;
  13281. if (!fieldInst.mFieldIncluded)
  13282. continue;
  13283. if (fieldDef->mIsConst)
  13284. continue;
  13285. auto fieldType = fieldInst.mResolvedType;
  13286. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  13287. continue;
  13288. if (fieldType->IsValuelessType())
  13289. continue;
  13290. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  13291. if (markVal)
  13292. {
  13293. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  13294. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  13295. SizedArray<BfIRValue, 2> llvmArgs;
  13296. llvmArgs.push_back(fieldRefPtr);
  13297. llvmArgs.push_back(markFuncPtr);
  13298. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  13299. }
  13300. }
  13301. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13302. CallChainedMethods(mCurMethodInstance, false);
  13303. }
  13304. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  13305. {
  13306. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  13307. if (mAwaitingInitFinish)
  13308. FinishInit();
  13309. if (!methodInstance->mIsReified)
  13310. BF_ASSERT(!mIsReified);
  13311. if (methodInstance->mMethodInfoEx != NULL)
  13312. {
  13313. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13314. {
  13315. if (methodGenericArg->IsMethodRef())
  13316. {
  13317. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  13318. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  13319. }
  13320. }
  13321. }
  13322. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  13323. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  13324. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  13325. {
  13326. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  13327. }
  13328. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  13329. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  13330. (mCompiler->mResolvePassData != NULL))
  13331. {
  13332. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  13333. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  13334. }
  13335. if (methodInstance->mHasBeenProcessed)
  13336. {
  13337. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  13338. return;
  13339. }
  13340. if (methodInstance->mFailedConstraints)
  13341. {
  13342. // The only way this should be able to happen is if we fail our generic param check
  13343. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  13344. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  13345. methodInstance->mHasBeenProcessed = true;
  13346. return;
  13347. }
  13348. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  13349. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  13350. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  13351. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  13352. {
  13353. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13354. auto owningModule = methodInstance->GetOwner()->mModule;
  13355. if (owningModule->mIsScratchModule)
  13356. {
  13357. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  13358. }
  13359. else
  13360. {
  13361. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  13362. if (owningModule->mOnDemandMethodCount > 0)
  13363. owningModule->mOnDemandMethodCount--;
  13364. }
  13365. }
  13366. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  13367. // self-referencing append allocations in ctor@calcAppend
  13368. methodInstance->mHasBeenProcessed = true;
  13369. mIncompleteMethodCount--;
  13370. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  13371. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  13372. auto methodDef = methodInstance->mMethodDef;
  13373. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13374. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  13375. {
  13376. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  13377. // so we get the new vdata for it
  13378. methodInstance->GetOwner()->mDirty = true;
  13379. }
  13380. int dependentGenericStartIdx = 0;
  13381. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  13382. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  13383. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13384. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  13385. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  13386. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  13387. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  13388. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  13389. if ((methodInstance->mIsReified) &&
  13390. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  13391. {
  13392. mCurTypeInstance->mHasBeenInstantiated = true;
  13393. }
  13394. // Warnings are shown in the capture phase
  13395. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  13396. mIgnoreWarnings = true;
  13397. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  13398. UseDefaultSrcPos();
  13399. // We may not actually be populated in relatively rare autocompelte cases
  13400. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  13401. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  13402. BfAstNode* nameNode = NULL;
  13403. if (methodDeclaration != NULL)
  13404. {
  13405. nameNode = methodDeclaration->mNameNode;
  13406. if (nameNode == NULL)
  13407. {
  13408. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  13409. nameNode = ctorDeclaration->mThisToken;
  13410. }
  13411. }
  13412. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  13413. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  13414. {
  13415. if (methodInstance->GetExplicitInterface() == NULL)
  13416. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  13417. else
  13418. {
  13419. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  13420. {
  13421. auto ifaceInst = ifaceEntry.mInterfaceType;
  13422. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  13423. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  13424. if (methodInstance->GetExplicitInterface() != ifaceInst)
  13425. continue;
  13426. ifaceInst->mTypeDef->PopulateMemberSets();
  13427. BfMethodDef* nextMethod = NULL;
  13428. BfMemberSetEntry* entry = NULL;
  13429. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  13430. nextMethod = (BfMethodDef*)entry->mMemberDef;
  13431. while (nextMethod != NULL)
  13432. {
  13433. auto checkMethod = nextMethod;
  13434. nextMethod = nextMethod->mNextWithSameName;
  13435. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  13436. if (implMethodInst == methodInstance)
  13437. {
  13438. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  13439. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  13440. }
  13441. }
  13442. }
  13443. }
  13444. if (methodDef->mIsOverride)
  13445. {
  13446. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  13447. {
  13448. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  13449. if (ventry.mDeclaringMethod.mMethodNum == -1)
  13450. continue;
  13451. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  13452. if (virtMethod != NULL)
  13453. {
  13454. if (virtMethod == methodInstance)
  13455. {
  13456. // Is matching method
  13457. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  13458. {
  13459. auto baseType = mCurTypeInstance->mBaseType;
  13460. if (baseType != NULL)
  13461. {
  13462. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  13463. baseType = baseType->mBaseType;
  13464. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  13465. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  13466. }
  13467. }
  13468. break;
  13469. }
  13470. }
  13471. }
  13472. }
  13473. }
  13474. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  13475. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13476. {
  13477. if (mBfIRBuilder->mIgnoreWrites)
  13478. return;
  13479. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  13480. if (!methodInstance->mIRFunction)
  13481. {
  13482. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  13483. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13484. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  13485. }
  13486. if (HasCompiledOutput())
  13487. {
  13488. BfDllImportEntry dllImportEntry;
  13489. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  13490. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13491. mDllImportEntries.push_back(dllImportEntry);
  13492. }
  13493. return;
  13494. }
  13495. StringT<128> mangledName;
  13496. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  13497. if (!methodInstance->mIRFunction)
  13498. {
  13499. bool isIntrinsic = false;
  13500. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  13501. }
  13502. if (methodInstance->mIsIntrinsic)
  13503. return;
  13504. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  13505. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  13506. if (methodDef->mBody != NULL)
  13507. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13508. else if (methodDeclaration != NULL)
  13509. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13510. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13511. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13512. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  13513. {
  13514. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  13515. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13516. {
  13517. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  13518. }
  13519. }
  13520. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  13521. BfMethodState methodState;
  13522. if (mCurMethodState != NULL)
  13523. methodState.mClosureState = mCurMethodState->mClosureState;
  13524. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  13525. {
  13526. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  13527. if (methodInstance->mHotMethod == NULL)
  13528. CheckHotMethod(methodInstance, mangledName);
  13529. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  13530. }
  13531. methodState.mPrevMethodState = mCurMethodState;
  13532. methodState.mMethodInstance = methodInstance;
  13533. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  13534. if (methodInstance->GetCustomAttributes() != NULL)
  13535. {
  13536. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  13537. if (typeOptionsIdx != -1)
  13538. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  13539. }
  13540. BfTypeState typeState(mCurTypeInstance);
  13541. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  13542. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  13543. BfMethodInstance* unspecializedMethodInstance = NULL;
  13544. if ((prevMethodState.mPrevVal != NULL) &&
  13545. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  13546. {
  13547. // This is 'inner' (probably a closure) - use binding from outer function
  13548. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  13549. }
  13550. else if ((methodInstance->mIsUnspecialized) ||
  13551. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  13552. {
  13553. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13554. }
  13555. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  13556. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation))))
  13557. {
  13558. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  13559. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  13560. if (!unspecializedMethodInstance->mHasBeenProcessed)
  13561. {
  13562. // Make sure the unspecialized method is processed so we can take its bindings
  13563. // Clear mCurMethodState so we don't think we're in a local method
  13564. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  13565. mContext->ProcessMethod(unspecializedMethodInstance);
  13566. }
  13567. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13568. }
  13569. if (methodDef->mMethodType == BfMethodType_Operator)
  13570. {
  13571. auto operatorDef = (BfOperatorDef*) methodDef;
  13572. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  13573. auto paramErrorRefNode = refNode;
  13574. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  13575. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  13576. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  13577. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  13578. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  13579. {
  13580. if (methodDef->mParams.size() != 2)
  13581. {
  13582. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  13583. }
  13584. else
  13585. {
  13586. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13587. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  13588. {
  13589. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  13590. }
  13591. }
  13592. BfType* wantType = NULL;
  13593. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  13594. {
  13595. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  13596. }
  13597. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  13598. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  13599. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  13600. }
  13601. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  13602. {
  13603. if (methodDef->mParams.size() != 1)
  13604. {
  13605. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  13606. }
  13607. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  13608. {
  13609. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  13610. }
  13611. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  13612. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  13613. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  13614. {
  13615. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  13616. }
  13617. }
  13618. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  13619. {
  13620. if (methodDef->mParams.size() != 1)
  13621. {
  13622. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  13623. }
  13624. if (mCurMethodInstance->mReturnType->IsVoid())
  13625. {
  13626. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  13627. }
  13628. }
  13629. else // Conversion
  13630. {
  13631. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  13632. {
  13633. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  13634. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  13635. }
  13636. if (methodDef->mParams.size() != 1)
  13637. {
  13638. auto refNode = paramErrorRefNode;
  13639. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  13640. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  13641. Fail("Conversion operators must declare one parameter", refNode);
  13642. }
  13643. else
  13644. {
  13645. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13646. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  13647. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  13648. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  13649. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  13650. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  13651. // happened here
  13652. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  13653. {
  13654. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  13655. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  13656. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  13657. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  13658. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  13659. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  13660. }
  13661. }
  13662. }
  13663. }
  13664. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  13665. if (methodDef->mMethodType == BfMethodType_Mixin)
  13666. wantsDIData = false;
  13667. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  13668. wantsDIData = false;
  13669. bool wantsDIVariables = wantsDIData;
  13670. if (methodDef->mIsExtern)
  13671. wantsDIVariables = false;
  13672. SizedArray<BfIRMDNode, 8> diParams;
  13673. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  13674. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  13675. BfType* thisType = NULL;
  13676. if (!methodDef->mIsStatic)
  13677. {
  13678. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  13679. thisType = methodState.mClosureState->mClosureType;
  13680. else
  13681. thisType = mCurTypeInstance;
  13682. }
  13683. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  13684. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  13685. //////////////////////////////////////////////////////////////////////////
  13686. //
  13687. {
  13688. if (methodDeclaration != NULL)
  13689. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13690. else if (methodDef->mBody != NULL)
  13691. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13692. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13693. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13694. }
  13695. BfIRMDNode diFunction;
  13696. if (wantsDIData)
  13697. {
  13698. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  13699. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  13700. int defLine = mCurFilePosition.mCurLine;
  13701. if (mDICompileUnit)
  13702. {
  13703. int flags = 0;
  13704. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  13705. if (methodDef->mProtection == BfProtection_Public)
  13706. flags = llvm::DINode::FlagPublic;
  13707. else if (methodDef->mProtection == BfProtection_Protected)
  13708. flags = llvm::DINode::FlagProtected;
  13709. else
  13710. flags = llvm::DINode::FlagPrivate;
  13711. if (methodDef->mIsOverride)
  13712. {
  13713. //flags |= llvm::DINode::FlagVirtual;
  13714. }
  13715. else if (methodDef->mIsVirtual)
  13716. flags |= llvm::DINode::FlagIntroducedVirtual;
  13717. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  13718. flags |= llvm::DINode::FlagStaticMember;
  13719. else
  13720. {
  13721. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  13722. flags |= llvm::DINode::FlagStaticMember;
  13723. }
  13724. flags |= llvm::DINode::FlagPrototyped;
  13725. if (methodDef->mMethodType == BfMethodType_Ctor)
  13726. {
  13727. flags |= llvm::DINode::FlagArtificial;
  13728. }
  13729. auto llvmFunction = methodInstance->mIRFunction;
  13730. SizedArray<BfIRMDNode, 1> genericArgs;
  13731. SizedArray<BfIRValue, 1> genericConstValueArgs;
  13732. String methodName;
  13733. if (methodInstance->GetForeignType() != NULL)
  13734. {
  13735. methodName += TypeToString(methodInstance->GetForeignType());
  13736. methodName += ".";
  13737. }
  13738. if (methodInstance->GetExplicitInterface() != NULL)
  13739. {
  13740. methodName += TypeToString(methodInstance->GetExplicitInterface());
  13741. methodName += ".";
  13742. }
  13743. methodName += methodDef->mName;
  13744. if (methodInstance->GetNumGenericArguments() != 0)
  13745. {
  13746. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13747. {
  13748. if (genericArg->IsConstExprValue())
  13749. {
  13750. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  13751. while (genericConstValueArgs.size() < genericArgs.size())
  13752. genericConstValueArgs.push_back(BfIRValue());
  13753. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  13754. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  13755. }
  13756. else
  13757. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  13758. }
  13759. methodName += "<";
  13760. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  13761. {
  13762. if (i > 0)
  13763. methodName += ", ";
  13764. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  13765. methodName += TypeToString(type);
  13766. }
  13767. methodName += ">";
  13768. }
  13769. if ((methodName.empty()) && (methodDeclaration != NULL))
  13770. {
  13771. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  13772. {
  13773. methodName += "operator";
  13774. if (operatorDecl->mIsConvOperator)
  13775. {
  13776. methodName += " ";
  13777. methodName += TypeToString(methodInstance->mReturnType);
  13778. }
  13779. else if (operatorDecl->mOpTypeToken != NULL)
  13780. methodName += operatorDecl->mOpTypeToken->ToString();
  13781. }
  13782. }
  13783. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  13784. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13785. // defLine + 1, diFuncType, false, true,
  13786. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  13787. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  13788. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13789. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13790. defLine + 1, diFuncType, false, true,
  13791. llvm::dwarf::DW_VIRTUALITY_none,
  13792. 0,
  13793. nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13794. }
  13795. }
  13796. //////////////////////////////////////////////////////////////////////////
  13797. // Head and Init get rolled into Entry afterwards.
  13798. methodState.mIRFunction = methodInstance->mIRFunction;
  13799. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  13800. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  13801. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  13802. methodState.mCurScope->mDIScope = diFunction;
  13803. auto llvmEntryBlock = methodState.mIREntryBlock;
  13804. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  13805. if (methodDef->mBody != NULL)
  13806. {
  13807. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13808. }
  13809. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  13810. {
  13811. // We want to be able to step into delegate invokes -- we actually step over them
  13812. if (methodDef->mName != "Invoke")
  13813. {
  13814. UpdateSrcPos(typeDef->mTypeDeclaration);
  13815. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  13816. }
  13817. }
  13818. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  13819. mBfIRBuilder->ClearDebugLocation();
  13820. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  13821. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  13822. if (methodDef->mImportKind != BfImportKind_Dynamic)
  13823. {
  13824. int localIdx = 0;
  13825. int argIdx = 0;
  13826. if (methodInstance->HasStructRet())
  13827. argIdx++;
  13828. //
  13829. bool doDbgAgg = false;
  13830. Array<BfIRValue> splatAddrValues;
  13831. for ( ; argIdx < irParamCount; localIdx++)
  13832. {
  13833. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13834. if ((isThis) && (thisType->IsValuelessType()))
  13835. isThis = false;
  13836. BfLocalVariable* paramVar = NULL;
  13837. while (true)
  13838. {
  13839. BF_ASSERT(localIdx < methodState.mLocals.size());
  13840. paramVar = methodState.mLocals[localIdx];
  13841. if ((paramVar->mCompositeCount == -1) &&
  13842. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  13843. break;
  13844. localIdx++;
  13845. }
  13846. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  13847. {
  13848. paramVar->mIsReadOnly = true;
  13849. }
  13850. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType() != BfTypeCode_None);
  13851. if (paramVar->mResolvedType->IsMethodRef())
  13852. wantsAddr = false;
  13853. // if ((methodDef->mHasAppend) && (argIdx == 1))
  13854. // {
  13855. // BF_ASSERT(paramVar->mName == "appendIdx");
  13856. // wantsAddr = true;
  13857. // }
  13858. if ((!doDbgAgg) && (paramVar->mIsSplat))
  13859. {
  13860. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13861. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13862. BfTypeUtils::SplatIterate([&](BfType* checkType)
  13863. {
  13864. BfIRType splatIRType;
  13865. if (checkType->IsComposite())
  13866. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  13867. else
  13868. splatIRType = mBfIRBuilder->MapType(checkType);
  13869. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  13870. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  13871. if (!paramVar->mAddr)
  13872. paramVar->mAddr = allocaInst;
  13873. if (WantsLifetimes())
  13874. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13875. splatAddrValues.push_back(allocaInst);
  13876. }, paramVar->mResolvedType);
  13877. mBfIRBuilder->SetInsertPoint(prevInsert);
  13878. }
  13879. else if (isThis)
  13880. {
  13881. if (wantsAddr)
  13882. {
  13883. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13884. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13885. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  13886. if (paramVar->mIsSplat)
  13887. {
  13888. if (doDbgAgg)
  13889. {
  13890. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  13891. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13892. mBfIRBuilder->SetAllocaAlignment(allocaInst, thisType->mAlign);
  13893. paramVar->mAddr = allocaInst;
  13894. if (WantsLifetimes())
  13895. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13896. }
  13897. }
  13898. else
  13899. {
  13900. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  13901. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  13902. wantPtr = true;
  13903. if (wantPtr)
  13904. {
  13905. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  13906. }
  13907. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  13908. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13909. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  13910. paramVar->mAddr = allocaInst;
  13911. if (WantsLifetimes())
  13912. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13913. }
  13914. mBfIRBuilder->SetInsertPoint(prevInsert);
  13915. }
  13916. }
  13917. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  13918. {
  13919. // Address doesn't change so we don't have to alloca it
  13920. BfIRType allocType;
  13921. int alignSize = mSystem->mPtrSize;
  13922. if (paramVar->mResolvedType->IsRef())
  13923. {
  13924. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  13925. }
  13926. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  13927. {
  13928. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  13929. alignSize = paramVar->mResolvedType->mAlign;
  13930. }
  13931. else
  13932. {
  13933. paramVar->mHasLocalStructBacking = true;
  13934. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  13935. if (typeInst != NULL)
  13936. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  13937. else
  13938. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  13939. }
  13940. if (wantsAddr)
  13941. {
  13942. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13943. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13944. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  13945. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  13946. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13947. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  13948. paramVar->mAddr = allocaInst;
  13949. mBfIRBuilder->SetInsertPoint(prevInsert);
  13950. if (WantsLifetimes())
  13951. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13952. }
  13953. }
  13954. else if (wantsAddr)
  13955. {
  13956. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  13957. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13958. paramVar->mAddr = allocaInst;
  13959. }
  13960. if (paramVar->mIsSplat)
  13961. {
  13962. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  13963. }
  13964. else
  13965. {
  13966. argIdx++;
  13967. }
  13968. }
  13969. if (methodDef->mBody != NULL)
  13970. UpdateSrcPos(methodDef->mBody);
  13971. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13972. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  13973. int declArgIdx = 0;
  13974. localIdx = 0;
  13975. argIdx = 0;
  13976. if (methodInstance->HasStructRet())
  13977. argIdx++;
  13978. int splatAddrIdx = 0;
  13979. while (localIdx < (int)methodState.mLocals.size())
  13980. {
  13981. int curLocalIdx = localIdx++;
  13982. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  13983. if (!paramVar->IsParam())
  13984. continue;
  13985. if (paramVar->mCompositeCount != -1)
  13986. continue;
  13987. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13988. if ((isThis) && (thisType->IsValuelessType()))
  13989. isThis = false;
  13990. BfIRMDNode diVariable;
  13991. if (wantsDIData)
  13992. {
  13993. String paramName = paramVar->mName;
  13994. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13995. if (isThis)
  13996. {
  13997. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  13998. paramName = "__closure";
  13999. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14000. {
  14001. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14002. bool wantRef = paramVar->mResolvedType->IsComposite();
  14003. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  14004. wantRef = true;
  14005. if (wantRef)
  14006. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14007. }
  14008. else if (!paramVar->mResolvedType->IsValueType())
  14009. {
  14010. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  14011. }
  14012. }
  14013. else
  14014. {
  14015. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14016. {
  14017. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14018. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14019. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14020. }
  14021. }
  14022. if ((!paramVar->mIsSplat) || (doDbgAgg))
  14023. {
  14024. if (paramVar->mResolvedType->IsValuelessType())
  14025. {
  14026. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  14027. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14028. }
  14029. else if (paramVar->mIsImplicitParam)
  14030. {
  14031. // Annotate this specially?
  14032. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14033. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14034. }
  14035. else
  14036. {
  14037. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14038. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14039. }
  14040. paramVar->mDbgVarInst = diVariable;
  14041. }
  14042. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  14043. {
  14044. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14045. // {
  14046. // // Only add this placeholder if we don't have any values
  14047. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14048. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14049. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  14050. // }
  14051. }
  14052. }
  14053. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  14054. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  14055. {
  14056. // Write our argument value into the .addr
  14057. mBfIRBuilder->ClearDebugLocation();
  14058. if (paramVar->mIsSplat)
  14059. {
  14060. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14061. if (doDbgAgg)
  14062. {
  14063. auto curArgIdx = argIdx;
  14064. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curDestAddr)
  14065. {
  14066. if (checkType->IsStruct())
  14067. {
  14068. auto checkTypeInstance = checkType->ToTypeInstance();
  14069. if (checkTypeInstance->mBaseType != NULL)
  14070. {
  14071. auto baseDestAddr = mBfIRBuilder->CreateBitCast(curDestAddr, mBfIRBuilder->MapTypeInstPtr(checkTypeInstance->mBaseType));
  14072. checkTypeLambda(checkTypeInstance->mBaseType, baseDestAddr);
  14073. }
  14074. if (checkTypeInstance->mIsUnion)
  14075. {
  14076. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14077. if (!unionInnerType->IsValuelessType())
  14078. {
  14079. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 1);
  14080. checkTypeLambda(unionInnerType, newDestAddr);
  14081. }
  14082. if (checkTypeInstance->IsEnum())
  14083. {
  14084. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14085. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 2);
  14086. checkTypeLambda(dscrType, newDestAddr);
  14087. }
  14088. }
  14089. else
  14090. {
  14091. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14092. {
  14093. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14094. if (fieldInstance->mDataIdx >= 0)
  14095. {
  14096. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, fieldInstance->mDataIdx);
  14097. checkTypeLambda(fieldInstance->GetResolvedType(), newDestAddr);
  14098. }
  14099. }
  14100. }
  14101. }
  14102. else if (checkType->IsMethodRef())
  14103. {
  14104. BF_FATAL("Unimplemented");
  14105. // BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  14106. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14107. // {
  14108. // checkTypeLambda->
  14109. // }
  14110. }
  14111. else if (!checkType->IsValuelessType())
  14112. {
  14113. mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), curDestAddr, paramVar->mResolvedType->mAlign);
  14114. curArgIdx++;
  14115. }
  14116. };
  14117. checkTypeLambda(paramVar->mResolvedType, paramVar->mAddr);
  14118. }
  14119. }
  14120. else
  14121. {
  14122. bool handled = false;
  14123. //if ((!isThis) || (!methodDef->mIsMutating && !methodDef->mNoSplat))
  14124. if (paramVar->mIsLowered)
  14125. {
  14126. auto loweredTypeCode = paramVar->mResolvedType->GetLoweredType();
  14127. BF_ASSERT(loweredTypeCode != BfTypeCode_None);
  14128. if (loweredTypeCode != BfTypeCode_None)
  14129. {
  14130. // We have a lowered type coming in, so we have to cast the .addr before storing
  14131. auto primType = GetPrimitiveType(loweredTypeCode);
  14132. auto primPtrType = CreatePointerType(primType);
  14133. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, mBfIRBuilder->MapType(primPtrType));
  14134. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, paramVar->mResolvedType->mSize);
  14135. // We don't want to allow directly using value
  14136. paramVar->mValue = BfIRValue();
  14137. handled = true;
  14138. }
  14139. }
  14140. if (!handled)
  14141. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  14142. }
  14143. }
  14144. if (!isThis)
  14145. declArgIdx++;
  14146. if (methodDef->mBody != NULL)
  14147. UpdateSrcPos(methodDef->mBody);
  14148. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14149. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14150. else if (methodDeclaration == NULL)
  14151. UseDefaultSrcPos();
  14152. // Write our argument value into the .addr
  14153. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14154. {
  14155. int splatComponentIdx = 0;
  14156. auto curArgIdx = argIdx;
  14157. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  14158. {
  14159. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  14160. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  14161. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  14162. mBfIRBuilder->ClearDebugLocation(storeInst);
  14163. if (wantsDIData)
  14164. {
  14165. BfIRMDNode diType;
  14166. if (checkType->IsComposite())
  14167. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  14168. else
  14169. diType = mBfIRBuilder->DbgGetType(checkType);
  14170. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14171. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14172. if (wantsDIVariables)
  14173. {
  14174. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  14175. }
  14176. }
  14177. curArgIdx++;
  14178. splatComponentIdx++;
  14179. };
  14180. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  14181. {
  14182. if (checkType->IsStruct())
  14183. {
  14184. auto checkTypeInstance = checkType->ToTypeInstance();
  14185. if (checkTypeInstance->mBaseType != NULL)
  14186. {
  14187. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  14188. }
  14189. if (checkTypeInstance->mIsUnion)
  14190. {
  14191. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14192. if (!unionInnerType->IsValuelessType())
  14193. {
  14194. _FinishSplatsIterate(unionInnerType, name + "$u");
  14195. }
  14196. if (checkTypeInstance->IsEnum())
  14197. {
  14198. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14199. _FinishSplatsIterate(dscrType, name + "$d");
  14200. }
  14201. }
  14202. else
  14203. {
  14204. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14205. {
  14206. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14207. auto fieldDef = fieldInstance->GetFieldDef();
  14208. if (fieldInstance->mDataIdx >= 0)
  14209. {
  14210. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  14211. }
  14212. }
  14213. }
  14214. }
  14215. else if (checkType->IsMethodRef())
  14216. {
  14217. auto methodRefType = (BfMethodRefType*)checkType;
  14218. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  14219. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  14220. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  14221. // {
  14222. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  14223. // if (!paramType->IsValuelessType())
  14224. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  14225. // }
  14226. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14227. {
  14228. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  14229. String paramName = methodInstance->GetParamName(paramIdx);
  14230. if (paramName == "this")
  14231. paramName = "__this";
  14232. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  14233. {
  14234. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14235. }
  14236. else
  14237. {
  14238. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14239. }
  14240. }
  14241. }
  14242. else if (!checkType->IsValuelessType())
  14243. {
  14244. _FinishSplats(checkType, name);
  14245. }
  14246. };
  14247. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14248. if (!paramVar->mConstValue)
  14249. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  14250. }
  14251. BfIRValue declareCall;
  14252. if (diVariable)
  14253. {
  14254. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14255. {
  14256. if (!paramVar->mAddr)
  14257. {
  14258. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  14259. {
  14260. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14261. {
  14262. // We don't need to set the location for this
  14263. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14264. }
  14265. }
  14266. else
  14267. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  14268. }
  14269. else
  14270. {
  14271. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  14272. }
  14273. }
  14274. }
  14275. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  14276. {
  14277. // We don't allow actually assignment to "this", so we just do a single load
  14278. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  14279. // we need to store it in the stack frame for debugging purposes
  14280. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  14281. mBfIRBuilder->ClearDebugLocation(loadedThis);
  14282. paramVar->mValue = loadedThis;
  14283. }
  14284. if ((wantsDIData) && (declareCall))
  14285. mBfIRBuilder->UpdateDebugLocation(declareCall);
  14286. if (paramVar->mIsSplat)
  14287. {
  14288. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14289. }
  14290. else if (!paramVar->mResolvedType->IsValuelessType())
  14291. {
  14292. argIdx++;
  14293. }
  14294. }
  14295. if (wantsDIData)
  14296. {
  14297. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  14298. }
  14299. }
  14300. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  14301. {
  14302. auto paramVar = mCurMethodState->mLocals[varIdx];
  14303. // We don't need this because the debug func type records the type of the splat param, and then the same can be inferred from the first
  14304. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  14305. // if (paramVar->mIsSplat)
  14306. // {
  14307. // if (wantsDIVariables)
  14308. // {
  14309. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  14310. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  14311. // }
  14312. // }
  14313. if (paramVar->mResolvedType->IsValuelessType())
  14314. {
  14315. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14316. {
  14317. // Only add this placeholder if we don't have any values
  14318. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14319. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14320. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14321. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14322. }
  14323. }
  14324. }
  14325. if (IsTargetingBeefBackend())
  14326. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  14327. if (methodState.mClosureState != NULL)
  14328. {
  14329. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  14330. {
  14331. BfLocalVariable* localVar = new BfLocalVariable();
  14332. *localVar = constLocal;
  14333. AddLocalVariableDef(localVar, true);
  14334. }
  14335. }
  14336. bool wantsRemoveBody = false;
  14337. bool skipBody = false;
  14338. bool skipUpdateSrcPos = false;
  14339. bool skipEndChecks = false;
  14340. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodDef->mImportKind != BfImportKind_Dynamic);
  14341. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14342. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  14343. hasExternSpecifier = true;
  14344. // Allocate, clear, set classVData
  14345. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  14346. {
  14347. CreateStaticCtor();
  14348. }
  14349. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14350. {
  14351. skipBody = true;
  14352. skipEndChecks = true;
  14353. if (HasCompiledOutput())
  14354. {
  14355. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  14356. mBfIRBuilder->ClearDebugLocation();
  14357. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  14358. BfTypeInstance* innerType = boxedType->mElementType;
  14359. PopulateType(innerType, BfPopulateType_DataAndMethods);
  14360. mBfIRBuilder->PopulateType(mCurTypeInstance);
  14361. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14362. if (methodInstance->mIsForeignMethodDef)
  14363. {
  14364. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  14365. }
  14366. BfTypeVector methodGenericArguments;
  14367. if (methodInstance->mMethodInfoEx != NULL)
  14368. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  14369. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  14370. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  14371. {
  14372. if (!methodInstance->mReturnType->IsValuelessType())
  14373. {
  14374. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  14375. CreateReturn(retVal);
  14376. }
  14377. }
  14378. else
  14379. {
  14380. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  14381. SizedArray<BfIRValue, 8> innerParams;
  14382. BfExprEvaluator exprEvaluator(this);
  14383. if (!innerType->IsValuelessType())
  14384. {
  14385. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  14386. BfTypedValue innerVal(thisValue, innerType, true);
  14387. if (boxedType->IsBoxedStructPtr())
  14388. {
  14389. innerVal = LoadValue(innerVal);
  14390. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  14391. }
  14392. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  14393. }
  14394. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14395. {
  14396. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  14397. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  14398. exprEvaluator.PushArg(localVal, innerParams);
  14399. }
  14400. if (!innerMethodInstance.mFunc)
  14401. {
  14402. BF_ASSERT(innerType->IsUnspecializedType());
  14403. }
  14404. else if (methodInstance->HasStructRet())
  14405. {
  14406. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14407. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(0), methodInstance->mReturnType, true);
  14408. exprEvaluator.mReceivingValue = &returnType;
  14409. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14410. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  14411. mBfIRBuilder->CreateRetVoid();
  14412. }
  14413. else
  14414. {
  14415. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14416. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14417. if (mCurMethodInstance->mReturnType->IsValueType())
  14418. retVal = LoadValue(retVal);
  14419. CreateReturn(retVal.mValue);
  14420. }
  14421. }
  14422. }
  14423. mCurMethodState->SetHadReturn(true);
  14424. mCurMethodState->mLeftBlockUncond = true;
  14425. }
  14426. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  14427. {
  14428. SetIllegalSrcPos();
  14429. mBfIRBuilder->ClearDebugLocation();
  14430. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  14431. auto thisVal = GetThis();
  14432. int prevSize = mContext->mBfObjectType->mInstSize;
  14433. int curSize = mCurTypeInstance->mInstSize;
  14434. if (curSize > prevSize)
  14435. {
  14436. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  14437. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  14438. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  14439. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  14440. }
  14441. skipUpdateSrcPos = true;
  14442. }
  14443. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  14444. {
  14445. EmitCtorBody(skipBody);
  14446. }
  14447. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  14448. {
  14449. EmitDtorBody();
  14450. skipBody = true;
  14451. }
  14452. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  14453. {
  14454. EmitIteratorBlock(skipBody);
  14455. }
  14456. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  14457. {
  14458. // We need to be able to mark deleted objects
  14459. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14460. }
  14461. auto customAttributes = methodInstance->GetCustomAttributes();
  14462. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  14463. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14464. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  14465. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  14466. {
  14467. // We chain even non-default ctors to the default ctors
  14468. auto defaultCtor = methodInstance;
  14469. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  14470. CallChainedMethods(defaultCtor, false);
  14471. }
  14472. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14473. if (methodDef->mBody == NULL)
  14474. {
  14475. if (methodDeclaration != NULL)
  14476. {
  14477. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  14478. {
  14479. if (operatorDeclaration->mIsConvOperator)
  14480. wantsRemoveBody = true;
  14481. }
  14482. }
  14483. bool isDllImport = false;
  14484. if (methodDef->mImportKind == BfImportKind_Static)
  14485. {
  14486. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14487. {
  14488. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14489. {
  14490. if (customAttr.mCtorArgs.size() == 1)
  14491. {
  14492. auto fileNameArg = customAttr.mCtorArgs[0];
  14493. int strNum = 0;
  14494. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  14495. if (constant != NULL)
  14496. {
  14497. if (constant->IsNull())
  14498. continue; // Invalid
  14499. strNum = constant->mInt32;
  14500. }
  14501. else
  14502. {
  14503. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  14504. }
  14505. if (!mImportFileNames.Contains(strNum))
  14506. mImportFileNames.Add(strNum);
  14507. }
  14508. }
  14509. }
  14510. //mImportFileNames
  14511. }
  14512. else if (methodDef->mImportKind == BfImportKind_Dynamic)
  14513. {
  14514. CreateDllImportMethod();
  14515. }
  14516. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  14517. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  14518. {
  14519. if (mCurTypeInstance->mTypeDef->mIsFunction)
  14520. {
  14521. // Emit nothing
  14522. }
  14523. else
  14524. {
  14525. CreateDelegateInvokeMethod();
  14526. mCurMethodState->SetHadReturn(true);
  14527. mCurMethodState->mLeftBlockUncond = true;
  14528. }
  14529. }
  14530. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14531. {
  14532. if (mCurTypeInstance->IsObject())
  14533. {
  14534. CreateDynamicCastMethod();
  14535. }
  14536. else
  14537. {
  14538. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14539. mCurMethodState->mHadReturn = true;
  14540. }
  14541. }
  14542. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14543. {
  14544. BfIRValue ret;
  14545. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  14546. {
  14547. // This can happen if we provide an invalid name
  14548. AssertErrorState();
  14549. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  14550. }
  14551. else
  14552. {
  14553. // Unfortunate DebugLoc shenanigans-
  14554. // Our params get removed if we don't have any DebugLocs, but we don't want to actually be able to step into this method,
  14555. // so we only set the loc on the CreateRet which gets inlined out
  14556. mBfIRBuilder->SaveDebugLocation();
  14557. mBfIRBuilder->ClearDebugLocation();
  14558. BfIRValue fromBool;
  14559. if (!mCurTypeInstance->IsTypedPrimitive())
  14560. {
  14561. fromBool = GetDefaultValue(methodInstance->mReturnType);
  14562. }
  14563. else
  14564. {
  14565. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  14566. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  14567. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  14568. }
  14569. mBfIRBuilder->RestoreDebugLocation();
  14570. ret = mBfIRBuilder->CreateRet(fromBool);
  14571. //ExtendLocalLifetimes(0);
  14572. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14573. }
  14574. mCurMethodState->SetHadReturn(true);
  14575. mCurMethodState->mLeftBlockUncond = true;
  14576. }
  14577. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  14578. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14579. {
  14580. BfIRValue ret;
  14581. // Unfortunate DebugLoc shenanigans-
  14582. // Our params get removed if we don't have any DebugLocs, but we don't want to actually be able to step into this method,
  14583. // so we only set the loc on the CreateRet which gets inlined out
  14584. mBfIRBuilder->SaveDebugLocation();
  14585. mBfIRBuilder->ClearDebugLocation();
  14586. BfIRValue fromBool;
  14587. mBfIRBuilder->RestoreDebugLocation();
  14588. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  14589. //ExtendLocalLifetimes(0);
  14590. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14591. mCurMethodState->SetHadReturn(true);
  14592. mCurMethodState->mLeftBlockUncond = true;
  14593. }
  14594. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14595. {
  14596. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14597. if (HasCompiledOutput())
  14598. {
  14599. EmitEnumToStringBody();
  14600. }
  14601. mBfIRBuilder->CreateRetVoid();
  14602. mCurMethodState->SetHadReturn(true);
  14603. mCurMethodState->mLeftBlockUncond = true;
  14604. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14605. }
  14606. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14607. {
  14608. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14609. if (HasCompiledOutput())
  14610. {
  14611. EmitTupleToStringBody();
  14612. }
  14613. mBfIRBuilder->CreateRetVoid();
  14614. mCurMethodState->SetHadReturn(true);
  14615. mCurMethodState->mLeftBlockUncond = true;
  14616. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14617. }
  14618. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  14619. {
  14620. CreateValueTypeEqualsMethod();
  14621. skipBody = true;
  14622. skipEndChecks = true;
  14623. }
  14624. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  14625. {
  14626. CreateValueTypeEqualsMethod();
  14627. skipBody = true;
  14628. skipEndChecks = true;
  14629. }
  14630. else if (HasCompiledOutput())
  14631. {
  14632. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  14633. {
  14634. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14635. {
  14636. EmitGCMarkMembers();
  14637. }
  14638. else if (!mCurTypeInstance->IsObject())
  14639. {
  14640. }
  14641. }
  14642. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  14643. {
  14644. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14645. {
  14646. EmitGCFindTLSMembers();
  14647. }
  14648. }
  14649. }
  14650. }
  14651. else if (!skipBody)
  14652. {
  14653. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  14654. if (isEmptyBodied) // Generate autoProperty things
  14655. {
  14656. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14657. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  14658. {
  14659. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  14660. Fail("Body expected", methodDef->mBody);
  14661. }
  14662. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  14663. {
  14664. if (methodInstance->mReturnType->IsValuelessType())
  14665. {
  14666. mBfIRBuilder->CreateRetVoid();
  14667. }
  14668. else if (HasCompiledOutput())
  14669. {
  14670. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14671. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14672. BfFieldDef* fieldDef = NULL;
  14673. if (fieldInstance != NULL)
  14674. fieldDef = fieldInstance->GetFieldDef();
  14675. BfType* retType = methodInstance->mReturnType;
  14676. if (retType->IsRef())
  14677. retType = retType->GetUnderlyingType();
  14678. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  14679. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14680. {
  14681. BfTypedValue lookupValue;
  14682. if (fieldDef->IsNonConstStatic())
  14683. lookupValue = ReferenceStaticField(fieldInstance);
  14684. else if (mCurTypeInstance->IsObject())
  14685. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  14686. else
  14687. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mFieldIdx);
  14688. if (!methodInstance->mReturnType->IsRef())
  14689. lookupValue = LoadValue(lookupValue);
  14690. mBfIRBuilder->CreateRet(lookupValue.mValue);
  14691. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14692. }
  14693. else
  14694. {
  14695. // This can happen if we have two properties with the same name but different types
  14696. AssertErrorState();
  14697. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14698. }
  14699. }
  14700. else
  14701. {
  14702. // During autocomplete, the actual type may not have the proper field instance
  14703. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14704. }
  14705. mCurMethodState->SetHadReturn(true);
  14706. }
  14707. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  14708. {
  14709. if (!mCompiler->IsAutocomplete())
  14710. {
  14711. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14712. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14713. auto fieldDef = fieldInstance->GetFieldDef();
  14714. auto& lastParam = mCurMethodState->mLocals.back();
  14715. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  14716. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14717. {
  14718. BfIRValue lookupAddr;
  14719. if (fieldDef->IsNonConstStatic())
  14720. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  14721. else
  14722. {
  14723. auto thisValue = GetThis();
  14724. if (thisValue.IsSplat())
  14725. {
  14726. BF_FATAL("Should not happen");
  14727. }
  14728. if (mCurTypeInstance->IsObject())
  14729. thisValue = LoadValue(thisValue);
  14730. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  14731. }
  14732. mBfIRBuilder->CreateStore(lastParam->mValue, lookupAddr);
  14733. }
  14734. else if (!fieldInstance->mResolvedType->IsValuelessType())
  14735. {
  14736. // This can happen if we have two properties with the same name but different types
  14737. AssertErrorState();
  14738. }
  14739. }
  14740. }
  14741. }
  14742. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  14743. {
  14744. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  14745. if (mCurMethodInstance->HasStructRet())
  14746. {
  14747. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  14748. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  14749. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(0), allocaInst);
  14750. mBfIRBuilder->ClearDebugLocation(storeInst);
  14751. mCurMethodState->mRetValAddr = allocaInst;
  14752. }
  14753. else
  14754. {
  14755. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  14756. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  14757. }
  14758. }
  14759. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14760. {
  14761. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  14762. BfGetSymbolReferenceKind prevSymbolKind;
  14763. BfAutoComplete* prevAutoComplete;
  14764. if (mCompiler->mResolvePassData != NULL)
  14765. {
  14766. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  14767. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  14768. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  14769. }
  14770. EmitCtorCalcAppend();
  14771. if (mCompiler->mResolvePassData != NULL)
  14772. {
  14773. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  14774. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  14775. }
  14776. }
  14777. else if (!isEmptyBodied)
  14778. {
  14779. if (!mCurMethodState->mIRExitBlock)
  14780. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14781. bool isExpressionBody = false;
  14782. if (methodDeclaration != NULL)
  14783. {
  14784. if (methodDeclaration->mFatArrowToken != NULL)
  14785. isExpressionBody = true;
  14786. }
  14787. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  14788. {
  14789. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  14790. {
  14791. isExpressionBody = true;
  14792. }
  14793. }
  14794. else
  14795. {
  14796. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14797. {
  14798. if (!block->mChildArr.IsEmpty())
  14799. {
  14800. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  14801. {
  14802. if (exprStmt->mTrailingSemicolon == NULL)
  14803. isExpressionBody = true;
  14804. }
  14805. }
  14806. }
  14807. else
  14808. isExpressionBody = true;
  14809. }
  14810. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  14811. {
  14812. while (fieldDtorBody != NULL)
  14813. {
  14814. VisitEmbeddedStatement(fieldDtorBody->mBody);
  14815. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  14816. }
  14817. }
  14818. else if (!isExpressionBody)
  14819. {
  14820. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14821. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  14822. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  14823. VisitCodeBlock(bodyBlock);
  14824. }
  14825. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  14826. {
  14827. if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  14828. {
  14829. BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  14830. Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  14831. }
  14832. auto expectingType = mCurMethodInstance->mReturnType;
  14833. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  14834. // {
  14835. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  14836. // }
  14837. //TODO: Why did we have all this stuff for handling void?
  14838. // if (expectingType->IsVoid())
  14839. // {
  14840. // bool wasReturnGenericParam = false;
  14841. // if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  14842. // {
  14843. // wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  14844. // }
  14845. // else
  14846. // {
  14847. // auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  14848. // if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  14849. // wasReturnGenericParam = true;
  14850. // }
  14851. //
  14852. // // If we the void return was from a generic specialization, allow us to return a void result,
  14853. // // otherwise treat expression as though it must be a statement
  14854. // bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  14855. // if (isStatement)
  14856. // expectingType = NULL;
  14857. // }
  14858. UpdateSrcPos(expressionBody);
  14859. auto retVal = CreateValueFromExpression(expressionBody, expectingType);
  14860. if ((retVal) && (expectingType != NULL))
  14861. {
  14862. mCurMethodState->mHadReturn = true;
  14863. retVal = LoadValue(retVal);
  14864. EmitReturn(retVal.mValue);
  14865. }
  14866. }
  14867. }
  14868. }
  14869. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  14870. if (skipUpdateSrcPos)
  14871. {
  14872. // Skip
  14873. }
  14874. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  14875. UpdateSrcPos(bodyBlock->mCloseBrace);
  14876. else if (methodDef->mBody != NULL)
  14877. UpdateSrcPos(methodDef->mBody);
  14878. else if (methodDeclaration != NULL)
  14879. UpdateSrcPos(methodDeclaration);
  14880. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14881. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14882. else
  14883. UseDefaultSrcPos();
  14884. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14885. {
  14886. if (mCurMethodState->mRetVal)
  14887. {
  14888. mCurMethodState->SetHadReturn(true);
  14889. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  14890. mBfIRBuilder->CreateRet(retVal);
  14891. }
  14892. else
  14893. AssertErrorState();
  14894. }
  14895. if (!mCurMethodState->mHadReturn)
  14896. {
  14897. // Clear off the stackallocs that have occurred after a scopeData break
  14898. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  14899. }
  14900. if (mCurMethodState->mIRExitBlock)
  14901. {
  14902. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  14903. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  14904. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  14905. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  14906. if (!mCurMethodState->mDIRetVal)
  14907. CreateDIRetVal();
  14908. }
  14909. for (auto localVar : mCurMethodState->mLocals)
  14910. {
  14911. if ((skipEndChecks) || (bodyBlock == NULL))
  14912. break;
  14913. LocalVariableDone(localVar, true);
  14914. }
  14915. if (mCurMethodState->mIRExitBlock)
  14916. {
  14917. if ((mCurMethodState->mRetVal) && (!mCurMethodInstance->HasStructRet()))
  14918. {
  14919. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  14920. CreateReturn(loadedVal);
  14921. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14922. if (mCurMethodState->mDIRetVal)
  14923. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  14924. }
  14925. else
  14926. {
  14927. // Have something on the last line to step onto
  14928. if (mHasFullDebugInfo)
  14929. {
  14930. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  14931. UpdateSrcPos(bodyBlock->mCloseBrace);
  14932. EmitEnsureInstructionAt();
  14933. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  14934. {
  14935. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  14936. mBfIRBuilder->EnsureFunctionPatchable();
  14937. }
  14938. }
  14939. mBfIRBuilder->CreateRetVoid();
  14940. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14941. if (mCurMethodState->mDIRetVal)
  14942. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  14943. }
  14944. }
  14945. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  14946. {
  14947. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  14948. {
  14949. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  14950. {
  14951. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  14952. mBfIRBuilder->EnsureFunctionPatchable();
  14953. }
  14954. mBfIRBuilder->CreateRetVoid();
  14955. }
  14956. }
  14957. else
  14958. {
  14959. if (!mCurMethodState->mHadReturn)
  14960. {
  14961. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  14962. if (bodyBlock != NULL)
  14963. {
  14964. if (bodyBlock->mCloseBrace != NULL)
  14965. {
  14966. BfAstNode* target = bodyBlock->mCloseBrace;
  14967. Fail("Method must return value", target);
  14968. }
  14969. else
  14970. {
  14971. // It's possible to not have a closing brace if the method ends in an EOF
  14972. AssertErrorState();
  14973. }
  14974. }
  14975. }
  14976. }
  14977. // Move 'init' into 'entry'
  14978. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  14979. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  14980. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  14981. {
  14982. // Don't keep instructions for unspecialized types
  14983. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14984. }
  14985. if ((hasExternSpecifier) && (!skipBody))
  14986. {
  14987. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  14988. // incase it gets called later by some hot-loaded coded
  14989. if (mCompiler->mOptions.mAllowHotSwapping)
  14990. CreateFakeCallerMethod(mangledName);
  14991. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14992. }
  14993. else if ((methodDef->mImportKind == BfImportKind_Dynamic) && (!mCompiler->IsHotCompile()))
  14994. {
  14995. // We only need the DLL stub when we may be hot swapping
  14996. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14997. }
  14998. else if (wantsRemoveBody)
  14999. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15000. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  15001. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  15002. // unspecialized types
  15003. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  15004. {
  15005. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  15006. methodInstance->mIRFunction = BfIRFunction();
  15007. }
  15008. CheckAddFailType();
  15009. if (mHadBuildError)
  15010. prevHadBuildError.CancelRestore();
  15011. if (mHadBuildWarning)
  15012. prevHadWarning.CancelRestore();
  15013. if (!methodDef->mIsLocalMethod)
  15014. ProcessMethod_ProcessDeferredLocals();
  15015. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15016. if (methodState.mHotDataReferenceBuilder != NULL)
  15017. {
  15018. AddHotDataReferences(&hotDataReferenceBuilder);
  15019. }
  15020. else
  15021. {
  15022. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  15023. {
  15024. // Remove the hot method data
  15025. auto hotMethod = methodInstance->mHotMethod;
  15026. auto prevMethod = hotMethod->mPrevVersion;
  15027. if (prevMethod != NULL)
  15028. {
  15029. // If there's a prev method then pull its data into the main HotMethod.
  15030. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  15031. // over to the main HotMethod definition to keep the HotMethod address
  15032. // invariant
  15033. for (auto ref : hotMethod->mReferences)
  15034. ref->Deref();
  15035. hotMethod->mReferences.Clear();
  15036. BF_ASSERT(prevMethod->mRefCount == 1);
  15037. hotMethod->mReferences = prevMethod->mReferences;
  15038. if (hotMethod->mSrcTypeVersion != NULL)
  15039. hotMethod->mSrcTypeVersion->Deref();
  15040. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  15041. prevMethod->mSrcTypeVersion = NULL;
  15042. prevMethod->mReferences.Clear();
  15043. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  15044. prevMethod->mPrevVersion = NULL;
  15045. prevMethod->Deref();
  15046. }
  15047. hotMethod->Deref();
  15048. methodInstance->mHotMethod = NULL;
  15049. }
  15050. }
  15051. }
  15052. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  15053. {
  15054. String name;
  15055. bool found = false;
  15056. auto checkMethodState = mCurMethodState;
  15057. while (checkMethodState != NULL)
  15058. {
  15059. if (checkMethodState->mClosureState == NULL)
  15060. break;
  15061. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  15062. {
  15063. found = true;
  15064. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  15065. break;
  15066. }
  15067. checkMethodState = checkMethodState->mPrevMethodState;
  15068. }
  15069. if (!found)
  15070. name += mCurMethodInstance->mMethodDef->mName;
  15071. int prevSepPos = (int)name.LastIndexOf('$');
  15072. if (prevSepPos != -1)
  15073. {
  15074. name.RemoveToEnd(prevSepPos);
  15075. }
  15076. name += "@";
  15077. name += baseName;
  15078. HashContext hashCtx;
  15079. if (anchorNode != NULL)
  15080. {
  15081. hashCtx.Mixin(anchorNode->GetStartCharId());
  15082. }
  15083. //
  15084. {
  15085. auto checkMethodState = declMethodState;
  15086. auto checkMixinState = declMixinState;
  15087. while (checkMethodState != NULL)
  15088. {
  15089. if (checkMixinState != NULL)
  15090. {
  15091. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  15092. }
  15093. checkMethodState = checkMethodState->mPrevMethodState;
  15094. if (checkMethodState != NULL)
  15095. checkMixinState = checkMethodState->mMixinState;
  15096. }
  15097. }
  15098. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15099. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15100. {
  15101. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  15102. {
  15103. StringT<128> genericTypeName;
  15104. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  15105. hashCtx.MixinStr(genericTypeName);
  15106. }
  15107. }
  15108. uint64 hashVal = hashCtx.Finish64();
  15109. name += "$";
  15110. name += BfTypeUtils::HashEncode64(hashVal);
  15111. return name;
  15112. }
  15113. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  15114. {
  15115. if (localMethod->mMethodDef != NULL)
  15116. return localMethod->mMethodDef;
  15117. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15118. auto declMethodState = localMethod->mDeclMethodState;
  15119. auto declMixinState = localMethod->mDeclMixinState;
  15120. auto typeInst = mCurTypeInstance;
  15121. BfAstNode* body = NULL;
  15122. BfAstNode* anchorNode = NULL;
  15123. auto _AllocDirectTypeRef = [&](BfType* type)
  15124. {
  15125. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  15126. directTypeRef->Init(type);
  15127. return directTypeRef;
  15128. };
  15129. auto methodDeclaration = localMethod->mMethodDeclaration;
  15130. if (methodDeclaration != NULL)
  15131. {
  15132. body = methodDeclaration->mBody;
  15133. anchorNode = methodDeclaration->mOpenParen;
  15134. }
  15135. else
  15136. {
  15137. body = localMethod->mLambdaBindExpr->mBody;
  15138. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  15139. }
  15140. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  15141. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  15142. BfMethodDef* methodDef;
  15143. if (methodDeclaration != NULL)
  15144. {
  15145. BfDefBuilder defBuilder(mCompiler->mSystem);
  15146. defBuilder.mPassInstance = mCompiler->mPassInstance;
  15147. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  15148. BfMethodDef* outerMethodDef = NULL;
  15149. if (localMethod->mOuterLocalMethod != NULL)
  15150. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  15151. else
  15152. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  15153. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  15154. }
  15155. else
  15156. {
  15157. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  15158. methodDef = new BfMethodDef();
  15159. methodDef->mName = localMethod->mMethodName;
  15160. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  15161. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  15162. methodDef->mBody = body;
  15163. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  15164. {
  15165. auto paramType = invokeMethod->GetParamType(paramIdx);
  15166. String paramName;
  15167. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  15168. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  15169. else
  15170. paramName = invokeMethod->GetParamName(paramIdx);
  15171. auto paramDef = new BfParameterDef();
  15172. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  15173. paramDef->mName = paramName;
  15174. methodDef->mParams.Add(paramDef);
  15175. }
  15176. }
  15177. methodDef->mIdx = ~methodLocalIdx;
  15178. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  15179. methodDef->mName = localMethod->mExpectedFullName;
  15180. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  15181. //
  15182. // if (!localMethod->mExpectedFullName.IsEmpty())
  15183. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  15184. methodDef->mIsStatic = true;
  15185. methodDef->mIsLocalMethod = true;
  15186. methodDef->mIsVirtual = false;
  15187. localMethod->mMethodDef = methodDef;
  15188. auto methodInstanceGroup = new BfMethodInstanceGroup();
  15189. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  15190. methodInstanceGroup->mMethodIdx = -1;
  15191. methodInstanceGroup->mOwner = mCurTypeInstance;
  15192. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  15193. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  15194. {
  15195. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  15196. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  15197. }
  15198. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  15199. {
  15200. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  15201. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  15202. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  15203. {
  15204. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  15205. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  15206. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  15207. autoComplete->mDefType = typeInst->mTypeDef;
  15208. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  15209. autoComplete->mReplaceLocalId = methodLocalIdx;
  15210. }
  15211. }
  15212. return localMethod->mMethodDef;
  15213. }
  15214. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  15215. {
  15216. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  15217. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  15218. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15219. auto declMethodState = localMethod->mDeclMethodState;
  15220. auto declMixinState = localMethod->mDeclMixinState;
  15221. auto callerMethodState = mCurMethodState;
  15222. auto typeInst = mCurTypeInstance;
  15223. auto methodDef = GetLocalMethodDef(localMethod);
  15224. BfAstNode* body = NULL;
  15225. auto methodDeclaration = localMethod->mMethodDeclaration;
  15226. if (methodDeclaration != NULL)
  15227. {
  15228. body = methodDeclaration->mBody;
  15229. }
  15230. else
  15231. {
  15232. body = localMethod->mLambdaBindExpr->mBody;
  15233. }
  15234. bool hadConcreteInterfaceGenericArgument = false;
  15235. BfTypeVector sanitizedMethodGenericArguments;
  15236. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  15237. // version of this method for this pass through the outermost method
  15238. int dependentGenericStartIdx = 0;
  15239. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15240. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  15241. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  15242. if (methodGenericArguments.size() == 0)
  15243. {
  15244. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15245. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  15246. }
  15247. else
  15248. {
  15249. int genericArgIdx = 0;
  15250. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  15251. // {
  15252. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  15253. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  15254. // }
  15255. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15256. {
  15257. auto genericArgType = methodGenericArguments[genericArgIdx];
  15258. BF_ASSERT(!genericArgType->IsRef());
  15259. if (genericArgType->IsConcreteInterfaceType())
  15260. {
  15261. hadConcreteInterfaceGenericArgument = true;
  15262. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  15263. genericArgType = concreteInterfaceType->mInterface;
  15264. }
  15265. sanitizedMethodGenericArguments.push_back(genericArgType);
  15266. }
  15267. }
  15268. bool wantPrematureMethodInstance = false;
  15269. if (!force)
  15270. {
  15271. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  15272. }
  15273. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  15274. bool isDefaultPass = true;
  15275. BfTypeVector lookupMethodGenericArguments;
  15276. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15277. {
  15278. auto genericArgType = methodGenericArguments[genericArgIdx];
  15279. BF_ASSERT(!genericArgType->IsRef());
  15280. lookupMethodGenericArguments.Add(genericArgType);
  15281. if (genericArgType->IsGenericParam())
  15282. {
  15283. auto genericParam = (BfGenericParamType*)genericArgType;
  15284. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  15285. isDefaultPass = false;
  15286. }
  15287. else
  15288. {
  15289. isDefaultPass = false;
  15290. }
  15291. }
  15292. bool hadExistingMethodInstance = false;
  15293. if (methodInstance != NULL)
  15294. {
  15295. hadExistingMethodInstance = true;
  15296. }
  15297. else
  15298. {
  15299. if (isDefaultPass)
  15300. {
  15301. methodInstance = methodInstGroup->mDefault;
  15302. if (methodInstance != NULL)
  15303. {
  15304. hadExistingMethodInstance = true;
  15305. }
  15306. else
  15307. {
  15308. methodInstance = new BfMethodInstance();
  15309. methodInstGroup->mDefault = methodInstance;
  15310. }
  15311. }
  15312. else
  15313. {
  15314. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  15315. if (methodInstGroup->mMethodSpecializationMap == NULL)
  15316. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  15317. BfMethodInstance** methodInstancePtr = NULL;
  15318. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  15319. {
  15320. methodInstance = *methodInstancePtr;
  15321. hadExistingMethodInstance = true;
  15322. }
  15323. else
  15324. {
  15325. methodInstance = new BfMethodInstance();
  15326. *methodInstancePtr = methodInstance;
  15327. }
  15328. }
  15329. }
  15330. if (hadExistingMethodInstance)
  15331. {
  15332. if ((!methodInstance->mDisallowCalling) ||
  15333. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  15334. return BfModuleMethodInstance(methodInstance);
  15335. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  15336. }
  15337. else
  15338. {
  15339. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  15340. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  15341. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  15342. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  15343. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  15344. methodInstance->mMethodDef = methodDef;
  15345. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  15346. if (hadConcreteInterfaceGenericArgument)
  15347. methodInstance->mIgnoreBody = true;
  15348. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  15349. for (auto genericArg : sanitizedMethodGenericArguments)
  15350. {
  15351. if (genericArg->IsPrimitiveType())
  15352. genericArg = GetWrappedStructType(genericArg);
  15353. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  15354. }
  15355. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15356. {
  15357. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  15358. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  15359. }
  15360. SetupMethodIdHash(methodInstance);
  15361. }
  15362. auto _SetupMethodInstance = [&]()
  15363. {
  15364. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  15365. // Generic constraints
  15366. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15367. {
  15368. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  15369. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  15370. }
  15371. };
  15372. //////////////////////////////////////////////////////////////////////////
  15373. auto _VisitLambdaBody = [&]()
  15374. {
  15375. if (localMethod->mDeclOnly)
  15376. return;
  15377. if (mCompiler->mCanceling)
  15378. return;
  15379. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  15380. {
  15381. VisitCodeBlock(blockBody);
  15382. }
  15383. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  15384. CreateValueFromExpression(bodyExpr);
  15385. };
  15386. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  15387. {
  15388. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  15389. auto result = ResolveTypeRef(typeRef);
  15390. if (result == NULL)
  15391. result = mContext->mBfObjectType;
  15392. return result;
  15393. };
  15394. BfTypeInstance* outerClosure = NULL;
  15395. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  15396. outerClosure = declMethodState->mClosureState->mClosureType;
  15397. BfMethodState methodState;
  15398. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  15399. BfIRFunctionType funcType;
  15400. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15401. SizedArray<BfIRType, 0> paramTypes;
  15402. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, false);
  15403. mBfIRBuilder->SaveDebugLocation();
  15404. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  15405. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15406. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15407. BfDeferredLocalAssignData deferredLocalAssignData;
  15408. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  15409. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  15410. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  15411. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15412. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  15413. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  15414. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  15415. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  15416. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  15417. methodState.mIRFunction = declMethodState->mIRFunction;
  15418. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  15419. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  15420. BfClosureState closureState;
  15421. if (methodDef->mMethodType == BfMethodType_Mixin)
  15422. {
  15423. if (declMethodState != NULL)
  15424. {
  15425. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  15426. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  15427. else if (declMethodState->mMethodInstance != NULL)
  15428. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  15429. }
  15430. }
  15431. if (closureState.mReturnType == NULL)
  15432. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  15433. closureState.mCapturing = true;
  15434. closureState.mLocalMethod = localMethod;
  15435. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  15436. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  15437. methodState.mClosureState = &closureState;
  15438. closureState.mClosureType = outerClosure;
  15439. int outerLocalsCount = (int)methodState.mLocals.size();
  15440. if (!hadExistingMethodInstance)
  15441. {
  15442. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  15443. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  15444. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  15445. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  15446. auto declareModule = this;
  15447. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15448. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15449. BF_ASSERT(declareModule != NULL);
  15450. methodInstance->mDeclModule = declareModule;
  15451. _SetupMethodInstance();
  15452. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15453. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  15454. }
  15455. if (wantPrematureMethodInstance)
  15456. {
  15457. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  15458. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  15459. // its true method instance
  15460. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  15461. //BF_ASSERT(moduleMethodInstance);
  15462. return BfModuleMethodInstance(methodInstance);
  15463. }
  15464. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  15465. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  15466. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  15467. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  15468. closureState.mClosureMethodDef = methodDef;
  15469. bool wantsVisitBody = true;
  15470. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  15471. wantsVisitBody = false;
  15472. if (methodInstance->mIsUnspecializedVariation)
  15473. wantsVisitBody = false;
  15474. if (wantsVisitBody)
  15475. {
  15476. BP_ZONE("VisitLambdaBody");
  15477. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  15478. // this capture stage for each of those times
  15479. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  15480. /*
  15481. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  15482. // that will not occur during the actual lambda method generation, for example: returning a value
  15483. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  15484. // our AST nodes will still be visited
  15485. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  15486. */
  15487. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15488. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  15489. mBfIRBuilder->SaveDebugLocation();
  15490. closureState.mCaptureVisitingBody = true;
  15491. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  15492. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  15493. NewScopeState();
  15494. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  15495. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  15496. {
  15497. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  15498. for (auto localDef : methodState.mLocals)
  15499. {
  15500. if (localDef->mResolvedType->IsVar())
  15501. continue;
  15502. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  15503. }
  15504. }
  15505. _VisitLambdaBody();
  15506. RestoreScopeState();
  15507. //ProcessMethod(methodInstance);
  15508. closureState.mCaptureVisitingBody = false;
  15509. mBfIRBuilder->RestoreDebugLocation();
  15510. }
  15511. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  15512. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  15513. {
  15514. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  15515. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  15516. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  15517. }
  15518. //RestoreScopeState();
  15519. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  15520. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  15521. closureState.mClosureMethodDef = NULL;
  15522. for (auto methodInstance : closureState.mLocalMethodRefs)
  15523. {
  15524. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  15525. }
  15526. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  15527. prevIgnoreWrites.Restore();
  15528. std::multiset<BfClosureCapturedEntry> capturedEntries;
  15529. //
  15530. {
  15531. auto varMethodState = declMethodState;
  15532. while (varMethodState != NULL)
  15533. {
  15534. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  15535. {
  15536. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  15537. methodDef->mIsStatic = false;
  15538. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15539. methodDef->mIsMutating = true;
  15540. }
  15541. bool copyOuterCaptures = false;
  15542. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  15543. {
  15544. auto localVar = varMethodState->mLocals[localIdx];
  15545. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15546. {
  15547. if (localVar->mIsThis)
  15548. {
  15549. // We can only set mutating if our owning type is mutating
  15550. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  15551. {
  15552. if (mCurTypeInstance->IsValueType())
  15553. {
  15554. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15555. methodDef->mIsMutating = true;
  15556. }
  15557. }
  15558. methodDef->mIsStatic = false;
  15559. continue;
  15560. }
  15561. if ((localVar->mIsThis) && (outerClosure != NULL))
  15562. {
  15563. continue;
  15564. }
  15565. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  15566. {
  15567. closureState.mConstLocals.push_back(*localVar);
  15568. continue;
  15569. }
  15570. BfClosureCapturedEntry capturedEntry;
  15571. auto capturedType = localVar->mResolvedType;
  15572. bool captureByRef = false;
  15573. if (!capturedType->IsRef())
  15574. {
  15575. if (localVar->mIsThis)
  15576. {
  15577. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  15578. captureByRef = true;
  15579. }
  15580. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15581. captureByRef = true;
  15582. }
  15583. else
  15584. {
  15585. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  15586. {
  15587. capturedType = ((BfRefType*)capturedType)->mElementType;
  15588. }
  15589. }
  15590. if (captureByRef)
  15591. {
  15592. //capturedEntry.mIsByReference = true;
  15593. capturedType = CreateRefType(capturedType);
  15594. }
  15595. else
  15596. {
  15597. //capturedEntry.mIsByReference = false;
  15598. }
  15599. capturedEntry.mNameNode = localVar->mNameNode;
  15600. capturedEntry.mType = capturedType;
  15601. capturedEntry.mName = localVar->mName;
  15602. //capturedEntry.mLocalVarDef = localVar;
  15603. capturedEntries.insert(capturedEntry);
  15604. }
  15605. }
  15606. varMethodState = varMethodState->mPrevMethodState;
  15607. if ((varMethodState == NULL) ||
  15608. (varMethodState->mMixinState != NULL) ||
  15609. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  15610. break;
  15611. }
  15612. }
  15613. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  15614. {
  15615. auto fieldDef = copyField->GetFieldDef();
  15616. BfClosureCapturedEntry capturedEntry;
  15617. capturedEntry.mName = copyField->GetFieldDef()->mName;
  15618. capturedEntry.mType = copyField->mResolvedType;
  15619. if (capturedEntry.mType->IsRef())
  15620. {
  15621. // Keep by ref
  15622. }
  15623. else if (!fieldDef->mIsReadOnly)
  15624. {
  15625. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  15626. }
  15627. capturedEntries.insert(capturedEntry);
  15628. }
  15629. int captureIdx = 0;
  15630. for (auto& capturedEntry : capturedEntries)
  15631. {
  15632. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  15633. }
  15634. /*if (isDefaultPass)
  15635. {
  15636. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  15637. int captureIdx = 0;
  15638. for (auto& capturedEntry : capturedEntries)
  15639. {
  15640. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  15641. BfParameterDef* paramDef = new BfParameterDef();
  15642. paramDef->mName = capturedEntry.mName;
  15643. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  15644. directTypeRef->mType = capturedEntry.mType;
  15645. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  15646. paramDef->mTypeRef = directTypeRef;
  15647. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  15648. methodDef->mParams.Insert(captureIdx, paramDef);
  15649. captureIdx++;
  15650. }
  15651. }
  15652. else
  15653. {
  15654. auto defaultMethodInstance = methodInstGroup->mDefault;
  15655. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  15656. }*/
  15657. methodState.Reset();
  15658. closureState.mCapturing = false;
  15659. //////////////////////////////////////////////////////////////////////////
  15660. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  15661. if (methodInstance->mReturnType != NULL)
  15662. {
  15663. BF_ASSERT(methodInstance->mDisallowCalling);
  15664. // We did a premature declaration (without captures)
  15665. methodInstance->UndoDeclaration();
  15666. methodInstance->mDisallowCalling = false;
  15667. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  15668. }
  15669. auto declareModule = this;
  15670. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15671. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15672. BF_ASSERT(declareModule != NULL);
  15673. methodInstance->mDeclModule = declareModule;
  15674. _SetupMethodInstance();
  15675. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  15676. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15677. closureState.mReturnType = methodInstance->mReturnType;
  15678. mCompiler->mStats.mMethodsQueued++;
  15679. mCompiler->UpdateCompletion();
  15680. declareModule->mIncompleteMethodCount++;
  15681. mCompiler->mStats.mMethodsProcessed++;
  15682. if (!methodInstance->mIsReified)
  15683. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  15684. auto deferMethodState = rootMethodState;
  15685. // Since we handle errors & warnings in the capture phase, we don't need to process any local methods for resolve-only (unless we're doing a mDbgVerifyCodeGen)
  15686. if ((!localMethod->mDeclOnly) && (!methodInstance->mIsUnspecializedVariation) &&
  15687. (!mWantsIRIgnoreWrites) && (methodDef->mMethodType != BfMethodType_Mixin))
  15688. {
  15689. BP_ZONE("BfDeferredLocalMethod:create");
  15690. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  15691. deferredLocalMethod->mLocalMethod = localMethod;
  15692. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  15693. deferredLocalMethod->mMethodInstance = methodInstance;
  15694. auto checkMethodState = declMethodState;
  15695. while (checkMethodState != NULL)
  15696. {
  15697. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  15698. {
  15699. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  15700. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15701. }
  15702. if (checkMethodState->mMixinState != NULL)
  15703. {
  15704. BfMixinRecord mixinRecord;
  15705. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  15706. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15707. }
  15708. checkMethodState = checkMethodState->mPrevMethodState;
  15709. }
  15710. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  15711. }
  15712. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15713. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  15714. mBfIRBuilder->RestoreDebugLocation();
  15715. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  15716. {
  15717. auto checkMethodState = mCurMethodState;
  15718. while (checkMethodState != NULL)
  15719. {
  15720. BfLocalMethod* nextLocalMethod = NULL;
  15721. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  15722. {
  15723. while (nextLocalMethod != NULL)
  15724. {
  15725. auto checkLocalMethod = nextLocalMethod;
  15726. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  15727. if (checkLocalMethod == localMethod)
  15728. continue;
  15729. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  15730. continue;
  15731. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  15732. if (checkMethodInstance == NULL)
  15733. continue; // Not generated yet
  15734. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  15735. {
  15736. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  15737. if (bfError != NULL)
  15738. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  15739. }
  15740. }
  15741. }
  15742. checkMethodState = checkMethodState->mPrevMethodState;
  15743. }
  15744. }
  15745. return BfModuleMethodInstance(methodInstance);
  15746. }
  15747. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  15748. {
  15749. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  15750. return 0;
  15751. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15752. int rootMethodGenericParamCount = 0;
  15753. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15754. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  15755. if (mCurMethodInstance == NULL)
  15756. return rootMethodGenericParamCount;
  15757. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  15758. return rootMethodGenericParamCount;
  15759. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  15760. if (callerLocalMethod == NULL)
  15761. return rootMethodGenericParamCount;
  15762. BfLocalMethod* calledLocalMethod = NULL;
  15763. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  15764. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  15765. {
  15766. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  15767. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  15768. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  15769. }
  15770. return rootMethodGenericParamCount;
  15771. }
  15772. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  15773. {
  15774. auto methodDef = methodInstance->mMethodDef;
  15775. if (methodInstance->GetCustomAttributes() != NULL)
  15776. return;
  15777. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15778. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  15779. auto typeInstance = methodInstance->GetOwner();
  15780. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  15781. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15782. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL))
  15783. {
  15784. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15785. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15786. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(methodDeclaration->mAttributes,
  15787. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method);
  15788. }
  15789. else if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mAttributes != NULL))
  15790. {
  15791. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15792. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15793. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mAttributes, BfAttributeTargets_Method);
  15794. }
  15795. }
  15796. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  15797. {
  15798. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  15799. {
  15800. // Don't create a func
  15801. return;
  15802. }
  15803. auto typeInstance = methodInstance->GetOwner();
  15804. auto methodDef = methodInstance->mMethodDef;
  15805. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  15806. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  15807. if (mCompiler->mResolvePassData == NULL)
  15808. {
  15809. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  15810. {
  15811. typeInstance->mHasStaticInitMethod = true;
  15812. }
  15813. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  15814. {
  15815. typeInstance->mHasStaticDtorMethod = true;
  15816. }
  15817. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  15818. {
  15819. typeInstance->mHasStaticMarkMethod = true;
  15820. }
  15821. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  15822. {
  15823. typeInstance->mHasTLSFindMethod = true;
  15824. }
  15825. }
  15826. if (isTemporaryFunc)
  15827. {
  15828. BF_ASSERT((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL));
  15829. mangledName = "autocomplete_tmp";
  15830. }
  15831. if (!mBfIRBuilder->mIgnoreWrites)
  15832. {
  15833. BfIRFunction prevFunc;
  15834. // Remove old version (if we have one)
  15835. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15836. if (prevFunc)
  15837. {
  15838. if (methodDef->mIsExtern)
  15839. {
  15840. // Allow this
  15841. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  15842. }
  15843. else if (typeInstance->IsIRFuncUsed(prevFunc))
  15844. {
  15845. // We can have a collision of names when we have generic methods that differ only in
  15846. // their constraints, but they should only collide in their unspecialized form
  15847. // since only one will be chosen for a given concrete type
  15848. mCurMethodInstance->mMangleWithIdx = true;
  15849. mangledName.Clear();
  15850. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  15851. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15852. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  15853. }
  15854. else
  15855. {
  15856. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  15857. mBfIRBuilder->Func_EraseFromParent(prevFunc);
  15858. }
  15859. }
  15860. }
  15861. if (typeInstance != mContext->mBfObjectType)
  15862. {
  15863. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  15864. GetMethodCustomAttributes(methodInstance);
  15865. }
  15866. // if (prevFunc)
  15867. // {
  15868. // if (methodDef->mIsExtern)
  15869. // {
  15870. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  15871. // methodInstance->mIRFunction = prevFunc;
  15872. // }
  15873. // else
  15874. // {
  15875. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  15876. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  15877. // {
  15878. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  15879. // BfLogSysM("Ignoring function name collision\n");
  15880. // }
  15881. // else
  15882. // {
  15883. // if (methodDef->mMethodDeclaration == NULL)
  15884. // {
  15885. // AssertErrorState();
  15886. // }
  15887. // else
  15888. // {
  15889. // BF_ASSERT(mIsSpecialModule);
  15890. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  15891. // {
  15892. // // We shouldn't have name collisions on the first run!
  15893. // AssertErrorState();
  15894. // }
  15895. // }
  15896. // }
  15897. // BfLogSysM("Before erase\n");
  15898. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  15899. // }
  15900. // }
  15901. bool isIntrinsic = false;
  15902. if (!methodInstance->mIRFunction)
  15903. {
  15904. BfIRFunction func;
  15905. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  15906. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  15907. {
  15908. if (!mIsReified)
  15909. wantsLLVMFunc = false;
  15910. }*/
  15911. if (wantsLLVMFunc)
  15912. {
  15913. func = GetIntrinsic(methodInstance, true);
  15914. if (func)
  15915. {
  15916. isIntrinsic = true;
  15917. }
  15918. else
  15919. {
  15920. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  15921. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  15922. if (methodInstance->mAlwaysInline)
  15923. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15924. // if (prevFunc)
  15925. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  15926. }
  15927. methodInstance->mIRFunction = func;
  15928. //if (!ignoreWrites)
  15929. //BF_ASSERT(!func.IsFake());
  15930. }
  15931. }
  15932. if (outIsIntrinsic != NULL)
  15933. *outIsIntrinsic = isIntrinsic;
  15934. if (!isIntrinsic)
  15935. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  15936. }
  15937. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  15938. {
  15939. if (methodInstance->mHotMethod != NULL)
  15940. return;
  15941. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  15942. {
  15943. auto srcTypeInst = methodInstance->GetOwner();
  15944. StringT<128> mangledName = inMangledName;
  15945. if (mangledName.IsEmpty())
  15946. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  15947. // We always keep the current primary method at the same address
  15948. BfHotMethod* hotMethod;
  15949. BfHotMethod** hotMethodPtr;
  15950. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  15951. {
  15952. hotMethod = new BfHotMethod();
  15953. *hotMethodPtr = hotMethod;
  15954. hotMethod->mRefCount = 1;
  15955. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15956. #ifdef BF_DBG_HOTMETHOD_IDX
  15957. static int sMethodIdx = 0;
  15958. hotMethod->mMethodIdx = sMethodIdx++;
  15959. #endif
  15960. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15961. }
  15962. else
  15963. {
  15964. hotMethod = *hotMethodPtr;
  15965. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  15966. {
  15967. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  15968. auto prevHotMethod = *hotMethodPtr;
  15969. hotMethod = new BfHotMethod();
  15970. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15971. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  15972. hotDupMethod->mRefCount++;
  15973. prevHotMethod->mReferences.Add(hotDupMethod);
  15974. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  15975. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15976. }
  15977. else if (mCompiler->IsHotCompile())
  15978. {
  15979. // Link the previous version into the mPrevVersion
  15980. BfHotMethod* prevMethod = new BfHotMethod();
  15981. prevMethod->mRefCount = 1;
  15982. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  15983. hotMethod->mPrevVersion = prevMethod;
  15984. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  15985. hotMethod->mSrcTypeVersion = NULL;
  15986. prevMethod->mFlags = hotMethod->mFlags;
  15987. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  15988. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  15989. #ifdef BF_DBG_HOTMETHOD_NAME
  15990. prevMethod->mMangledName = hotMethod->mMangledName;
  15991. #endif
  15992. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  15993. }
  15994. else
  15995. {
  15996. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15997. hotMethod->Clear(true);
  15998. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15999. }
  16000. }
  16001. if (methodInstance->mIsClosure)
  16002. {
  16003. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  16004. }
  16005. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  16006. hotMethod->mSrcTypeVersion->mRefCount++;
  16007. hotMethod->mRefCount++;
  16008. #ifdef BF_DBG_HOTMETHOD_NAME
  16009. hotMethod->mMangledName = mangledName;
  16010. #endif
  16011. methodInstance->mHotMethod = hotMethod;
  16012. }
  16013. }
  16014. // methodDeclaration is NULL for default constructors
  16015. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  16016. {
  16017. BP_ZONE("BfModule::BfMethodDeclaration");
  16018. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  16019. // to effectively make mIgnoreWrites method-scoped
  16020. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized);
  16021. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  16022. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  16023. if (mCompiler->IsAutocomplete())
  16024. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  16025. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  16026. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16027. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  16028. if (mAwaitingInitFinish)
  16029. FinishInit();
  16030. auto typeInstance = mCurTypeInstance;
  16031. auto typeDef = typeInstance->mTypeDef;
  16032. auto methodDef = mCurMethodInstance->mMethodDef;
  16033. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  16034. if (typeInstance->IsClosure())
  16035. {
  16036. if (methodDef->mName == "Invoke")
  16037. return;
  16038. }
  16039. auto methodInstance = mCurMethodInstance;
  16040. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  16041. addToWorkList = false;
  16042. bool hasNonGenericParams = false;
  16043. bool hasGenericParams = false;
  16044. int dependentGenericStartIdx = 0;
  16045. if (methodDef->mIsLocalMethod)
  16046. {
  16047. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  16048. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  16049. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  16050. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  16051. // over the local method each time
  16052. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  16053. dependentGenericStartIdx = 0;
  16054. if (rootMethodInstance->mMethodInfoEx != NULL)
  16055. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16056. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  16057. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  16058. }
  16059. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  16060. {
  16061. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  16062. if (genericArgType->IsGenericParam())
  16063. {
  16064. hasGenericParams = true;
  16065. auto genericParam = (BfGenericParamType*)genericArgType;
  16066. methodInstance->mIsUnspecialized = true;
  16067. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  16068. methodInstance->mIsUnspecializedVariation = true;
  16069. }
  16070. else
  16071. {
  16072. hasNonGenericParams = true;
  16073. if (genericArgType->IsUnspecializedType())
  16074. {
  16075. methodInstance->mIsUnspecialized = true;
  16076. methodInstance->mIsUnspecializedVariation = true;
  16077. }
  16078. }
  16079. }
  16080. if ((hasGenericParams) && (hasNonGenericParams))
  16081. {
  16082. methodInstance->mIsUnspecializedVariation = true;
  16083. }
  16084. if (typeInstance->IsUnspecializedType())
  16085. {
  16086. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  16087. // actually want to do method processing on it
  16088. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  16089. methodInstance->mIsUnspecializedVariation = true;
  16090. methodInstance->mIsUnspecialized = true;
  16091. }
  16092. methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  16093. for (auto genericParamDef : methodDef->mGenericParams)
  16094. {
  16095. if (mCompiler->IsAutocomplete())
  16096. {
  16097. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16098. //autoComplete->CheckTypeRef()
  16099. }
  16100. }
  16101. if (methodInstance->mIsUnspecializedVariation)
  16102. {
  16103. }
  16104. if (methodInstance->mIsUnspecializedVariation)
  16105. BF_ASSERT(methodInstance->mIsUnspecialized);
  16106. if (methodDef->mMethodType == BfMethodType_Mixin)
  16107. methodInstance->mIsUnspecialized = true;
  16108. BfAutoComplete* bfAutocomplete = NULL;
  16109. if (mCompiler->mResolvePassData != NULL)
  16110. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  16111. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->GetNumGenericArguments(); genericParamIdx++)
  16112. {
  16113. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  16114. ResolveGenericParamConstraints(methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx], methodDef->mGenericParams, genericParamIdx);
  16115. if (bfAutocomplete != NULL)
  16116. {
  16117. for (auto nameNode : genericParamDef->mNameNodes)
  16118. {
  16119. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  16120. }
  16121. }
  16122. }
  16123. if (methodInstance->mMethodInfoEx != NULL)
  16124. {
  16125. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  16126. {
  16127. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  16128. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16129. if (genericParam->mTypeConstraint != NULL)
  16130. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16131. }
  16132. }
  16133. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  16134. {
  16135. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16136. BfAstNode* nameNode = methodDeclaration->mNameNode;
  16137. if (nameNode == NULL)
  16138. {
  16139. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  16140. nameNode = ctorDeclaration->mThisToken;
  16141. }
  16142. if (autoComplete->IsAutocompleteNode(nameNode))
  16143. {
  16144. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  16145. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  16146. autoComplete->mDefType = typeDef;
  16147. autoComplete->mDefMethod = methodDef;
  16148. autoComplete->SetDefinitionLocation(nameNode);
  16149. if (methodDef->mIsOverride)
  16150. {
  16151. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  16152. {
  16153. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  16154. if (ventry.mDeclaringMethod.mMethodNum == -1)
  16155. continue;
  16156. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  16157. if (virtMethod != NULL)
  16158. {
  16159. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  16160. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  16161. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  16162. {
  16163. // Is matching method
  16164. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  16165. {
  16166. auto baseType = typeInstance->mBaseType;
  16167. if (baseType != NULL)
  16168. {
  16169. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  16170. baseType = baseType->mBaseType;
  16171. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  16172. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  16173. autoComplete->mDefType = baseType->mTypeDef;
  16174. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  16175. }
  16176. }
  16177. break;
  16178. }
  16179. }
  16180. }
  16181. }
  16182. }
  16183. }
  16184. bool reportErrors = true;
  16185. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16186. reportErrors = true;
  16187. // Only the defining contexts needs to report errors here
  16188. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  16189. if (methodDef->mMethodType == BfMethodType_Dtor)
  16190. {
  16191. if (methodDef->mIsStatic)
  16192. {
  16193. }
  16194. else
  16195. {
  16196. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  16197. {
  16198. BfAstNode* refNode = methodDeclaration;
  16199. if (refNode == NULL)
  16200. {
  16201. // Whatever caused this ctor to be generated should have caused another failure
  16202. // But that failure might not be generated until the ctor is generated
  16203. }
  16204. else
  16205. {
  16206. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  16207. if (dtorDecl != NULL)
  16208. refNode = dtorDecl->mThisToken;
  16209. Fail("Structs cannot have destructors", refNode);
  16210. }
  16211. }
  16212. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16213. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  16214. (mCurTypeInstance != mContext->mBfObjectType))
  16215. {
  16216. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  16217. }
  16218. }
  16219. }
  16220. BfType* resolvedReturnType = NULL;
  16221. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  16222. (methodDef->mReturnTypeRef != NULL))
  16223. {
  16224. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16225. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  16226. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  16227. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  16228. {
  16229. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  16230. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16231. }
  16232. if (resolvedReturnType == NULL)
  16233. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16234. }
  16235. else
  16236. {
  16237. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  16238. }
  16239. BF_ASSERT(resolvedReturnType != NULL);
  16240. mCurMethodInstance->mReturnType = resolvedReturnType;
  16241. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  16242. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  16243. //if (!methodInstance->IsSpecializedGenericMethod())
  16244. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16245. if (methodDef->mExplicitInterface != NULL)
  16246. {
  16247. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16248. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  16249. auto explicitInterface = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  16250. if (explicitInterface != NULL)
  16251. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  16252. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  16253. {
  16254. bool interfaceFound = false;
  16255. for (auto ifaceInst : typeInstance->mInterfaces)
  16256. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  16257. if (!interfaceFound)
  16258. {
  16259. if (methodDef->mMethodDeclaration != NULL)
  16260. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  16261. else
  16262. {
  16263. // For property decls, we should have already given the error during type population
  16264. if (mCompiler->mRevision == 1)
  16265. AssertErrorState();
  16266. }
  16267. }
  16268. }
  16269. }
  16270. bool isThisStruct = mCurTypeInstance->IsStruct();
  16271. BfType* thisType = NULL;
  16272. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  16273. {
  16274. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  16275. {
  16276. thisType = mCurTypeInstance;
  16277. if (thisType == NULL)
  16278. return;
  16279. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  16280. {
  16281. BfTypeUtils::SplatIterate([&](BfType* checkType)
  16282. {
  16283. PopulateType(checkType, BfPopulateType_Data);
  16284. }, thisType);
  16285. }
  16286. }
  16287. else
  16288. {
  16289. thisType = mCurTypeInstance;
  16290. PopulateType(thisType, BfPopulateType_Declaration);
  16291. }
  16292. }
  16293. int implicitParamCount = 0;
  16294. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  16295. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  16296. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  16297. bool hadDelegateParams = false;
  16298. bool hadParams = false;
  16299. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  16300. {
  16301. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  16302. BfParameterDef* paramDef = NULL;
  16303. int paramDefIdx = -1;
  16304. if (paramIdx < implicitParamCount)
  16305. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  16306. else
  16307. {
  16308. paramDefIdx = paramIdx - implicitParamCount;
  16309. paramDef = methodDef->mParams[paramDefIdx];
  16310. }
  16311. if (hadParams)
  16312. break;
  16313. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  16314. (paramDef->mParamKind != BfParamKind_AppendIdx))
  16315. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  16316. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  16317. {
  16318. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16319. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16320. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  16321. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  16322. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  16323. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  16324. }
  16325. BfType* resolvedParamType = NULL;
  16326. if (closureCaptureEntry != NULL)
  16327. resolvedParamType = closureCaptureEntry->mType;
  16328. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  16329. {
  16330. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  16331. resolvedParamType = mContext->mBfObjectType;
  16332. }
  16333. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  16334. {
  16335. if (methodDef->mMethodType != BfMethodType_Mixin)
  16336. {
  16337. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  16338. resolvedParamType = mContext->mBfObjectType;
  16339. }
  16340. else
  16341. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16342. }
  16343. BfType* unresolvedParamType = resolvedParamType;
  16344. bool wasGenericParam = false;
  16345. if (resolvedParamType == NULL)
  16346. {
  16347. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16348. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration,
  16349. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  16350. }
  16351. if (resolvedParamType == NULL)
  16352. {
  16353. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16354. unresolvedParamType = resolvedParamType;
  16355. if (mCurTypeInstance->IsBoxed())
  16356. {
  16357. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  16358. // If we failed a lookup here then we better have also failed it in the original type
  16359. BF_ASSERT(boxedType->mElementType->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType));
  16360. }
  16361. }
  16362. if (!methodInstance->IsSpecializedGenericMethod())
  16363. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16364. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  16365. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  16366. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  16367. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  16368. {
  16369. BfMethodState methodState;
  16370. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16371. methodState.mTempKind = BfMethodState::TempKind_Static;
  16372. BfTypedValue defaultValue;
  16373. if (resolvedParamType->IsConstExprValue())
  16374. {
  16375. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  16376. BfExprEvaluator exprEvaluator(this);
  16377. exprEvaluator.mExpectingType = constExprType->mType;
  16378. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  16379. defaultValue = exprEvaluator.GetResult();
  16380. }
  16381. else
  16382. {
  16383. BfConstResolver constResolver(this);
  16384. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, BfConstResolveFlag_NoCast);
  16385. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  16386. {
  16387. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  16388. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  16389. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  16390. {
  16391. defaultValue = castedDefaultValue; // Good!
  16392. }
  16393. else if (!CanImplicitlyCast(defaultValue, resolvedParamType))
  16394. {
  16395. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  16396. // a conversion operator.
  16397. // This should throw an error
  16398. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  16399. AssertErrorState();
  16400. if (!defaultValue.mValue.IsConst())
  16401. defaultValue = BfTypedValue();
  16402. }
  16403. }
  16404. }
  16405. if (!defaultValue)
  16406. {
  16407. defaultValue = GetDefaultTypedValue(resolvedParamType);
  16408. if (!defaultValue.mValue.IsConst())
  16409. defaultValue = BfTypedValue();
  16410. }
  16411. if (defaultValue)
  16412. {
  16413. BF_ASSERT(defaultValue.mValue.IsConst());
  16414. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  16415. mCurMethodInstance->mDefaultValues.Add(BfIRValue());
  16416. CurrentAddToConstHolder(defaultValue.mValue);
  16417. mCurMethodInstance->mDefaultValues.Add(defaultValue.mValue);
  16418. }
  16419. }
  16420. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  16421. {
  16422. bool addParams = true;
  16423. bool isValid = false;
  16424. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  16425. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  16426. {
  16427. // Span<T>
  16428. isValid = true;
  16429. }
  16430. else if (resolvedParamType->IsArray())
  16431. {
  16432. // Array is the 'normal' params type
  16433. isValid = true;
  16434. }
  16435. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  16436. {
  16437. hadDelegateParams = true;
  16438. // This means we copy the params from a delegate
  16439. BfMethodParam methodParam;
  16440. methodParam.mResolvedType = resolvedParamType;
  16441. methodParam.mParamDefIdx = paramDefIdx;
  16442. methodParam.mDelegateParamIdx = 0;
  16443. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16444. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  16445. {
  16446. methodParam.mDelegateParamIdx = delegateParamIdx;
  16447. mCurMethodInstance->mParams.Add(methodParam);
  16448. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  16449. if (!methodInstance->IsSpecializedGenericMethod())
  16450. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16451. }
  16452. isValid = true;
  16453. addParams = false;
  16454. }
  16455. else if (resolvedParamType->IsGenericParam())
  16456. {
  16457. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  16458. if (genericParamInstance->mTypeConstraint != NULL)
  16459. {
  16460. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16461. if (genericParamInstance->mTypeConstraint->IsArray())
  16462. {
  16463. BfMethodParam methodParam;
  16464. methodParam.mResolvedType = resolvedParamType;
  16465. methodParam.mParamDefIdx = paramDefIdx;
  16466. mCurMethodInstance->mParams.Add(methodParam);
  16467. isValid = true;
  16468. }
  16469. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16470. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  16471. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  16472. {
  16473. mCurMethodInstance->mHadGenericDelegateParams = true;
  16474. isValid = true;
  16475. addParams = false;
  16476. }
  16477. }
  16478. }
  16479. else
  16480. {
  16481. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  16482. if ((paramTypeInst != NULL) &&
  16483. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  16484. {
  16485. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  16486. isValid = true;
  16487. addParams = false;
  16488. }
  16489. }
  16490. if (!isValid)
  16491. {
  16492. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  16493. // Failure case, make it an Object[]
  16494. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  16495. }
  16496. if (addParams)
  16497. {
  16498. BfMethodParam methodParam;
  16499. methodParam.mResolvedType = resolvedParamType;
  16500. methodParam.mParamDefIdx = paramDefIdx;
  16501. mCurMethodInstance->mParams.push_back(methodParam);
  16502. }
  16503. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  16504. {
  16505. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  16506. }
  16507. }
  16508. else
  16509. {
  16510. BfMethodParam methodParam;
  16511. methodParam.mResolvedType = resolvedParamType;
  16512. methodParam.mParamDefIdx = paramDefIdx;
  16513. mCurMethodInstance->mParams.Add(methodParam);
  16514. }
  16515. }
  16516. if (hadDelegateParams)
  16517. {
  16518. HashSet<String> usedNames;
  16519. Dictionary<int, int> usedParamDefIdx;
  16520. for (auto methodParam : methodDef->mParams)
  16521. {
  16522. usedNames.Add(methodParam->mName);
  16523. }
  16524. for (auto& methodParam : mCurMethodInstance->mParams)
  16525. {
  16526. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  16527. {
  16528. int* refCount = NULL;
  16529. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  16530. (*refCount)++;
  16531. }
  16532. }
  16533. for (auto& methodParam : mCurMethodInstance->mParams)
  16534. {
  16535. if (methodParam.mDelegateParamIdx != -1)
  16536. {
  16537. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  16538. methodParam.mDelegateParamNameCombine = true;
  16539. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16540. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  16541. if (usedNames.Contains(paramName))
  16542. methodParam.mDelegateParamNameCombine = true;
  16543. }
  16544. }
  16545. }
  16546. int argIdx = 0;
  16547. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  16548. if (methodInstance->HasStructRet())
  16549. argIdx++;
  16550. if (!methodDef->mIsStatic)
  16551. {
  16552. if (methodInstance->GetParamIsSplat(-1))
  16553. argIdx += methodInstance->GetParamType(-1)->GetSplatCount();
  16554. else if (!methodInstance->GetOwner()->IsValuelessType())
  16555. argIdx++;
  16556. }
  16557. for (auto& methodParam : mCurMethodInstance->mParams)
  16558. {
  16559. if (methodParam.mResolvedType->IsMethodRef())
  16560. {
  16561. methodParam.mIsSplat = true;
  16562. }
  16563. else if (methodParam.mResolvedType->IsComposite())
  16564. {
  16565. PopulateType(methodParam.mResolvedType, BfPopulateType_Data);
  16566. if (methodParam.mResolvedType->IsSplattable())
  16567. {
  16568. int splatCount = methodParam.mResolvedType->GetSplatCount();
  16569. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16570. {
  16571. methodParam.mIsSplat = true;
  16572. argIdx += splatCount;
  16573. continue;
  16574. }
  16575. }
  16576. }
  16577. argIdx++;
  16578. }
  16579. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  16580. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  16581. {
  16582. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  16583. }
  16584. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  16585. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  16586. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  16587. (!methodDef->mIsSkipCall))
  16588. {
  16589. if (methodDeclaration->mEndSemicolon == NULL)
  16590. {
  16591. AssertParseErrorState();
  16592. }
  16593. else
  16594. {
  16595. bool isError = true;
  16596. if (typeInstance->IsTypedPrimitive())
  16597. {
  16598. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16599. {
  16600. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  16601. {
  16602. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  16603. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  16604. {
  16605. isError = false;
  16606. }
  16607. }
  16608. }
  16609. }
  16610. if (isError)
  16611. {
  16612. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  16613. MethodToString(methodInstance).c_str()),
  16614. methodDef->GetRefNode());
  16615. }
  16616. }
  16617. }
  16618. if (methodDef->IsEmptyPartial())
  16619. hasExternSpecifier = true;
  16620. if (!methodInstance->IsAutocompleteMethod())
  16621. {
  16622. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  16623. int implicitParamCount = methodInstance->GetImplicitParamCount();
  16624. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  16625. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  16626. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  16627. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  16628. int paramIdx = 0;
  16629. int defaultParamIdx = 0;
  16630. while (true)
  16631. {
  16632. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  16633. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  16634. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  16635. {
  16636. paramIdx++;
  16637. continue;
  16638. }
  16639. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  16640. {
  16641. defaultParamIdx++;
  16642. continue;
  16643. }
  16644. if ((isDone) || (isDefaultDone))
  16645. {
  16646. // If we have generic delegate params, it's possible we will fail constraints later if we specialize with an invalid type, but we can't allow that
  16647. // to cause us to throw an assertion in the declaration here
  16648. if (!defaultMethodInstance->mHadGenericDelegateParams)
  16649. BF_ASSERT((isDone) && (isDefaultDone));
  16650. break;
  16651. }
  16652. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType->IsGenericParam();
  16653. paramIdx++;
  16654. defaultParamIdx++;
  16655. }
  16656. }
  16657. StringT<128> mangledName;
  16658. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16659. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16660. {
  16661. auto paramType = methodInstance->GetParamType(paramIdx);
  16662. if (paramType->IsComposite())
  16663. PopulateType(paramType, BfPopulateType_Data);
  16664. if (!methodInstance->IsParamSkipped(paramIdx))
  16665. {
  16666. if (paramType->IsStruct())
  16667. {
  16668. //
  16669. }
  16670. else
  16671. {
  16672. PopulateType(paramType, BfPopulateType_Declaration);
  16673. }
  16674. }
  16675. }
  16676. // Only process method in default unspecialized mode, not in variations
  16677. if (methodInstance->mIsUnspecializedVariation)
  16678. return;
  16679. PopulateType(resolvedReturnType, BfPopulateType_Data);
  16680. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  16681. if (resolvedReturnType->IsValuelessType())
  16682. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  16683. if (!mBfIRBuilder->mIgnoreWrites)
  16684. {
  16685. bool isIntrinsic = false;
  16686. if (!methodInstance->mIRFunction)
  16687. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  16688. if (isIntrinsic)
  16689. {
  16690. addToWorkList = false;
  16691. }
  16692. }
  16693. auto func = methodInstance->mIRFunction;
  16694. // if (methodInstance->mIsReified)
  16695. // CheckHotMethod(methodInstance, mangledName);
  16696. BfLogSysM("DoMethodDeclaration %s Module: %p Type: %p MethodInst: %p Reified: %d Unspecialized: %d IRFunction: %d MethodId:%llx\n", mangledName.c_str(), this, mCurTypeInstance, methodInstance, methodInstance->mIsReified, mCurTypeInstance->IsUnspecializedType(), methodInstance->mIRFunction.mId, methodInstance->mIdHash);
  16697. SizedArray<BfIRMDNode, 8> diParams;
  16698. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  16699. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  16700. {
  16701. //CS0708
  16702. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  16703. }
  16704. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  16705. {
  16706. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  16707. methodDef->mIsVirtual = false;
  16708. }
  16709. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  16710. {
  16711. if (methodDef->mIsStatic)
  16712. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  16713. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  16714. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  16715. else if (methodDef->mMethodType == BfMethodType_Ctor)
  16716. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16717. else if (methodDef->mMethodType == BfMethodType_Dtor)
  16718. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16719. }
  16720. if (isTemporaryFunc)
  16721. {
  16722. // This handles temporary methods for autocomplete types
  16723. BF_ASSERT(mIsScratchModule);
  16724. BF_ASSERT(mCompiler->IsAutocomplete());
  16725. BfLogSysM("DoMethodDeclaration autocomplete bailout\n");
  16726. return; // Bail out early for autocomplete pass
  16727. }
  16728. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  16729. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  16730. // autocompleter. Why did we have this check anyway?
  16731. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  16732. {
  16733. AddMethodReference(methodInstance);
  16734. mFuncReferences[methodInstance] = func;
  16735. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  16736. }*/
  16737. if (mParentModule != NULL)
  16738. {
  16739. // For extension modules we need to keep track of our own methods so we can know which methods
  16740. // we have defined ourselves and which are from the parent module or other extensions
  16741. if (!func.IsFake())
  16742. mFuncReferences[methodInstance] = func;
  16743. }
  16744. if (addToWorkList)
  16745. {
  16746. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  16747. if (wasAwaitingDecl)
  16748. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16749. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  16750. {
  16751. if (!wasAwaitingDecl)
  16752. AddMethodToWorkList(methodInstance);
  16753. }
  16754. else
  16755. {
  16756. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  16757. methodInstance->mIgnoreBody = true;
  16758. if (typeInstance->IsUnspecializedType())
  16759. {
  16760. // Don't hold on to actual Function for unspecialized types
  16761. methodInstance->mIRFunction = BfIRFunction();
  16762. }
  16763. }
  16764. }
  16765. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  16766. (!methodDef->mIsLocalMethod) &&
  16767. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)))
  16768. {
  16769. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  16770. {
  16771. //TODO:
  16772. //CS0053
  16773. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  16774. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16775. methodDef->mReturnTypeRef, true);
  16776. }
  16777. else
  16778. {
  16779. //CS0050
  16780. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  16781. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16782. methodDef->mReturnTypeRef, true);
  16783. }
  16784. }
  16785. if ((typeInstance->IsInterface()) && (methodDef->mMethodType == BfMethodType_Ctor))
  16786. {
  16787. Fail("Interfaces cannot contain constructors", methodDeclaration);
  16788. }
  16789. // Don't compare specialized generic methods against normal methods
  16790. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  16791. (!methodDef->mIsLocalMethod))
  16792. {
  16793. if (!methodInstance->mIsForeignMethodDef)
  16794. {
  16795. typeDef->PopulateMemberSets();
  16796. BfMethodDef* nextMethod = NULL;
  16797. BfMemberSetEntry* entry = NULL;
  16798. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16799. nextMethod = (BfMethodDef*)entry->mMemberDef;
  16800. while (nextMethod != NULL)
  16801. {
  16802. auto checkMethod = nextMethod;
  16803. nextMethod = nextMethod->mNextWithSameName;
  16804. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  16805. {
  16806. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  16807. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  16808. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16809. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16810. {
  16811. bool canChain = false;
  16812. if ((methodDef->mParams.empty()) &&
  16813. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  16814. {
  16815. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  16816. canChain = true;
  16817. else if (methodDef->mMethodType == BfMethodType_Normal)
  16818. {
  16819. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  16820. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  16821. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  16822. canChain = true;
  16823. }
  16824. }
  16825. if (canChain)
  16826. {
  16827. bool isBetter;
  16828. bool isWorse;
  16829. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  16830. if (isBetter && !isWorse)
  16831. {
  16832. methodInstance->mChainType = BfMethodChainType_ChainHead;
  16833. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  16834. }
  16835. else
  16836. {
  16837. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  16838. methodInstance->mChainType = BfMethodChainType_ChainMember;
  16839. }
  16840. }
  16841. else if ((checkMethod->mBody == NULL) && (methodDef->mBody != NULL) &&
  16842. (checkMethod->mDeclaringType != methodDef->mDeclaringType))
  16843. {
  16844. // We're allowed to override an empty-bodied method
  16845. checkMethodInstance->mChainType = BfMethodChainType_ChainSkip;
  16846. }
  16847. else
  16848. {
  16849. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  16850. continue;
  16851. bool silentlyAllow = false;
  16852. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  16853. {
  16854. if (typeInstance->IsInterface())
  16855. {
  16856. if (methodDef->mIsOverride)
  16857. silentlyAllow = true;
  16858. }
  16859. else
  16860. silentlyAllow = true;
  16861. }
  16862. if (!silentlyAllow)
  16863. {
  16864. if (!methodDef->mName.IsEmpty())
  16865. {
  16866. auto refNode = methodDef->GetRefNode();
  16867. auto bfError = Fail("Method already declared with the same parameter types", refNode, true);
  16868. if (bfError != NULL)
  16869. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  16870. }
  16871. }
  16872. }
  16873. }
  16874. }
  16875. }
  16876. }
  16877. // Virtual methods give their error while slotting
  16878. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  16879. (!methodDef->mIsLocalMethod) &&
  16880. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  16881. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  16882. {
  16883. bool foundHiddenMethod = false;
  16884. auto baseType = typeInstance->mBaseType;
  16885. while (baseType != NULL)
  16886. {
  16887. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  16888. auto baseTypeDef = baseType->mTypeDef;
  16889. baseTypeDef->PopulateMemberSets();
  16890. BfMethodDef* checkMethod = NULL;
  16891. BfMemberSetEntry* entry = NULL;
  16892. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16893. checkMethod = (BfMethodDef*)entry->mMemberDef;
  16894. while (checkMethod != NULL)
  16895. {
  16896. if (checkMethod->mMethodDeclaration == NULL)
  16897. continue;
  16898. if (baseType->mMethodInstanceGroups.size() == 0)
  16899. {
  16900. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  16901. break;
  16902. }
  16903. if (checkMethod == methodDef)
  16904. continue;
  16905. if (checkMethod->mName != methodDef->mName)
  16906. continue;
  16907. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  16908. if (checkMethodInstance != NULL)
  16909. {
  16910. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16911. (checkMethod->mProtection != BfProtection_Private) &&
  16912. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16913. {
  16914. if (!methodDef->mIsNew)
  16915. {
  16916. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  16917. if (refNode != NULL)
  16918. {
  16919. BfError* bfError = Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if the hiding was intentional.", TypeToString(baseType).c_str()), refNode); //CDH TODO should we mention override keyword in warning text?
  16920. if (bfError != NULL)
  16921. bfError->mIsPersistent = true;
  16922. }
  16923. }
  16924. foundHiddenMethod = true;
  16925. break;
  16926. }
  16927. }
  16928. checkMethod = checkMethod->mNextWithSameName;
  16929. }
  16930. if (foundHiddenMethod)
  16931. break;
  16932. baseType = baseType->mBaseType;
  16933. }
  16934. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  16935. {
  16936. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  16937. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  16938. methodDeclaration->mNewSpecifier;
  16939. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  16940. }
  16941. }
  16942. }
  16943. mCompiler->mStats.mMethodDeclarations++;
  16944. mCompiler->UpdateCompletion();
  16945. }
  16946. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  16947. {
  16948. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  16949. auto typeInstance = mCurTypeInstance;
  16950. auto methodDef = methodInstance->mMethodDef;
  16951. int virtualMethodMatchIdx = -1;
  16952. if (typeInstance->mHotTypeData != NULL)
  16953. {
  16954. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  16955. {
  16956. BF_ASSERT(mCompiler->IsHotCompile());
  16957. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  16958. // may slot this override anyway (?)
  16959. int vTableStart = 0;
  16960. if (typeInstance->mBaseType != NULL)
  16961. vTableStart = typeInstance->mBaseType->mVirtualMethodTableSize;
  16962. StringT<128> mangledName;
  16963. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  16964. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  16965. {
  16966. // O(1) checking when virtual methods haven't changed
  16967. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  16968. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  16969. if (mangledName == entry.mFuncName)
  16970. {
  16971. virtualMethodMatchIdx = vTableStart + checkIdx;
  16972. break;
  16973. }
  16974. }
  16975. if (virtualMethodMatchIdx != -1)
  16976. {
  16977. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  16978. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  16979. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  16980. }
  16981. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  16982. }
  16983. }
  16984. if (virtualMethodMatchIdx == -1)
  16985. {
  16986. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  16987. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  16988. typeInstance->mVirtualMethodTable.push_back(entry);
  16989. }
  16990. }
  16991. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  16992. {
  16993. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  16994. {
  16995. // When we provide an extension override in the same project a root type override
  16996. isBetter = true;
  16997. isWorse = false;
  16998. }
  16999. else
  17000. {
  17001. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17002. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17003. }
  17004. }
  17005. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  17006. {
  17007. BP_ZONE("BfModule::SlotVirtualMethod");
  17008. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  17009. return false;
  17010. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  17011. {
  17012. if (!mCompiler->mOptions.mAllowHotSwapping)
  17013. return;
  17014. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  17015. return;
  17016. if (methodInstance->mHotMethod == NULL)
  17017. CheckHotMethod(methodInstance, "");
  17018. if (methodInstance->mHotMethod == NULL)
  17019. return;
  17020. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  17021. if (declMethodInstance->mHotMethod == NULL)
  17022. CheckHotMethod(declMethodInstance, "");
  17023. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  17024. virtualDecl->mRefCount++;
  17025. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  17026. };
  17027. auto typeInstance = mCurTypeInstance;
  17028. auto typeDef = typeInstance->mTypeDef;
  17029. auto methodDef = methodInstance->mMethodDef;
  17030. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17031. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17032. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  17033. BfAstNode* declaringNode = methodDeclaration;
  17034. if (propertyMethodDeclaration != NULL)
  17035. declaringNode = propertyMethodDeclaration->mNameNode;
  17036. BfMethodInstance* methodOverriden = NULL;
  17037. bool usedMethod = false;
  17038. BfTokenNode* virtualToken = NULL;
  17039. if (propertyDeclaration != NULL)
  17040. virtualToken = propertyDeclaration->mVirtualSpecifier;
  17041. else if (methodDeclaration != NULL)
  17042. virtualToken = methodDeclaration->mVirtualSpecifier;
  17043. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  17044. {
  17045. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  17046. }
  17047. else if (methodDef->mIsVirtual)
  17048. {
  17049. if (mCompiler->IsHotCompile())
  17050. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  17051. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  17052. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  17053. BfTypeInstance* checkBase = typeInstance;
  17054. // If we are in an extension, look in ourselves first
  17055. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  17056. checkBase = checkBase->mBaseType;
  17057. if (typeInstance->IsValueType())
  17058. {
  17059. if (typeInstance->mBaseType == NULL)
  17060. return false; // It's actually ValueType
  17061. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  17062. if (!methodDef->mIsOverride)
  17063. {
  17064. Fail("Structs cannot have virtual methods", virtualToken, true);
  17065. return false;
  17066. }
  17067. checkBase = mContext->mBfObjectType;
  17068. if (checkBase->mVirtualMethodTableSize == 0)
  17069. PopulateType(checkBase, BfPopulateType_Full);
  17070. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  17071. return false; // System circular ref, don't do struct checking on those
  17072. }
  17073. int virtualMethodMatchIdx = -1;
  17074. bool hadHidingError = false;
  17075. BfMethodInstance* bestOverrideMethodInstance = NULL;
  17076. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  17077. int bestOverrideMethodIdx = -1;
  17078. int ambiguousOverrideMethodIdx = -1;
  17079. if (checkBase != NULL)
  17080. {
  17081. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17082. auto lookupType = checkBase;
  17083. while (lookupType != NULL)
  17084. {
  17085. lookupType->mTypeDef->PopulateMemberSets();
  17086. BfMethodDef* nextMethodDef = NULL;
  17087. BfMemberSetEntry* entry;
  17088. if (lookupType->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17089. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  17090. while (nextMethodDef != NULL)
  17091. {
  17092. auto checkMethodDef = nextMethodDef;
  17093. nextMethodDef = nextMethodDef->mNextWithSameName;
  17094. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  17095. continue;
  17096. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  17097. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  17098. continue;
  17099. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  17100. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17101. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17102. {
  17103. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17104. continue;
  17105. }
  17106. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17107. if (baseMethodInstance == NULL)
  17108. {
  17109. AssertErrorState();
  17110. continue;
  17111. }
  17112. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17113. {
  17114. if (methodDef->mIsOverride)
  17115. {
  17116. BfMethodInstance* checkMethodInstance;
  17117. if (typeInstance->IsValueType())
  17118. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17119. else
  17120. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17121. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17122. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17123. continue;
  17124. if (bestOverrideMethodInstance != NULL)
  17125. {
  17126. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17127. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17128. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17129. if (isBetter == isWorse)
  17130. {
  17131. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17132. }
  17133. else
  17134. {
  17135. if (isWorse)
  17136. continue;
  17137. ambiguousOverrideMethodInstance = NULL;
  17138. }
  17139. }
  17140. bestOverrideMethodInstance = checkMethodInstance;
  17141. bestOverrideMethodIdx = checkMethodIdx;
  17142. }
  17143. else
  17144. {
  17145. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17146. {
  17147. if (!hadHidingError)
  17148. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17149. hadHidingError = true;
  17150. }
  17151. }
  17152. }
  17153. }
  17154. lookupType = lookupType->mBaseType;
  17155. }
  17156. }
  17157. //TODO:
  17158. if ((checkBase != NULL)
  17159. && (false)
  17160. )
  17161. {
  17162. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17163. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  17164. {
  17165. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17166. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17167. {
  17168. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17169. continue;
  17170. }
  17171. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17172. if (baseMethodInstance == NULL)
  17173. {
  17174. AssertErrorState();
  17175. continue;
  17176. }
  17177. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17178. {
  17179. if (methodDef->mIsOverride)
  17180. {
  17181. BfMethodInstance* checkMethodInstance;
  17182. if (typeInstance->IsValueType())
  17183. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17184. else
  17185. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17186. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17187. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17188. continue;
  17189. if (bestOverrideMethodInstance != NULL)
  17190. {
  17191. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17192. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17193. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17194. if (isBetter == isWorse)
  17195. {
  17196. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17197. }
  17198. else
  17199. {
  17200. if (isWorse)
  17201. continue;
  17202. ambiguousOverrideMethodInstance = NULL;
  17203. }
  17204. }
  17205. bestOverrideMethodInstance = checkMethodInstance;
  17206. bestOverrideMethodIdx = checkMethodIdx;
  17207. }
  17208. else
  17209. {
  17210. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17211. {
  17212. if (!hadHidingError)
  17213. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17214. hadHidingError = true;
  17215. }
  17216. }
  17217. }
  17218. }
  17219. }
  17220. if (bestOverrideMethodInstance != NULL)
  17221. {
  17222. if (ambiguousOverrideMethodInstance != NULL)
  17223. {
  17224. bool allow = false;
  17225. // If neither of these declarations "include" each other then it's okay. This can happen when we have two extensions that create the same virtual method but with different constraints.
  17226. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  17227. bool canSeeEachOther = false;
  17228. //
  17229. {
  17230. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  17231. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17232. canSeeEachOther = true;
  17233. }
  17234. //
  17235. {
  17236. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  17237. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17238. canSeeEachOther = true;
  17239. }
  17240. if (!canSeeEachOther)
  17241. {
  17242. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  17243. }
  17244. else
  17245. {
  17246. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  17247. if (error != NULL)
  17248. {
  17249. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  17250. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  17251. }
  17252. }
  17253. }
  17254. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17255. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  17256. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  17257. {
  17258. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  17259. {
  17260. BfTypeReference* returnTypeRef;
  17261. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17262. {
  17263. returnTypeRef = propertyDeclaration->mTypeRef;
  17264. Fail("Property differs from overridden property by type", returnTypeRef, true);
  17265. }
  17266. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17267. {
  17268. returnTypeRef = methodDeclaration->mReturnType;
  17269. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  17270. }
  17271. else
  17272. {
  17273. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  17274. }
  17275. return usedMethod;
  17276. }
  17277. }
  17278. if (methodDef->mIsOverride)
  17279. {
  17280. // We can have multiple matches when a virtual method is used to implement interface methods
  17281. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  17282. // vtable entries for this method signature
  17283. virtualMethodMatchIdx = bestOverrideMethodIdx;
  17284. if (!typeInstance->IsValueType())
  17285. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17286. if (typeInstance->IsValueType())
  17287. {
  17288. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17289. }
  17290. else
  17291. {
  17292. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17293. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17294. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  17295. {
  17296. methodOverriden = overridenRef;
  17297. BfMethodInstance* setMethodInstance = methodInstance;
  17298. bool doOverride = true;
  17299. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  17300. {
  17301. bool isBetter = false;
  17302. bool isWorse = false;
  17303. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  17304. if (isBetter == isWorse)
  17305. {
  17306. // We have to resolve later per-project
  17307. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  17308. {
  17309. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17310. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  17311. }
  17312. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  17313. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  17314. doOverride = false;
  17315. }
  17316. else
  17317. {
  17318. if ((isBetter) && (ambiguityContext != NULL))
  17319. {
  17320. ambiguityContext->Remove(virtualMethodMatchIdx);
  17321. }
  17322. doOverride = isBetter;
  17323. }
  17324. }
  17325. if (doOverride)
  17326. {
  17327. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17328. _AddVirtualDecl(declMethodInstance);
  17329. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  17330. }
  17331. }
  17332. }
  17333. if (methodOverriden != NULL)
  17334. {
  17335. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  17336. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  17337. {
  17338. const char* protectionNames[] = {"hidden", "private", "protected", "public"};
  17339. BfAstNode* protectionRefNode = NULL;
  17340. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17341. {
  17342. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  17343. if (protectionRefNode == NULL)
  17344. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  17345. if (protectionRefNode == NULL)
  17346. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  17347. }
  17348. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17349. {
  17350. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  17351. if (protectionRefNode == NULL)
  17352. protectionRefNode = methodDeclaration->mNameNode;
  17353. }
  17354. if (protectionRefNode != NULL)
  17355. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  17356. }
  17357. }
  17358. }
  17359. }
  17360. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  17361. {
  17362. if (methodDef->mIsOverride)
  17363. {
  17364. BfTokenNode* overrideToken = NULL;
  17365. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17366. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  17367. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17368. overrideToken = methodDeclaration->mVirtualSpecifier;
  17369. if (overrideToken != NULL)
  17370. {
  17371. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  17372. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  17373. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  17374. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  17375. else
  17376. Fail("No suitable method found to override", overrideToken, true);
  17377. }
  17378. return usedMethod;
  17379. }
  17380. UniqueSlotVirtualMethod(methodInstance);
  17381. }
  17382. else
  17383. usedMethod = true;
  17384. if (typeInstance->IsValueType())
  17385. return usedMethod;
  17386. }
  17387. bool foundInterface = false;
  17388. bool hadAnyMatch = false;
  17389. // See if this method matches interfaces
  17390. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17391. {
  17392. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17393. if (ifaceInst->IsIncomplete())
  17394. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  17395. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17396. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17397. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  17398. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  17399. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  17400. continue;
  17401. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  17402. continue;
  17403. bool hadMatch = false;
  17404. bool hadNameMatch = false;
  17405. BfType* expectedReturnType = NULL;
  17406. bool showedError = false;
  17407. // We go through our VTable looking for NULL entries within the interface sections
  17408. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  17409. // because a normal method declared in this type could have matched earlier
  17410. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  17411. ifaceInst->mTypeDef->PopulateMemberSets();
  17412. BfMethodDef* checkMethodDef = NULL;
  17413. BfMemberSetEntry* entry;
  17414. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17415. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  17416. while (checkMethodDef != NULL)
  17417. {
  17418. int iMethodIdx = checkMethodDef->mIdx;
  17419. int iTableIdx = iMethodIdx + startIdx;
  17420. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  17421. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  17422. bool storeIFaceMethod = false;
  17423. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  17424. continue;
  17425. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  17426. auto iMethodInst = iMethodGroup.mDefault;
  17427. if (iMethodInst == NULL)
  17428. {
  17429. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  17430. AssertErrorState();
  17431. continue;
  17432. }
  17433. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  17434. hadNameMatch = true;
  17435. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  17436. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  17437. {
  17438. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  17439. }
  17440. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  17441. {
  17442. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  17443. {
  17444. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  17445. {
  17446. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  17447. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  17448. if (error != NULL)
  17449. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  17450. showedError = true;
  17451. }
  17452. }
  17453. }
  17454. if (doesMethodSignatureMatch)
  17455. {
  17456. usedMethod = true;
  17457. hadMatch = true;
  17458. hadAnyMatch = true;
  17459. storeIFaceMethod = true;
  17460. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  17461. {
  17462. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  17463. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  17464. {
  17465. // When autocompletion regenerates a single method body but not the whole type then
  17466. // we will see ourselves in the vtable already
  17467. return usedMethod;
  17468. }
  17469. bool isBetter = false;
  17470. bool isWorse = false;
  17471. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  17472. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  17473. if (isBetter == isWorse)
  17474. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  17475. if (isBetter == isWorse)
  17476. {
  17477. if (ambiguityContext != NULL)
  17478. {
  17479. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  17480. }
  17481. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  17482. storeIFaceMethod = true;
  17483. }
  17484. else
  17485. {
  17486. if ((isBetter) && (ambiguityContext != NULL))
  17487. ambiguityContext->Remove(~iTableIdx);
  17488. storeIFaceMethod = isBetter;
  17489. }
  17490. }
  17491. }
  17492. if (storeIFaceMethod)
  17493. {
  17494. _AddVirtualDecl(iMethodInst);
  17495. *iMethodPtr = methodInstance;
  17496. }
  17497. checkMethodDef = checkMethodDef->mNextWithSameName;
  17498. }
  17499. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  17500. {
  17501. if (expectedReturnType != NULL)
  17502. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  17503. else if (hadNameMatch)
  17504. Fail("Method parameters don't match interface method", declaringNode, true);
  17505. else
  17506. Fail("Method name not found in interface", methodDef->GetRefNode(), true);
  17507. }
  17508. }
  17509. // Any overriden virtual methods that were used in interfaces also need to be replaced
  17510. if (methodOverriden != NULL)
  17511. {
  17512. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  17513. {
  17514. if (methodEntry.mMethodRef == methodOverriden)
  17515. methodEntry.mMethodRef = methodInstance;
  17516. }
  17517. }
  17518. return usedMethod;
  17519. }
  17520. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  17521. {
  17522. auto typeInstance = mCurTypeInstance;
  17523. auto methodDef = methodInstance->mMethodDef;
  17524. if (methodDef->mMethodType == BfMethodType_Ctor)
  17525. return true;
  17526. bool foundOverride = false;
  17527. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  17528. {
  17529. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  17530. }
  17531. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  17532. {
  17533. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  17534. }
  17535. BfAstNode* declaringNode = methodDef->GetRefNode();
  17536. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17537. {
  17538. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17539. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17540. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17541. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  17542. continue;
  17543. ifaceInst->mTypeDef->PopulateMemberSets();
  17544. BfMethodDef* nextMethod = NULL;
  17545. BfMemberSetEntry* entry = NULL;
  17546. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17547. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17548. while (nextMethod != NULL)
  17549. {
  17550. auto checkMethod = nextMethod;
  17551. nextMethod = nextMethod->mNextWithSameName;
  17552. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17553. if (ifaceMethod == NULL)
  17554. continue;
  17555. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17556. {
  17557. if (methodDef->mIsOverride)
  17558. {
  17559. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  17560. {
  17561. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  17562. if (error != NULL)
  17563. {
  17564. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  17565. }
  17566. }
  17567. foundOverride = true;
  17568. }
  17569. else if (!methodDef->mIsNew)
  17570. {
  17571. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  17572. }
  17573. }
  17574. }
  17575. }
  17576. if ((methodDef->mIsOverride) && (!foundOverride))
  17577. {
  17578. // This allows us to declare a method in the base definition or in an extension and then provide
  17579. // an implementation in a more-specific extension
  17580. typeInstance->mTypeDef->PopulateMemberSets();
  17581. BfMethodDef* nextMethod = NULL;
  17582. BfMemberSetEntry* entry = NULL;
  17583. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17584. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17585. while (nextMethod != NULL)
  17586. {
  17587. auto checkMethod = nextMethod;
  17588. nextMethod = nextMethod->mNextWithSameName;
  17589. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17590. if (ifaceMethod == NULL)
  17591. continue;
  17592. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17593. continue;
  17594. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17595. {
  17596. foundOverride = true;
  17597. }
  17598. }
  17599. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17600. // {
  17601. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  17602. // if (ifaceMethod == NULL)
  17603. // continue;
  17604. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17605. // continue;
  17606. //
  17607. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17608. // {
  17609. // foundOverride = true;
  17610. // }
  17611. // }
  17612. }
  17613. if (methodDef->mIsOverride)
  17614. {
  17615. if (!foundOverride)
  17616. {
  17617. BfTokenNode* overrideToken = NULL;
  17618. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17619. overrideToken = propertyDeclaration->mVirtualSpecifier;
  17620. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17621. overrideToken = methodDeclaration->mVirtualSpecifier;
  17622. if (overrideToken != NULL)
  17623. {
  17624. Fail("No suitable method found to override", overrideToken, true);
  17625. }
  17626. else
  17627. {
  17628. // Possible cause - DTOR with params
  17629. AssertErrorState();
  17630. }
  17631. }
  17632. return true;
  17633. }
  17634. // Generic methods can't be called virtually
  17635. if (methodInstance->GetNumGenericParams() != 0)
  17636. return true;
  17637. // Only public methods can be called virtually
  17638. if (methodDef->mProtection != BfProtection_Public)
  17639. return true;
  17640. UniqueSlotVirtualMethod(methodInstance);
  17641. return true;
  17642. }
  17643. void BfModule::DbgFinish()
  17644. {
  17645. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  17646. return;
  17647. if (mAwaitingInitFinish)
  17648. FinishInit();
  17649. if (mHasForceLinkMarker)
  17650. return;
  17651. String markerName;
  17652. BfIRValue linkMarker;
  17653. if (mBfIRBuilder->DbgHasInfo())
  17654. {
  17655. bool needForceLinking = false;
  17656. for (auto& ownedType : mOwnedTypeInstances)
  17657. {
  17658. bool hasConfirmedReference = false;
  17659. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  17660. {
  17661. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  17662. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) &&
  17663. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  17664. {
  17665. hasConfirmedReference = true;
  17666. }
  17667. }
  17668. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  17669. needForceLinking = true;
  17670. }
  17671. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  17672. {
  17673. BfMethodState methodState;
  17674. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17675. methodState.mTempKind = BfMethodState::TempKind_Static;
  17676. mHasForceLinkMarker = true;
  17677. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  17678. SizedArray<BfIRType, 0> paramTypes;
  17679. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  17680. String linkName = "FORCELINKMOD_" + mModuleName;
  17681. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  17682. mBfIRBuilder->SetActiveFunction(func);
  17683. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  17684. mBfIRBuilder->SetInsertPoint(entryBlock);
  17685. auto firstType = mOwnedTypeInstances[0];
  17686. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  17687. SizedArray<BfIRMDNode, 1> diParamTypes;
  17688. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  17689. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  17690. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  17691. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  17692. methodState.mCurScope->mDIScope = diScope;
  17693. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  17694. SizedArray<BfIRValue, 8> args;
  17695. BfExprEvaluator exprEvaluator(this);
  17696. for (auto& ownedType : mOwnedTypeInstances)
  17697. {
  17698. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  17699. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  17700. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  17701. }
  17702. mBfIRBuilder->CreateRetVoid();
  17703. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  17704. }
  17705. }
  17706. }
  17707. bool BfModule::Finish()
  17708. {
  17709. BP_ZONE("BfModule::Finish");
  17710. BfLogSysM("BfModule finish: %p\n", this);
  17711. if (mHadBuildError)
  17712. {
  17713. // Don't AssertErrorState here, this current pass may not have failed but
  17714. // the module was still queued in mFinishedModuleWorkList
  17715. ClearModule();
  17716. return true;
  17717. }
  17718. if (mUsedSlotCount != -1)
  17719. {
  17720. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  17721. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  17722. }
  17723. BF_ASSERT(mAddedToCount);
  17724. mAddedToCount = false;
  17725. mAwaitingFinish = false;
  17726. mCompiler->mStats.mModulesFinished++;
  17727. if (HasCompiledOutput())
  17728. {
  17729. DbgFinish();
  17730. if (mAwaitingInitFinish)
  17731. FinishInit();
  17732. for (auto ownedTypeInst : mOwnedTypeInstances)
  17733. {
  17734. // Generate dbg info and add global variables if we haven't already
  17735. mBfIRBuilder->PopulateType(ownedTypeInst);
  17736. }
  17737. if (mBfIRBuilder->DbgHasInfo())
  17738. {
  17739. mBfIRBuilder->DbgFinalize();
  17740. }
  17741. String objOutputPath;
  17742. String irOutputPath;
  17743. mIsModuleMutable = false;
  17744. //mOutFileNames.Clear();
  17745. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  17746. bool writeModule = mBfIRBuilder->HasExports();
  17747. String outputPath;
  17748. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  17749. auto& compilerOpts = mCompiler->mOptions;
  17750. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  17751. auto moduleOptions = GetModuleOptions();
  17752. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  17753. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  17754. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  17755. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  17756. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  17757. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  17758. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  17759. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  17760. bool allowWriteToLib = true;
  17761. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) && (mModuleName != "vdata"))
  17762. {
  17763. codeGenOptions.mWriteToLib = true;
  17764. mWroteToLib = true;
  17765. }
  17766. else
  17767. {
  17768. mWroteToLib = false;
  17769. }
  17770. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  17771. {
  17772. outputPath = mModuleName;
  17773. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  17774. BfModuleFileName moduleFileName;
  17775. if (mParentModule != NULL)
  17776. {
  17777. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  17778. {
  17779. if (checkPair.mValue == this)
  17780. moduleFileName.mProjects = checkPair.mKey;
  17781. }
  17782. }
  17783. moduleFileName.mProjects.Add(mProject);
  17784. if (fileIdx > 0)
  17785. outputPath += StrFormat("@%d", fileIdx + 1);
  17786. if (mCompiler->mOptions.mWriteIR)
  17787. irOutputPath = outputPath + ".ll";
  17788. if (mCompiler->mOptions.mGenerateObj)
  17789. {
  17790. objOutputPath = outputPath + BF_OBJ_EXT;
  17791. moduleFileName.mFileName = objOutputPath;
  17792. }
  17793. else if (mCompiler->mOptions.mWriteIR)
  17794. {
  17795. moduleFileName.mFileName = irOutputPath;
  17796. }
  17797. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mWriteIR))
  17798. {
  17799. BF_FATAL("Neither obj nor IR specified");
  17800. }
  17801. moduleFileName.mModuleWritten = writeModule;
  17802. moduleFileName.mWroteToLib = mWroteToLib;
  17803. if (!mOutFileNames.Contains(moduleFileName))
  17804. mOutFileNames.Add(moduleFileName);
  17805. }
  17806. if (mCompiler->IsHotCompile())
  17807. {
  17808. codeGenOptions.mIsHotCompile = true;
  17809. //TODO: Why did we have this 'mWroteToLib' check? 'vdata' didn't get this flag set, which
  17810. // is required for rebuilding vdata after we hot create a vdata
  17811. //if (mWroteToLib)
  17812. {
  17813. if (mParentModule != NULL)
  17814. mParentModule->mHadHotObjectWrites = true;
  17815. mHadHotObjectWrites = true;
  17816. }
  17817. }
  17818. //TODO: Testing VDATA
  17819. /*if (mModuleName == "vdata")
  17820. {
  17821. codeGenOptions.mOptLevel = 4;
  17822. }*/
  17823. codeGenOptions.GenerateHash();
  17824. BP_ZONE("BfModule::Finish.WriteObjectFile");
  17825. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  17826. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  17827. mLastModuleWrittenRevision = mCompiler->mRevision;
  17828. }
  17829. else
  17830. {
  17831. for (auto type : mOwnedTypeInstances)
  17832. {
  17833. BF_ASSERT(!type->IsIncomplete());
  17834. }
  17835. }
  17836. for (auto& specModulePair : mSpecializedMethodModules)
  17837. {
  17838. auto specModule = specModulePair.mValue;
  17839. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  17840. {
  17841. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  17842. }
  17843. }
  17844. CleanupFileInstances();
  17845. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  17846. return true;
  17847. }
  17848. void BfModule::ReportMemory(MemReporter* memReporter)
  17849. {
  17850. memReporter->Add(sizeof(BfModule));
  17851. if (mBfIRBuilder != NULL)
  17852. {
  17853. memReporter->BeginSection("IRBuilder_ConstData");
  17854. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  17855. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  17856. memReporter->EndSection();
  17857. memReporter->BeginSection("IRBuilder_BFIR");
  17858. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  17859. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  17860. memReporter->EndSection();
  17861. memReporter->Add(sizeof(BfIRBuilder));
  17862. }
  17863. memReporter->BeginSection("FileInstanceMap");
  17864. memReporter->AddMap(mFileInstanceMap);
  17865. memReporter->AddMap(mNamedFileInstanceMap);
  17866. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  17867. memReporter->EndSection();
  17868. memReporter->AddVec(mOwnedTypeInstances, false);
  17869. memReporter->AddVec(mSpecializedMethodModules, false);
  17870. memReporter->AddVec(mOutFileNames, false);
  17871. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  17872. memReporter->AddMap(mInterfaceSlotRefs, false);
  17873. memReporter->AddMap(mStaticFieldRefs, false);
  17874. memReporter->AddMap(mClassVDataRefs, false);
  17875. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  17876. memReporter->AddMap(mTypeDataRefs, false);
  17877. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  17878. memReporter->AddMap(mDeferredMethodCallData, false);
  17879. memReporter->AddHashSet(mDeferredMethodIds, false);
  17880. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  17881. }
  17882. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  17883. // be transient through the next compile
  17884. void BfModule::ClearModuleData()
  17885. {
  17886. BfLogSysM("ClearModuleData %p\n", this);
  17887. if (mAddedToCount)
  17888. {
  17889. mCompiler->mStats.mModulesFinished++;
  17890. mAddedToCount = false;
  17891. }
  17892. mDICompileUnit = BfIRMDNode();
  17893. mIsModuleMutable = false;
  17894. mIncompleteMethodCount = 0;
  17895. mHasGenericMethods = false;
  17896. // We don't want to clear these because we want it to persist through module extensions-
  17897. // otherwise we may think an extension succeeds even though the base module failed
  17898. //mHadBuildError = false;
  17899. //mHadBuildWarning = false;
  17900. mClassVDataRefs.Clear();
  17901. mClassVDataExtRefs.Clear();
  17902. for (auto& kv : mTypeDataRefs)
  17903. kv.mValue = BfIRValue();
  17904. mStringCharPtrPool.Clear();
  17905. mStringObjectPool.Clear();
  17906. mStaticFieldRefs.Clear();
  17907. BF_ASSERT(!mIgnoreErrors);
  17908. for (auto prevIRBuilder : mPrevIRBuilders)
  17909. delete prevIRBuilder;
  17910. mPrevIRBuilders.Clear();
  17911. for (auto& specPair : mSpecializedMethodModules)
  17912. {
  17913. auto specModule = specPair.mValue;
  17914. specModule->ClearModuleData();
  17915. }
  17916. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  17917. mBuiltInFuncs[i] = BfIRFunction();
  17918. if (mNextAltModule != NULL)
  17919. mNextAltModule->ClearModuleData();
  17920. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  17921. delete mBfIRBuilder;
  17922. mBfIRBuilder = NULL;
  17923. mWantsIRIgnoreWrites = false;
  17924. }
  17925. void BfModule::DisownMethods()
  17926. {
  17927. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  17928. mBuiltInFuncs[i] = BfIRFunction();
  17929. BfModule* methodModule = this;
  17930. if (mParentModule != NULL)
  17931. methodModule = mParentModule;
  17932. for (auto typeInst : methodModule->mOwnedTypeInstances)
  17933. {
  17934. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  17935. {
  17936. if (methodGroup.mDefault != NULL)
  17937. {
  17938. if (methodGroup.mDefault->mIRFunction)
  17939. {
  17940. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  17941. if (methodGroup.mDefault->mDeclModule == this)
  17942. {
  17943. methodGroup.mDefault->mIRFunction = BfIRFunction();
  17944. }
  17945. }
  17946. }
  17947. if (methodGroup.mMethodSpecializationMap != NULL)
  17948. {
  17949. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  17950. {
  17951. auto methodInstance = mapPair.mValue;
  17952. if (methodInstance->mDeclModule == this)
  17953. {
  17954. methodInstance->mIRFunction = BfIRFunction();
  17955. }
  17956. }
  17957. }
  17958. }
  17959. }
  17960. }
  17961. void BfModule::ClearModule()
  17962. {
  17963. ClearModuleData();
  17964. DisownMethods();
  17965. for (auto& specPair : mSpecializedMethodModules)
  17966. {
  17967. auto specModule = specPair.mValue;
  17968. specModule->ClearModule();
  17969. }
  17970. if (mNextAltModule != NULL)
  17971. mNextAltModule->ClearModule();
  17972. }