BfModule.cpp 912 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(disable:4996)
  4. #pragma warning(push) // 6
  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 "BfConstResolver.h"
  12. #include "BfMangler.h"
  13. #include "BeefySysLib/util/PerfTimer.h"
  14. #include "BeefySysLib/util/BeefPerf.h"
  15. #include "BeefySysLib/util/StackHelper.h"
  16. #include "BfSourceClassifier.h"
  17. #include "BfAutoComplete.h"
  18. #include "BfDemangler.h"
  19. #include "BfResolvePass.h"
  20. #include "BfFixits.h"
  21. #include "BfIRCodeGen.h"
  22. #include "BfDefBuilder.h"
  23. #include "BfDeferEvalChecker.h"
  24. #include "CeMachine.h"
  25. #include "CeDebugger.h"
  26. #include <fcntl.h>
  27. #include <time.h>
  28. #pragma warning (disable:4267)
  29. //#include "llvm/Support/Compiler.h"
  30. //#include "llvm/IR/IRBuilder.h"
  31. //#include "llvm/IR/Type.h"
  32. #include "llvm/IR/DIBuilder.h"
  33. //#include "llvm/IR/DebugInfo.h"
  34. //#include "llvm/IR/Argument.h"
  35. //#include "llvm/IR/Constants.h"
  36. #pragma warning(pop)
  37. //////////////////////////////////////////////////////////////////////////
  38. static bool gDebugStuff = false;
  39. USING_NS_BF;
  40. //////////////////////////////////////////////////////////////////////////
  41. void BfLocalVariable::Init()
  42. {
  43. if (mResolvedType->IsValuelessType())
  44. {
  45. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  46. return;
  47. }
  48. if (mAssignedKind != BfLocalVarAssignKind_None)
  49. return;
  50. bool isStruct = mResolvedType->IsStruct();
  51. if (mResolvedType->IsRef())
  52. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  53. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  54. {
  55. auto resolvedTypeRef = mResolvedType;
  56. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  57. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  58. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  59. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  60. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  61. {
  62. // Base ctor is responsible for initializing its own fields
  63. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  64. }
  65. if (mUnassignedFieldFlags == 0)
  66. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  67. }
  68. else
  69. {
  70. mUnassignedFieldFlags = 1;
  71. }
  72. }
  73. BfLocalMethod::~BfLocalMethod()
  74. {
  75. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  76. if (mMethodDeclaration != NULL)
  77. {
  78. mSource->mRefCount--;
  79. BF_ASSERT(mSource->mRefCount >= 0);
  80. }
  81. delete mMethodInstanceGroup;
  82. delete mMethodDef;
  83. }
  84. void BfLocalMethod::Dispose()
  85. {
  86. if (mMethodInstanceGroup == NULL)
  87. return;
  88. if (mMethodInstanceGroup->mDefault != NULL)
  89. mMethodInstanceGroup->mDefault->Dispose();
  90. if (mMethodInstanceGroup->mMethodSpecializationMap != NULL)
  91. {
  92. for (auto& kv : *mMethodInstanceGroup->mMethodSpecializationMap)
  93. kv.mValue->Dispose();
  94. }
  95. }
  96. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  97. {
  98. mIsChained = doChain;
  99. if (outerLocalAssignData == NULL)
  100. return;
  101. mChainedAssignData = outerLocalAssignData;
  102. if (!doChain)
  103. {
  104. outerLocalAssignData->BreakExtendChain();
  105. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  106. }
  107. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  108. }
  109. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  110. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  111. // if ((GetValue(out a)) && (GetValue(out b)) {}
  112. void BfDeferredLocalAssignData::BreakExtendChain()
  113. {
  114. if (!mIsChained)
  115. return;
  116. mIsChained = false;
  117. if (mChainedAssignData == NULL)
  118. return;
  119. mChainedAssignData->BreakExtendChain();
  120. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  121. }
  122. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  123. {
  124. BreakExtendChain();
  125. if (otherLocalAssignData.mLeftBlockUncond)
  126. {
  127. // Intersection of self and infinity is self
  128. }
  129. else if (mLeftBlockUncond)
  130. {
  131. // Intersection of infinity and other is other
  132. mAssignedLocals = otherLocalAssignData.mAssignedLocals;
  133. }
  134. else
  135. {
  136. for (int i = 0; i < (int)mAssignedLocals.size(); )
  137. {
  138. auto& local = mAssignedLocals[i];
  139. bool wantRemove = true;
  140. bool foundOtherFields = false;
  141. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  142. {
  143. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  144. {
  145. if ((otherLocalAssignData.mLocalVarField == local.mLocalVarField) || (otherLocalAssignData.mLocalVarField == -1))
  146. {
  147. if (otherLocalAssignData.mAssignKind == BfLocalVarAssignKind_Conditional)
  148. local.mAssignKind = BfLocalVarAssignKind_Conditional;
  149. wantRemove = false;
  150. }
  151. else
  152. foundOtherFields = true;
  153. }
  154. }
  155. if ((wantRemove) && (foundOtherFields))
  156. {
  157. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  158. {
  159. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  160. {
  161. mAssignedLocals.Add(otherLocalAssignData);
  162. }
  163. }
  164. }
  165. if (wantRemove)
  166. {
  167. mAssignedLocals.RemoveAt(i);
  168. }
  169. else
  170. i++;
  171. }
  172. }
  173. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  174. mLeftBlockUncond = mLeftBlockUncond && otherLocalAssignData.mLeftBlockUncond;
  175. }
  176. void BfDeferredLocalAssignData::Validate() const
  177. {
  178. for (auto var : mAssignedLocals)
  179. {
  180. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  181. }
  182. }
  183. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  184. {
  185. BreakExtendChain();
  186. Validate();
  187. otherLocalAssignData.Validate();
  188. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  189. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  190. {
  191. if (!mAssignedLocals.Contains(*otherItr))
  192. mAssignedLocals.push_back(*otherItr);
  193. ++otherItr;
  194. }
  195. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  196. mLeftBlockUncond = mLeftBlockUncond || otherLocalAssignData.mLeftBlockUncond;
  197. }
  198. BfMethodState::~BfMethodState()
  199. {
  200. BF_ASSERT(mPendingNullConditional == NULL);
  201. if (mPrevMethodState != NULL)
  202. {
  203. BF_ASSERT(mCurAccessId == 1);
  204. BF_ASSERT(mCurLocalVarId <= 0);
  205. }
  206. for (auto local : mLocals)
  207. {
  208. if (local->mIsBumpAlloc)
  209. local->~BfLocalVariable();
  210. else
  211. delete local;
  212. }
  213. for (auto& kv : mLambdaCache)
  214. delete kv.mValue;
  215. }
  216. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  217. {
  218. auto checkMethodState = this;
  219. while (checkMethodState != NULL)
  220. {
  221. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  222. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  223. return checkMethodState;
  224. checkMethodState = checkMethodState->mPrevMethodState;
  225. }
  226. BF_FATAL("Failed to find method state for localvar");
  227. return NULL;
  228. }
  229. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx, BfLocalVarAssignKind assignKind, bool isFromDeferredAssignData)
  230. {
  231. auto localVarMethodState = GetMethodStateForLocal(localVar);
  232. if (localVarMethodState != this)
  233. {
  234. return;
  235. }
  236. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  237. {
  238. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  239. // 'a' is always defined, but 'b' isn't:
  240. // if (Check(out a) || Check(out b)) { } int z = a;
  241. auto deferredLocalAssignData = mDeferredLocalAssignData;
  242. if ((deferredLocalAssignData != NULL) &&
  243. (deferredLocalAssignData->mIsIfCondition) &&
  244. (!deferredLocalAssignData->mIfMayBeSkipped))
  245. {
  246. ifDeferredLocalAssignData = deferredLocalAssignData;
  247. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  248. }
  249. while ((deferredLocalAssignData != NULL) &&
  250. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  251. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  252. if (assignKind == BfLocalVarAssignKind_None)
  253. assignKind = ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mLeftBlock)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  254. if (localVar->mAssignedKind >= assignKind)
  255. {
  256. // Leave it alone
  257. }
  258. else if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  259. {
  260. if (fieldIdx >= 0)
  261. {
  262. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  263. if (localVar->mResolvedType->IsUnion())
  264. {
  265. // We need more 'smarts' to determine assignment of unions
  266. localVar->mUnassignedFieldFlags = 0;
  267. }
  268. if (localVar->mUnassignedFieldFlags == 0)
  269. {
  270. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  271. localVar->mAssignedKind = assignKind;
  272. }
  273. }
  274. else
  275. {
  276. localVar->mAssignedKind = assignKind;
  277. }
  278. }
  279. else
  280. {
  281. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  282. BfAssignedLocal defineVal = {localVar, fieldIdx, assignKind};
  283. if (!deferredLocalAssignData->Contains(defineVal))
  284. deferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  285. if (ifDeferredLocalAssignData != NULL)
  286. {
  287. if (!ifDeferredLocalAssignData->Contains(defineVal))
  288. ifDeferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  289. }
  290. }
  291. }
  292. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  293. }
  294. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  295. {
  296. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  297. if (deferredLocalAssignData.mLeftBlockUncond)
  298. {
  299. for (int localIdx = 0; localIdx < (int)mLocals.size(); localIdx++)
  300. {
  301. auto localDef = mLocals[localIdx];
  302. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  303. {
  304. bool hadAssignment = false;
  305. if (mDeferredLocalAssignData != NULL)
  306. {
  307. for (auto& entry : mDeferredLocalAssignData->mAssignedLocals)
  308. if (entry.mLocalVar == localDef)
  309. hadAssignment = true;
  310. }
  311. if (!hadAssignment)
  312. {
  313. LocalDefined(localDef);
  314. }
  315. }
  316. }
  317. }
  318. else
  319. {
  320. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  321. {
  322. LocalDefined(assignedLocal.mLocalVar, assignedLocal.mLocalVarField, assignedLocal.mAssignKind, true);
  323. }
  324. }
  325. }
  326. void BfMethodState::Reset()
  327. {
  328. mHeadScope.mDeferredCallEntries.DeleteAll();
  329. }
  330. //////////////////////////////////////////////////////////////////////////
  331. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  332. {
  333. Entry* entry = NULL;
  334. if (mEntries.TryAdd(id, NULL, &entry))
  335. {
  336. entry->mInterfaceEntry = interfaceEntry;
  337. entry->mMethodIdx = methodIdx;
  338. }
  339. if (!entry->mCandidates.Contains(candidateA))
  340. entry->mCandidates.push_back(candidateA);
  341. if (!entry->mCandidates.Contains(candidateB))
  342. entry->mCandidates.push_back(candidateB);
  343. }
  344. void BfAmbiguityContext::Remove(int id)
  345. {
  346. mEntries.Remove(id);
  347. }
  348. void BfAmbiguityContext::Finish()
  349. {
  350. for (auto& entryPair : mEntries)
  351. {
  352. int id = entryPair.mKey;
  353. auto entry = &entryPair.mValue;
  354. if (id >= 0)
  355. {
  356. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  357. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  358. if (error != NULL)
  359. {
  360. for (auto candidate : entry->mCandidates)
  361. {
  362. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  363. mModule->MethodToString(candidate, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType)).c_str()), candidate->mMethodDef->GetRefNode());
  364. }
  365. }
  366. }
  367. else
  368. {
  369. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  370. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  371. if (error != NULL)
  372. {
  373. for (auto candidate : entry->mCandidates)
  374. {
  375. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  376. mModule->MethodToString(candidate, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType)).c_str()), candidate->mMethodDef->GetRefNode());
  377. }
  378. }
  379. }
  380. }
  381. mEntries.Clear();
  382. }
  383. //////////////////////////////////////////////////////////////////////////
  384. class HasAppendAllocVisitor : BfElementVisitor
  385. {
  386. public:
  387. bool mHas;
  388. public:
  389. HasAppendAllocVisitor()
  390. {
  391. mHas = false;
  392. }
  393. void Visit(BfObjectCreateExpression* objCreateExpr)
  394. {
  395. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  396. {
  397. if (newToken->GetToken() == BfToken_Append)
  398. {
  399. mHas = true;
  400. }
  401. }
  402. }
  403. bool HasAppendAlloc(BfAstNode* node)
  404. {
  405. mHas = false;
  406. VisitChild(node);
  407. return mHas;
  408. }
  409. };
  410. class AppendAllocVisitor : public BfStructuralVisitor
  411. {
  412. public:
  413. BfModule* mModule;
  414. HasAppendAllocVisitor mHasAppendAllocVisitor;
  415. BfTypedValue mConstAccum;
  416. bool mFailed;
  417. bool mIsFirstConstPass;
  418. int mCurAppendAlign;
  419. public:
  420. AppendAllocVisitor()
  421. {
  422. mFailed = false;
  423. mIsFirstConstPass = false;
  424. mCurAppendAlign = 1;
  425. }
  426. void EmitAppendAlign(int align, int sizeMultiple = 0)
  427. {
  428. if (align <= 1)
  429. return;
  430. if (mIsFirstConstPass)
  431. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  432. if (sizeMultiple == 0)
  433. sizeMultiple = align;
  434. if (mCurAppendAlign == 0)
  435. mCurAppendAlign = sizeMultiple;
  436. else
  437. {
  438. if (sizeMultiple % align == 0)
  439. mCurAppendAlign = align;
  440. else
  441. mCurAppendAlign = sizeMultiple % align;
  442. }
  443. BF_ASSERT(mCurAppendAlign > 0);
  444. if (mConstAccum)
  445. {
  446. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  447. if (constant != NULL)
  448. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  449. else
  450. BF_ASSERT(mIsFirstConstPass);
  451. return;
  452. }
  453. mModule->EmitAppendAlign(align, sizeMultiple);
  454. }
  455. void Visit(BfAstNode* astNode) override
  456. {
  457. mModule->VisitChild(astNode);
  458. }
  459. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  460. {
  461. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  462. {
  463. if (newToken->GetToken() == BfToken_Append)
  464. {
  465. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  466. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  467. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  468. BfArrayType* arrayType = NULL;
  469. bool isArrayAlloc = false;
  470. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  471. SizedArray<BfIRValue, 2> dimLengthVals;
  472. BfType* origResolvedTypeRef = NULL;
  473. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  474. {
  475. if (variableDecl != NULL)
  476. {
  477. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  478. if (origResolvedTypeRef->IsObject())
  479. {
  480. if (origResolvedTypeRef->IsArray())
  481. {
  482. arrayType = (BfArrayType*)origResolvedTypeRef;
  483. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  484. isArrayAlloc = true;
  485. }
  486. }
  487. else if (origResolvedTypeRef->IsPointer())
  488. {
  489. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  490. }
  491. }
  492. }
  493. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  494. {
  495. isArrayAlloc = true;
  496. bool handled = false;
  497. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  498. {
  499. if (variableDecl->mTypeRef != NULL)
  500. {
  501. auto variableType = mModule->ResolveTypeRef(variableDecl->mTypeRef);
  502. if (variableType != NULL)
  503. {
  504. if (variableType->IsArray())
  505. origResolvedTypeRef = variableType->GetUnderlyingType();
  506. }
  507. handled = true;
  508. }
  509. }
  510. if (!handled)
  511. {
  512. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType, BfPopulateType_Declaration);
  513. }
  514. if (origResolvedTypeRef == NULL)
  515. {
  516. mModule->AssertErrorState();
  517. return;
  518. }
  519. int dimensions = 1;
  520. if (arrayTypeRef->mParams.size() != 0)
  521. {
  522. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  523. for (auto arg : arrayTypeRef->mParams)
  524. {
  525. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  526. {
  527. if (tokenNode->GetToken() == BfToken_Comma)
  528. {
  529. if (isRawArrayAlloc)
  530. {
  531. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  532. continue;
  533. }
  534. dimensions++;
  535. continue;
  536. }
  537. }
  538. auto expr = BfNodeDynCast<BfExpression>(arg);
  539. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  540. {
  541. mModule->CreateValueFromExpression(expr, intType);
  542. continue;
  543. }
  544. BfTypedValue dimLength;
  545. if (expr == NULL)
  546. {
  547. // Not specified
  548. dimLengthVals.push_back(BfIRValue());
  549. continue;
  550. }
  551. if (arg != NULL)
  552. dimLength = mModule->CreateValueFromExpression(expr, intType);
  553. if (!dimLength)
  554. {
  555. dimLength = mModule->GetDefaultTypedValue(intType);
  556. }
  557. dimLengthVals.push_back(dimLength.mValue);
  558. }
  559. }
  560. if (!isRawArrayAlloc)
  561. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  562. }
  563. if (origResolvedTypeRef == NULL)
  564. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  565. if (origResolvedTypeRef == NULL)
  566. {
  567. mModule->AssertErrorState();
  568. return;
  569. }
  570. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  571. auto resolvedTypeRef = origResolvedTypeRef;
  572. auto resultType = resolvedTypeRef;
  573. BfIRValue sizeValue;
  574. int curAlign = 0;
  575. if (isArrayAlloc)
  576. {
  577. int dimensions = 1;
  578. if (arrayType != NULL)
  579. dimensions = arrayType->mDimensions;
  580. bool sizeFailed = false;
  581. //
  582. {
  583. BfAstNode* initNode = objCreateExpr;
  584. for (int dim = 0; dim < dimensions; dim++)
  585. {
  586. BfAstNode* nextInitNode = NULL;
  587. int dimSize = -1;
  588. if (initNode == objCreateExpr)
  589. {
  590. dimSize = objCreateExpr->mArguments.size();
  591. if (!objCreateExpr->mArguments.IsEmpty())
  592. nextInitNode = objCreateExpr->mArguments[0];
  593. }
  594. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  595. {
  596. dimSize = (int)tupleNode->mCommas.size() + 1;
  597. }
  598. if (dimSize >= 0)
  599. {
  600. if (dim >= dimLengthVals.size())
  601. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  602. }
  603. else
  604. {
  605. sizeFailed = true;
  606. }
  607. }
  608. }
  609. BfIRValue allocCount;
  610. if (!sizeFailed)
  611. {
  612. if (!dimLengthVals.IsEmpty())
  613. {
  614. allocCount = dimLengthVals[0];
  615. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  616. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  617. }
  618. }
  619. if (!allocCount)
  620. {
  621. mFailed = true;
  622. if (!mIsFirstConstPass)
  623. {
  624. if (!mConstAccum)
  625. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  626. return;
  627. }
  628. }
  629. mModule->PopulateType(resultType, resultType->IsValueType() ? BfPopulateType_Data : BfPopulateType_Declaration);
  630. if (isRawArrayAlloc)
  631. {
  632. curAlign = resultType->mAlign;
  633. EmitAppendAlign(resultType->mAlign);
  634. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  635. }
  636. else
  637. {
  638. if (arrayType == NULL)
  639. arrayType = mModule->CreateArrayType(resultType, 1);
  640. // Array is a special case where the total size isn't aligned with mAlign
  641. // since we add arbitrary elements to the end without padding the end to align
  642. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  643. curAlign = arrayType->mAlign;
  644. auto firstElementField = &arrayType->mFieldInstances.back();
  645. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  646. sizeValue = mModule->GetConstValue(arrayClassSize);
  647. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  648. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  649. }
  650. }
  651. else
  652. {
  653. auto typeInst = resultType->ToTypeInstance();
  654. if (typeInst != NULL)
  655. {
  656. curAlign = typeInst->mInstAlign;
  657. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  658. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  659. }
  660. else
  661. {
  662. curAlign = resultType->mAlign;
  663. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  664. sizeValue = mModule->GetConstValue(resultType->mSize);
  665. }
  666. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  667. BfExprEvaluator exprEvaluator(mModule);
  668. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  669. BfFunctionBindResult bindResult;
  670. bindResult.mWantsArgs = true;
  671. exprEvaluator.mFunctionBindResult = &bindResult;
  672. SizedArray<BfExpression*, 8> copiedArgs;
  673. for (BfExpression* arg : objCreateExpr->mArguments)
  674. copiedArgs.push_back(arg);
  675. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  676. BfResolvedArgs argValues(&sizedArgExprs);
  677. if (typeInst != NULL)
  678. {
  679. exprEvaluator.ResolveArgValues(argValues);
  680. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, BfMethodGenericArguments(), true);
  681. }
  682. exprEvaluator.mFunctionBindResult = NULL;
  683. if (bindResult.mMethodInstance != NULL)
  684. {
  685. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  686. {
  687. auto calcAppendArgs = bindResult.mIRArgs;
  688. BF_ASSERT(calcAppendArgs[0].IsFake());
  689. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  690. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  691. auto subDependSize = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, calcAppendArgs);
  692. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  693. {
  694. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  695. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  696. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  697. }
  698. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  699. if ((!subDependSize) && (!mConstAccum))
  700. {
  701. BF_ASSERT(calcAppendMethodModule.mFunc);
  702. subDependSize = exprEvaluator.CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  703. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  704. }
  705. if (subDependSize)
  706. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  707. else
  708. mFailed = true;
  709. }
  710. }
  711. }
  712. if (sizeValue)
  713. {
  714. if (mConstAccum)
  715. {
  716. if (!sizeValue.IsConst())
  717. {
  718. mFailed = true;
  719. if (!mIsFirstConstPass)
  720. return;
  721. }
  722. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  723. }
  724. else
  725. {
  726. auto prevVal = mModule->mBfIRBuilder->CreateAlignedLoad(accumValuePtr, intPtrType->mAlign);
  727. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  728. mModule->mBfIRBuilder->CreateAlignedStore(addedVal, accumValuePtr, intPtrType->mAlign);
  729. }
  730. }
  731. }
  732. }
  733. }
  734. void Visit(BfObjectCreateExpression* objCreateExpr) override
  735. {
  736. DoObjectCreate(objCreateExpr, NULL);
  737. }
  738. void Visit(BfVariableDeclaration* varDecl) override
  739. {
  740. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  741. {
  742. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  743. DoObjectCreate(objectCreateExpr, varDecl);
  744. else
  745. VisitChild(varDecl->mInitializer);
  746. if (varDecl->mNameNode != NULL)
  747. {
  748. BfLocalVariable* localDef = new BfLocalVariable();
  749. localDef->mName = varDecl->mNameNode->ToString();
  750. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  751. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  752. localDef->mIsReadOnly = true;
  753. localDef->mParamFailed = true;
  754. localDef->mReadFromId = 0;
  755. mModule->AddLocalVariableDef(localDef);
  756. }
  757. }
  758. else
  759. {
  760. mModule->Visit(varDecl);
  761. }
  762. }
  763. void Visit(BfExpressionStatement* exprStatement) override
  764. {
  765. VisitChild(exprStatement->mExpression);
  766. }
  767. // void Visit(BfIfStatement* ifStmt) override
  768. // {
  769. // mModule->DoIfStatement(ifStmt,
  770. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  771. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  772. // }
  773. void Visit(BfBlock* block) override
  774. {
  775. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  776. return;
  777. int appendAllocIdx = -1;
  778. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  779. {
  780. auto child = block->mChildArr.mVals[childIdx];
  781. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  782. {
  783. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  784. {
  785. auto emitChild = block->mChildArr.mVals[emitIdx];
  786. mModule->UpdateSrcPos(emitChild);
  787. VisitChild(emitChild);
  788. if ((mFailed) && (!mIsFirstConstPass))
  789. break;
  790. }
  791. break;
  792. }
  793. }
  794. }
  795. };
  796. //////////////////////////////////////////////////////////////////////////
  797. BfModule* gLastCreatedModule = NULL;
  798. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  799. {
  800. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  801. gLastCreatedModule = this;
  802. mContext = context;
  803. mModuleName = moduleName;
  804. if (!moduleName.empty())
  805. {
  806. StringT<256> upperModuleName = moduleName;
  807. MakeUpper(upperModuleName);
  808. mContext->mUsedModuleNames.Add(upperModuleName);
  809. }
  810. mAddedToCount = false;
  811. mParentModule = NULL;
  812. mNextAltModule = NULL;
  813. mBfIRBuilder = NULL;
  814. mWantsIRIgnoreWrites = false;
  815. mModuleOptions = NULL;
  816. mLastUsedRevision = -1;
  817. mUsedSlotCount = -1;
  818. mIsReified = true;
  819. mGeneratesCode = true;
  820. mReifyQueued = false;
  821. mIsSpecialModule = false;
  822. mIsComptimeModule = false;
  823. mIsScratchModule = false;
  824. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  825. mHadBuildError = false;
  826. mHadBuildWarning = false;
  827. mIgnoreErrors = false;
  828. mHadIgnoredError = false;
  829. mIgnoreWarnings = false;
  830. mReportErrors = true;
  831. mIsInsideAutoComplete = false;
  832. mIsDeleting = false;
  833. mSkipInnerLookup = false;
  834. mIsHotModule = false;
  835. mSetIllegalSrcPosition = false;
  836. mNoResolveGenericParams = false;
  837. mWroteToLib = false;
  838. mContext = context;
  839. mCompiler = context->mCompiler;
  840. mSystem = mCompiler->mSystem;
  841. mProject = NULL;
  842. mCurMethodState = NULL;
  843. mAttributeState = NULL;
  844. mCurLocalMethodId = 0;
  845. mParentNodeEntry = NULL;
  846. mRevision = -1;
  847. mRebuildIdx = 0;
  848. mLastModuleWrittenRevision = 0;
  849. mIsModuleMutable = false;
  850. mExtensionCount = 0;
  851. mIncompleteMethodCount = 0;
  852. mOnDemandMethodCount = 0;
  853. mHasGenericMethods = false;
  854. mCurMethodInstance = NULL;
  855. mCurTypeInstance = NULL;
  856. mAwaitingInitFinish = false;
  857. mAwaitingFinish = false;
  858. mHasFullDebugInfo = false;
  859. mHadHotObjectWrites = false;
  860. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  861. mBuiltInFuncs[i] = BfIRFunction();
  862. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  863. }
  864. void BfReportMemory();
  865. BfModule::~BfModule()
  866. {
  867. mRevision = -2;
  868. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  869. if (!mIsDeleting)
  870. RemoveModuleData();
  871. }
  872. void BfModule::RemoveModuleData()
  873. {
  874. BF_ASSERT(!mIsDeleting);
  875. if (!mModuleName.empty())
  876. {
  877. // Note: module names not necessarily unique
  878. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  879. }
  880. CleanupFileInstances();
  881. delete mBfIRBuilder;
  882. mBfIRBuilder = NULL;
  883. //delete mCpu;
  884. for (auto prevModule : mPrevIRBuilders)
  885. delete prevModule;
  886. mPrevIRBuilders.Clear();
  887. for (auto& pairVal : mDeferredMethodCallData)
  888. delete pairVal.mValue;
  889. mDeferredMethodCallData.Clear();
  890. mDeferredMethodIds.Clear();
  891. for (auto& specModulePair : mSpecializedMethodModules)
  892. delete specModulePair.mValue;
  893. mSpecializedMethodModules.Clear();
  894. if (mNextAltModule != NULL)
  895. delete mNextAltModule;
  896. mNextAltModule = NULL;
  897. if (mModuleOptions != NULL)
  898. delete mModuleOptions;
  899. mModuleOptions = NULL;
  900. BfReportMemory();
  901. }
  902. void BfModule::Init(bool isFullRebuild)
  903. {
  904. mContext->mFinishedModuleWorkList.Remove(this);
  905. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  906. BF_ASSERT(mIsReified);
  907. if (!mIsScratchModule)
  908. {
  909. mCompiler->mStats.mModulesStarted++;
  910. if (mIsReified)
  911. mCompiler->mStats.mReifiedModuleCount++;
  912. mAddedToCount = true;
  913. }
  914. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  915. mFuncReferences.Clear();
  916. mClassVDataRefs.Clear();
  917. mClassVDataExtRefs.Clear();
  918. //mTypeDataRefs.Clear();
  919. mDbgRawAllocDataRefs.Clear();
  920. CleanupFileInstances();
  921. mStaticFieldRefs.Clear();
  922. //mInterfaceSlotRefs.Clear();
  923. // If we are just doing an extension then the ownede types aren't rebuilt.
  924. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  925. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  926. if (isFullRebuild)
  927. mRevision = mCompiler->mRevision;
  928. BF_ASSERT(mCurTypeInstance == NULL);
  929. mIsModuleMutable = true;
  930. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  931. if (!mIsComptimeModule)
  932. {
  933. #ifdef _DEBUG
  934. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  935. #else
  936. EnsureIRBuilder(false);
  937. #endif
  938. }
  939. mCurMethodState = NULL;
  940. mAwaitingInitFinish = true;
  941. mOnDemandMethodCount = 0;
  942. mAwaitingFinish = false;
  943. mHasForceLinkMarker = false;
  944. mUsedSlotCount = -1;
  945. }
  946. bool BfModule::WantsFinishModule()
  947. {
  948. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  949. }
  950. bool BfModule::IsHotCompile()
  951. {
  952. return mCompiler->IsHotCompile() && !mIsComptimeModule;
  953. }
  954. void BfModule::FinishInit()
  955. {
  956. BF_ASSERT(mAwaitingInitFinish);
  957. auto moduleOptions = GetModuleOptions();
  958. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  959. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple, mCompiler->mOptions.mTargetCPU);
  960. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  961. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  962. {
  963. // Og+ requires debug info
  964. moduleOptions.mEmitDebugInfo = 1;
  965. }
  966. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  967. if (mIsComptimeModule)
  968. mHasFullDebugInfo = true;
  969. if (((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified)) ||
  970. (mIsComptimeModule))
  971. {
  972. mBfIRBuilder->DbgInit();
  973. }
  974. else
  975. mHasFullDebugInfo = false;
  976. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  977. ((moduleOptions.mEmitDebugInfo != 0)))
  978. {
  979. if (mCompiler->mOptions.IsCodeView())
  980. {
  981. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  982. }
  983. else
  984. {
  985. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  986. }
  987. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  988. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  989. }
  990. mAwaitingInitFinish = false;
  991. }
  992. void BfModule::CalcGeneratesCode()
  993. {
  994. if ((!mIsReified) || (mIsScratchModule))
  995. {
  996. mGeneratesCode = false;
  997. return;
  998. }
  999. mGeneratesCode = false;
  1000. for (auto typeInst : mOwnedTypeInstances)
  1001. if (!typeInst->IsInterface())
  1002. mGeneratesCode = true;
  1003. }
  1004. void BfModule::ReifyModule()
  1005. {
  1006. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  1007. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  1008. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  1009. mIsReified = true;
  1010. CalcGeneratesCode();
  1011. mReifyQueued = false;
  1012. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  1013. mCompiler->mStats.mModulesReified++;
  1014. }
  1015. void BfModule::UnreifyModule()
  1016. {
  1017. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  1018. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  1019. mIsReified = false;
  1020. CalcGeneratesCode();
  1021. mReifyQueued = false;
  1022. StartNewRevision(RebuildKind_None, true);
  1023. mCompiler->mStats.mModulesUnreified++;
  1024. }
  1025. void BfModule::CleanupFileInstances()
  1026. {
  1027. for (auto& itr : mNamedFileInstanceMap)
  1028. {
  1029. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  1030. delete itr.mValue;
  1031. }
  1032. mCurFilePosition.mFileInstance = NULL;//
  1033. mFileInstanceMap.Clear();
  1034. mNamedFileInstanceMap.Clear();
  1035. }
  1036. void BfModule::Cleanup()
  1037. {
  1038. CleanupFileInstances();
  1039. }
  1040. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  1041. {
  1042. if (HasCompiledOutput())
  1043. {
  1044. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  1045. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  1046. {
  1047. StartExtension();
  1048. }
  1049. }
  1050. else
  1051. {
  1052. EnsureIRBuilder();
  1053. }
  1054. }
  1055. void BfModule::SetupIRBuilder(bool dbgVerifyCodeGen)
  1056. {
  1057. if (mIsScratchModule)
  1058. {
  1059. mBfIRBuilder->mIgnoreWrites = true;
  1060. BF_ASSERT(!dbgVerifyCodeGen);
  1061. }
  1062. #ifdef _DEBUG
  1063. if (mCompiler->mIsResolveOnly)
  1064. {
  1065. // For "deep" verification testing
  1066. /*if (!mIsSpecialModule)
  1067. dbgVerifyCodeGen = true;*/
  1068. // We only want to turn this off on smaller builds for testing
  1069. mBfIRBuilder->mIgnoreWrites = true;
  1070. if (dbgVerifyCodeGen)
  1071. mBfIRBuilder->mIgnoreWrites = false;
  1072. if (!mBfIRBuilder->mIgnoreWrites)
  1073. {
  1074. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  1075. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1076. }
  1077. }
  1078. else if (!mGeneratesCode)
  1079. {
  1080. mBfIRBuilder->mIgnoreWrites = true;
  1081. }
  1082. else
  1083. {
  1084. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  1085. // code as we walk the AST
  1086. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1087. if (
  1088. (mModuleName == "-")
  1089. //|| (mModuleName == "")
  1090. //|| (mModuleName == "Tests_FuncRefs")
  1091. )
  1092. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1093. // Just for testing!
  1094. //mBfIRBuilder->mIgnoreWrites = true;
  1095. }
  1096. #else
  1097. if (mCompiler->mIsResolveOnly)
  1098. {
  1099. // Always ignore writes in resolveOnly for release builds
  1100. mBfIRBuilder->mIgnoreWrites = true;
  1101. }
  1102. else
  1103. {
  1104. // Just for memory testing! This breaks everything.
  1105. //mBfIRBuilder->mIgnoreWrites = true;
  1106. // For "deep" verification testing
  1107. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1108. }
  1109. #endif
  1110. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  1111. }
  1112. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  1113. {
  1114. BF_ASSERT(!mIsDeleting);
  1115. if (mBfIRBuilder == NULL)
  1116. {
  1117. if ((!mIsScratchModule) && (!mAddedToCount))
  1118. {
  1119. mCompiler->mStats.mModulesStarted++;
  1120. mAddedToCount = true;
  1121. }
  1122. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  1123. /*if (mCompiler->mIsResolveOnly)
  1124. BF_ASSERT(mIsResolveOnly);*/
  1125. mBfIRBuilder = new BfIRBuilder(this);
  1126. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  1127. SetupIRBuilder(dbgVerifyCodeGen);
  1128. }
  1129. }
  1130. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1131. {
  1132. String name = "FORCELINKMOD_" + module->mModuleName;
  1133. if (outName != NULL)
  1134. *outName = name;
  1135. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1136. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1137. }
  1138. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1139. {
  1140. BP_ZONE("BfModule::StartNewRevision");
  1141. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1142. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1143. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1144. if (mCompiler->mCompileState == BfCompiler::CompileState_Cleanup)
  1145. {
  1146. // Cleaning up local methods may cause some necessary NewRevisions
  1147. force = true;
  1148. }
  1149. // Already on new revision?
  1150. if ((mRevision == mCompiler->mRevision) && (!force))
  1151. return;
  1152. mHadBuildError = false;
  1153. mHadBuildWarning = false;
  1154. mExtensionCount = 0;
  1155. mRevision = mCompiler->mRevision;
  1156. mRebuildIdx++;
  1157. ClearModuleData(!force);
  1158. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1159. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1160. {
  1161. mStringPoolRefs.Clear();
  1162. mUnreifiedStringPoolRefs.Clear();
  1163. }
  1164. mDllImportEntries.Clear();
  1165. mImportFileNames.Clear();
  1166. for (auto& pairVal : mDeferredMethodCallData)
  1167. delete pairVal.mValue;
  1168. mDeferredMethodCallData.Clear();
  1169. mDeferredMethodIds.Clear();
  1170. mModuleRefs.Clear();
  1171. mOutFileNames.Clear();
  1172. mTypeDataRefs.Clear();
  1173. mInterfaceSlotRefs.Clear();
  1174. if (rebuildKind == BfModule::RebuildKind_None)
  1175. {
  1176. for (auto& specPair : mSpecializedMethodModules)
  1177. {
  1178. auto specModule = specPair.mValue;
  1179. if (specModule->mIsReified != mIsReified)
  1180. {
  1181. if (mIsReified)
  1182. specModule->ReifyModule();
  1183. else
  1184. specModule->UnreifyModule();
  1185. }
  1186. }
  1187. }
  1188. else
  1189. {
  1190. for (auto& specPair : mSpecializedMethodModules)
  1191. {
  1192. auto specModule = specPair.mValue;
  1193. BfLogSysM("Setting module mIsDeleting %p due to parent module starting a new revision\n", specModule);
  1194. // This module is no longer needed
  1195. specModule->RemoveModuleData();
  1196. specModule->mIsDeleting = true;
  1197. mContext->mDeletingModules.Add(specModule);
  1198. }
  1199. }
  1200. mSpecializedMethodModules.Clear();
  1201. delete mNextAltModule;
  1202. mNextAltModule = NULL;
  1203. BF_ASSERT(mModuleOptions == NULL);
  1204. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1205. bool needsTypePopulated = false;
  1206. int oldOnDemandCount = 0;
  1207. // We don't have to rebuild types in the unspecialized module because there is no
  1208. // data that's needed -- their method instances are all NULL and the module
  1209. // doesn't get included in the build
  1210. if (this != mContext->mScratchModule)
  1211. {
  1212. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1213. {
  1214. auto typeInst = mOwnedTypeInstances[typeIdx];
  1215. if (!typeInst->IsDeleting())
  1216. {
  1217. typeInst->mIsReified = mIsReified;
  1218. if (rebuildKind != BfModule::RebuildKind_None)
  1219. {
  1220. if (typeInst->IsOnDemand())
  1221. {
  1222. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1223. if (rebuildKind == BfModule::RebuildKind_All)
  1224. mContext->DeleteType(typeInst);
  1225. else
  1226. {
  1227. RebuildMethods(typeInst);
  1228. }
  1229. }
  1230. else
  1231. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1232. mContext->RebuildType(typeInst, false, false, true);
  1233. //mContext->RebuildType(typeInst, false, false, false);
  1234. }
  1235. else
  1236. {
  1237. auto _HandleMethod = [&](BfMethodInstance* methodInstance)
  1238. {
  1239. if ((methodInstance != NULL) && (methodInstance->mDeclModule != NULL))
  1240. methodInstance->mDeclModule = this;
  1241. };
  1242. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1243. {
  1244. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1245. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  1246. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  1247. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  1248. {
  1249. oldOnDemandCount++;
  1250. }
  1251. _HandleMethod(methodGroup.mDefault);
  1252. if (methodGroup.mMethodSpecializationMap != NULL)
  1253. for (auto& kv : *methodGroup.mMethodSpecializationMap)
  1254. _HandleMethod(kv.mValue);
  1255. }
  1256. }
  1257. if (typeInst->IsDeleting())
  1258. typeIdx--;
  1259. }
  1260. }
  1261. }
  1262. if (!mIsDeleting)
  1263. Init();
  1264. mOnDemandMethodCount += oldOnDemandCount;
  1265. VerifyOnDemandMethods();
  1266. }
  1267. void BfModule::StartExtension()
  1268. {
  1269. BF_ASSERT(!mIsModuleMutable);
  1270. BfLogSysM("Extension started of module %p\n", this);
  1271. mExtensionCount++;
  1272. if (mBfIRBuilder != NULL)
  1273. mPrevIRBuilders.push_back(mBfIRBuilder);
  1274. mBfIRBuilder = NULL;
  1275. mWantsIRIgnoreWrites = false;
  1276. mFuncReferences.Clear();
  1277. mClassVDataRefs.Clear();
  1278. mClassVDataExtRefs.Clear();
  1279. for (auto& kv : mTypeDataRefs)
  1280. kv.mValue = BfIRValue();
  1281. mDbgRawAllocDataRefs.Clear();
  1282. mStringCharPtrPool.Clear();
  1283. mStringObjectPool.Clear();
  1284. mStaticFieldRefs.Clear();
  1285. for (auto& kv : mInterfaceSlotRefs)
  1286. kv.mValue = BfIRValue();
  1287. for (auto& pairVal : mDeferredMethodCallData)
  1288. delete pairVal.mValue;
  1289. mDeferredMethodCallData.Clear();
  1290. mDeferredMethodIds.Clear();
  1291. DisownMethods();
  1292. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1293. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1294. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1295. Init(false);
  1296. if (!wasAwaitingInitFinish)
  1297. FinishInit();
  1298. mOnDemandMethodCount = prevOnDemandMethodCount;
  1299. }
  1300. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1301. {
  1302. auto hasObjectDebugFlags = mContext->mBfObjectType->mFieldInstances[0].mResolvedType->IsInteger();
  1303. BfIRValue vDataValue;
  1304. if (hasObjectDebugFlags)
  1305. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1306. else
  1307. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1308. typeValueParams.push_back(vDataValue);
  1309. if (hasObjectDebugFlags)
  1310. {
  1311. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1312. typeValueParams.push_back(GetDefaultValue(primType));
  1313. }
  1314. }
  1315. BfIRValue BfModule::GetConstValue(int64 val)
  1316. {
  1317. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1318. }
  1319. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1320. {
  1321. BfType* checkType = type;
  1322. if (type->IsTypedPrimitive())
  1323. {
  1324. checkType = type->GetUnderlyingType();
  1325. }
  1326. if (checkType->IsPrimitiveType())
  1327. {
  1328. auto primType = (BfPrimitiveType*)checkType;
  1329. if (checkType->IsFloat())
  1330. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1331. else
  1332. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1333. }
  1334. return BfIRValue();
  1335. }
  1336. BfIRValue BfModule::GetConstValue8(int val)
  1337. {
  1338. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1339. }
  1340. BfIRValue BfModule::GetConstValue32(int32 val)
  1341. {
  1342. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1343. }
  1344. BfIRValue BfModule::GetConstValue64(int64 val)
  1345. {
  1346. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1347. }
  1348. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1349. {
  1350. PopulateType(type, BfPopulateType_Data);
  1351. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1352. if (type->IsTypedPrimitive())
  1353. {
  1354. auto underlyingType = type->GetUnderlyingType();
  1355. if (underlyingType == NULL)
  1356. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1357. return GetDefaultValue(type->GetUnderlyingType());
  1358. }
  1359. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1360. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1361. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1362. if ((type->IsIntegral()) || (type->IsBoolean()))
  1363. {
  1364. auto primType = (BfPrimitiveType*)type;
  1365. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1366. }
  1367. if (type->IsFloat())
  1368. {
  1369. auto primType = (BfPrimitiveType*)type;
  1370. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1371. }
  1372. return mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(type));
  1373. }
  1374. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1375. {
  1376. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1377. if (type->mSize == 0)
  1378. return BfTypedValue(BfIRValue::sValueless, type);
  1379. else if (mBfIRBuilder != NULL)
  1380. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1381. else
  1382. return BfTypedValue(BfIRValue(BfIRValueFlags_Value, -1), type);
  1383. }
  1384. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1385. {
  1386. if (type->IsVar())
  1387. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1388. PopulateType(type, BfPopulateType_Data);
  1389. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1390. if (defaultValueKind == BfDefaultValueKind_Undef)
  1391. {
  1392. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(type)), type);
  1393. }
  1394. BfTypedValue typedValue;
  1395. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1396. {
  1397. if (type->IsRef())
  1398. {
  1399. BfRefType* refType = (BfRefType*)type;
  1400. BfType* underlyingType = refType->GetUnderlyingType();
  1401. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1402. }
  1403. else
  1404. {
  1405. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1406. }
  1407. if (!mBfIRBuilder->mIgnoreWrites)
  1408. {
  1409. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1410. GetConstValue(type->mSize), type->mAlign);
  1411. }
  1412. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1413. typedValue = LoadValue(typedValue);
  1414. return typedValue;
  1415. }
  1416. if ((type->IsRef()) && (!allowRef))
  1417. {
  1418. BfRefType* refType = (BfRefType*)type;
  1419. BfType* underlyingType = refType->GetUnderlyingType();
  1420. if (underlyingType->IsValuelessType())
  1421. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1422. else
  1423. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1424. }
  1425. else
  1426. {
  1427. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1428. }
  1429. return typedValue;
  1430. }
  1431. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1432. {
  1433. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1434. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1435. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1436. BfIRValue strConstant;
  1437. if (define)
  1438. {
  1439. strConstant = mBfIRBuilder->CreateConstString(str);
  1440. }
  1441. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1442. true, BfIRLinkageType_External,
  1443. strConstant, stringDataName);
  1444. if (define)
  1445. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1446. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1447. }
  1448. void BfModule::FixConstValueParams(BfTypeInstance* typeInst, SizedArrayImpl<BfIRValue>& valueParams, bool fillInPadding)
  1449. {
  1450. if ((!typeInst->mTypeDef->mIsCombinedPartial) && (!fillInPadding))
  1451. return;
  1452. int prevDataIdx = -1;
  1453. int usedDataIdx = 0;
  1454. int valueParamIdx = 0;
  1455. if (typeInst->mBaseType != NULL)
  1456. {
  1457. usedDataIdx++;
  1458. valueParamIdx++;
  1459. prevDataIdx++;
  1460. }
  1461. int startingParamsSize = (int)valueParams.mSize;
  1462. for (int fieldIdx = 0; fieldIdx < (int)typeInst->mFieldInstances.size(); fieldIdx++)
  1463. {
  1464. auto fieldInstance = &typeInst->mFieldInstances[fieldIdx];
  1465. if (fieldInstance->mDataIdx < 0)
  1466. continue;
  1467. BF_ASSERT(fieldInstance->mDataIdx > prevDataIdx);
  1468. if (fillInPadding)
  1469. {
  1470. for (int i = prevDataIdx + 1; i < fieldInstance->mDataIdx; i++)
  1471. valueParams.Insert(valueParamIdx++, mBfIRBuilder->CreateConstArrayZero(0));
  1472. }
  1473. valueParamIdx++;
  1474. prevDataIdx = fieldInstance->mDataIdx;
  1475. usedDataIdx++;
  1476. if (usedDataIdx <= valueParams.mSize)
  1477. continue;
  1478. valueParams.Add(GetDefaultValue(fieldInstance->mResolvedType));
  1479. }
  1480. }
  1481. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1482. {
  1483. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1484. mBfIRBuilder->PopulateType(stringTypeInst);
  1485. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1486. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1487. BfIRValue stringValData;
  1488. if (define)
  1489. {
  1490. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1491. mStringCharPtrPool[stringId] = stringCharsVal;
  1492. SizedArray<BfIRValue, 8> typeValueParams;
  1493. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1494. FixConstValueParams(stringTypeInst->mBaseType, typeValueParams);
  1495. auto objData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1496. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1497. typeValueParams.clear();
  1498. typeValueParams.push_back(objData);
  1499. if (lenByteCount == 4)
  1500. {
  1501. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1502. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1503. }
  1504. else
  1505. {
  1506. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1507. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1508. }
  1509. typeValueParams.push_back(stringCharsVal); // mPtr
  1510. FixConstValueParams(stringTypeInst, typeValueParams);
  1511. stringValData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1512. }
  1513. mBfIRBuilder->PopulateType(stringTypeInst);
  1514. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1515. mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full),
  1516. true,
  1517. BfIRLinkageType_External,
  1518. define ? stringValData : BfIRValue(),
  1519. stringObjName);
  1520. return stringValLiteral;
  1521. }
  1522. bool BfModule::HasStringId(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1523. {
  1524. if (constHolder == NULL)
  1525. constHolder = mBfIRBuilder;
  1526. auto constant = constHolder->GetConstant(constantStr);
  1527. if (constant == NULL)
  1528. return false;
  1529. while (constant->mConstType == BfConstType_BitCast)
  1530. {
  1531. auto constBitCast = (BfConstantBitCast*)constant;
  1532. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1533. }
  1534. if (constant->mTypeCode == BfTypeCode_StringId)
  1535. {
  1536. return true;
  1537. }
  1538. return false;
  1539. }
  1540. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1541. {
  1542. if (constHolder == NULL)
  1543. constHolder = mBfIRBuilder;
  1544. auto constant = constHolder->GetConstant(constantStr);
  1545. if (constant == NULL)
  1546. return -1;
  1547. if (constant->mTypeCode == BfTypeCode_StringId)
  1548. {
  1549. return constant->mInt32;
  1550. }
  1551. while (constant->mConstType == BfConstType_BitCast)
  1552. {
  1553. auto constBitCast = (BfConstantBitCast*)constant;
  1554. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1555. }
  1556. if (constant->mConstType == BfConstType_GEP32_2)
  1557. {
  1558. auto constGEP = (BfConstantGEP32_2*)constant;
  1559. constant = constHolder->GetConstantById(constGEP->mTarget);
  1560. }
  1561. if (constant->mConstType == BfConstType_GlobalVar)
  1562. {
  1563. auto constGV = (BfGlobalVar*)constant;
  1564. const char* strDataPrefix = "__bfStrData";
  1565. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1566. return atoi(constGV->mName + strlen(strDataPrefix));
  1567. const char* strObjPrefix = "__bfStrObj";
  1568. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1569. return atoi(constGV->mName + strlen(strObjPrefix));
  1570. }
  1571. return -1;
  1572. }
  1573. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1574. {
  1575. int strId = GetStringPoolIdx(constantStr, constHolder);
  1576. if (strId != -1)
  1577. {
  1578. auto& entry = mContext->mStringObjectIdMap[strId];
  1579. return &entry.mString;
  1580. }
  1581. return NULL;
  1582. }
  1583. CeDbgState* BfModule::GetCeDbgState()
  1584. {
  1585. if (!mIsComptimeModule)
  1586. return NULL;
  1587. if ((mCompiler->mCeMachine != NULL) && (mCompiler->mCeMachine->mDebugger != NULL))
  1588. return mCompiler->mCeMachine->mDebugger->mCurDbgState;
  1589. return NULL;
  1590. }
  1591. BfIRValue BfModule::GetStringCharPtr(int stringId, bool force)
  1592. {
  1593. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1594. {
  1595. mUnreifiedStringPoolRefs.Add(stringId);
  1596. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, stringId);
  1597. }
  1598. BfIRValue* irValue = NULL;
  1599. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1600. return *irValue;
  1601. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1602. if (!mStringObjectPool.ContainsKey(stringId))
  1603. mStringPoolRefs.Add(stringId);
  1604. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1605. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1606. *irValue = strCharPtrConst;
  1607. return strCharPtrConst;
  1608. }
  1609. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue, bool force)
  1610. {
  1611. if (strValue.IsConst())
  1612. {
  1613. int stringId = GetStringPoolIdx(strValue);
  1614. BF_ASSERT(stringId != -1);
  1615. return GetStringCharPtr(stringId, force);
  1616. }
  1617. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1618. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1619. return charPtr;
  1620. }
  1621. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str, bool force)
  1622. {
  1623. return GetStringCharPtr(GetStringObjectValue(str, force), force);
  1624. }
  1625. BfIRValue BfModule::GetStringObjectValue(int strId, bool define, bool force)
  1626. {
  1627. BfIRValue* objValue;
  1628. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1629. return *objValue;
  1630. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1631. return GetStringObjectValue(stringPoolEntry.mString, define, force);
  1632. }
  1633. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define, bool force)
  1634. {
  1635. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1636. mBfIRBuilder->PopulateType(stringType);
  1637. int strId = mContext->GetStringLiteralId(str);
  1638. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1639. {
  1640. auto refModule = this;
  1641. if ((this == mContext->mUnreifiedModule) && (mCurTypeInstance != NULL))
  1642. refModule = mCurTypeInstance->mModule;
  1643. refModule->mUnreifiedStringPoolRefs.Add(strId);
  1644. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, strId);
  1645. }
  1646. BfIRValue* irValuePtr = NULL;
  1647. if (mStringObjectPool.TryGetValue(strId, &irValuePtr))
  1648. return *irValuePtr;
  1649. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1650. if (!mStringCharPtrPool.ContainsKey(strId))
  1651. mStringPoolRefs.Add(strId);
  1652. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1653. mStringObjectPool[strId] = strObject;
  1654. mStringPoolRefs.Add(strId);
  1655. return strObject;
  1656. }
  1657. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1658. {
  1659. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1660. type,
  1661. true,
  1662. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1663. constant,
  1664. name.c_str());
  1665. return newConst;
  1666. }
  1667. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1668. {
  1669. auto curScope = mCurMethodState->mCurScope;
  1670. if (curScope->mLabelNode != NULL)
  1671. {
  1672. curScope->mLabelNode->ToString(curScope->mLabel);
  1673. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1674. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1675. auto autoComplete = mCompiler->GetAutoComplete();
  1676. if (autoComplete != NULL)
  1677. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1678. }
  1679. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1680. {
  1681. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1682. while (checkScope != NULL)
  1683. {
  1684. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1685. {
  1686. auto errorNode = Warn(0, StrFormat("Duplicate scope label '%s'", checkScope->mLabel.c_str()), curScope->mLabelNode);
  1687. if (errorNode != NULL)
  1688. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1689. break;
  1690. }
  1691. checkScope = checkScope->mPrevScope;
  1692. }
  1693. }
  1694. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1695. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1696. {
  1697. if (prevScope->mHadScopeValueRetain)
  1698. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1699. else
  1700. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1701. }
  1702. mCurMethodState->mBlockNestLevel++;
  1703. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1704. {
  1705. // DIScope could be NULL if we're in an unspecialized method (for example)
  1706. if (mCurMethodState->mCurScope->mDIScope)
  1707. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1708. }
  1709. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1710. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1711. mCurMethodState->mCurScope->mMixinState = mCurMethodState->mMixinState;
  1712. }
  1713. void BfModule::RestoreScoreState_LocalVariables(int localVarStart)
  1714. {
  1715. while (localVarStart < (int)mCurMethodState->mLocals.size())
  1716. {
  1717. auto localVar = mCurMethodState->mLocals.back();
  1718. LocalVariableDone(localVar, false);
  1719. mCurMethodState->mLocals.pop_back();
  1720. if (localVar->mShadowedLocal != NULL)
  1721. {
  1722. BfLocalVarEntry* localVarEntryPtr;
  1723. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1724. {
  1725. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1726. }
  1727. }
  1728. else
  1729. {
  1730. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1731. }
  1732. if (localVar->mIsBumpAlloc)
  1733. localVar->~BfLocalVariable();
  1734. else
  1735. delete localVar;
  1736. }
  1737. }
  1738. void BfModule::RestoreScopeState()
  1739. {
  1740. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1741. mCurMethodState->mBlockNestLevel--;
  1742. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1743. {
  1744. BfIRBlock afterEndBlock;
  1745. if (!mCurMethodState->mLeftBlockUncond)
  1746. {
  1747. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1748. mBfIRBuilder->CreateBr(afterEndBlock);
  1749. mBfIRBuilder->ClearDebugLocation_Last();
  1750. }
  1751. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1752. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1753. if (afterEndBlock)
  1754. {
  1755. mBfIRBuilder->AddBlock(afterEndBlock);
  1756. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1757. }
  1758. }
  1759. mCurMethodState->mCurScope->mDone = true;
  1760. if (!mCurMethodState->mLeftBlockUncond)
  1761. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1762. EmitDeferredCallProcessorInstances(mCurMethodState->mCurScope);
  1763. RestoreScoreState_LocalVariables(mCurMethodState->mCurScope->mLocalVarStart);
  1764. if (mCurMethodState->mCurScope->mValueScopeStart)
  1765. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1766. mCurMethodState->mCurScope = prevScopeData;
  1767. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1768. }
  1769. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1770. {
  1771. if (mBfIRBuilder->mIgnoreWrites)
  1772. return mBfIRBuilder->GetFakeVal();
  1773. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1774. mBfIRBuilder->PopulateType(type);
  1775. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1776. if (!mBfIRBuilder->mIgnoreWrites)
  1777. BF_ASSERT(!prevInsertBlock.IsFake());
  1778. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1779. BfIRValue allocaInst;
  1780. if (arraySize)
  1781. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1782. else
  1783. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1784. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1785. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1786. if (name != NULL)
  1787. mBfIRBuilder->SetName(allocaInst, name);
  1788. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1789. if ((addLifetime) && (WantsLifetimes()))
  1790. {
  1791. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1792. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1793. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1794. }
  1795. return allocaInst;
  1796. }
  1797. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1798. {
  1799. if (mBfIRBuilder->mIgnoreWrites)
  1800. return mBfIRBuilder->GetFakeVal();
  1801. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1802. mBfIRBuilder->PopulateType(typeInst);
  1803. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1804. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1805. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1806. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1807. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1808. if (name != NULL)
  1809. mBfIRBuilder->SetName(allocaInst, name);
  1810. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1811. if ((addLifetime) && (WantsLifetimes()))
  1812. {
  1813. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1814. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1815. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1816. }
  1817. return allocaInst;
  1818. }
  1819. BfDeferredCallEntry* BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape, BfIRBlock valBlock)
  1820. {
  1821. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1822. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1823. /*if (mCurMethodState->mInHeadScope)
  1824. isScopeAlloc = true;*/
  1825. if (scopeData == NULL)
  1826. return NULL;
  1827. auto checkBaseType = val.mType->ToTypeInstance();
  1828. if ((checkBaseType != NULL) && (checkBaseType->IsObject()) && (!arraySize))
  1829. {
  1830. bool hadDtorCall = false;
  1831. while (checkBaseType != NULL)
  1832. {
  1833. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  1834. if (dtorMethodDef != NULL)
  1835. {
  1836. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  1837. if (dtorMethodInstance)
  1838. {
  1839. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1840. BfIRValue useVal = val.mValue;
  1841. BfIRBlock prevBlock = mBfIRBuilder->GetInsertBlock();
  1842. if (valBlock)
  1843. mBfIRBuilder->SetInsertPoint(valBlock);
  1844. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1845. if (!useVal.IsConst())
  1846. mBfIRBuilder->ClearDebugLocation(useVal);
  1847. if (valBlock)
  1848. mBfIRBuilder->SetInsertPoint(prevBlock);
  1849. if (isDynAlloc)
  1850. {
  1851. //
  1852. }
  1853. else if (condAlloca)
  1854. {
  1855. BF_ASSERT(!IsTargetingBeefBackend());
  1856. BF_ASSERT(!isDynAlloc);
  1857. auto valPtr = CreateAlloca(checkBaseType);
  1858. mBfIRBuilder->ClearDebugLocation_Last();
  1859. mBfIRBuilder->CreateAlignedStore(useVal, valPtr, checkBaseType->mAlign);
  1860. mBfIRBuilder->ClearDebugLocation_Last();
  1861. useVal = valPtr;
  1862. }
  1863. SizedArray<BfIRValue, 1> llvmArgs;
  1864. llvmArgs.push_back(useVal);
  1865. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1866. if (deferredCall != NULL)
  1867. {
  1868. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1869. if (condAlloca)
  1870. deferredCall->mArgsNeedLoad = true;
  1871. }
  1872. hadDtorCall = true;
  1873. break;
  1874. }
  1875. }
  1876. checkBaseType = checkBaseType->mBaseType;
  1877. }
  1878. return NULL;
  1879. }
  1880. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1881. if (mayEscape)
  1882. {
  1883. if ((!IsOptimized()) && (!mIsComptimeModule) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1884. {
  1885. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1886. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1887. if (!isDyn)
  1888. {
  1889. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1890. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1891. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1892. if (!dtorMethodInstance.mMethodInstance)
  1893. {
  1894. Fail(StrFormat("Unable to find %s", methodName));
  1895. }
  1896. else
  1897. {
  1898. SizedArray<BfIRValue, 1> llvmArgs;
  1899. if (IsTargetingBeefBackend())
  1900. {
  1901. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1902. //mBfIRBuilder->ClearDebugLocation_Last();
  1903. }
  1904. else
  1905. llvmArgs.push_back(val.mValue);
  1906. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1907. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1908. if (arraySize)
  1909. llvmArgs.push_back(arraySize);
  1910. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1911. }
  1912. }
  1913. else
  1914. {
  1915. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1916. {
  1917. BfIRValue clearSize = arraySize;
  1918. if (val.mType->GetStride() > 1)
  1919. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1920. const char* methodName = "SetDeletedX";
  1921. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1922. BF_ASSERT(dtorMethodInstance);
  1923. if (!dtorMethodInstance)
  1924. {
  1925. Fail(StrFormat("Unable to find %s", methodName));
  1926. }
  1927. else
  1928. {
  1929. SizedArray<BfIRValue, 1> llvmArgs;
  1930. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1931. //mBfIRBuilder->ClearDebugLocation_Last();
  1932. llvmArgs.push_back(clearSize);
  1933. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1934. }
  1935. }
  1936. else
  1937. {
  1938. intptr clearSize = val.mType->mSize;
  1939. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1940. if (constant != NULL)
  1941. clearSize = (intptr)(clearSize * constant->mInt64);
  1942. const char* funcName = "SetDeleted1";
  1943. if (clearSize >= 16)
  1944. funcName = "SetDeleted16";
  1945. else if (clearSize >= 8)
  1946. funcName = "SetDeleted8";
  1947. else if (clearSize >= 4)
  1948. funcName = "SetDeleted4";
  1949. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1950. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1951. if (!dtorMethodInstance)
  1952. {
  1953. Fail(StrFormat("Unable to find %s", funcName));
  1954. }
  1955. else
  1956. {
  1957. SizedArray<BfIRValue, 1> llvmArgs;
  1958. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1959. //mBfIRBuilder->ClearDebugLocation_Last();
  1960. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1961. }
  1962. }
  1963. }
  1964. }
  1965. }
  1966. return NULL;
  1967. }
  1968. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1969. {
  1970. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1971. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1972. return false;
  1973. auto checkTypeInstance = startTypeInstance;
  1974. while (checkTypeInstance != NULL)
  1975. {
  1976. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1977. {
  1978. if (fieldInstance.mMergedDataIdx != -1)
  1979. {
  1980. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1981. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1982. {
  1983. // For fields added in extensions, we automatically initialize those if necessary
  1984. auto fieldDef = fieldInstance.GetFieldDef();
  1985. if (!fieldDef->mDeclaringType->IsExtension())
  1986. return false;
  1987. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  1988. {
  1989. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1990. mBfIRBuilder->SaveDebugLocation();
  1991. if (localVar->IsParam())
  1992. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1993. else
  1994. {
  1995. BF_ASSERT(localVar->mDeclBlock);
  1996. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1997. }
  1998. mBfIRBuilder->ClearDebugLocation();
  1999. BfIRValue curVal;
  2000. if (localVar->mIsThis)
  2001. curVal = mBfIRBuilder->GetArgument(0);
  2002. else
  2003. curVal = localVar->mAddr;
  2004. auto subTypeInstance = startTypeInstance;
  2005. while (subTypeInstance != checkTypeInstance)
  2006. {
  2007. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  2008. subTypeInstance = subTypeInstance->mBaseType;
  2009. }
  2010. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  2011. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  2012. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  2013. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  2014. mBfIRBuilder->RestoreDebugLocation();
  2015. }
  2016. localVar->mUnassignedFieldFlags &= ~checkMask;
  2017. if (localVar->mUnassignedFieldFlags == 0)
  2018. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2019. }
  2020. }
  2021. }
  2022. checkTypeInstance = checkTypeInstance->mBaseType;
  2023. }
  2024. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  2025. }
  2026. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  2027. {
  2028. BfAstNode* localNameNode = localVar->mNameNode;
  2029. if ((localVar->mIsThis) && (mCurMethodInstance != NULL))
  2030. {
  2031. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  2032. }
  2033. if (localNameNode != NULL)
  2034. {
  2035. bool isOut = false;
  2036. if (localVar->mResolvedType->IsRef())
  2037. {
  2038. auto refType = (BfRefType*)localVar->mResolvedType;
  2039. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  2040. }
  2041. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  2042. {
  2043. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  2044. TryLocalVariableInit(localVar);
  2045. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  2046. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  2047. // We may have init blocks that we aren't processing here...
  2048. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  2049. deferFullAnalysis = true;
  2050. //bool deferFullAnalysis = true;
  2051. bool deferUsageWarning = deferFullAnalysis && (mCompiler->IsAutocomplete()) &&
  2052. (mCompiler->mResolvePassData->mAutoComplete->mResolveType != BfResolveType_GetFixits);
  2053. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  2054. (!localVar->mIsImplicitParam))
  2055. {
  2056. if (deferUsageWarning)
  2057. {
  2058. // Ignore
  2059. }
  2060. else if (localVar->mIsThis)
  2061. {
  2062. bool foundFields = false;
  2063. auto checkTypeInstance = mCurTypeInstance;
  2064. while (checkTypeInstance != NULL)
  2065. {
  2066. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  2067. {
  2068. if (fieldInstance.mMergedDataIdx == -1)
  2069. continue;
  2070. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  2071. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  2072. {
  2073. auto fieldDef = fieldInstance.GetFieldDef();
  2074. if (mCurMethodInstance->mMethodDef->mDeclaringType->mIsPartial)
  2075. {
  2076. if (mCurMethodInstance->mMethodDef->mDeclaringType != fieldInstance.GetFieldDef()->mDeclaringType)
  2077. {
  2078. // This extension is only responsible for its own fields
  2079. foundFields = true;
  2080. continue;
  2081. }
  2082. if (fieldDef->GetInitializer() != NULL)
  2083. {
  2084. // This initializer was handled in CtorNoBody
  2085. foundFields = true;
  2086. continue;
  2087. }
  2088. }
  2089. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  2090. {
  2091. String propName;
  2092. if (propertyDeclaration->mNameNode != NULL)
  2093. propertyDeclaration->mNameNode->ToString(propName);
  2094. if (checkTypeInstance == mCurTypeInstance)
  2095. {
  2096. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  2097. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2098. }
  2099. else
  2100. {
  2101. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  2102. TypeToString(checkTypeInstance).c_str(),
  2103. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2104. }
  2105. }
  2106. else
  2107. {
  2108. if (checkTypeInstance == mCurTypeInstance)
  2109. {
  2110. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  2111. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2112. }
  2113. else
  2114. {
  2115. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  2116. TypeToString(checkTypeInstance).c_str(),
  2117. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2118. }
  2119. }
  2120. foundFields = true;
  2121. }
  2122. }
  2123. checkTypeInstance = checkTypeInstance->mBaseType;
  2124. }
  2125. if (!foundFields)
  2126. {
  2127. if (mCurTypeInstance->mInstSize > 0)
  2128. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  2129. }
  2130. }
  2131. else if (localVar->IsParam())
  2132. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  2133. else if (!deferUsageWarning)
  2134. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2135. }
  2136. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  2137. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2138. }
  2139. }
  2140. }
  2141. void BfModule::CreateRetValLocal()
  2142. {
  2143. if (mCurMethodState->mRetVal)
  2144. {
  2145. BfLocalVariable* localDef = new BfLocalVariable();
  2146. localDef->mName = "return";
  2147. localDef->mResolvedType = mCurMethodState->mRetVal.mType;
  2148. localDef->mAddr = mCurMethodState->mRetVal.mValue;
  2149. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2150. AddLocalVariableDef(localDef);
  2151. }
  2152. else if (mCurMethodState->mRetValAddr)
  2153. {
  2154. BfLocalVariable* localDef = new BfLocalVariable();
  2155. localDef->mName = "return";
  2156. localDef->mResolvedType = CreateRefType(mCurMethodInstance->mReturnType);
  2157. localDef->mAddr = mCurMethodState->mRetValAddr;
  2158. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2159. AddLocalVariableDef(localDef);
  2160. }
  2161. }
  2162. void BfModule::MarkDynStack(BfScopeData* scopeData)
  2163. {
  2164. auto checkScope = mCurMethodState->mCurScope;
  2165. while (true)
  2166. {
  2167. if (checkScope == scopeData)
  2168. break;
  2169. checkScope->mHadOuterDynStack = true;
  2170. checkScope = checkScope->mPrevScope;
  2171. }
  2172. }
  2173. void BfModule::SaveStackState(BfScopeData* scopeData)
  2174. {
  2175. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  2176. // scopes within scopeData restore the stack
  2177. auto checkScope = mCurMethodState->mCurScope;
  2178. while (true)
  2179. {
  2180. if (checkScope == scopeData)
  2181. {
  2182. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  2183. {
  2184. if (mBfIRBuilder->mHasDebugInfo)
  2185. mBfIRBuilder->SaveDebugLocation();
  2186. auto prevPos = mBfIRBuilder->GetInsertBlock();
  2187. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  2188. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  2189. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  2190. mBfIRBuilder->SetInsertPoint(prevPos);
  2191. if (mBfIRBuilder->mHasDebugInfo)
  2192. mBfIRBuilder->RestoreDebugLocation();
  2193. }
  2194. break;
  2195. }
  2196. if (checkScope->mSavedStack)
  2197. {
  2198. for (auto usage : checkScope->mSavedStackUses)
  2199. mBfIRBuilder->EraseInstFromParent(usage);
  2200. checkScope->mSavedStackUses.Clear();
  2201. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  2202. checkScope->mSavedStack = BfIRValue();
  2203. }
  2204. checkScope = checkScope->mPrevScope;
  2205. }
  2206. }
  2207. BfIRValue BfModule::ValueScopeStart()
  2208. {
  2209. if (IsTargetingBeefBackend())
  2210. return mBfIRBuilder->CreateValueScopeStart();
  2211. return BfIRValue();
  2212. }
  2213. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  2214. {
  2215. if (valueScopeStart)
  2216. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  2217. }
  2218. BfProjectSet* BfModule::GetVisibleProjectSet()
  2219. {
  2220. if (mCurMethodState == NULL)
  2221. return NULL;
  2222. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  2223. {
  2224. HashSet<BfType*> seenTypes;
  2225. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  2226. {
  2227. if (mCurMethodState->mVisibleProjectSet.Add(project))
  2228. {
  2229. for (auto dep : project->mDependencies)
  2230. _AddProject(dep);
  2231. }
  2232. };
  2233. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  2234. {
  2235. auto typeInstance = type->ToTypeInstance();
  2236. if (typeInstance == NULL)
  2237. {
  2238. if (type->IsSizedArray())
  2239. _AddType(type->GetUnderlyingType());
  2240. return;
  2241. }
  2242. if (typeInstance->IsTuple())
  2243. {
  2244. for (auto& fieldInst : typeInstance->mFieldInstances)
  2245. {
  2246. if (fieldInst.mDataIdx != -1)
  2247. _AddType(fieldInst.mResolvedType);
  2248. }
  2249. }
  2250. _AddProject(typeInstance->mTypeDef->mProject);
  2251. if (typeInstance->mGenericTypeInfo == NULL)
  2252. return;
  2253. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2254. {
  2255. if (seenTypes.Add(type))
  2256. _AddType(type);
  2257. }
  2258. };
  2259. if (mCurTypeInstance != NULL)
  2260. _AddType(mCurTypeInstance);
  2261. auto methodState = mCurMethodState;
  2262. while (methodState != NULL)
  2263. {
  2264. if (methodState->mMethodInstance != NULL)
  2265. {
  2266. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  2267. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  2268. {
  2269. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2270. _AddType(type);
  2271. }
  2272. }
  2273. methodState = methodState->mPrevMethodState;
  2274. }
  2275. }
  2276. return &mCurMethodState->mVisibleProjectSet;
  2277. }
  2278. bool BfModule::IsProjectVisible(BfProject* project)
  2279. {
  2280. auto visibleProjectSet = GetVisibleProjectSet();
  2281. if (visibleProjectSet != NULL)
  2282. return visibleProjectSet->Contains(project);
  2283. auto activeTypeDef = GetActiveTypeDef();
  2284. if (activeTypeDef != NULL)
  2285. {
  2286. if (activeTypeDef->mProject == project)
  2287. return true;
  2288. return activeTypeDef->mProject->HasDependency(project);
  2289. }
  2290. return false;
  2291. }
  2292. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2293. {
  2294. auto bfParser = astNode->GetSourceData()->ToParserData();
  2295. if (bfParser == NULL)
  2296. return NULL;
  2297. BfFileInstance** fileInstancePtr = NULL;
  2298. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2299. {
  2300. return *fileInstancePtr;
  2301. }
  2302. else
  2303. {
  2304. // It's possible two parsers have the same file name (ie: mNextRevision)
  2305. BfFileInstance** namedFileInstancePtr = NULL;
  2306. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2307. {
  2308. auto bfFileInstance = *namedFileInstancePtr;
  2309. *fileInstancePtr = bfFileInstance;
  2310. return bfFileInstance;
  2311. }
  2312. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2313. auto bfFileInstance = new BfFileInstance();
  2314. *fileInstancePtr = bfFileInstance;
  2315. *namedFileInstancePtr = bfFileInstance;
  2316. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2317. bfFileInstance->mParser = bfParser;
  2318. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2319. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasLineInfo()))
  2320. {
  2321. String fileName = bfParser->mFileName;
  2322. for (int i = 0; i < (int)fileName.length(); i++)
  2323. {
  2324. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2325. fileName[i] = DIR_SEP_CHAR;
  2326. }
  2327. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, BF_MAX(slashPos, 0)), bfParser->mMD5Hash);
  2328. }
  2329. return bfFileInstance;
  2330. }
  2331. }
  2332. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2333. {
  2334. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2335. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2336. return;
  2337. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2338. if (astNode == NULL)
  2339. return;
  2340. auto bfParser = astNode->GetSourceData()->ToParserData();
  2341. if (bfParser == NULL)
  2342. return;
  2343. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2344. {
  2345. if (mCurFilePosition.mFileInstance != NULL)
  2346. {
  2347. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2348. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2349. }
  2350. auto bfFileInstance = GetFileFromNode(astNode);
  2351. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2352. {
  2353. mCurFilePosition = bfFileInstance->mPrevPosition;
  2354. }
  2355. else
  2356. {
  2357. mCurFilePosition.mFileInstance = bfFileInstance;
  2358. mCurFilePosition.mCurLine = 0;
  2359. mCurFilePosition.mCurColumn = 0;
  2360. mCurFilePosition.mCurSrcPos = 0;
  2361. }
  2362. }
  2363. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2364. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2365. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2366. if (jumpEntry->mCharIdx > srcPos)
  2367. jumpEntry--;
  2368. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2369. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2370. mCurFilePosition.mCurColumn = 0;
  2371. while (mCurFilePosition.mCurSrcPos < srcPos)
  2372. {
  2373. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2374. {
  2375. mCurFilePosition.mCurLine++;
  2376. mCurFilePosition.mCurColumn = 0;
  2377. }
  2378. else
  2379. {
  2380. mCurFilePosition.mCurColumn++;
  2381. }
  2382. mCurFilePosition.mCurSrcPos++;
  2383. }
  2384. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2385. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasLineInfo()) && (mCurMethodState != NULL))
  2386. {
  2387. int column = mCurFilePosition.mCurColumn + 1;
  2388. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2389. {
  2390. // Set to illegal position
  2391. column = 0;
  2392. }
  2393. if (mSetIllegalSrcPosition)
  2394. column = 0;
  2395. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2396. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2397. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2398. {
  2399. // This is from a different scope...
  2400. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2401. {
  2402. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2403. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2404. }
  2405. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2406. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2407. }
  2408. else
  2409. {
  2410. if (mCurMethodState->mCurScope->mAltDIFile)
  2411. {
  2412. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2413. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2414. }
  2415. }
  2416. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2417. if (mCurMethodState->mCrossingMixin)
  2418. inlineAt = BfIRMDNode();
  2419. if ((!useDIScope) && (mIsComptimeModule))
  2420. useDIScope = wantDIFile;
  2421. if (!useDIScope)
  2422. mBfIRBuilder->ClearDebugLocation();
  2423. else
  2424. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2425. if ((flags & BfSrcPosFlag_Expression) == 0)
  2426. mBfIRBuilder->CreateStatementStart();
  2427. }
  2428. }
  2429. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2430. {
  2431. // We've turned off expr src pos (for now?)
  2432. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2433. }
  2434. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2435. {
  2436. if (mCompiler->mBfObjectTypeDef != NULL)
  2437. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2438. SetIllegalSrcPos();
  2439. }
  2440. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2441. {
  2442. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2443. {
  2444. auto curScope = mCurMethodState->mCurScope->mDIScope;
  2445. if (curScope)
  2446. {
  2447. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2448. {
  2449. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2450. mBfIRBuilder->SetCurrentDebugLocation(0, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2451. }
  2452. else
  2453. {
  2454. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2455. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2456. }
  2457. }
  2458. if ((flags & BfSrcPosFlag_Expression) == 0)
  2459. mBfIRBuilder->CreateStatementStart();
  2460. }
  2461. }
  2462. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2463. {
  2464. // We've turned off expr src pos (for now?)
  2465. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2466. }
  2467. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2468. {
  2469. if ((protection == BfProtection_Public) ||
  2470. (((protection == BfProtection_Protected) || (protection == BfProtection_ProtectedInternal)) && (allowProtected)) ||
  2471. ((protection == BfProtection_Private) && (allowPrivate)))
  2472. return true;
  2473. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2474. {
  2475. mAttributeState->mUsed = true;
  2476. return true;
  2477. }
  2478. if (((protection == BfProtection_Internal) || (protection == BfProtection_ProtectedInternal)) && (checkType != NULL))
  2479. {
  2480. if (CheckInternalProtection(checkType))
  2481. return true;
  2482. }
  2483. return false;
  2484. }
  2485. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2486. {
  2487. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2488. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2489. {
  2490. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2491. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2492. }
  2493. allowProtected = allowPrivate;
  2494. }
  2495. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2496. {
  2497. if ((memberOwner != NULL) && (mCurMethodState != NULL) && (mCurMethodState->mPrivateTypeInstance == memberOwner))
  2498. return true;
  2499. if (memberProtection == BfProtection_Hidden)
  2500. return false;
  2501. if (memberProtection == BfProtection_Public)
  2502. return true;
  2503. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2504. {
  2505. BfTypeInstance* curCheckType = mCurTypeInstance;
  2506. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2507. {
  2508. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2509. curCheckType = mixinOwner;
  2510. }
  2511. bool allowPrivate = (curCheckType != NULL) && (memberOwner->IsInstanceOf(curCheckType->mTypeDef));
  2512. if (curCheckType != NULL)
  2513. {
  2514. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2515. if (memberOwner->mTypeDef->IsGlobalsContainer())
  2516. allowPrivate |= curCheckType->mTypeDef->mNamespace == memberOwner->mTypeDef->mNamespace;
  2517. }
  2518. if (allowPrivate)
  2519. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2520. else
  2521. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2522. }
  2523. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2524. return true;
  2525. if ((memberProtection == BfProtection_Protected) || (memberProtection == BfProtection_ProtectedInternal))
  2526. {
  2527. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2528. {
  2529. bool allowProtected = false;
  2530. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2531. auto curCheckType = mCurTypeInstance;
  2532. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2533. {
  2534. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2535. curCheckType = mixinOwner;
  2536. }
  2537. if ((flags & BfProtectionCheckFlag_InstanceLookup) != 0)
  2538. {
  2539. auto lookupCheckType = lookupStartType;
  2540. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2541. {
  2542. if (lookupCheckType == curCheckType)
  2543. {
  2544. allowProtected = true;
  2545. break;
  2546. }
  2547. if (lookupCheckType == memberOwner)
  2548. break;
  2549. lookupCheckType = lookupCheckType->mBaseType;
  2550. if (lookupCheckType == NULL)
  2551. break;
  2552. }
  2553. }
  2554. else
  2555. {
  2556. auto lookupCheckType = curCheckType;
  2557. while (lookupCheckType->mInheritDepth >= memberOwner->mInheritDepth)
  2558. {
  2559. if (lookupCheckType == memberOwner)
  2560. {
  2561. allowProtected = true;
  2562. break;
  2563. }
  2564. lookupCheckType = lookupCheckType->mBaseType;
  2565. if (lookupCheckType == NULL)
  2566. break;
  2567. }
  2568. }
  2569. if (!allowProtected)
  2570. {
  2571. // It's possible our outer type is derived from 'memberOwner'
  2572. while (curCheckType->mTypeDef->mNestDepth > 0)
  2573. {
  2574. curCheckType = GetOuterType(curCheckType);
  2575. if (curCheckType == NULL)
  2576. break;
  2577. auto lookupCheckType = lookupStartType;
  2578. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2579. {
  2580. if (lookupCheckType == curCheckType)
  2581. {
  2582. allowProtected = true;
  2583. break;
  2584. }
  2585. if (lookupCheckType == memberOwner)
  2586. break;
  2587. lookupCheckType = lookupCheckType->mBaseType;
  2588. if (lookupCheckType == NULL)
  2589. break;
  2590. }
  2591. }
  2592. }
  2593. if (allowProtected)
  2594. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2595. else
  2596. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2597. }
  2598. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2599. return true;
  2600. }
  2601. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2602. {
  2603. mAttributeState->mUsed = true;
  2604. return true;
  2605. }
  2606. if (((memberProtection == BfProtection_Internal) || (memberProtection == BfProtection_ProtectedInternal)) && (memberOwner != NULL))
  2607. {
  2608. if (CheckInternalProtection(memberOwner->mTypeDef))
  2609. return true;
  2610. }
  2611. return false;
  2612. }
  2613. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2614. {
  2615. if (mCompiler->mResolvePassData != NULL)
  2616. {
  2617. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2618. sourceClassifier->SetElementType(astNode, elementType);
  2619. }
  2620. }
  2621. bool BfModule::PreFail()
  2622. {
  2623. if (!mIgnoreErrors)
  2624. return true;
  2625. SetFail();
  2626. return false;
  2627. }
  2628. void BfModule::SetFail()
  2629. {
  2630. if (mIgnoreErrors)
  2631. {
  2632. if (mAttributeState != NULL)
  2633. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2634. }
  2635. }
  2636. void BfModule::VerifyOnDemandMethods()
  2637. {
  2638. #ifdef _DEBUG
  2639. // if (mParentModule != NULL)
  2640. // {
  2641. // BF_ASSERT(mOnDemandMethodCount == 0);
  2642. // mParentModule->VerifyOnDemandMethods();
  2643. // return;
  2644. // }
  2645. //
  2646. // int onDemandCount = 0;
  2647. // for (auto type : mOwnedTypeInstances)
  2648. // {
  2649. // auto typeInst = type->ToTypeInstance();
  2650. // for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  2651. // {
  2652. // if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  2653. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  2654. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  2655. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  2656. // onDemandCount++;
  2657. // }
  2658. // }
  2659. //
  2660. // BF_ASSERT(mOnDemandMethodCount == onDemandCount);
  2661. #endif
  2662. }
  2663. bool BfModule::IsSkippingExtraResolveChecks()
  2664. {
  2665. if (mIsComptimeModule)
  2666. return false;
  2667. return mCompiler->IsSkippingExtraResolveChecks();
  2668. }
  2669. bool BfModule::AddErrorContext(StringImpl& errorString, BfAstNode* refNode, BfWhileSpecializingFlags& isWhileSpecializing, bool isWarning)
  2670. {
  2671. bool isWhileSpecializingMethod = false;
  2672. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2673. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2674. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2675. errorString += StrFormat("\n while generating append size calculating method");
  2676. else if (refNode == NULL)
  2677. {
  2678. if (mCurTypeInstance != NULL)
  2679. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2680. else if (mProject != NULL)
  2681. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2682. }
  2683. if (mCurTypeInstance != NULL)
  2684. {
  2685. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2686. {
  2687. // Propogate the fail all the way to the main method (assuming we're in a local method or lambda)
  2688. if (isWarning)
  2689. methodInstance->mHasWarning = true;
  2690. else
  2691. methodInstance->mHasFailed = true;
  2692. if (!methodInstance->mHasStartedDeclaration)
  2693. StartMethodDeclaration(methodInstance, NULL);
  2694. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2695. if (isSpecializedMethod)
  2696. {
  2697. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2698. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2699. if (unspecializedMethod == methodInstance)
  2700. {
  2701. // This is a local method inside a generic method
  2702. BF_ASSERT(methodInstance->mMethodDef->mIsLocalMethod);
  2703. }
  2704. else
  2705. {
  2706. if (isWarning)
  2707. {
  2708. if (unspecializedMethod->mHasWarning)
  2709. return false; // At least SOME error has already been reported
  2710. }
  2711. else
  2712. {
  2713. if (unspecializedMethod->mHasFailed)
  2714. return false; // At least SOME error has already been reported
  2715. }
  2716. }
  2717. }
  2718. if (isSpecializedMethod)
  2719. {
  2720. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2721. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2722. isWhileSpecializingMethod = true;
  2723. }
  2724. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2725. {
  2726. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2727. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2728. isWhileSpecializingMethod = true;
  2729. }
  2730. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2731. {
  2732. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2733. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2734. }
  2735. return true;
  2736. };
  2737. bool hadMethodInstance = false;
  2738. if (mCurMethodState != NULL)
  2739. {
  2740. auto checkMethodState = mCurMethodState;
  2741. while (checkMethodState != NULL)
  2742. {
  2743. auto methodInstance = checkMethodState->mMethodInstance;
  2744. if (methodInstance == NULL)
  2745. {
  2746. checkMethodState = checkMethodState->mPrevMethodState;
  2747. continue;
  2748. }
  2749. hadMethodInstance = true;
  2750. if (!_CheckMethodInstance(methodInstance))
  2751. return false;
  2752. checkMethodState = checkMethodState->mPrevMethodState;
  2753. }
  2754. }
  2755. if ((!hadMethodInstance) && (mCurMethodInstance != NULL))
  2756. {
  2757. if (!_CheckMethodInstance(mCurMethodInstance))
  2758. return false;
  2759. }
  2760. }
  2761. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2762. {
  2763. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2764. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2765. }
  2766. return true;
  2767. }
  2768. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent, bool deferError)
  2769. {
  2770. BP_ZONE("BfModule::Fail");
  2771. if (mIgnoreErrors)
  2772. {
  2773. mHadIgnoredError = true;
  2774. if (mAttributeState != NULL)
  2775. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2776. return NULL;
  2777. }
  2778. if (!mReportErrors)
  2779. {
  2780. mCompiler->mPassInstance->SilentFail();
  2781. return NULL;
  2782. }
  2783. if (refNode != NULL)
  2784. refNode = BfNodeToNonTemporary(refNode);
  2785. //BF_ASSERT(refNode != NULL);
  2786. if (mIsComptimeModule)
  2787. {
  2788. if (auto ceDbgState = GetCeDbgState())
  2789. {
  2790. // Follow normal fail path
  2791. }
  2792. else
  2793. {
  2794. mHadBuildError = true;
  2795. if ((mCompiler->mCeMachine->mCurContext != NULL) && (mCompiler->mCeMachine->mCurContext->mCurCallSource != NULL) &&
  2796. (mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode != NULL))
  2797. {
  2798. BfError* bfError = mCompiler->mPassInstance->Fail("Comptime method generation had errors",
  2799. mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode);
  2800. if (bfError != NULL)
  2801. mCompiler->mPassInstance->MoreInfo(error, refNode);
  2802. return bfError;
  2803. }
  2804. return NULL;
  2805. }
  2806. }
  2807. if ((mCurMethodState != NULL) && (mCurMethodState->mConstResolveState != NULL) && (mCurMethodState->mConstResolveState->mInCalcAppend))
  2808. {
  2809. mCurMethodState->mConstResolveState->mFailed = true;
  2810. return NULL;
  2811. }
  2812. if (mCurMethodInstance != NULL)
  2813. mCurMethodInstance->mHasFailed = true;
  2814. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2815. return NULL;
  2816. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2817. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2818. if (!mHadBuildError)
  2819. mHadBuildError = true;
  2820. if (mParentModule != NULL)
  2821. mParentModule->mHadBuildError = true;
  2822. if (mCurTypeInstance != NULL)
  2823. AddFailType(mCurTypeInstance);
  2824. BfLogSysM("BfModule::Fail module %p type %p %s @ %s\n", this, mCurTypeInstance, error.c_str(), (refNode != NULL) ? refNode->LocationToString().c_str() : "???");
  2825. String errorString = error;
  2826. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2827. if (!AddErrorContext(errorString, refNode, isWhileSpecializing, false))
  2828. return NULL;
  2829. BfError* bfError = NULL;
  2830. if (isWhileSpecializing)
  2831. deferError = true;
  2832. if (!mHadBuildError)
  2833. mHadBuildError = true;
  2834. // Check mixins
  2835. {
  2836. auto checkMethodState = mCurMethodState;
  2837. while (checkMethodState != NULL)
  2838. {
  2839. auto rootMixinState = checkMethodState->GetRootMixinState();
  2840. if (rootMixinState != NULL)
  2841. {
  2842. String mixinErr = StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str());
  2843. if (deferError)
  2844. bfError = mCompiler->mPassInstance->DeferFail(mixinErr, rootMixinState->mSource);
  2845. else
  2846. bfError = mCompiler->mPassInstance->Fail(mixinErr, rootMixinState->mSource);
  2847. if (bfError == NULL)
  2848. return NULL;
  2849. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2850. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2851. auto mixinState = checkMethodState->mMixinState;
  2852. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2853. {
  2854. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2855. mixinState = mixinState->mPrevMixinState;
  2856. }
  2857. return bfError;
  2858. }
  2859. checkMethodState = checkMethodState->mPrevMethodState;
  2860. }
  2861. }
  2862. if (deferError)
  2863. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2864. else if (refNode == NULL)
  2865. bfError = mCompiler->mPassInstance->Fail(errorString);
  2866. else
  2867. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2868. if (bfError != NULL)
  2869. {
  2870. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2871. bfError->mProject = mProject;
  2872. bfError->mIsPersistent = isPersistent;
  2873. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2874. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2875. else if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2876. mCompiler->mPassInstance->MoreInfo("Error in emitted code", mCurMethodState->mEmitRefNode);
  2877. }
  2878. return bfError;
  2879. }
  2880. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2881. {
  2882. if (mHadBuildError)
  2883. return NULL;
  2884. return Fail(error, refNode);
  2885. }
  2886. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2887. {
  2888. if (mIgnoreErrors)
  2889. return NULL;
  2890. if (refNode != NULL)
  2891. refNode = BfNodeToNonTemporary(refNode);
  2892. mHadBuildError = true;
  2893. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2894. if (bfError != NULL)
  2895. bfError->mProject = mProject;
  2896. return bfError;
  2897. }
  2898. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent, bool showInSpecialized)
  2899. {
  2900. if (mIgnoreErrors || mIgnoreWarnings)
  2901. return NULL;
  2902. if (!mReportErrors)
  2903. {
  2904. mCompiler->mPassInstance->SilentFail();
  2905. return NULL;
  2906. }
  2907. BfAstNode* unwarnNode = refNode;
  2908. //
  2909. {
  2910. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2911. while (parentNodeEntry != NULL)
  2912. {
  2913. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2914. break;
  2915. unwarnNode = parentNodeEntry->mNode;
  2916. parentNodeEntry = parentNodeEntry->mPrev;
  2917. }
  2918. }
  2919. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2920. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2921. {
  2922. return NULL;
  2923. }
  2924. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2925. if (mCurMethodInstance != NULL)
  2926. {
  2927. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2928. {
  2929. if (!showInSpecialized)
  2930. return NULL;
  2931. }
  2932. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2933. return NULL; // No ctorCalcAppend warnings
  2934. }
  2935. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2936. {
  2937. if (!showInSpecialized)
  2938. return NULL;
  2939. }
  2940. if (refNode != NULL)
  2941. refNode = BfNodeToNonTemporary(refNode);
  2942. String warningString = warning;
  2943. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2944. if (!AddErrorContext(warningString, refNode, isWhileSpecializing, true))
  2945. return NULL;
  2946. bool deferWarning = isWhileSpecializing != BfWhileSpecializingFlag_None;
  2947. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2948. {
  2949. // We used to bubble up warnings into the mixin injection site, BUT
  2950. // we are now assuming any relevant warnings will be given at the declaration site
  2951. return NULL;
  2952. }
  2953. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2954. {
  2955. BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Emitted code had errors", mCurMethodState->mEmitRefNode);
  2956. if (bfError != NULL)
  2957. mCompiler->mPassInstance->MoreInfo(warningString, refNode);
  2958. return bfError;
  2959. }
  2960. BfError* bfError;
  2961. if (refNode != NULL)
  2962. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warningString, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2963. else
  2964. bfError = mCompiler->mPassInstance->Warn(warningNum, warningString);
  2965. if (bfError != NULL)
  2966. {
  2967. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2968. bfError->mProject = mProject;
  2969. AddFailType(mCurTypeInstance);
  2970. mHadBuildWarning = true;
  2971. bfError->mIsPersistent = isPersistent;
  2972. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2973. {
  2974. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2975. if (parser != NULL)
  2976. {
  2977. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2978. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2979. if (warningNum != 0)
  2980. {
  2981. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  2982. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  2983. }
  2984. }
  2985. }
  2986. }
  2987. return bfError;
  2988. }
  2989. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfFieldInstance* fieldInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  2990. {
  2991. if (customAttributes == NULL)
  2992. return;
  2993. auto _AddDeclarationMoreInfo = [&]()
  2994. {
  2995. if (methodInstance != NULL)
  2996. {
  2997. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  2998. mCompiler->mPassInstance->MoreInfo(
  2999. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  3000. methodInstance->mMethodDef->GetRefNode());
  3001. }
  3002. else
  3003. {
  3004. mCompiler->mPassInstance->MoreInfo(
  3005. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  3006. typeInstance->mTypeDef->GetRefNode());
  3007. }
  3008. };
  3009. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  3010. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  3011. if ((customAttribute != NULL) && (targetSrc != NULL))
  3012. {
  3013. String err;
  3014. if (fieldInstance != NULL)
  3015. err = StrFormat("'%s' is obsolete", FieldToString(fieldInstance).c_str());
  3016. else if (methodInstance != NULL)
  3017. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  3018. else
  3019. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3020. bool isError = false;
  3021. if (customAttribute->mCtorArgs.size() >= 1)
  3022. {
  3023. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  3024. if (constant->mTypeCode == BfTypeCode_Boolean)
  3025. {
  3026. isError = constant->mBool;
  3027. }
  3028. else if (constant->mTypeCode == BfTypeCode_StringId)
  3029. {
  3030. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3031. if (str != NULL)
  3032. {
  3033. err += ":\n '";
  3034. err += *str;
  3035. err += "'";
  3036. }
  3037. if (customAttribute->mCtorArgs.size() >= 2)
  3038. {
  3039. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  3040. isError = constant->mBool;
  3041. }
  3042. }
  3043. }
  3044. BfError* error = NULL;
  3045. if (isError)
  3046. error = Fail(err, targetSrc);
  3047. else
  3048. error = Warn(0, err, targetSrc, false, true);
  3049. if (error != NULL)
  3050. _AddDeclarationMoreInfo();
  3051. }
  3052. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  3053. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3054. {
  3055. String err;
  3056. if (fieldInstance != NULL)
  3057. err += StrFormat("Method error: '", FieldToString(fieldInstance).c_str());
  3058. else if (methodInstance != NULL)
  3059. err += StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  3060. else
  3061. err += StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3062. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3063. if (str != NULL)
  3064. err += *str;
  3065. err += "'";
  3066. if (Fail(err, targetSrc) != NULL)
  3067. _AddDeclarationMoreInfo();
  3068. }
  3069. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  3070. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  3071. {
  3072. String err;
  3073. if (fieldInstance != NULL)
  3074. err += StrFormat("Field warning: '", FieldToString(fieldInstance).c_str());
  3075. else if (methodInstance != NULL)
  3076. err += StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  3077. else
  3078. err += StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3079. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3080. if (str != NULL)
  3081. err += *str;
  3082. err += "'";
  3083. if (Warn(0, err, targetSrc, false, true) != NULL)
  3084. _AddDeclarationMoreInfo();
  3085. }
  3086. }
  3087. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  3088. {
  3089. if (mBfIRBuilder->mOpFailed)
  3090. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  3091. }
  3092. void BfModule::FatalError(const StringImpl& error, const char* file, int line, int column)
  3093. {
  3094. static bool sHadFatalError = false;
  3095. static bool sHadReentrancy = false;
  3096. if (sHadFatalError)
  3097. {
  3098. return;
  3099. sHadReentrancy = true;
  3100. }
  3101. sHadFatalError = true;
  3102. String fullError = error;
  3103. if (file != NULL)
  3104. {
  3105. fullError += StrFormat(" at %s:%d", file, line);
  3106. if (column != -1)
  3107. fullError += StrFormat(":%d", column);
  3108. }
  3109. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3110. if (mCurTypeInstance != NULL)
  3111. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3112. if (mCurMethodInstance != NULL)
  3113. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3114. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3115. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3116. if (sHadReentrancy)
  3117. fullError += "\nError had reentrancy";
  3118. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  3119. }
  3120. void BfModule::FatalError(const StringImpl& error, BfAstNode* refNode)
  3121. {
  3122. if (refNode != NULL)
  3123. {
  3124. auto parser = refNode->GetParserData();
  3125. if (parser != NULL)
  3126. {
  3127. int line = -1;
  3128. int lineChar = -1;
  3129. parser->GetLineCharAtIdx(refNode->mSrcStart, line, lineChar);
  3130. if (line != -1)
  3131. FatalError(error, parser->mFileName.c_str(), line, lineChar);
  3132. }
  3133. }
  3134. FatalError(error);
  3135. }
  3136. void BfModule::InternalError(const StringImpl& error, BfAstNode* refNode, const char* file, int line)
  3137. {
  3138. String fullError = error;
  3139. if (file != NULL)
  3140. fullError += StrFormat(" at %s:%d", file, line);
  3141. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3142. if (mCurTypeInstance != NULL)
  3143. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3144. if (mCurMethodInstance != NULL)
  3145. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3146. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3147. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3148. Fail(String("INTERNAL ERROR: ") + fullError, refNode);
  3149. }
  3150. void BfModule::NotImpl(BfAstNode* astNode)
  3151. {
  3152. Fail("INTERNAL ERROR: Not implemented", astNode);
  3153. }
  3154. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  3155. {
  3156. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  3157. if (!allowPrivate)
  3158. allowPrivate |= memberType->IsInterface();
  3159. bool allowProtected = allowPrivate;
  3160. //TODO: We had this commented out, but this makes accessing protected properties fail
  3161. if (mCurTypeInstance != NULL)
  3162. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  3163. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  3164. {
  3165. return false;
  3166. }
  3167. return true;
  3168. }
  3169. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  3170. {
  3171. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  3172. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  3173. auto memberTypeInstance = memberType->ToTypeInstance();
  3174. if (memberTypeInstance == NULL)
  3175. {
  3176. auto underlyingType = memberType->GetUnderlyingType();
  3177. if (underlyingType != NULL)
  3178. return CheckDefineMemberProtection(protection, underlyingType);
  3179. return true;
  3180. }
  3181. if (memberTypeInstance->mTypeDef->mProtection < protection)
  3182. return false;
  3183. if (memberTypeInstance->IsGenericTypeInstance())
  3184. {
  3185. // When we're a generic struct, our data layout can depend on our generic parameters as well
  3186. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  3187. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3188. {
  3189. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  3190. return false;
  3191. }
  3192. }
  3193. return true;
  3194. }
  3195. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags, BfDepContext* depContext)
  3196. {
  3197. if (usedType == userType)
  3198. return;
  3199. if (((flags & BfDependencyMap::DependencyFlag_ConstValue) != 0) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_FieldType))
  3200. {
  3201. // This can be an `int32[UsedType.cVal]` type reference
  3202. flags = (BfDependencyMap::DependencyFlags)(flags | BfDependencyMap::DependencyFlag_ValueTypeSizeDep);
  3203. }
  3204. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  3205. {
  3206. if (userType->IsMethodRef())
  3207. {
  3208. // We cannot short-circuit dependencies because of method group ref counting
  3209. }
  3210. else
  3211. return;
  3212. }
  3213. if (usedType->IsSpecializedByAutoCompleteMethod())
  3214. {
  3215. if ((flags & (BfDependencyMap::DependencyFlag_TypeGenericArg | BfDependencyMap::DependencyFlag_MethodGenericArg |
  3216. BfDependencyMap::DependencyFlag_OuterType | BfDependencyMap::DependencyFlag_DerivedFrom)) == 0)
  3217. return;
  3218. }
  3219. // if (usedType->IsBoxed())
  3220. // {
  3221. // NOP;
  3222. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  3223. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  3224. // {
  3225. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  3226. // }
  3227. // }
  3228. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  3229. // BfType* origUsedType = usedType;
  3230. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  3231. // if (isDataAccess)
  3232. // {
  3233. // while (true)
  3234. // {
  3235. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  3236. // usedType = usedType->GetUnderlyingType();
  3237. // else if (usedType->IsArray())
  3238. // {
  3239. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  3240. // }
  3241. // else
  3242. // break;
  3243. // }
  3244. // }
  3245. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  3246. {
  3247. bool addType = true;
  3248. auto checkType = usedType;
  3249. PopulateType(checkType, BfPopulateType_Data);
  3250. if (checkType->IsValuelessType())
  3251. addType = false;
  3252. else if (checkType->IsPrimitiveType())
  3253. addType = false;
  3254. else
  3255. {
  3256. auto checkTypeInst = checkType->ToTypeInstance();
  3257. if (checkTypeInst == NULL)
  3258. {
  3259. addType = false;
  3260. }
  3261. else
  3262. {
  3263. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  3264. addType = false;
  3265. }
  3266. }
  3267. if (addType)
  3268. {
  3269. auto checkTypeInst = checkType->ToTypeInstance();
  3270. if (checkTypeInst->mHotTypeData != NULL)
  3271. {
  3272. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  3273. BF_ASSERT(hotTypeVersion != NULL);
  3274. if (hotTypeVersion != NULL)
  3275. {
  3276. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  3277. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  3278. (checkType->IsComposite()))
  3279. isAllocation = true;
  3280. if (isAllocation)
  3281. {
  3282. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  3283. }
  3284. else
  3285. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  3286. }
  3287. }
  3288. }
  3289. }
  3290. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  3291. {
  3292. auto usingModule = userType->GetModule();
  3293. BfModule* usedModule;
  3294. if (usedType->IsFunction())
  3295. {
  3296. if (mCompiler->mFunctionTypeDef != NULL)
  3297. {
  3298. auto functionType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  3299. usedModule = functionType->GetModule();
  3300. }
  3301. }
  3302. else
  3303. usedModule = usedType->GetModule();
  3304. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  3305. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  3306. {
  3307. if ((flags & ~(BfDependencyMap::DependencyFlag_OuterType)) == 0)
  3308. {
  3309. // Not a 'use' dependency
  3310. }
  3311. else
  3312. {
  3313. usingModule->mModuleRefs.Add(usedModule);
  3314. }
  3315. }
  3316. }
  3317. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  3318. {
  3319. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  3320. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  3321. if (genericArg == usedType)
  3322. return;
  3323. }
  3324. auto depFlag = flags;
  3325. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  3326. {
  3327. if (usedType->IsDependendType())
  3328. {
  3329. // Cause a rebuild but not an outright deletion of the type
  3330. // We can only do this if the 'usedType' can actually hold the dependency which can actually trigger a deletion chain
  3331. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef;
  3332. }
  3333. }
  3334. if (usedType->IsTypeAlias())
  3335. {
  3336. auto underlyingType = usedType->GetUnderlyingType();
  3337. if (underlyingType != NULL)
  3338. {
  3339. BfDepContext newDepContext;
  3340. if (depContext == NULL)
  3341. depContext = &newDepContext;
  3342. if (++depContext->mAliasDepth > 8)
  3343. {
  3344. if (!depContext->mDeepSeenAliases.Add(underlyingType))
  3345. return; // Circular!
  3346. }
  3347. AddDependency(underlyingType, userType, depFlag);
  3348. }
  3349. }
  3350. else if (!usedType->IsGenericTypeInstance())
  3351. {
  3352. auto underlyingType = usedType->GetUnderlyingType();
  3353. if (underlyingType != NULL)
  3354. AddDependency(underlyingType, userType, depFlag);
  3355. }
  3356. BfDependedType* checkDType = usedType->ToDependedType();
  3357. if (checkDType == NULL)
  3358. return;
  3359. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  3360. mContext->MarkAsReferenced(checkDType);
  3361. #ifdef _DEBUG
  3362. // If a MethodRef depends ON US, that means it's a local method that we own
  3363. if (userType->IsMethodRef())
  3364. {
  3365. auto methodRefType = (BfMethodRefType*)userType;
  3366. BF_ASSERT(methodRefType->mOwner == checkDType);
  3367. }
  3368. #endif
  3369. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  3370. return;
  3371. if ((checkDType->IsGenericTypeInstance()) && (!userType->IsMethodRef()))
  3372. {
  3373. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  3374. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3375. {
  3376. AddDependency(genericArg, userType, depFlag);
  3377. }
  3378. }
  3379. if (checkDType->IsTuple())
  3380. {
  3381. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  3382. {
  3383. if (field.mDataIdx != -1)
  3384. AddDependency(field.mResolvedType, userType, depFlag);
  3385. }
  3386. }
  3387. }
  3388. void BfModule::AddDependency(BfGenericParamInstance* genericParam, BfTypeInstance* usingType)
  3389. {
  3390. if ((genericParam->mExternType != NULL) && (!genericParam->mExternType->IsGenericParam()))
  3391. AddDependency(genericParam->mExternType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3392. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  3393. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3394. for (auto& operatorConstraint : genericParam->mOperatorConstraints)
  3395. {
  3396. if (operatorConstraint.mLeftType != NULL)
  3397. AddDependency(operatorConstraint.mLeftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3398. if (operatorConstraint.mRightType != NULL)
  3399. AddDependency(operatorConstraint.mRightType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3400. }
  3401. if (genericParam->mTypeConstraint != NULL)
  3402. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3403. }
  3404. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  3405. {
  3406. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  3407. {
  3408. if (methodInstance->mHotMethod == NULL)
  3409. CheckHotMethod(methodInstance, "");
  3410. BF_ASSERT(methodInstance->mHotMethod != NULL);
  3411. if (devirtualized)
  3412. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  3413. else
  3414. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  3415. }
  3416. }
  3417. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  3418. {
  3419. auto checkTypeInst = typeInst;
  3420. while (checkTypeInst != NULL)
  3421. {
  3422. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  3423. return true;
  3424. checkTypeInst = checkTypeInst->mBaseType;
  3425. }
  3426. return false;
  3427. }
  3428. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  3429. {
  3430. if (mContext->mCurTypeState == NULL)
  3431. return;
  3432. BP_ZONE("PopulateGlobalContainersList");
  3433. BfTypeDef* userTypeDef = GetActiveTypeDef();
  3434. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  3435. {
  3436. mContext->mCurTypeState->mGlobalContainers.Clear();
  3437. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  3438. {
  3439. BfAtomComposite findStr;
  3440. if (namespaceIdx != -1)
  3441. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  3442. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  3443. while (typeDefItr)
  3444. {
  3445. auto typeDef = *typeDefItr;
  3446. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  3447. {
  3448. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  3449. {
  3450. BfGlobalContainerEntry globalEntry;
  3451. globalEntry.mTypeDef = typeDef;
  3452. globalEntry.mTypeInst = NULL;
  3453. typeDef->PopulateMemberSets();
  3454. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  3455. }
  3456. }
  3457. else if (!typeDef->mIsPartial)
  3458. {
  3459. //break;
  3460. }
  3461. typeDefItr.MoveToNextHashMatch();
  3462. }
  3463. }
  3464. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  3465. }
  3466. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  3467. // reifing types
  3468. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  3469. {
  3470. if (globalEntry.mTypeInst == NULL)
  3471. {
  3472. bool include = false;
  3473. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  3474. include = true;
  3475. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  3476. {
  3477. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  3478. include = true;
  3479. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  3480. include = true;
  3481. }
  3482. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  3483. {
  3484. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  3485. include = true;
  3486. }
  3487. if (include)
  3488. {
  3489. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  3490. if (type != NULL)
  3491. globalEntry.mTypeInst = type->ToTypeInstance();
  3492. }
  3493. }
  3494. }
  3495. }
  3496. BfStaticSearch* BfModule::GetStaticSearch()
  3497. {
  3498. auto activeTypeDef = GetActiveTypeDef();
  3499. BfStaticSearch* staticSearch = NULL;
  3500. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3501. return staticSearch;
  3502. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3503. return staticSearch;
  3504. return NULL;
  3505. }
  3506. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  3507. {
  3508. auto activeTypeDef = GetActiveTypeDef();
  3509. BfInternalAccessSet* internalAccessSet = NULL;
  3510. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3511. return internalAccessSet;
  3512. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3513. return internalAccessSet;
  3514. return NULL;
  3515. }
  3516. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  3517. {
  3518. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  3519. return true;
  3520. if ((mCurMethodInstance != NULL) &&
  3521. ((mCurMethodInstance->mIsUnspecializedVariation) || (mCurMethodInstance->IsSpecializedGenericMethod())))
  3522. return true;
  3523. auto internalAccessSet = GetInternalAccessSet();
  3524. if (internalAccessSet == NULL)
  3525. return false;
  3526. for (auto& nameComposite : internalAccessSet->mNamespaces)
  3527. {
  3528. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  3529. return true;
  3530. }
  3531. for (auto internalType : internalAccessSet->mTypes)
  3532. {
  3533. auto checkTypeDef = usingTypeDef->GetDefinition();
  3534. while (checkTypeDef != NULL)
  3535. {
  3536. if (checkTypeDef == internalType->mTypeDef->GetDefinition())
  3537. return true;
  3538. checkTypeDef = checkTypeDef->mOuterType;
  3539. }
  3540. }
  3541. return false;
  3542. }
  3543. void PrintUsers(llvm::MDNode* md);
  3544. BfModuleOptions BfModule::GetModuleOptions()
  3545. {
  3546. if (mIsScratchModule)
  3547. return BfModuleOptions();
  3548. if (mModuleOptions != NULL)
  3549. return *mModuleOptions;
  3550. BfModuleOptions moduleOptions;
  3551. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3552. if (mProject != NULL)
  3553. {
  3554. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3555. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3556. }
  3557. auto headModule = this;
  3558. while (headModule->mParentModule != NULL)
  3559. headModule = headModule->mParentModule;
  3560. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata") || mIsSpecialModule);
  3561. if (headModule->mOwnedTypeInstances.size() > 0)
  3562. {
  3563. auto typeInst = headModule->mOwnedTypeInstances[0];
  3564. if (typeInst->mTypeOptionsIdx == -2)
  3565. PopulateType(typeInst);
  3566. if (typeInst->mTypeOptionsIdx != -1)
  3567. {
  3568. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3569. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3570. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3571. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3572. }
  3573. }
  3574. return moduleOptions;
  3575. }
  3576. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3577. {
  3578. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3579. return BfCheckedKind_Unchecked;
  3580. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3581. auto typeOptions = GetTypeOptions();
  3582. if (typeOptions != NULL)
  3583. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3584. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3585. }
  3586. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3587. {
  3588. BF_ASSERT(typeInstance != NULL);
  3589. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_InFailTypes) != 0)
  3590. return;
  3591. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_InFailTypes);
  3592. mContext->mFailTypes.TryAdd(typeInstance, BfFailKind_Normal);
  3593. }
  3594. void BfModule::DeferRebuildType(BfTypeInstance* typeInstance)
  3595. {
  3596. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_RebuildQueued) != 0)
  3597. return;
  3598. mCompiler->mHasQueuedTypeRebuilds = true;
  3599. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_RebuildQueued);
  3600. AddFailType(typeInstance);
  3601. }
  3602. void BfModule::CheckAddFailType()
  3603. {
  3604. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3605. // but we still need to add the owning type to the FailTypes list
  3606. //.. OLD:
  3607. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3608. /*if (mCurTypeInstance->mModule != this)
  3609. return;*/
  3610. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3611. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3612. // being recompiled. This forces types with warnings to be recompiled.
  3613. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3614. // constantly warning-aware
  3615. if ((mHadBuildError) ||
  3616. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3617. {
  3618. //mContext->mFailTypes.Add(mCurTypeInstance);
  3619. }
  3620. }
  3621. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3622. {
  3623. if (!mCompiler->IsHotCompile())
  3624. return;
  3625. typeInst->mDirty = true;
  3626. for (auto& dep : typeInst->mDependencyMap)
  3627. {
  3628. auto depType = dep.mKey;
  3629. auto depFlags = dep.mValue.mFlags;
  3630. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3631. {
  3632. MarkDerivedDirty(depType->ToTypeInstance());
  3633. }
  3634. }
  3635. }
  3636. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3637. {
  3638. auto fieldType = fieldInstance->GetResolvedType();
  3639. auto field = fieldInstance->GetFieldDef();
  3640. if (fieldType->IsVar())
  3641. return;
  3642. BfIRValue initValue;
  3643. if (field->mIsConst)
  3644. {
  3645. if (fieldType->IsPointer())
  3646. fieldType = fieldType->GetUnderlyingType();
  3647. }
  3648. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3649. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3650. storageKind = BfIRStorageKind_Export;
  3651. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3652. storageKind = BfIRStorageKind_Import;
  3653. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3654. initValue = GetDefaultValue(fieldType);
  3655. if (fieldInstance->mOwner->IsUnspecializedType())
  3656. {
  3657. // Placeholder
  3658. auto ptrVal = CreatePointerType(fieldType);
  3659. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3660. }
  3661. else
  3662. {
  3663. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3664. StringT<4096> staticVarName;
  3665. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3666. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3667. {
  3668. BfIRType irType;
  3669. if (fieldInstance->IsAppendedObject())
  3670. {
  3671. irType = mBfIRBuilder->MapTypeInst(fieldType->ToTypeInstance(), BfIRPopulateType_Eventually_Full);
  3672. initValue = mBfIRBuilder->CreateConstAggZero(irType);
  3673. }
  3674. else
  3675. irType = mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full);
  3676. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3677. irType,
  3678. false,
  3679. BfIRLinkageType_External,
  3680. initValue,
  3681. staticVarName,
  3682. isThreadLocal);
  3683. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3684. if (storageKind != BfIRStorageKind_Normal)
  3685. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3686. BF_ASSERT(globalVar);
  3687. mStaticFieldRefs[fieldInstance] = globalVar;
  3688. }
  3689. }
  3690. }
  3691. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3692. {
  3693. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3694. BfType* fieldType = NULL;
  3695. if (fieldInstance != NULL)
  3696. {
  3697. fieldType = fieldInstance->GetResolvedType();
  3698. if (fieldType == NULL)
  3699. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3700. }
  3701. else
  3702. {
  3703. BF_ASSERT(mCompiler->IsAutocomplete());
  3704. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3705. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3706. {
  3707. fieldType = typeInstance;
  3708. }
  3709. else
  3710. {
  3711. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3712. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3713. if (isLet || isVar)
  3714. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3715. else
  3716. fieldType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  3717. if (fieldType == NULL)
  3718. fieldType = mContext->mBfObjectType;
  3719. }
  3720. }
  3721. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3722. return;
  3723. if (mContext->mFieldResolveReentrys.size() > 1)
  3724. {
  3725. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3726. {
  3727. String failStr = "Circular data reference detected between the following fields:";
  3728. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3729. {
  3730. if (i > 1)
  3731. failStr += ",";
  3732. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3733. }
  3734. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3735. if (err)
  3736. err->mIsPersistent = true;
  3737. return;
  3738. }
  3739. }
  3740. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3741. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3742. if (fieldInstance == NULL)
  3743. popTypeResolveReentry.Pop();
  3744. auto typeDef = typeInstance->mTypeDef;
  3745. BfIRValue constValue;
  3746. if (fieldDef->mIsExtern)
  3747. {
  3748. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3749. {
  3750. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3751. Fail("Extern consts must be pointer types", fieldDef->mTypeRef);
  3752. }
  3753. if (fieldDef->GetInitializer() != NULL)
  3754. {
  3755. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3756. Fail("Extern consts cannot have initializers", fieldDef->GetNameNode());
  3757. }
  3758. }
  3759. else if (fieldDef->GetInitializer() == NULL)
  3760. {
  3761. if (fieldDef->IsEnumCaseEntry())
  3762. {
  3763. if (typeInstance->IsTypedPrimitive())
  3764. {
  3765. BfFieldInstance* prevFieldInstance = NULL;
  3766. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3767. {
  3768. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3769. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3770. {
  3771. prevFieldInstance = checkFieldInst;
  3772. break;
  3773. }
  3774. }
  3775. if (prevFieldInstance == NULL)
  3776. constValue = GetConstValue(0, typeInstance);
  3777. else
  3778. {
  3779. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3780. if (prevFieldInstance->mConstIdx == -1)
  3781. {
  3782. if (!mCompiler->IsAutocomplete())
  3783. AssertErrorState();
  3784. constValue = GetConstValue(0, typeInstance);
  3785. }
  3786. else
  3787. {
  3788. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3789. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3790. }
  3791. }
  3792. }
  3793. }
  3794. else
  3795. {
  3796. Fail("Const requires initializer", fieldDef->GetNameNode());
  3797. }
  3798. }
  3799. else if (mBfIRBuilder != NULL)
  3800. {
  3801. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3802. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3803. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3804. BfMethodState methodState;
  3805. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3806. methodState.mTempKind = BfMethodState::TempKind_Static;
  3807. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3808. if ((fieldType->IsVar()) || (fieldType->IsUndefSizedArray()))
  3809. {
  3810. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3811. if (!initValue)
  3812. {
  3813. AssertErrorState();
  3814. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3815. }
  3816. if (fieldInstance != NULL)
  3817. {
  3818. if (fieldType->IsUndefSizedArray())
  3819. {
  3820. if ((initValue.mType->IsSizedArray()) && (initValue.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3821. {
  3822. fieldInstance->mResolvedType = initValue.mType;
  3823. }
  3824. }
  3825. else
  3826. fieldInstance->mResolvedType = initValue.mType;
  3827. }
  3828. constValue = initValue.mValue;
  3829. }
  3830. else
  3831. {
  3832. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3833. constValue = uncastedInitValue.mValue;
  3834. }
  3835. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3836. {
  3837. // Illegal
  3838. constValue = BfIRValue();
  3839. }
  3840. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3841. }
  3842. if (fieldInstance != NULL)
  3843. {
  3844. fieldType = fieldInstance->GetResolvedType();
  3845. if ((fieldType == NULL) || (fieldType->IsVar()))
  3846. {
  3847. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3848. AssertErrorState();
  3849. // Default const type is 'int'
  3850. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3851. if (fieldInstance != NULL)
  3852. {
  3853. fieldInstance->mResolvedType = initValue.mType;
  3854. }
  3855. constValue = initValue.mValue;
  3856. }
  3857. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3858. {
  3859. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3860. CurrentAddToConstHolder(constValue);
  3861. fieldInstance->mConstIdx = constValue.mId;
  3862. }
  3863. }
  3864. }
  3865. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3866. {
  3867. bool isDeclType = (field->mFieldDeclaration != NULL) && BfNodeDynCastExact<BfExprModTypeRef>(field->mTypeRef) != NULL;
  3868. auto fieldType = fieldInstance->GetResolvedType();
  3869. if ((field->mIsConst) && (!isDeclType))
  3870. {
  3871. ResolveConstField(typeInstance, fieldInstance, field);
  3872. return fieldInstance->GetResolvedType();
  3873. }
  3874. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3875. if (!fieldInstance->mIsInferredType)
  3876. return fieldType;
  3877. if ((!fieldType->IsVar()) && (!fieldType->IsUndefSizedArray()))
  3878. return fieldType;
  3879. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3880. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3881. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mType != typeInstance);
  3882. auto typeDef = typeInstance->mTypeDef;
  3883. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3884. {
  3885. AssertErrorState();
  3886. return fieldType;
  3887. }
  3888. bool hadInferenceCycle = false;
  3889. if (mContext->mFieldResolveReentrys.size() > 1)
  3890. {
  3891. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3892. {
  3893. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3894. {
  3895. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3896. auto fieldDef = fieldInst->GetFieldDef();
  3897. auto fieldOwner = fieldInst->mOwner;
  3898. auto fieldModule = fieldOwner->mModule;
  3899. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3900. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3901. }
  3902. return fieldType;
  3903. }
  3904. }
  3905. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3906. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3907. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3908. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3909. if ((field->GetInitializer() == NULL) && (!isDeclType))
  3910. {
  3911. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3912. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3913. return fieldType;
  3914. }
  3915. BfType* resolvedType = NULL;
  3916. if (!hadInferenceCycle)
  3917. {
  3918. BfTypeState typeState;
  3919. typeState.mPrevState = mContext->mCurTypeState;
  3920. typeState.mType = typeInstance;
  3921. typeState.mCurFieldDef = field;
  3922. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3923. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3924. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3925. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3926. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3927. BfMethodState methodState;
  3928. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3929. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3930. if (!staticOnly)
  3931. {
  3932. //BfLocalVariable localVar;
  3933. //methodState.mLocals.push_back(localVar);
  3934. }
  3935. if (isDeclType)
  3936. {
  3937. auto fieldDef = fieldInstance->GetFieldDef();
  3938. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3939. }
  3940. else
  3941. {
  3942. BfTypedValue valueFromExpr;
  3943. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3944. FixIntUnknown(valueFromExpr);
  3945. if (fieldType->IsUndefSizedArray())
  3946. {
  3947. if ((valueFromExpr.mType != NULL) && (valueFromExpr.mType->IsSizedArray()) && (valueFromExpr.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3948. resolvedType = valueFromExpr.mType;
  3949. }
  3950. else
  3951. resolvedType = valueFromExpr.mType;
  3952. }
  3953. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3954. }
  3955. if (resolvedType == NULL)
  3956. return fieldType;
  3957. fieldInstance->SetResolvedType(resolvedType);
  3958. if (field->mIsStatic)
  3959. {
  3960. }
  3961. else if (fieldInstance->mDataIdx >= 0)
  3962. {
  3963. }
  3964. else
  3965. {
  3966. BF_ASSERT(typeInstance->IsIncomplete());
  3967. }
  3968. return resolvedType;
  3969. }
  3970. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3971. {
  3972. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3973. auto fieldType = fieldInstance->GetResolvedType();
  3974. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3975. {
  3976. int fieldIdx = 0;
  3977. int fieldCount = 0;
  3978. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  3979. fieldIdx--;
  3980. int count = fieldCount;
  3981. if (fieldIdx == -1)
  3982. count = 1;
  3983. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3984. auto thisVariable = GetThisVariable();
  3985. if (thisVariable != NULL)
  3986. {
  3987. for (int i = 0; i < count; i++)
  3988. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  3989. }
  3990. }
  3991. }
  3992. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3993. {
  3994. if (fieldInstance->mCustomAttributes == NULL)
  3995. return false;
  3996. auto fieldDef = fieldInstance->GetFieldDef();
  3997. if (!fieldDef->mIsStatic)
  3998. return false;
  3999. bool isThreadLocal = false;
  4000. if (fieldInstance->mCustomAttributes != NULL)
  4001. {
  4002. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4003. {
  4004. if (customAttr.mType->ToTypeInstance()->IsInstanceOf(mCompiler->mThreadStaticAttributeTypeDef))
  4005. return true;
  4006. }
  4007. }
  4008. return false;
  4009. }
  4010. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  4011. {
  4012. if (fieldDef == NULL)
  4013. fieldDef = fieldInstance->GetFieldDef();
  4014. if (fieldType == NULL)
  4015. fieldType = fieldInstance->GetResolvedType();
  4016. if (initializer == NULL)
  4017. {
  4018. if (fieldDef == NULL)
  4019. return BfTypedValue();
  4020. initializer = fieldDef->GetInitializer();
  4021. }
  4022. BfTypedValue staticVarRef;
  4023. BfTypedValue result;
  4024. if (initializer == NULL)
  4025. {
  4026. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  4027. }
  4028. else
  4029. {
  4030. if (mCompiler->mIsResolveOnly)
  4031. {
  4032. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  4033. {
  4034. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  4035. sourceClassifier->VisitChildNoRef(initializer);
  4036. }
  4037. }
  4038. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  4039. {
  4040. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  4041. BfConstResolver constResolver(this);
  4042. constResolver.Resolve(initializer);
  4043. return GetDefaultTypedValue(fieldType);
  4044. }
  4045. else if (mCurTypeInstance->IsUnspecializedTypeVariation())
  4046. {
  4047. return GetDefaultTypedValue(fieldType);
  4048. }
  4049. else if (fieldDef->mIsConst)
  4050. {
  4051. int ceExecuteId = -1;
  4052. if (mCompiler->mCeMachine != NULL)
  4053. ceExecuteId = mCompiler->mCeMachine->mExecuteId;
  4054. BfTypeState typeState;
  4055. typeState.mType = mCurTypeInstance;
  4056. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  4057. typeState.mCurFieldDef = fieldDef;
  4058. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  4059. BfConstResolver constResolver(this);
  4060. if (fieldType->IsVar())
  4061. return constResolver.Resolve(initializer);
  4062. else
  4063. {
  4064. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  4065. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  4066. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  4067. {
  4068. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  4069. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  4070. resolveFlags = BfConstResolveFlag_NoCast;
  4071. }
  4072. UpdateSrcPos(initializer);
  4073. auto result = constResolver.Resolve(initializer, fieldType, resolveFlags);
  4074. if ((mCompiler->mCeMachine != NULL) && (fieldInstance != NULL))
  4075. {
  4076. if (mCompiler->mCeMachine->mExecuteId != ceExecuteId)
  4077. fieldInstance->mHadConstEval = true;
  4078. }
  4079. if (auto autoComplete = mCompiler->GetAutoComplete())
  4080. autoComplete->CheckResult(initializer, result);
  4081. return result;
  4082. }
  4083. }
  4084. BfExprEvaluator exprEvaluator(this);
  4085. if (doStore)
  4086. {
  4087. staticVarRef = ReferenceStaticField(fieldInstance);
  4088. exprEvaluator.mReceivingValue = &staticVarRef;
  4089. }
  4090. if (fieldType->IsVar())
  4091. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4092. else
  4093. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4094. if (doStore)
  4095. {
  4096. if (exprEvaluator.mReceivingValue == NULL)
  4097. doStore = false; // Already stored
  4098. }
  4099. }
  4100. if (fieldInstance != NULL)
  4101. MarkFieldInitialized(fieldInstance);
  4102. if ((doStore) && (result))
  4103. {
  4104. if (fieldInstance->mResolvedType->IsUndefSizedArray())
  4105. {
  4106. if ((!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mFastFinish))
  4107. AssertErrorState();
  4108. }
  4109. else
  4110. {
  4111. result = LoadValue(result);
  4112. if (!result.mType->IsValuelessType())
  4113. mBfIRBuilder->CreateAlignedStore(result.mValue, staticVarRef.mValue, result.mType->mAlign);
  4114. }
  4115. }
  4116. return result;
  4117. }
  4118. void BfModule::AppendedObjectInit(BfFieldInstance* fieldInst)
  4119. {
  4120. BfExprEvaluator exprEvaluator(this);
  4121. bool failed = false;
  4122. auto fieldDef = fieldInst->GetFieldDef();
  4123. auto initializer = fieldDef->GetInitializer();
  4124. BfResolvedArgs resolvedArgs;
  4125. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(initializer))
  4126. {
  4127. bool isDot = false;
  4128. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  4129. isDot = (memberRefExpr->mTarget == NULL) && (memberRefExpr->mMemberName == NULL);
  4130. if (!isDot)
  4131. {
  4132. auto resolvedType = ResolveTypeRef(invocationExpr->mTarget, {});
  4133. if ((resolvedType == NULL) || (resolvedType != fieldInst->mResolvedType))
  4134. failed = true;
  4135. }
  4136. SetAndRestoreValue<BfType*> prevExpectingType(exprEvaluator.mExpectingType, fieldInst->mResolvedType);
  4137. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  4138. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  4139. }
  4140. else if (initializer != NULL)
  4141. {
  4142. GetFieldInitializerValue(fieldInst);
  4143. failed = true;
  4144. }
  4145. if (failed)
  4146. Fail("Append fields can only be initialized with a call to their constructor", initializer);
  4147. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  4148. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4149. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4150. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  4151. auto fieldTypeInst = fieldInst->mResolvedType->ToTypeInstance();
  4152. BfIRValue fieldAddr;
  4153. if (fieldDef->mIsStatic)
  4154. {
  4155. fieldAddr = ReferenceStaticField(fieldInst).mValue;
  4156. }
  4157. else
  4158. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  4159. auto thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  4160. auto indexVal = BfTypedValue(CreateAlloca(intType), CreateRefType(intType));
  4161. auto intThisVal = mBfIRBuilder->CreatePtrToInt(thisValue.mValue, (intType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  4162. auto curValPtr = mBfIRBuilder->CreateAdd(intThisVal, GetConstValue(fieldTypeInst->mInstSize, intType));
  4163. mBfIRBuilder->CreateStore(curValPtr, indexVal.mValue);
  4164. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 0);
  4165. auto vDataRef = CreateClassVDataGlobal(fieldInst->mResolvedType->ToTypeInstance());
  4166. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  4167. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  4168. mBfIRBuilder->CreateStore(srcVal, destAddr);
  4169. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  4170. {
  4171. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4172. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4173. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(thisValue.mValue, ptrType);
  4174. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_AppendAlloc), thisFlagsPtr);
  4175. }
  4176. exprEvaluator.MatchConstructor(fieldDef->GetNameNode(), NULL, thisValue, fieldInst->mResolvedType->ToTypeInstance(), resolvedArgs, false, BfMethodGenericArguments(), true, &indexVal);
  4177. }
  4178. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  4179. {
  4180. }
  4181. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  4182. {
  4183. PopulateType(classType);
  4184. if (isInterfacePass)
  4185. {
  4186. for (auto ifaceInst : classType->mInterfaces)
  4187. {
  4188. if (exChecks->Contains(ifaceInst.mInterfaceType))
  4189. continue;
  4190. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  4191. continue;
  4192. if (ifaceInst.mDeclaringType->IsExtension())
  4193. {
  4194. bool needsExCheck = false;
  4195. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  4196. {
  4197. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  4198. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  4199. {
  4200. exChecks->push_back(ifaceInst.mInterfaceType);
  4201. continue;
  4202. }
  4203. else
  4204. {
  4205. // We can only do an 'exCheck' if we're actually going to slot this interface
  4206. }
  4207. }
  4208. }
  4209. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  4210. }
  4211. }
  4212. else
  4213. {
  4214. outVals->push_back(classType->mTypeId);
  4215. }
  4216. if (classType->mBaseType != NULL)
  4217. {
  4218. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  4219. }
  4220. }
  4221. void BfModule::CreateDynamicCastMethod()
  4222. {
  4223. auto objType = mContext->mBfObjectType;
  4224. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  4225. {
  4226. // The main reason to punt on this method for ResolveOnly is because types can be created
  4227. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  4228. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  4229. // remove this punt when we recycle typeId's
  4230. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  4231. mCurMethodState->mHadReturn = true;
  4232. return;
  4233. }
  4234. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  4235. auto func = mCurMethodState->mIRFunction;
  4236. auto thisValue = mBfIRBuilder->GetArgument(0);
  4237. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  4238. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4239. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  4240. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  4241. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  4242. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  4243. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  4244. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4245. SizedArray<int, 8> typeMatches;
  4246. SizedArray<BfTypeInstance*, 8> exChecks;
  4247. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  4248. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  4249. {
  4250. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  4251. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  4252. BfTypeVector genericArgs;
  4253. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  4254. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  4255. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef->GetDefinition(), genericArgs, BfPopulateType_Declaration);
  4256. typeMatches.push_back(unboundType->mTypeId);
  4257. }
  4258. if (mCurTypeInstance->IsBoxed())
  4259. {
  4260. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  4261. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  4262. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  4263. if (innerType->IsTypedPrimitive())
  4264. {
  4265. auto underlyingType = innerType->GetUnderlyingType();
  4266. typeMatches.push_back(underlyingType->mTypeId);
  4267. }
  4268. auto innerTypeInst = innerType->ToTypeInstance();
  4269. if ((innerTypeInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef)) ||
  4270. (innerTypeInst->IsInstanceOf(mCompiler->mPointerTTypeDef)) ||
  4271. (innerTypeInst->IsInstanceOf(mCompiler->mMethodRefTypeDef)))
  4272. {
  4273. PopulateType(innerTypeInst);
  4274. //TODO: What case was this supposed to handle?
  4275. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  4276. }
  4277. }
  4278. auto curBlock = mBfIRBuilder->GetInsertBlock();
  4279. BfIRValue vDataPtr;
  4280. if (!exChecks.empty())
  4281. {
  4282. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4283. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  4284. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  4285. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4286. }
  4287. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  4288. for (auto typeMatch : typeMatches)
  4289. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  4290. Array<BfIRValue> incomingFalses;
  4291. for (auto ifaceTypeInst : exChecks)
  4292. {
  4293. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  4294. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  4295. mBfIRBuilder->SetInsertPoint(nextBB);
  4296. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  4297. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4298. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4299. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4300. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  4301. incomingFalses.push_back(nextBB);
  4302. }
  4303. mBfIRBuilder->AddBlock(trueBB);
  4304. mBfIRBuilder->SetInsertPoint(trueBB);
  4305. mBfIRBuilder->CreateBr(exitBB);
  4306. mBfIRBuilder->AddBlock(exitBB);
  4307. mBfIRBuilder->SetInsertPoint(exitBB);
  4308. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  4309. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  4310. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  4311. for (auto incomingFalseBlock : incomingFalses)
  4312. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  4313. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  4314. mBfIRBuilder->CreateRet(phi);
  4315. mCurMethodState->mHadReturn = true;
  4316. }
  4317. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  4318. {
  4319. BfExprEvaluator exprEvaluator(this);
  4320. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  4321. auto typeInst = rightValue.mType->ToTypeInstance();
  4322. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  4323. BfTypedValue result = exprEvaluator.GetResult();
  4324. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  4325. {
  4326. // Fail?
  4327. }
  4328. if ((result) && (!result.mType->IsVar()))
  4329. {
  4330. auto nextBB = mBfIRBuilder->CreateBlock("next");
  4331. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  4332. mBfIRBuilder->AddBlock(nextBB);
  4333. mBfIRBuilder->SetInsertPoint(nextBB);
  4334. }
  4335. }
  4336. void BfModule::CreateFakeCallerMethod(const String& funcName)
  4337. {
  4338. if (mCurMethodInstance->mHasFailed)
  4339. return;
  4340. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  4341. return;
  4342. BF_ASSERT(mCurMethodInstance->mIRFunction);
  4343. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  4344. SizedArray<BfIRType, 4> paramTypes;
  4345. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  4346. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  4347. mBfIRBuilder->SetActiveFunction(func);
  4348. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  4349. mBfIRBuilder->SetInsertPoint(entryBlock);
  4350. BfMethodState methodState;
  4351. methodState.mIRHeadBlock = entryBlock;
  4352. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4353. SizedArray<BfIRValue, 8> args;
  4354. BfExprEvaluator exprEvaluator(this);
  4355. if (mCurMethodInstance->GetStructRetIdx() == 0)
  4356. {
  4357. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4358. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4359. }
  4360. if (mCurMethodInstance->HasThis())
  4361. {
  4362. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  4363. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  4364. }
  4365. if (mCurMethodInstance->GetStructRetIdx() == 1)
  4366. {
  4367. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4368. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4369. }
  4370. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  4371. {
  4372. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  4373. if (paramType->IsValuelessType())
  4374. continue;
  4375. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  4376. }
  4377. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  4378. mBfIRBuilder->CreateRetVoid();
  4379. }
  4380. void BfModule::CreateDelegateEqualsMethod()
  4381. {
  4382. if (mBfIRBuilder->mIgnoreWrites)
  4383. return;
  4384. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4385. if (refNode == NULL)
  4386. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4387. UpdateSrcPos(refNode);
  4388. SetIllegalSrcPos();
  4389. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4390. auto resultVal = CreateAlloca(boolType);
  4391. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4392. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4393. auto delegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  4394. mBfIRBuilder->PopulateType(delegateType);
  4395. BfExprEvaluator exprEvaluator(this);
  4396. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4397. BfTypedValue lhsDelegate = BfTypedValue(mBfIRBuilder->CreateBitCast(leftTypedVal.mValue, mBfIRBuilder->MapType(delegateType)), delegateType);
  4398. BfTypedValue rhsDelegate = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4399. rhsDelegate = LoadValue(rhsDelegate);
  4400. BfTypedValue rightTypedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(rhsDelegate.mValue, mBfIRBuilder->MapType(mCurTypeInstance)), mCurTypeInstance);
  4401. auto& targetFieldInstance = delegateType->mFieldInstances[0];
  4402. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(lhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4403. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4404. leftValue = LoadValue(leftValue);
  4405. rightValue = LoadValue(rightValue);
  4406. EmitEquals(leftValue, rightValue, exitBB, false);
  4407. bool hadComparison = false;
  4408. for (auto& fieldRef : mCurTypeInstance->mFieldInstances)
  4409. {
  4410. BfFieldInstance* fieldInstance = &fieldRef;
  4411. if (fieldInstance->mDataOffset == -1)
  4412. continue;
  4413. auto fieldType = fieldInstance->mResolvedType;
  4414. if (fieldType->IsValuelessType())
  4415. continue;
  4416. if (fieldType->IsVar())
  4417. continue;
  4418. if (fieldType->IsMethodRef())
  4419. continue;
  4420. if (fieldType->IsRef())
  4421. fieldType = CreatePointerType(fieldType->GetUnderlyingType());
  4422. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(leftTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4423. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rightTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4424. if (!fieldInstance->mResolvedType->IsComposite())
  4425. {
  4426. leftValue = LoadValue(leftValue);
  4427. rightValue = LoadValue(rightValue);
  4428. }
  4429. EmitEquals(leftValue, rightValue, exitBB, false);
  4430. }
  4431. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4432. mBfIRBuilder->CreateBr(exitBB);
  4433. mBfIRBuilder->AddBlock(exitBB);
  4434. mBfIRBuilder->SetInsertPoint(exitBB);
  4435. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4436. ClearLifetimeEnds();
  4437. mBfIRBuilder->CreateRet(loadedResult);
  4438. mCurMethodState->mHadReturn = true;
  4439. }
  4440. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  4441. {
  4442. if (mCurMethodInstance->mIsUnspecialized)
  4443. return;
  4444. if (mBfIRBuilder->mIgnoreWrites)
  4445. return;
  4446. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  4447. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  4448. bool isValid = true;
  4449. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4450. if (compareType->IsValuelessType())
  4451. {
  4452. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4453. return;
  4454. }
  4455. if (compareType->IsTypedPrimitive())
  4456. {
  4457. BfExprEvaluator exprEvaluator(this);
  4458. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  4459. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  4460. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  4461. mBfIRBuilder->CreateRet(cmpResult);
  4462. return;
  4463. }
  4464. auto compareDType = compareType->ToDependedType();
  4465. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  4466. if (compareTypeInst != NULL)
  4467. {
  4468. if (compareType->IsPrimitiveType())
  4469. compareTypeInst = GetWrappedStructType(compareType);
  4470. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  4471. {
  4472. isValid = false;
  4473. }
  4474. mBfIRBuilder->PopulateType(compareTypeInst);
  4475. }
  4476. if (!isValid)
  4477. {
  4478. ClearLifetimeEnds();
  4479. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4480. return;
  4481. }
  4482. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  4483. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4484. if (refNode == NULL)
  4485. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4486. UpdateSrcPos(refNode);
  4487. SetIllegalSrcPos();
  4488. auto resultVal = CreateAlloca(boolType);
  4489. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4490. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4491. if (compareType->IsValuelessType())
  4492. {
  4493. // Always equal, nothing to do
  4494. }
  4495. else if (compareType->IsSizedArray())
  4496. {
  4497. auto sizedArrayType = (BfSizedArrayType*)compareType;
  4498. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  4499. {
  4500. BfTypedValue result;
  4501. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index, true);
  4502. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4503. if (!result.mType->IsValueType())
  4504. result = LoadValue(result);
  4505. return result;
  4506. };
  4507. if (sizedArrayType->mElementCount > 6)
  4508. {
  4509. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4510. auto itr = CreateAlloca(intPtrType);
  4511. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  4512. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  4513. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  4514. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  4515. mBfIRBuilder->CreateBr(loopBB);
  4516. mBfIRBuilder->SetInsertPoint(loopBB);
  4517. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  4518. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  4519. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  4520. mBfIRBuilder->SetInsertPoint(bodyBB);
  4521. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  4522. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  4523. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4524. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  4525. mBfIRBuilder->CreateStore(incValue, itr);
  4526. mBfIRBuilder->CreateBr(loopBB);
  4527. mBfIRBuilder->SetInsertPoint(doneBB);
  4528. }
  4529. else
  4530. {
  4531. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  4532. {
  4533. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4534. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4535. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4536. }
  4537. }
  4538. }
  4539. else if (compareType->IsMethodRef())
  4540. {
  4541. auto methodRefType = (BfMethodRefType*)compareType;
  4542. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  4543. BfExprEvaluator exprEvaluator(this);
  4544. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4545. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4546. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  4547. // values for the same method reference -- they will always refer back to the same local variables.
  4548. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  4549. if (dataIdx != -1)
  4550. {
  4551. bool failed = false;
  4552. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  4553. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  4554. BF_ASSERT(!failed);
  4555. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4556. }
  4557. }
  4558. else if (compareTypeInst->IsEnum())
  4559. {
  4560. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4561. BfExprEvaluator exprEvaluator(this);
  4562. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4563. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4564. auto dscrType = compareTypeInst->GetDiscriminatorType();
  4565. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  4566. leftValue = LoadValue(leftValue);
  4567. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  4568. rightValue = LoadValue(rightValue);
  4569. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  4570. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  4571. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4572. int enumCount = 0;
  4573. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4574. {
  4575. BfFieldInstance* fieldInstance = &fieldRef;
  4576. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4577. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4578. {
  4579. enumCount = -fieldInstance->mDataIdx;
  4580. }
  4581. }
  4582. if (enumCount > 0)
  4583. {
  4584. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  4585. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  4586. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4587. {
  4588. BfFieldInstance* fieldInstance = &fieldRef;
  4589. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4590. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4591. {
  4592. int enumIdx = -fieldInstance->mDataIdx - 1;
  4593. if (fieldInstance->mResolvedType->mSize == 0)
  4594. {
  4595. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  4596. }
  4597. else
  4598. {
  4599. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  4600. mBfIRBuilder->SetInsertPoint(caseBlock);
  4601. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  4602. BfTypedValue leftTuple;
  4603. BfTypedValue rightTuple;
  4604. if (leftPayload.IsAddr())
  4605. {
  4606. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4607. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4608. }
  4609. else
  4610. {
  4611. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4612. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4613. }
  4614. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  4615. mBfIRBuilder->CreateBr(matchedBlock);
  4616. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  4617. }
  4618. }
  4619. }
  4620. mBfIRBuilder->AddBlock(matchedBlock);
  4621. mBfIRBuilder->SetInsertPoint(matchedBlock);
  4622. }
  4623. }
  4624. else if (compareTypeInst->IsUnion())
  4625. {
  4626. auto innerType = compareTypeInst->GetUnionInnerType();
  4627. if (!innerType->IsValuelessType())
  4628. {
  4629. BfExprEvaluator exprEvaluator(this);
  4630. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4631. leftTypedVal = AggregateSplat(leftTypedVal);
  4632. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  4633. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4634. rightTypedVal = AggregateSplat(rightTypedVal);
  4635. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  4636. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  4637. }
  4638. }
  4639. else
  4640. {
  4641. BfExprEvaluator exprEvaluator(this);
  4642. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4643. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4644. bool hadComparison = false;
  4645. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4646. {
  4647. BfFieldInstance* fieldInstance = &fieldRef;
  4648. if (fieldInstance->mDataOffset == -1)
  4649. continue;
  4650. if (fieldInstance->mResolvedType->IsValuelessType())
  4651. continue;
  4652. if (fieldInstance->mResolvedType->IsVar())
  4653. continue;
  4654. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4655. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4656. if (!fieldInstance->mResolvedType->IsComposite())
  4657. {
  4658. leftValue = LoadValue(leftValue);
  4659. rightValue = LoadValue(rightValue);
  4660. }
  4661. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4662. }
  4663. auto baseTypeInst = compareTypeInst->mBaseType;
  4664. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  4665. {
  4666. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  4667. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  4668. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4669. }
  4670. }
  4671. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4672. mBfIRBuilder->CreateBr(exitBB);
  4673. mBfIRBuilder->AddBlock(exitBB);
  4674. mBfIRBuilder->SetInsertPoint(exitBB);
  4675. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4676. ClearLifetimeEnds();
  4677. mBfIRBuilder->CreateRet(loadedResult);
  4678. mCurMethodState->mHadReturn = true;
  4679. }
  4680. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  4681. {
  4682. if (mBfIRBuilder->mIgnoreWrites)
  4683. return mBfIRBuilder->GetFakeVal();
  4684. PopulateType(typeInstance, mIsComptimeModule ? BfPopulateType_Data : BfPopulateType_DataAndMethods);
  4685. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4686. if (mIsComptimeModule)
  4687. {
  4688. auto idVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, typeInstance->mTypeId);
  4689. return mBfIRBuilder->CreateIntToPtr(idVal, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4690. }
  4691. BfIRValue* globalVariablePtr = NULL;
  4692. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  4693. int numElements = 1;
  4694. if (mSystem->mPtrSize == 4)
  4695. numElements++;
  4696. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  4697. {
  4698. numElements += mCompiler->mMaxInterfaceSlots;
  4699. auto maxIFaceVirtIdx = 0;
  4700. if (!typeInstance->IsInterface())
  4701. {
  4702. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4703. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4704. numElements += typeInstance->GetOrigVTableSize();
  4705. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  4706. if (typeInstance->mHotTypeData != NULL)
  4707. {
  4708. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4709. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4710. }
  4711. numElements += ifaceMethodLen;
  4712. }
  4713. if (outNumElements != NULL)
  4714. *outNumElements = numElements;
  4715. }
  4716. StringT<128> classVDataName;
  4717. String memberName = "sBfClassVData";
  4718. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  4719. {
  4720. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  4721. memberName += "_";
  4722. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  4723. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  4724. }
  4725. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  4726. if (outMangledName != NULL)
  4727. *outMangledName = classVDataName;
  4728. BfIRValue globalVariable;
  4729. if (globalVariablePtr != NULL)
  4730. {
  4731. globalVariable = *globalVariablePtr;
  4732. }
  4733. else
  4734. {
  4735. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4736. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4737. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4738. arrayType,
  4739. true,
  4740. BfIRLinkageType_External,
  4741. BfIRValue(),
  4742. classVDataName);
  4743. mClassVDataRefs[typeInstance] = globalVariable;
  4744. }
  4745. return globalVariable;
  4746. }
  4747. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4748. {
  4749. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4750. if (mIsComptimeModule)
  4751. return mBfIRBuilder->Comptime_GetBfType(typeInstance->mTypeId, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4752. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4753. }
  4754. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4755. {
  4756. if (mBfIRBuilder->mIgnoreWrites)
  4757. return mBfIRBuilder->GetFakeVal();
  4758. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4759. BF_ASSERT(numElements >= 0);
  4760. if (numElements <= 0)
  4761. return BfIRValue();
  4762. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4763. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4764. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4765. BF_ASSERT(declTypeInst == implTypeInst);
  4766. else
  4767. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4768. if (declTypeInst != implTypeInst)
  4769. {
  4770. BfTypeInstance* highestImpl = declTypeInst;
  4771. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4772. {
  4773. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4774. break; // Start of an ext entry for another type
  4775. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4776. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4777. highestImpl = checkImplTypeInst;
  4778. }
  4779. if (highestImpl != implTypeInst)
  4780. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4781. }
  4782. BfVDataExtEntry mapEntry;
  4783. mapEntry.mDeclTypeInst = declTypeInst;
  4784. mapEntry.mImplTypeInst = implTypeInst;
  4785. BfIRValue* irValuePtr = NULL;
  4786. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4787. return *irValuePtr;
  4788. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4789. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4790. StringT<512> classVDataName;
  4791. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4792. if (declTypeInst != implTypeInst)
  4793. {
  4794. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4795. }
  4796. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4797. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4798. SizedArray<BfIRValue, 32> vData;
  4799. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4800. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4801. {
  4802. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4803. break; // Start of an ext entry for another type
  4804. BfIRValue vValue;
  4805. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4806. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4807. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4808. {
  4809. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4810. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4811. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4812. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4813. {
  4814. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4815. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4816. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4817. vValue = funcPtr;
  4818. }
  4819. }
  4820. if (!vValue)
  4821. vValue = voidPtrNull;
  4822. vData.Add(vValue);
  4823. }
  4824. BF_ASSERT((int)vData.size() == numElements);
  4825. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4826. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4827. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4828. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4829. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4830. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, vData);
  4831. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4832. mClassVDataExtRefs[mapEntry] = globalVariable;
  4833. return globalVariable;
  4834. }
  4835. BfIRValue BfModule::CreateTypeDataRef(BfType* type, bool forceConstant)
  4836. {
  4837. if (mBfIRBuilder->mIgnoreWrites)
  4838. {
  4839. return mBfIRBuilder->CreateTypeOf(type);
  4840. }
  4841. if (mIsComptimeModule)
  4842. {
  4843. if (forceConstant)
  4844. return mBfIRBuilder->CreateTypeOfComptime(type);
  4845. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4846. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4847. return mBfIRBuilder->Comptime_GetReflectType(type->mTypeId, mBfIRBuilder->MapType(typeTypeInst));
  4848. }
  4849. PopulateType(type);
  4850. BfIRValue globalVariable;
  4851. BfIRValue* globalVariablePtr = NULL;
  4852. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  4853. {
  4854. if (*globalVariablePtr)
  4855. return mBfIRBuilder->CreateTypeOf(type, *globalVariablePtr);
  4856. }
  4857. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4858. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4859. auto typeInstance = type->ToTypeInstance();
  4860. StringT<4096> typeDataName;
  4861. if (typeInstance != NULL)
  4862. {
  4863. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4864. }
  4865. else
  4866. {
  4867. typeDataName += "sBfTypeData.";
  4868. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  4869. }
  4870. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  4871. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  4872. mBfIRBuilder->SetReflectTypeData(mBfIRBuilder->MapType(type), globalVariable);
  4873. mTypeDataRefs[type] = globalVariable;
  4874. return mBfIRBuilder->CreateTypeOf(type, globalVariable);
  4875. }
  4876. void BfModule::EncodeAttributeData(BfTypeInstance* typeInstance, BfType* argType, BfIRValue arg, SizedArrayImpl<uint8>& data, Dictionary<int, int>& usedStringIdMap)
  4877. {
  4878. #define PUSH_INT8(val) data.push_back((uint8)val)
  4879. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4880. #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); }
  4881. #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); \
  4882. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4883. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4884. bool handled = false;
  4885. if (constant == NULL)
  4886. {
  4887. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  4888. return;
  4889. }
  4890. if (argType->IsObject())
  4891. {
  4892. if ((argType->IsInstanceOf(mCompiler->mStringTypeDef)) || (argType == mContext->mBfObjectType))
  4893. {
  4894. if (constant->mTypeCode == BfTypeCode_StringId)
  4895. {
  4896. int stringId = constant->mInt32;
  4897. int* orderedIdPtr;
  4898. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4899. {
  4900. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4901. }
  4902. GetStringObjectValue(stringId, true, true);
  4903. PUSH_INT8(0xFF); // String
  4904. PUSH_INT32(*orderedIdPtr);
  4905. return;
  4906. }
  4907. }
  4908. }
  4909. if (argType->IsPointer())
  4910. {
  4911. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  4912. {
  4913. if (constant->mTypeCode == BfTypeCode_StringId)
  4914. {
  4915. int stringId = constant->mInt32;
  4916. int* orderedIdPtr;
  4917. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4918. {
  4919. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4920. }
  4921. GetStringObjectValue(stringId, true, true);
  4922. PUSH_INT8(0xFF); // String
  4923. PUSH_INT32(*orderedIdPtr);
  4924. return;
  4925. }
  4926. }
  4927. }
  4928. if (constant->mConstType == BfConstType_BitCastNull)
  4929. {
  4930. PUSH_INT8(BfTypeCode_NullPtr);
  4931. return;
  4932. }
  4933. if (constant->mConstType == BfConstType_BitCast)
  4934. {
  4935. auto bitcast = (BfConstantBitCast*)constant;
  4936. EncodeAttributeData(typeInstance, argType, BfIRValue(BfIRValueFlags_Const, bitcast->mTarget), data, usedStringIdMap);
  4937. return;
  4938. }
  4939. PUSH_INT8(constant->mTypeCode);
  4940. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4941. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4942. (constant->mTypeCode == BfTypeCode_Double))
  4943. {
  4944. PUSH_INT64(constant->mInt64);
  4945. }
  4946. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4947. (constant->mTypeCode == BfTypeCode_UInt32) ||
  4948. (constant->mTypeCode == BfTypeCode_Char32))
  4949. {
  4950. PUSH_INT32(constant->mInt32);
  4951. }
  4952. else if (constant->mTypeCode == BfTypeCode_Float)
  4953. {
  4954. float val = (float)constant->mDouble;
  4955. PUSH_INT32(*(int*)&val);
  4956. }
  4957. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4958. (constant->mTypeCode == BfTypeCode_UInt16) ||
  4959. (constant->mTypeCode == BfTypeCode_Char16))
  4960. {
  4961. PUSH_INT16(constant->mInt16);
  4962. }
  4963. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4964. (constant->mTypeCode == BfTypeCode_UInt8) ||
  4965. (constant->mTypeCode == BfTypeCode_Boolean) ||
  4966. (constant->mTypeCode == BfTypeCode_Char8))
  4967. {
  4968. PUSH_INT8(constant->mInt8);
  4969. }
  4970. else if (constant->mConstType == BfConstType_TypeOf)
  4971. {
  4972. auto typeOf = (BfTypeOf_Const*)constant;
  4973. PUSH_INT32(typeOf->mType->mTypeId);
  4974. }
  4975. else if (constant->mConstType == BfConstType_AggZero)
  4976. {
  4977. for (int i = 0; i < argType->mSize; i++)
  4978. data.Add(0);
  4979. }
  4980. else if (constant->mConstType == BfConstType_Box)
  4981. {
  4982. auto box = (BfConstantBox*)constant;
  4983. PUSH_INT32(box->mToType.mId);
  4984. BfType* resultType = NULL;
  4985. if (box->mToType.mKind == BfIRTypeData::TypeKind_TypeId)
  4986. resultType = mContext->FindTypeById(box->mToType.mId);
  4987. if ((resultType != NULL) && (resultType->IsBoxed()))
  4988. {
  4989. auto boxedType = (BfBoxedType*)resultType;
  4990. int dataOffset = 0;
  4991. if (!boxedType->mFieldInstances.IsEmpty())
  4992. dataOffset = BF_MAX(boxedType->mFieldInstances.back().mDataOffset, 0);
  4993. int dataSize = boxedType->mInstSize - dataOffset;
  4994. for (int i = 0; i < dataSize; i++)
  4995. data.Add(0);
  4996. typeInstance->mConstHolder->WriteConstant(BfIRValue(BfIRValueFlags_Const, box->mTarget), &data[data.mSize - dataSize], boxedType->GetUnderlyingType());
  4997. return;
  4998. }
  4999. //int dataOffset =
  5000. //mBfIRBuilder->WriteConstant()
  5001. // BfType* resultType = NULL;
  5002. // if (box->mToType.mKind == BfIRTypeData::TypeKind_TypeId)
  5003. // resultType = mContext->FindTypeById(box->mToType.mId);
  5004. //
  5005. // if ((resultType != NULL) && (resultType->IsBoxed()))
  5006. // {
  5007. // auto boxedType = (BfBoxedType*)resultType;
  5008. // EncodeAttributeData(typeInstance, boxedType->GetUnderlyingType(), BfIRValue(BfIRValueFlags_Const, box->mTarget), data, usedStringIdMap);
  5009. // return;
  5010. // }
  5011. Fail(StrFormat("Unhandled constant box in '%s'", TypeToString(typeInstance).c_str()));
  5012. }
  5013. // else if (constant->mConstType == BfConstType_Agg)
  5014. // {
  5015. // BF_ASSERT(argType->IsComposite());
  5016. // if (argType->IsSizedArray())
  5017. // {
  5018. // auto argSizedArrayType = (BfSizedArrayType*)argType;
  5019. // }
  5020. // else
  5021. // {
  5022. // auto argTypeInstance = argType->ToTypeInstance();
  5023. // }
  5024. // }
  5025. else
  5026. {
  5027. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  5028. }
  5029. }
  5030. BfIRValue BfModule::CreateFieldData(BfFieldInstance* fieldInstance, int customAttrIdx)
  5031. {
  5032. bool isComptimeArg = mBfIRBuilder->mIgnoreWrites;
  5033. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5034. auto typeInstance = fieldInstance->mOwner;
  5035. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5036. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5037. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5038. BfType* typeIdType = intType;
  5039. BfTypeInstance* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef)->ToTypeInstance();
  5040. BfIRValue emptyValueType = mBfIRBuilder->mIgnoreWrites ?
  5041. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>()) :
  5042. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>());
  5043. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, !mIsComptimeModule);
  5044. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  5045. int typeId = 0;
  5046. auto fieldType = fieldInstance->GetResolvedType();
  5047. if (fieldType->IsGenericParam())
  5048. {
  5049. //TODO:
  5050. }
  5051. else
  5052. typeId = fieldType->mTypeId;
  5053. BfFieldFlags fieldFlags = (BfFieldFlags)0;
  5054. if (fieldDef->mProtection == BfProtection_Protected)
  5055. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Protected);
  5056. if (fieldDef->mProtection == BfProtection_Public)
  5057. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Public);
  5058. if (fieldDef->mIsStatic)
  5059. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Static);
  5060. if (fieldDef->mIsConst)
  5061. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Const);
  5062. if (fieldDef->IsEnumCaseEntry())
  5063. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_EnumCase);
  5064. if (fieldDef->mIsReadOnly)
  5065. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_ReadOnly);
  5066. if (fieldInstance->IsAppendedObject())
  5067. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Appended);
  5068. BfIRValue constValue;
  5069. BfIRValue constValue2;
  5070. if (fieldInstance->mIsEnumPayloadCase)
  5071. {
  5072. int tagId = -fieldInstance->mDataIdx - 1;
  5073. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, tagId);
  5074. }
  5075. else if (fieldInstance->GetFieldDef()->mIsConst)
  5076. {
  5077. if (fieldInstance->mConstIdx != -1)
  5078. {
  5079. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  5080. uint64 val = constant->mUInt64;
  5081. if (constant->mTypeCode == BfTypeCode_Float)
  5082. {
  5083. float f = (float)*(double*)&val;
  5084. val = *(uint32*)&f;
  5085. }
  5086. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5087. if (is32Bit)
  5088. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val >> 32);
  5089. }
  5090. }
  5091. else if (fieldInstance->GetFieldDef()->mIsStatic)
  5092. {
  5093. BfTypedValue refVal;
  5094. if (mIsComptimeModule)
  5095. {
  5096. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mFieldIdx);
  5097. }
  5098. else
  5099. {
  5100. refVal = ReferenceStaticField(fieldInstance);
  5101. }
  5102. if (refVal.mValue.IsConst())
  5103. {
  5104. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  5105. if (constant->mConstType == BfConstType_GlobalVar)
  5106. {
  5107. auto globalVar = (BfGlobalVar*)constant;
  5108. if (globalVar->mName[0] == '#')
  5109. refVal = BfTypedValue();
  5110. }
  5111. }
  5112. if (!isComptimeArg)
  5113. {
  5114. if (refVal.IsAddr())
  5115. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5116. else if ((fieldInstance->IsAppendedObject()) && (refVal))
  5117. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5118. }
  5119. }
  5120. if (!constValue)
  5121. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  5122. BfIRValue result;
  5123. if (is32Bit)
  5124. {
  5125. if (!constValue2)
  5126. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  5127. SizedArray<BfIRValue, 8> fieldVals =
  5128. {
  5129. emptyValueType,
  5130. fieldNameConst, // mName
  5131. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5132. constValue, // mData
  5133. constValue2, // mDataHi
  5134. GetConstValue(fieldFlags, shortType), // mFlags
  5135. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5136. };
  5137. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5138. result = isComptimeArg ?
  5139. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5140. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5141. }
  5142. else
  5143. {
  5144. SizedArray<BfIRValue, 8> fieldVals =
  5145. {
  5146. emptyValueType,
  5147. fieldNameConst, // mName
  5148. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5149. constValue, // mData
  5150. GetConstValue(fieldFlags, shortType), // mFlags
  5151. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5152. };
  5153. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5154. result = isComptimeArg ?
  5155. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5156. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5157. }
  5158. return result;
  5159. }
  5160. void BfModule::CreateSlotOfs(BfTypeInstance* typeInstance)
  5161. {
  5162. int virtSlotIdx = -1;
  5163. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5164. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5165. // For interfaces we ONLY emit the slot num
  5166. StringT<512> slotVarName;
  5167. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  5168. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  5169. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  5170. GetConstValue32(virtSlotIdx), slotVarName);
  5171. }
  5172. BfIRValue BfModule::GetTypeTypeData(BfType* type, BfCreateTypeDataContext& ctx, bool needsTypeData, bool wantsTypeDecl, bool needsTypeNames, int& typeFlags, int& typeCode)
  5173. {
  5174. BfTypeInstance* typeInstance = type->ToTypeInstance();
  5175. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  5176. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  5177. BfIRValue typeTypeData;
  5178. if (needsTypeData)
  5179. {
  5180. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  5181. BfTypeInstance* typeDataSource = NULL;
  5182. if (typeInstance != NULL)
  5183. {
  5184. if (typeInstance->IsUnspecializedType())
  5185. {
  5186. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  5187. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  5188. }
  5189. else if (typeInstance->IsArray())
  5190. {
  5191. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  5192. typeFlags |= BfTypeFlags_Array;
  5193. }
  5194. else if (typeInstance->IsGenericTypeInstance())
  5195. {
  5196. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  5197. typeFlags |= BfTypeFlags_SpecializedGeneric;
  5198. }
  5199. else
  5200. typeDataSource = typeInstanceTypeInstance;
  5201. }
  5202. else if (type->IsPointer())
  5203. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5204. else if (type->IsRef())
  5205. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5206. else if (type->IsSizedArray())
  5207. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5208. else if (type->IsConstExprValue())
  5209. typeDataSource = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5210. else if (type->IsGenericParam())
  5211. {
  5212. typeFlags |= BfTypeFlags_GenericParam;
  5213. typeDataSource = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5214. }
  5215. else
  5216. typeDataSource = mContext->mBfTypeType;
  5217. if (wantsTypeDecl)
  5218. {
  5219. typeDataSource = ResolveTypeDef(mCompiler->mTypeTypeDeclDef)->ToTypeInstance();
  5220. }
  5221. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type) && (!mIsComptimeModule))
  5222. {
  5223. CreateTypeData(typeDataSource, ctx, false, true, needsTypeNames, true);
  5224. }
  5225. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  5226. ctx.mReflectTypeSet.Add(typeDataSource);
  5227. }
  5228. else
  5229. {
  5230. //typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  5231. typeTypeData = mBfIRBuilder->CreateConstNull();
  5232. }
  5233. if (typeInstance != NULL)
  5234. {
  5235. BF_ASSERT((type->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || mIsComptimeModule);
  5236. typeCode = typeInstance->mTypeDef->mTypeCode;
  5237. if (typeInstance->IsBoxed())
  5238. typeCode = BfTypeCode_Object;
  5239. }
  5240. else if (type->IsPrimitiveType())
  5241. {
  5242. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  5243. typeCode = primType->mTypeDef->mTypeCode;
  5244. }
  5245. else if (type->IsPointer())
  5246. {
  5247. typeCode = BfTypeCode_Pointer;
  5248. typeFlags |= BfTypeFlags_Pointer;
  5249. }
  5250. else if (type->IsRef())
  5251. {
  5252. typeCode = BfTypeCode_Pointer;
  5253. typeFlags |= BfTypeFlags_Pointer;
  5254. }
  5255. if (type->IsObject())
  5256. {
  5257. typeFlags |= BfTypeFlags_Object;
  5258. if ((!wantsTypeDecl) && (typeInstance->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted))
  5259. {
  5260. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  5261. if ((methodInstance != NULL) && (methodInstance->GetOwner() != mContext->mBfObjectType))
  5262. typeFlags |= BfTypeFlags_HasDestructor;
  5263. }
  5264. }
  5265. if (type->IsStruct())
  5266. typeFlags |= BfTypeFlags_Struct;
  5267. if (type->IsInterface())
  5268. typeFlags |= BfTypeFlags_Interface;
  5269. if (type->IsBoxed())
  5270. {
  5271. typeFlags |= BfTypeFlags_Boxed;
  5272. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  5273. typeFlags |= BfTypeFlags_Pointer;
  5274. }
  5275. if (type->IsPrimitiveType())
  5276. typeFlags |= BfTypeFlags_Primitive;
  5277. if (type->IsTypedPrimitive())
  5278. typeFlags |= BfTypeFlags_TypedPrimitive;
  5279. if (type->IsTuple())
  5280. typeFlags |= BfTypeFlags_Tuple;
  5281. if (type->IsNullable())
  5282. typeFlags |= BfTypeFlags_Nullable;
  5283. if (type->IsSizedArray())
  5284. typeFlags |= BfTypeFlags_SizedArray;
  5285. if (type->IsConstExprValue())
  5286. typeFlags |= BfTypeFlags_ConstExpr;
  5287. if ((!wantsTypeDecl) && (type->IsSplattable()))
  5288. typeFlags |= BfTypeFlags_Splattable;
  5289. if (type->IsUnion())
  5290. typeFlags |= BfTypeFlags_Union;
  5291. if (type->IsDelegate())
  5292. typeFlags |= BfTypeFlags_Delegate;
  5293. if (type->IsFunction())
  5294. typeFlags |= BfTypeFlags_Function;
  5295. if ((!wantsTypeDecl) && (type->mDefineState != BfTypeDefineState_CETypeInit) && (type->WantsGCMarking()))
  5296. typeFlags |= BfTypeFlags_WantsMarking;
  5297. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsStatic))
  5298. typeFlags |= BfTypeFlags_Static;
  5299. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  5300. typeFlags |= BfTypeFlags_Abstract;
  5301. return typeTypeData;
  5302. }
  5303. BfIRValue BfModule::CreateTypeDeclData(BfType* type, BfProject* curProject)
  5304. {
  5305. auto typeDeclType = ResolveTypeDef(mCompiler->mTypeTypeDeclDef)->ToTypeInstance();
  5306. int typeCode = 0;
  5307. int typeFlags = 0;
  5308. BfCreateTypeDataContext createTypeDataCtx;
  5309. BfIRValue typeTypeData = GetTypeTypeData(type, createTypeDataCtx, true, true, true, typeFlags, typeCode);
  5310. SizedArray<BfIRValue, 4> typeValueParams;
  5311. GetConstClassValueParam(typeTypeData, typeValueParams);
  5312. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5313. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5314. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5315. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5316. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5317. BfType* typeIdType = intType;
  5318. auto typeInst = type->ToTypeInstance();
  5319. auto outerType = GetOuterType(type);
  5320. BfType* baseType = NULL;
  5321. if (typeInst != NULL)
  5322. baseType = typeInst->mBaseType;
  5323. enum BfTypeDeclFlags
  5324. {
  5325. BfTypeDeclFlag_DeclaredInDependency = 1,
  5326. BfTypeDeclFlag_DeclaredInDependent = 2,
  5327. BfTypeDeclFlag_DeclaredInCurrent = 4,
  5328. BfTypeDeclFlag_AlwaysVisible = 8,
  5329. BfTypeDeclFlag_SometimesVisible = 0x10
  5330. };
  5331. int flags = 0;
  5332. if (typeInst != NULL)
  5333. {
  5334. auto declProject = typeInst->mTypeDef->mProject;
  5335. auto depKind = curProject->GetDependencyKind(declProject);
  5336. if (depKind == BfProject::DependencyKind_Identity)
  5337. {
  5338. flags |= BfTypeDeclFlag_DeclaredInCurrent | BfTypeDeclFlag_AlwaysVisible | BfTypeDeclFlag_SometimesVisible;
  5339. }
  5340. else if (depKind == BfProject::DependencyKind_Dependency)
  5341. {
  5342. flags |= BfTypeDeclFlag_DeclaredInDependency | BfTypeDeclFlag_AlwaysVisible | BfTypeDeclFlag_SometimesVisible;
  5343. }
  5344. else if (depKind == BfProject::DependencyKind_Dependent_Exclusive)
  5345. {
  5346. flags |= BfTypeDeclFlag_DeclaredInDependent | BfTypeDeclFlag_AlwaysVisible | BfTypeDeclFlag_SometimesVisible;
  5347. }
  5348. else if (depKind == BfProject::DependencyKind_Dependent_Shared)
  5349. {
  5350. flags |= BfTypeDeclFlag_DeclaredInDependent | BfTypeDeclFlag_SometimesVisible;
  5351. }
  5352. }
  5353. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5354. SizedArray<BfIRValue, 9> typeDataParams =
  5355. {
  5356. objectData,
  5357. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5358. GetConstValue((outerType != NULL) ? outerType->mTypeId : 0, typeIdType), // mOuterTypeId
  5359. GetConstValue(typeFlags, intType), // mTypeFlags
  5360. GetConstValue(flags, byteType), // mFlags
  5361. GetConstValue(typeCode, byteType), // mTypeCode
  5362. };
  5363. FixConstValueParams(typeDeclType, typeDataParams);
  5364. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(typeDeclType, BfIRPopulateType_Full), typeDataParams);
  5365. String typeDataName = StrFormat("sBfTypeDeclData.%d", type->mTypeId);
  5366. BfIRValue typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeDeclType), true,
  5367. BfIRLinkageType_External, typeData, typeDataName);
  5368. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5369. return typeDataVar;
  5370. }
  5371. BfIRValue BfModule::CreateTypeData(BfType* type, BfCreateTypeDataContext& ctx, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  5372. {
  5373. if ((IsHotCompile()) && (!type->mDirty))
  5374. return BfIRValue();
  5375. BfIRValue* irValuePtr = NULL;
  5376. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  5377. {
  5378. return *irValuePtr;
  5379. }
  5380. BfTypeInstance* typeInstance = type->ToTypeInstance();
  5381. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  5382. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  5383. if (typeInstanceType == NULL)
  5384. {
  5385. AssertErrorState();
  5386. return BfIRValue();
  5387. }
  5388. int typeCode = BfTypeCode_None;
  5389. int typeFlags = 0;
  5390. BfIRValue typeTypeData = GetTypeTypeData(type, ctx, needsTypeData, false, needsTypeNames, typeFlags, typeCode);
  5391. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5392. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5393. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5394. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5395. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5396. BfType* typeIdType = intType;
  5397. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  5398. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  5399. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  5400. auto voidPtrNull = GetDefaultValue(voidPtrType);
  5401. SizedArray<BfIRValue, 4> typeValueParams;
  5402. GetConstClassValueParam(typeTypeData, typeValueParams);
  5403. FixConstValueParams(mContext->mBfObjectType, typeValueParams);
  5404. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5405. StringT<512> typeDataName;
  5406. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  5407. {
  5408. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  5409. if (typeInstance->mTypeDef->IsGlobalsContainer())
  5410. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  5411. }
  5412. else
  5413. {
  5414. typeDataName += "sBfTypeData.";
  5415. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  5416. }
  5417. int virtSlotIdx = -1;
  5418. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5419. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5420. int memberDataOffset = 0;
  5421. if (type->IsInterface())
  5422. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  5423. else if (typeInstance != NULL)
  5424. {
  5425. for (auto& fieldInstance : typeInstance->mFieldInstances)
  5426. {
  5427. if (fieldInstance.mDataOffset != -1)
  5428. {
  5429. memberDataOffset = fieldInstance.mDataOffset;
  5430. break;
  5431. }
  5432. }
  5433. }
  5434. int boxedTypeId = 0;
  5435. if ((type->IsValueType()) || (type->IsWrappableType()))
  5436. {
  5437. auto boxedType = CreateBoxedType(type, false);
  5438. if ((boxedType != NULL) && (boxedType->mIsReified))
  5439. boxedTypeId = boxedType->mTypeId;
  5440. }
  5441. int stackCount = 0;
  5442. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  5443. {
  5444. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5445. if (typeOptions->mAllocStackTraceDepth != -1)
  5446. stackCount = BF_MIN(0xFF, BF_MAX(0x01, typeOptions->mAllocStackTraceDepth));
  5447. }
  5448. SizedArray<BfIRValue, 9> typeDataParams =
  5449. {
  5450. objectData,
  5451. GetConstValue(type->mSize, intType), // mSize
  5452. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5453. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  5454. GetConstValue(typeFlags, intType), // mTypeFlags
  5455. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  5456. GetConstValue(typeCode, byteType), // mTypeCode
  5457. GetConstValue(type->mAlign, byteType), // mAlign
  5458. GetConstValue(stackCount, byteType), // mAllocStackCountOverride
  5459. };
  5460. FixConstValueParams(mContext->mBfTypeType, typeDataParams);
  5461. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  5462. if (typeInstance == NULL)
  5463. {
  5464. BfIRValue typeDataVar;
  5465. if (needsTypeData)
  5466. {
  5467. if (type->IsPointer())
  5468. {
  5469. auto pointerType = (BfPointerType*)type;
  5470. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  5471. {
  5472. typeData,
  5473. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  5474. };
  5475. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5476. FixConstValueParams(reflectPointerType, pointerTypeDataParms);
  5477. auto pointerTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  5478. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  5479. BfIRLinkageType_External, pointerTypeData, typeDataName);
  5480. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5481. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5482. }
  5483. else if (type->IsRef())
  5484. {
  5485. auto refType = (BfRefType*)type;
  5486. SizedArray<BfIRValue, 3> refTypeDataParms =
  5487. {
  5488. typeData,
  5489. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  5490. GetConstValue((int8)refType->mRefKind, byteType),
  5491. };
  5492. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5493. FixConstValueParams(reflectRefType, refTypeDataParms);
  5494. auto refTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  5495. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  5496. BfIRLinkageType_External, refTypeData, typeDataName);
  5497. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5498. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5499. }
  5500. else if (type->IsSizedArray())
  5501. {
  5502. auto sizedArrayType = (BfSizedArrayType*)type;
  5503. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  5504. {
  5505. typeData,
  5506. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  5507. GetConstValue(sizedArrayType->mElementCount, intType)
  5508. };
  5509. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5510. FixConstValueParams(reflectSizedArrayType, sizedArrayTypeDataParms);
  5511. auto sizedArrayTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  5512. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  5513. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  5514. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5515. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5516. }
  5517. else if (type->IsConstExprValue())
  5518. {
  5519. auto constExprType = (BfConstExprValueType*)type;
  5520. SizedArray<BfIRValue, 3> constExprTypeDataParms =
  5521. {
  5522. typeData,
  5523. GetConstValue(constExprType->mType->mTypeId, typeIdType),
  5524. GetConstValue(constExprType->mValue.mInt64, longType)
  5525. };
  5526. auto reflectConstExprType = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5527. FixConstValueParams(reflectConstExprType, constExprTypeDataParms);
  5528. auto ConstExprTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectConstExprType, BfIRPopulateType_Full), constExprTypeDataParms);
  5529. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectConstExprType), true,
  5530. BfIRLinkageType_External, ConstExprTypeData, typeDataName);
  5531. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5532. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5533. }
  5534. else if (type->IsGenericParam())
  5535. {
  5536. auto genericParamType = (BfGenericParamType*)type;
  5537. SizedArray<BfIRValue, 3> genericParamTypeDataParms =
  5538. {
  5539. typeData
  5540. };
  5541. auto reflectGenericParamType = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5542. FixConstValueParams(reflectGenericParamType, genericParamTypeDataParms);
  5543. auto genericParamTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectGenericParamType, BfIRPopulateType_Full), genericParamTypeDataParms);
  5544. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectGenericParamType), true,
  5545. BfIRLinkageType_External, genericParamTypeData, typeDataName);
  5546. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5547. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5548. }
  5549. else
  5550. {
  5551. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  5552. BfIRLinkageType_External, typeData, typeDataName);
  5553. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5554. }
  5555. }
  5556. else
  5557. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5558. mTypeDataRefs[type] = typeDataVar;
  5559. return typeDataVar;
  5560. }
  5561. // Reserve position
  5562. mTypeDataRefs[typeInstance] = BfIRValue();
  5563. if ((typeInstance->IsReified()) && (!mIsComptimeModule))
  5564. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5565. BfTypeDef* typeDef = typeInstance->mTypeDef;
  5566. StringT<512> mangledName;
  5567. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  5568. if (!mIsComptimeModule)
  5569. {
  5570. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5571. {
  5572. auto methodDef = typeDef->mMethods[methodIdx];
  5573. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  5574. if (methodInstance == NULL)
  5575. continue;
  5576. if (typeInstance->IsUnspecializedType())
  5577. continue;
  5578. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5579. {
  5580. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  5581. {
  5582. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  5583. // We need to create an empty thunk for this chained method
  5584. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  5585. mBfIRBuilder->SetActiveFunction(func);
  5586. auto block = mBfIRBuilder->CreateBlock("entry", true);
  5587. mBfIRBuilder->SetInsertPoint(block);
  5588. mBfIRBuilder->CreateRetVoid();
  5589. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  5590. }
  5591. }
  5592. }
  5593. }
  5594. SizedArray<BfIRValue, 32> vData;
  5595. BfIRValue classVDataVar;
  5596. String classVDataName;
  5597. if (typeInstance->mSlotNum >= 0)
  5598. {
  5599. CreateSlotOfs(typeInstance);
  5600. }
  5601. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  5602. {
  5603. int dynCastDataElems = 0;
  5604. int numElements = 1;
  5605. int vDataOfs = mCompiler->GetVDataPrefixDataCount(); // The number of intptrs before the iface slot map
  5606. numElements += mCompiler->mMaxInterfaceSlots;
  5607. if (!typeInstance->IsInterface())
  5608. {
  5609. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  5610. numElements += mCompiler->GetDynCastVDataCount();
  5611. numElements += typeInstance->mVirtualMethodTableSize;
  5612. }
  5613. int expectNumElements = 0;
  5614. if (!typeDef->mIsStatic)
  5615. {
  5616. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  5617. }
  5618. for (int i = 0; i < mCompiler->GetVDataPrefixDataCount(); i++)
  5619. vData.push_back(BfIRValue()); // Type
  5620. SizedArray<BfIRValue, 1> extVTableData;
  5621. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  5622. if (!typeInstance->IsInterface())
  5623. {
  5624. Array<int32> dynCastData;
  5625. if (typeInstance->IsBoxed())
  5626. {
  5627. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  5628. dynCastData.Add(underlyingType->mInheritanceId);
  5629. }
  5630. else
  5631. dynCastData.Add(typeInstance->mInheritanceId);
  5632. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  5633. dynCastData.Add(0);
  5634. dynCastData.Add(0);
  5635. auto checkTypeInst = typeInstance;
  5636. while (checkTypeInst != NULL)
  5637. {
  5638. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5639. {
  5640. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  5641. {
  5642. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  5643. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  5644. }
  5645. }
  5646. checkTypeInst = checkTypeInst->GetImplBaseType();
  5647. }
  5648. if (mSystem->mPtrSize == 8)
  5649. {
  5650. int intPtrCount = (dynCastDataElems + 1) / 2;
  5651. vDataOfs += intPtrCount;
  5652. uint64* intPtrData = (uint64*)&dynCastData[0];
  5653. for (int i = 0; i < intPtrCount; i++)
  5654. {
  5655. uint64 val = intPtrData[i];
  5656. if (val == 0)
  5657. {
  5658. vData.push_back(voidPtrNull);
  5659. }
  5660. else
  5661. {
  5662. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5663. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5664. }
  5665. }
  5666. }
  5667. else
  5668. {
  5669. int intPtrCount = dynCastDataElems;
  5670. vDataOfs += intPtrCount;
  5671. uint32* intPtrData = (uint32*)&dynCastData[0];
  5672. for (int i = 0; i < intPtrCount; i++)
  5673. {
  5674. uint32 val = intPtrData[i];
  5675. if (val == 0)
  5676. {
  5677. vData.push_back(voidPtrNull);
  5678. }
  5679. else
  5680. {
  5681. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  5682. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5683. }
  5684. }
  5685. }
  5686. }
  5687. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  5688. vData.push_back(voidPtrNull);
  5689. struct _InterfaceMatchEntry
  5690. {
  5691. BfTypeInterfaceEntry* mEntry;
  5692. BfTypeInstance* mEntrySource;
  5693. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  5694. };
  5695. int highestIFaceVirtIdx = 0;
  5696. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  5697. auto checkTypeInst = typeInstance;
  5698. bool forceInterfaceSet = false;
  5699. while (checkTypeInst != NULL)
  5700. {
  5701. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5702. {
  5703. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  5704. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject)))
  5705. continue;
  5706. _InterfaceMatchEntry* matchEntry = NULL;
  5707. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  5708. {
  5709. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  5710. if (compareCheckTypeInst->IsBoxed())
  5711. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  5712. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  5713. if (compareEntrySource->IsBoxed())
  5714. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  5715. auto prevEntry = matchEntry->mEntry;
  5716. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  5717. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  5718. if ((!isBetter) && (!isWorse))
  5719. {
  5720. // Unboxed comparison to Object fix
  5721. if (compareCheckTypeInst == mContext->mBfObjectType)
  5722. isWorse = true;
  5723. else if (compareEntrySource == mContext->mBfObjectType)
  5724. isBetter = true;
  5725. }
  5726. if (forceInterfaceSet)
  5727. {
  5728. isBetter = true;
  5729. isWorse = false;
  5730. }
  5731. if (isBetter == isWorse)
  5732. CompareDeclTypes(checkTypeInst, interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  5733. if (isBetter == isWorse)
  5734. {
  5735. if (matchEntry->mAmbiguousEntries.empty())
  5736. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  5737. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  5738. continue;
  5739. }
  5740. else if (isBetter)
  5741. {
  5742. matchEntry->mEntry = &interfaceEntry;
  5743. matchEntry->mEntrySource = checkTypeInst;
  5744. matchEntry->mAmbiguousEntries.Clear();
  5745. }
  5746. else
  5747. continue;
  5748. }
  5749. else
  5750. {
  5751. _InterfaceMatchEntry matchEntry;
  5752. matchEntry.mEntry = &interfaceEntry;
  5753. matchEntry.mEntrySource = checkTypeInst;
  5754. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  5755. }
  5756. }
  5757. checkTypeInst = checkTypeInst->GetImplBaseType();
  5758. }
  5759. for (auto interfacePair : interfaceMap)
  5760. {
  5761. auto& interfaceMatchEntry = interfacePair.mValue;
  5762. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  5763. {
  5764. 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());
  5765. if (error != NULL)
  5766. {
  5767. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  5768. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  5769. }
  5770. }
  5771. }
  5772. if ((!mIsComptimeModule) && (!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  5773. {
  5774. int startTabIdx = (int)vData.size();
  5775. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  5776. BfTypeInstance* checkTypeInst = typeInstance;
  5777. while (checkTypeInst != NULL)
  5778. {
  5779. origVirtTypeStack.push_back(checkTypeInst);
  5780. checkTypeInst = checkTypeInst->GetImplBaseType();
  5781. }
  5782. Array<BfVirtualMethodEntry> origVTable;
  5783. int origVirtIdx = 0;
  5784. if (typeInstance->mTypeDef->mIsCombinedPartial)
  5785. {
  5786. HashSet<String> reslotNames;
  5787. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5788. {
  5789. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5790. if (entry.mDeclaringMethod.mMethodNum == -1)
  5791. continue;
  5792. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5793. if ((methodInstance == NULL) ||
  5794. ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))))
  5795. {
  5796. if (origVTable.empty())
  5797. origVTable = typeInstance->mVirtualMethodTable;
  5798. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  5799. if (declMethodInstance != NULL)
  5800. {
  5801. if ((mIsComptimeModule) || (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject)))
  5802. {
  5803. // Prepare to reslot...
  5804. entry.mImplementingMethod = entry.mDeclaringMethod;
  5805. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  5806. }
  5807. else
  5808. {
  5809. // Decl isn't accessible, null out entry
  5810. entry.mImplementingMethod = BfMethodRef();
  5811. }
  5812. }
  5813. }
  5814. }
  5815. if (!reslotNames.IsEmpty())
  5816. {
  5817. BfAmbiguityContext ambiguityContext;
  5818. ambiguityContext.mTypeInstance = typeInstance;
  5819. ambiguityContext.mModule = this;
  5820. ambiguityContext.mIsProjectSpecific = true;
  5821. ambiguityContext.mIsReslotting = true;
  5822. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5823. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  5824. {
  5825. auto methodInstance = methodGroup.mDefault;
  5826. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  5827. continue;
  5828. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  5829. continue;
  5830. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  5831. continue;
  5832. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  5833. continue;
  5834. SlotVirtualMethod(methodInstance, &ambiguityContext);
  5835. }
  5836. ambiguityContext.Finish();
  5837. }
  5838. }
  5839. bool isInExts = false;
  5840. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5841. {
  5842. BfIRValue vValue = voidPtrNull;
  5843. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5844. BfModuleMethodInstance moduleMethodInst;
  5845. if (entry.mDeclaringMethod.mMethodNum == -1)
  5846. {
  5847. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  5848. isInExts = true;
  5849. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  5850. if (vExt)
  5851. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  5852. }
  5853. else
  5854. {
  5855. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  5856. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  5857. {
  5858. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  5859. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  5860. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5861. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5862. {
  5863. BF_ASSERT((mIsComptimeModule) || typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  5864. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5865. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5866. vValue = funcPtr;
  5867. }
  5868. }
  5869. }
  5870. while (origVirtTypeStack.size() != 0)
  5871. {
  5872. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  5873. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  5874. {
  5875. // Moved past current base vtable size
  5876. origVirtTypeStack.pop_back();
  5877. continue;
  5878. }
  5879. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  5880. {
  5881. // We are within the original vtable size
  5882. int idx = startTabIdx + origVirtIdx;
  5883. origVirtIdx++;
  5884. vData.push_back(vValue);
  5885. }
  5886. else
  5887. {
  5888. // This is a new entry, it only gets added to the ext
  5889. BF_ASSERT(isInExts);
  5890. }
  5891. break;
  5892. }
  5893. }
  5894. if (!origVTable.empty())
  5895. typeInstance->mVirtualMethodTable = origVTable;
  5896. }
  5897. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  5898. if (typeInstance->mHotTypeData != NULL)
  5899. {
  5900. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  5901. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  5902. }
  5903. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  5904. int iFaceMethodStartIdx = (int)vData.size();
  5905. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  5906. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  5907. vData[i] = voidPtrNull;
  5908. if (expectNumElements != 0)
  5909. BF_ASSERT(expectNumElements == vData.size());
  5910. //BF_ASSERT(vData.size() == expectNumElements);
  5911. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  5912. // ifaceMethodExtData.Add(voidPtrNull);
  5913. int ifaceEntryIdx = iFaceMethodStartIdx;
  5914. for (auto& interfacePair : interfaceMap)
  5915. {
  5916. auto interfaceEntry = interfacePair.mValue.mEntry;
  5917. if (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  5918. {
  5919. BF_ASSERT(mIsComptimeModule);
  5920. break;
  5921. }
  5922. bool makeEmpty = false;
  5923. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject)))
  5924. makeEmpty = true;
  5925. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5926. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  5927. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5928. {
  5929. BfIRValue pushValue;
  5930. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5931. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5932. continue;
  5933. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5934. continue;
  5935. if (makeEmpty)
  5936. {
  5937. pushValue = voidPtrNull;
  5938. }
  5939. else
  5940. {
  5941. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5942. auto methodInstance = (BfMethodInstance*)methodRef;
  5943. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5944. {
  5945. BF_ASSERT(methodInstance->mIsReified);
  5946. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5947. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5948. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5949. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5950. pushValue = funcPtr;
  5951. }
  5952. else
  5953. {
  5954. pushValue = voidPtrNull;
  5955. }
  5956. }
  5957. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5958. if (idx < ifaceMethodExtStart)
  5959. {
  5960. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  5961. vData[iFaceMethodStartIdx + idx] = pushValue;
  5962. }
  5963. else
  5964. {
  5965. BF_ASSERT(useExt);
  5966. int extIdx = idx - ifaceMethodExtStart;
  5967. while (extIdx >= ifaceMethodExtData.size())
  5968. ifaceMethodExtData.Add(voidPtrNull);
  5969. ifaceMethodExtData[extIdx] = pushValue;
  5970. }
  5971. }
  5972. }
  5973. if (typeInstance->IsBoxed())
  5974. {
  5975. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  5976. if (boxedType->IsBoxedStructPtr())
  5977. {
  5978. // Force override of GetHashCode so we use the pointer address as the hash code
  5979. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  5980. // Force override of GetHashCode so we use the pointer address as the hash code
  5981. for (auto& checkIFace : checkTypeInst->mInterfaces)
  5982. {
  5983. if (checkIFace.mStartVirtualIdx < 0)
  5984. continue;
  5985. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5986. {
  5987. BfIRValue pushValue;
  5988. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5989. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5990. continue;
  5991. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5992. continue;
  5993. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5994. auto methodInstance = (BfMethodInstance*)methodRef;
  5995. BF_ASSERT(methodInstance->mIsReified);
  5996. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5997. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5998. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5999. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  6000. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  6001. vData[iFaceMethodStartIdx + idx] = funcPtr;
  6002. }
  6003. }
  6004. }
  6005. }
  6006. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic) && (!mIsComptimeModule))
  6007. {
  6008. BfIRValue ifaceMethodExtVar;
  6009. if ((!ifaceMethodExtData.IsEmpty()) && (!mIsComptimeModule))
  6010. {
  6011. StringT<512> classVDataName;
  6012. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  6013. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  6014. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  6015. BfIRLinkageType_External, BfIRValue(), classVDataName);
  6016. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  6017. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, ifaceMethodExtData);
  6018. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  6019. }
  6020. for (auto& ifaceInstPair : interfaceMap)
  6021. {
  6022. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  6023. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  6024. if (slotNum >= 0)
  6025. {
  6026. BfIRValue vtablePtr;
  6027. int idx = interfaceEntry->mStartVirtualIdx;
  6028. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  6029. if ((endVirtualIdx > ifaceMethodExtStart) && (ifaceMethodExtVar))
  6030. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  6031. else
  6032. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  6033. int slotVirtIdx = slotNum + vDataOfs;
  6034. if (vData[slotVirtIdx] == voidPtrNull)
  6035. {
  6036. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  6037. }
  6038. else
  6039. {
  6040. if (mCompiler->IsHotCompile())
  6041. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  6042. else
  6043. Fail("Interface slot collision error", typeDef->GetRefNode());
  6044. }
  6045. }
  6046. }
  6047. }
  6048. }
  6049. BfIRValue typeNameConst;
  6050. BfIRValue namespaceConst;
  6051. if (needsTypeNames)
  6052. {
  6053. typeNameConst = GetStringObjectValue(typeDef->mName->mString, !mIsComptimeModule);
  6054. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), !mIsComptimeModule);
  6055. }
  6056. else
  6057. {
  6058. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  6059. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  6060. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  6061. }
  6062. int baseTypeId = 0;
  6063. if (typeInstance->mBaseType != NULL)
  6064. {
  6065. baseTypeId = typeInstance->mBaseType->mTypeId;
  6066. }
  6067. BfTypeOptions* typeOptions = NULL;
  6068. if (typeInstance->mTypeOptionsIdx >= 0)
  6069. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6070. SizedArray<BfIRValue, 16> customAttrs;
  6071. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  6072. BfIRValue castedClassVData;
  6073. if (classVDataVar)
  6074. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  6075. else
  6076. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  6077. bool freflectIncludeTypeData = false;
  6078. bool reflectIncludeAllFields = false;
  6079. bool reflectIncludeAllMethods = false;
  6080. if (TypeIsSubTypeOf(typeInstance, attributeType))
  6081. {
  6082. reflectIncludeAllFields = true;
  6083. reflectIncludeAllMethods = true;
  6084. }
  6085. if (typeInstance->IsTuple())
  6086. {
  6087. // Required to generate tuple name at runtime
  6088. reflectIncludeAllFields = true;
  6089. }
  6090. BfReflectKind reflectKind = BfReflectKind_Type;
  6091. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  6092. {
  6093. BfReflectKind reflectKind = BfReflectKind_None;
  6094. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  6095. if (customAttrs != NULL)
  6096. {
  6097. for (auto& attr : customAttrs->mAttributes)
  6098. {
  6099. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  6100. }
  6101. delete customAttrs;
  6102. }
  6103. return reflectKind;
  6104. };
  6105. reflectKind = GetReflectKind(reflectKind, typeInstance);
  6106. // Fields
  6107. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  6108. BfIRValue emptyValueType = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  6109. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  6110. {
  6111. if (customAttributes == NULL)
  6112. return -1;
  6113. Array<BfCustomAttribute*> reflectAttributes;
  6114. for (auto& attr : customAttributes->mAttributes)
  6115. {
  6116. bool wantAttribute = false;
  6117. if (attr.mType->mCustomAttributes != NULL)
  6118. {
  6119. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  6120. if (usageAttribute != NULL)
  6121. {
  6122. // Check for Flags arg
  6123. if (usageAttribute->mCtorArgs.size() < 2)
  6124. continue;
  6125. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  6126. if (constant == NULL)
  6127. continue;
  6128. if (constant->mTypeCode == BfTypeCode_Boolean)
  6129. continue;
  6130. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  6131. wantAttribute = true;
  6132. }
  6133. }
  6134. if ((wantAttribute) && (attr.mType->mIsReified))
  6135. {
  6136. reflectAttributes.Add(&attr);
  6137. }
  6138. }
  6139. if (reflectAttributes.size() == 0)
  6140. return -1;
  6141. #define PUSH_INT8(val) data.push_back((uint8)val)
  6142. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  6143. #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); }
  6144. SizedArray<uint8, 16> data;
  6145. int customAttrIdx = (int)customAttrs.size();
  6146. data.push_back((uint8)reflectAttributes.size());
  6147. for (auto attr : reflectAttributes)
  6148. {
  6149. // Size prefix
  6150. int sizeIdx = (int)data.size();
  6151. PUSH_INT16(0); // mSize
  6152. PUSH_INT32(attr->mType->mTypeId); // mType
  6153. int ctorIdx = -1;
  6154. int ctorCount = 0;
  6155. attr->mType->mTypeDef->PopulateMemberSets();
  6156. BfMemberSetEntry* entry;
  6157. if (attr->mType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  6158. {
  6159. BfMethodDef* nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6160. while (nextMethodDef != NULL)
  6161. {
  6162. if (nextMethodDef == attr->mCtor)
  6163. ctorIdx = ctorCount;
  6164. nextMethodDef = nextMethodDef->mNextWithSameName;
  6165. ctorCount++;
  6166. }
  6167. }
  6168. BF_ASSERT(ctorIdx != -1);
  6169. if (ctorIdx != -1)
  6170. ctorIdx = (ctorCount - 1) - ctorIdx;
  6171. PUSH_INT16(ctorIdx);
  6172. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  6173. int argIdx = 0;
  6174. for (auto arg : attr->mCtorArgs)
  6175. {
  6176. auto argType = ctorMethodInstance->GetParamType(argIdx);
  6177. EncodeAttributeData(typeInstance, argType, arg, data, ctx.mUsedStringIdMap);
  6178. argIdx++;
  6179. }
  6180. int size = (int)data.size() - sizeIdx;
  6181. *((uint16*)&data[sizeIdx]) = size;
  6182. }
  6183. #undef PUSH_INT8
  6184. #undef PUSH_INT16
  6185. #undef PUSH_INT32
  6186. SizedArray<BfIRValue, 16> dataValues;
  6187. for (uint8 val : data)
  6188. dataValues.push_back(GetConstValue8(val));
  6189. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  6190. auto customAttrConst = mBfIRBuilder->CreateConstAgg_Value(dataArrayType, dataValues);
  6191. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  6192. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  6193. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  6194. customAttrs.push_back(customAttrArrayPtr);
  6195. return customAttrIdx;
  6196. };
  6197. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  6198. SizedArray<int, 16> reflectFieldIndices;
  6199. for (int pass = 0; pass < 2; pass++)
  6200. {
  6201. bool skippedField = false;
  6202. reflectFieldIndices.clear();
  6203. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  6204. {
  6205. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6206. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  6207. if (fieldDef == NULL)
  6208. continue;
  6209. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6210. bool includeField = reflectIncludeAllFields;
  6211. if (fieldInstance->mCustomAttributes != NULL)
  6212. {
  6213. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  6214. {
  6215. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6216. {
  6217. includeField = true;
  6218. }
  6219. else
  6220. {
  6221. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6222. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  6223. }
  6224. }
  6225. }
  6226. if ((fieldReflectKind & BfReflectKind_User) != 0)
  6227. includeField = true;
  6228. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  6229. includeField = true;
  6230. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  6231. includeField = true;
  6232. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  6233. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  6234. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  6235. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  6236. includeField |= forceReflectFields;
  6237. if (!includeField)
  6238. {
  6239. skippedField = true;
  6240. continue;
  6241. }
  6242. reflectFieldIndices.Add(fieldIdx);
  6243. }
  6244. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  6245. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  6246. // possible because we write out a SplatData structure containing just TypeIds in that case
  6247. if (pass == 0)
  6248. {
  6249. if (!typeInstance->IsSplattable())
  6250. break;
  6251. if (!skippedField)
  6252. break;
  6253. if (reflectFieldIndices.size() == 0)
  6254. break;
  6255. }
  6256. }
  6257. SizedArray<BfIRValue, 16> fieldTypes;
  6258. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  6259. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  6260. {
  6261. BfType* payloadType = typeInstance->GetUnionInnerType();
  6262. if (!payloadType->IsValuelessType())
  6263. {
  6264. BfIRValue payloadNameConst = GetStringObjectValue("$payload", !mIsComptimeModule);
  6265. SizedArray<BfIRValue, 8> payloadFieldVals;
  6266. if (is32Bit)
  6267. {
  6268. payloadFieldVals =
  6269. {
  6270. emptyValueType,
  6271. payloadNameConst, // mName
  6272. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6273. GetConstValue(0, intPtrType), // mData
  6274. GetConstValue(0, intPtrType), // mDataHi
  6275. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6276. GetConstValue(-1, intType), // mCustomAttributesIdx
  6277. };
  6278. }
  6279. else
  6280. {
  6281. payloadFieldVals =
  6282. {
  6283. emptyValueType,
  6284. payloadNameConst, // mName
  6285. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6286. GetConstValue(0, intPtrType), // mData
  6287. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6288. GetConstValue(-1, intType), // mCustomAttributesIdx
  6289. };
  6290. }
  6291. FixConstValueParams(reflectFieldDataType->ToTypeInstance(), payloadFieldVals);
  6292. auto payloadFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  6293. fieldTypes.push_back(payloadFieldData);
  6294. }
  6295. BfType* dscrType = typeInstance->GetDiscriminatorType();
  6296. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", !mIsComptimeModule);
  6297. SizedArray<BfIRValue, 8> dscrFieldVals;
  6298. if (is32Bit)
  6299. {
  6300. dscrFieldVals =
  6301. {
  6302. emptyValueType,
  6303. dscrNameConst, // mName
  6304. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6305. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6306. GetConstValue(0, intPtrType), // mDataHi
  6307. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6308. GetConstValue(-1, intType), // mCustomAttributesIdx
  6309. };
  6310. }
  6311. else
  6312. {
  6313. dscrFieldVals =
  6314. {
  6315. emptyValueType,
  6316. dscrNameConst, // mName
  6317. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6318. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6319. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6320. GetConstValue(-1, intType), // mCustomAttributesIdx
  6321. };
  6322. }
  6323. auto dscrFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  6324. fieldTypes.push_back(dscrFieldData);
  6325. }
  6326. for (auto fieldIdx : reflectFieldIndices)
  6327. {
  6328. if (!needsTypeData)
  6329. break;
  6330. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6331. fieldTypes.push_back(CreateFieldData(fieldInstance, _HandleCustomAttrs(fieldInstance->mCustomAttributes)));
  6332. }
  6333. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  6334. BfIRValue fieldDataPtr;
  6335. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  6336. if (fieldTypes.size() == 0)
  6337. {
  6338. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  6339. {
  6340. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  6341. SizedArray<BfIRValue, 3> splatTypes;
  6342. SizedArray<BfIRValue, 3> splatOffsets;
  6343. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  6344. {
  6345. auto checkTypeInstance = checkType->ToTypeInstance();
  6346. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  6347. PopulateType(checkTypeInstance);
  6348. if (checkType->IsStruct())
  6349. {
  6350. int dataEnd = offset;
  6351. if (checkTypeInstance->mBaseType != NULL)
  6352. _CheckSplat(checkTypeInstance->mBaseType, offset);
  6353. if (checkTypeInstance->mIsUnion)
  6354. {
  6355. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  6356. _CheckSplat(unionInnerType, offset);
  6357. }
  6358. else
  6359. {
  6360. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  6361. {
  6362. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  6363. if (fieldInstance->mDataIdx >= 0)
  6364. {
  6365. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  6366. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  6367. }
  6368. }
  6369. }
  6370. if (checkTypeInstance->IsEnum())
  6371. {
  6372. // Add discriminator
  6373. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  6374. if (checkTypeInstance->mPacking > 0)
  6375. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  6376. _CheckSplat(dscrType, dataEnd);
  6377. }
  6378. }
  6379. else if (checkType->IsMethodRef())
  6380. {
  6381. // auto methodRefType = (BfMethodRefType*)checkType;
  6382. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6383. // {
  6384. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6385. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  6386. // else
  6387. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  6388. // }
  6389. }
  6390. else if (!checkType->IsValuelessType())
  6391. {
  6392. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  6393. splatOffsets.Add(GetConstValue(offset, intType));
  6394. }
  6395. };
  6396. _CheckSplat(type, 0);
  6397. while (splatTypes.size() < 3)
  6398. {
  6399. splatTypes.Add(GetConstValue(0, typeIdType));
  6400. splatOffsets.Add(GetConstValue(0, intType));
  6401. }
  6402. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  6403. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  6404. SizedArray<BfIRValue, 8> splatVals =
  6405. {
  6406. emptyValueType,
  6407. splatTypesConst,
  6408. splatOffsetsConst
  6409. };
  6410. auto fieldSplatData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  6411. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  6412. fieldSplatData, typeDataName + ".splats");
  6413. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6414. }
  6415. else
  6416. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  6417. }
  6418. else
  6419. {
  6420. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  6421. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstAgg_Value(fieldDataConstType, fieldTypes);
  6422. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  6423. fieldDataConst, "fields." + typeDataName);
  6424. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6425. }
  6426. /// Methods
  6427. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  6428. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  6429. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  6430. struct _SortedMethodInfo
  6431. {
  6432. BfMethodDef* mMethodDef;
  6433. BfMethodCustomAttributes* mMethodCustomAttributes;
  6434. };
  6435. Array<_SortedMethodInfo> sortedMethodList;
  6436. SizedArray<BfIRValue, 16> methodTypes;
  6437. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  6438. {
  6439. if (!needsTypeData)
  6440. break;
  6441. // Disable const method reflection info for now
  6442. if (mIsComptimeModule)
  6443. break;
  6444. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6445. if (!methodInstanceGroup->IsImplemented())
  6446. continue;
  6447. auto methodDef = typeDef->mMethods[methodIdx];
  6448. if (methodDef->mIsNoReflect)
  6449. continue;
  6450. if (methodDef->mHasComptime)
  6451. continue;
  6452. auto defaultMethod = methodInstanceGroup->mDefault;
  6453. if (defaultMethod == NULL)
  6454. continue;
  6455. if (defaultMethod->mIsUnspecialized)
  6456. continue;
  6457. if (!defaultMethod->mIsReified)
  6458. continue;
  6459. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  6460. continue;
  6461. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  6462. continue;
  6463. if (!defaultMethod->mMethodDef->CanReflect())
  6464. continue;
  6465. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6466. bool includeMethod = reflectIncludeAllMethods;
  6467. if (typeInstance->IsDelegateOrFunction())
  6468. includeMethod = true;
  6469. BfMethodCustomAttributes* methodCustomAttributes = NULL;
  6470. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  6471. {
  6472. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes;
  6473. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  6474. {
  6475. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6476. {
  6477. includeMethod = true;
  6478. }
  6479. else
  6480. {
  6481. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6482. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  6483. }
  6484. }
  6485. }
  6486. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject)))
  6487. continue;
  6488. //
  6489. {
  6490. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  6491. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  6492. {
  6493. BfTypeState typeState;
  6494. typeState.mPrevState = mContext->mCurTypeState;
  6495. typeState.mForceActiveTypeDef = methodDef->mDeclaringType;
  6496. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  6497. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  6498. {
  6499. if (paramDecl->mAttributes != NULL)
  6500. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  6501. }
  6502. }
  6503. }
  6504. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  6505. includeMethod = true;
  6506. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  6507. includeMethod = true;
  6508. if ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend))
  6509. {
  6510. if ((methodReflectKind & BfReflectKind_Constructors) != 0)
  6511. includeMethod = true;
  6512. if ((methodDef->IsDefaultCtor()) && ((methodReflectKind & BfReflectKind_DefaultConstructor) != 0))
  6513. includeMethod = true;
  6514. }
  6515. if ((!includeMethod) && (typeOptions != NULL))
  6516. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  6517. if (!includeMethod)
  6518. continue;
  6519. sortedMethodList.Add({ methodDef, methodCustomAttributes });
  6520. }
  6521. auto _GetMethodKind = [](BfMethodDef* methodDef)
  6522. {
  6523. if (methodDef->mMethodType == BfMethodType_Ctor)
  6524. return 0;
  6525. return 1;
  6526. };
  6527. std::sort(sortedMethodList.begin(), sortedMethodList.end(), [_GetMethodKind](const _SortedMethodInfo& lhs, const _SortedMethodInfo& rhs)
  6528. {
  6529. int lhsKind = _GetMethodKind(lhs.mMethodDef);
  6530. int rhsKind = _GetMethodKind(rhs.mMethodDef);
  6531. if (lhsKind != rhsKind)
  6532. return lhsKind < rhsKind;
  6533. if (lhs.mMethodDef->mName != rhs.mMethodDef->mName)
  6534. return lhs.mMethodDef->mName < rhs.mMethodDef->mName;
  6535. return lhs.mMethodDef->mIdx < rhs.mMethodDef->mIdx;
  6536. });
  6537. for (auto& methodInfo : sortedMethodList)
  6538. {
  6539. auto methodDef = methodInfo.mMethodDef;
  6540. int methodIdx = methodDef->mIdx;
  6541. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6542. auto defaultMethod = methodInstanceGroup->mDefault;
  6543. BfModuleMethodInstance moduleMethodInstance;
  6544. BfIRValue funcVal = voidPtrNull;
  6545. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  6546. (!typeInstance->IsUnspecializedType()) &&
  6547. (methodDef->mMethodType != BfMethodType_Ignore) &&
  6548. (methodDef->mMethodType != BfMethodType_Mixin) &&
  6549. (!methodDef->mIsAbstract) &&
  6550. (methodDef->mGenericParams.size() == 0))
  6551. {
  6552. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6553. if (moduleMethodInstance.mFunc)
  6554. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6555. }
  6556. BfIRValue methodNameConst = GetStringObjectValue(methodDef->GetReflectName(), !mIsComptimeModule);
  6557. BfMethodFlags methodFlags = defaultMethod->GetMethodFlags();
  6558. int customAttrIdx = -1;
  6559. int returnCustomAttrIdx = -1;
  6560. if (methodInfo.mMethodCustomAttributes != NULL)
  6561. {
  6562. customAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mCustomAttributes);
  6563. returnCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mReturnCustomAttributes);
  6564. }
  6565. enum ParamFlags
  6566. {
  6567. ParamFlag_None = 0,
  6568. ParamFlag_Splat = 1,
  6569. ParamFlag_Implicit = 2,
  6570. ParamFlag_AppendIdx = 4,
  6571. ParamFlag_Params = 8
  6572. };
  6573. SizedArray<BfIRValue, 8> paramVals;
  6574. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  6575. {
  6576. String paramName = defaultMethod->GetParamName(paramIdx);
  6577. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  6578. ParamFlags paramFlags = ParamFlag_None;
  6579. if (defaultMethod->GetParamIsSplat(paramIdx))
  6580. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  6581. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  6582. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Implicit | ParamFlag_AppendIdx);
  6583. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_Params)
  6584. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Params);
  6585. BfIRValue paramNameConst = GetStringObjectValue(paramName, !mIsComptimeModule);
  6586. int paramCustomAttrIdx = -1;
  6587. if ((methodInfo.mMethodCustomAttributes != NULL) && (paramIdx < (int)methodInfo.mMethodCustomAttributes->mParamCustomAttributes.mSize))
  6588. paramCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mParamCustomAttributes[paramIdx]);
  6589. SizedArray<BfIRValue, 8> paramDataVals =
  6590. {
  6591. emptyValueType,
  6592. paramNameConst,
  6593. GetConstValue(paramType->mTypeId, typeIdType),
  6594. GetConstValue((int32)paramFlags, shortType),
  6595. GetConstValue(-1, intType), // defaultIdx
  6596. GetConstValue(paramCustomAttrIdx, intType) // customAttrIdx
  6597. };
  6598. auto paramData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  6599. paramVals.Add(paramData);
  6600. }
  6601. BfIRValue paramsVal;
  6602. if (paramVals.size() > 0)
  6603. {
  6604. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  6605. BfIRValue paramDataConst = mBfIRBuilder->CreateConstAgg_Value(paramDataArrayType, paramVals);
  6606. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  6607. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  6608. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  6609. }
  6610. else
  6611. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  6612. int vDataVal = -1;
  6613. if (defaultMethod->mVirtualTableIdx != -1)
  6614. {
  6615. int vDataIdx = -1;
  6616. if (type->IsInterface())
  6617. {
  6618. vDataIdx = defaultMethod->mVirtualTableIdx;
  6619. }
  6620. else
  6621. {
  6622. vDataIdx = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  6623. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  6624. {
  6625. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  6626. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6627. if (extMethodIdx >= 0)
  6628. {
  6629. // Extension?
  6630. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6631. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  6632. }
  6633. else
  6634. {
  6635. // Map this new virtual index back to the original index
  6636. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  6637. }
  6638. }
  6639. else
  6640. {
  6641. vDataIdx += defaultMethod->mVirtualTableIdx;
  6642. }
  6643. }
  6644. if (vDataVal == -1)
  6645. vDataVal = vDataIdx * mSystem->mPtrSize;
  6646. }
  6647. SizedArray<BfIRValue, 8> methodDataVals =
  6648. {
  6649. emptyValueType,
  6650. methodNameConst, // mName
  6651. funcVal, // mFuncPtr
  6652. paramsVal,
  6653. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  6654. GetConstValue((int)paramVals.size(), shortType),
  6655. GetConstValue(methodFlags, shortType),
  6656. GetConstValue(methodIdx, intType),
  6657. GetConstValue(vDataVal, intType),
  6658. GetConstValue(customAttrIdx, intType),
  6659. GetConstValue(returnCustomAttrIdx, intType),
  6660. };
  6661. auto methodData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  6662. methodTypes.push_back(methodData);
  6663. }
  6664. BfIRValue methodDataPtr;
  6665. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  6666. if (methodTypes.size() == 0)
  6667. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  6668. else
  6669. {
  6670. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  6671. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methodTypes);
  6672. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6673. methodDataConst, "methods." + typeDataName);
  6674. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  6675. }
  6676. /////
  6677. int interfaceCount = 0;
  6678. BfIRValue interfaceDataPtr;
  6679. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  6680. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  6681. Array<bool> wantsIfaceMethod;
  6682. bool wantsIfaceMethods = false;
  6683. if ((typeInstance->mInterfaces.IsEmpty()) || (!needsTypeData))
  6684. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  6685. else
  6686. {
  6687. SizedArray<BfIRValue, 16> interfaces;
  6688. for (auto& interface : typeInstance->mInterfaces)
  6689. {
  6690. SizedArray<BfIRValue, 8> interfaceDataVals =
  6691. {
  6692. emptyValueType,
  6693. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  6694. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  6695. GetConstValue(interface.mStartVirtualIdx, intType),
  6696. };
  6697. auto interfaceData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  6698. interfaces.push_back(interfaceData);
  6699. if (!mIsComptimeModule)
  6700. {
  6701. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6702. {
  6703. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  6704. if (ifaceMethodGroup->mExplicitlyReflected)
  6705. {
  6706. wantsIfaceMethods = true;
  6707. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  6708. while (tableIdx >= wantsIfaceMethod.size())
  6709. wantsIfaceMethod.Add(false);
  6710. wantsIfaceMethod[tableIdx] = true;
  6711. }
  6712. }
  6713. }
  6714. }
  6715. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  6716. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstAgg_Value(interfaceDataArrayType, interfaces);
  6717. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  6718. interfaceDataConst, "interfaces." + typeDataName);
  6719. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  6720. interfaceCount = (int)interfaces.size();
  6721. }
  6722. BfIRValue interfaceMethodTable;
  6723. int ifaceMethodTableSize = 0;
  6724. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  6725. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  6726. {
  6727. SizedArray<BfIRValue, 16> methods;
  6728. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  6729. {
  6730. BfIRValue funcVal = voidPtrNull;
  6731. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  6732. {
  6733. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  6734. if (!methodEntry.mMethodRef.IsNull())
  6735. {
  6736. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  6737. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  6738. (!methodInstance->mMethodDef->mIsAbstract))
  6739. {
  6740. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  6741. if (moduleMethodInstance.mFunc)
  6742. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6743. }
  6744. }
  6745. }
  6746. methods.Add(funcVal);
  6747. }
  6748. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  6749. methods.pop_back();
  6750. if (!methods.IsEmpty())
  6751. {
  6752. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  6753. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methods);
  6754. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6755. methodDataConst, "imethods." + typeDataName);
  6756. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  6757. ifaceMethodTableSize = (int)methods.size();
  6758. }
  6759. }
  6760. if (!interfaceMethodTable)
  6761. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6762. /////
  6763. int underlyingType = 0;
  6764. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  6765. {
  6766. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  6767. }
  6768. int outerTypeId = 0;
  6769. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  6770. if (outerType != NULL)
  6771. {
  6772. outerTypeId = outerType->mTypeId;
  6773. }
  6774. //
  6775. BfIRValue customAttrDataPtr;
  6776. if (customAttrs.size() > 0)
  6777. {
  6778. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  6779. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstAgg_Value(customAttrsArrayType, customAttrs);
  6780. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  6781. customAttrsConst, "customAttrs." + typeDataName);
  6782. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  6783. }
  6784. else
  6785. {
  6786. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6787. }
  6788. SizedArray<BfIRValue, 32> typeDataVals =
  6789. {
  6790. typeData,
  6791. castedClassVData, // mTypeClassVData
  6792. typeNameConst, // mName
  6793. namespaceConst, // mNamespace
  6794. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  6795. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  6796. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  6797. GetConstValue(baseTypeId, typeIdType), // mBaseType
  6798. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  6799. GetConstValue(outerTypeId, typeIdType), // mOuterType
  6800. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  6801. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  6802. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  6803. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  6804. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  6805. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  6806. GetConstValue(0, shortType), // mPropertyDataCount
  6807. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  6808. interfaceDataPtr, // mInterfaceDataPtr
  6809. interfaceMethodTable, // mInterfaceMethodTable
  6810. methodDataPtr, // mMethodDataPtr
  6811. voidPtrNull, // mPropertyDataPtr
  6812. fieldDataPtr, // mFieldDataPtr
  6813. customAttrDataPtr, // mCustomAttrDataPtr
  6814. };
  6815. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  6816. FixConstValueParams(typeInstanceType->ToTypeInstance(), typeDataVals);
  6817. auto typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, typeDataVals);
  6818. if (!needsTypeData)
  6819. {
  6820. // No need for anything beyond typeInstanceData
  6821. }
  6822. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  6823. {
  6824. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6825. SizedArray<BfIRValue, 4> unspecializedData =
  6826. {
  6827. typeInstanceData,
  6828. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  6829. };
  6830. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  6831. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6832. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, unspecializedData);
  6833. }
  6834. else if (typeInstance->IsGenericTypeInstance())
  6835. {
  6836. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6837. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  6838. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef->GetDefinition());
  6839. SizedArray<BfIRValue, 4> resolvedTypes;
  6840. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  6841. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  6842. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  6843. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  6844. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  6845. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstAgg_Value(genericArrayType, resolvedTypes);
  6846. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  6847. resolvedTypesConst, "resolvedTypes." + typeDataName);
  6848. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  6849. SizedArray<BfIRValue, 3> specGenericData =
  6850. {
  6851. typeInstanceData,
  6852. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  6853. resovledTypesPtr, // mFieldDataPtr
  6854. };
  6855. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6856. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, specGenericData);
  6857. if (typeInstance->IsArray())
  6858. {
  6859. auto arrayType = (BfArrayType*)typeInstance;
  6860. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  6861. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  6862. SizedArray<BfIRValue, 4> arrayData =
  6863. {
  6864. typeInstanceData,
  6865. GetConstValue(elementType->mSize, intType), // mElementSize
  6866. GetConstValue(1, byteType), // mRank
  6867. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  6868. };
  6869. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  6870. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  6871. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, arrayData);
  6872. }
  6873. }
  6874. BfIRValue typeDataVar;
  6875. if (needsTypeData)
  6876. {
  6877. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  6878. BfIRLinkageType_External, typeInstanceData, typeDataName);
  6879. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  6880. if (mBfIRBuilder->DbgHasInfo())
  6881. {
  6882. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  6883. }
  6884. }
  6885. else
  6886. {
  6887. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  6888. }
  6889. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  6890. mTypeDataRefs[typeInstance] = typeDataVar;
  6891. if ((!mIsComptimeModule) && (classVDataVar))
  6892. {
  6893. BF_ASSERT(!classVDataName.IsEmpty());
  6894. //vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  6895. int unboxedTypeId = type->mTypeId;
  6896. if (type->IsBoxed())
  6897. unboxedTypeId = type->GetUnderlyingType()->mTypeId;
  6898. if (mSystem->mPtrSize == 4)
  6899. {
  6900. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(type->mTypeId, intPtrType), voidPtrIRType);
  6901. vData[1] = mBfIRBuilder->CreateIntToPtr(GetConstValue(unboxedTypeId, intPtrType), voidPtrIRType);
  6902. }
  6903. else
  6904. {
  6905. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(((int64)unboxedTypeId << 32) | type->mTypeId, intPtrType), voidPtrIRType);
  6906. }
  6907. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  6908. auto classVDataConstData = mBfIRBuilder->CreateConstAgg_Value(classVDataConstDataType, vData);
  6909. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  6910. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6911. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  6912. else
  6913. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  6914. if (mBfIRBuilder->DbgHasInfo())
  6915. {
  6916. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6917. BfType* voidPtrType = CreatePointerType(voidType);
  6918. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6919. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  6920. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  6921. }
  6922. }
  6923. return typeDataVar;
  6924. }
  6925. BfIRValue BfModule::FixClassVData(BfIRValue value)
  6926. {
  6927. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  6928. return value;
  6929. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  6930. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  6931. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  6932. }
  6933. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  6934. {
  6935. // Note: this is not just for perf, it fixes a field var-type resolution issue
  6936. if (mBfIRBuilder->mIgnoreWrites)
  6937. return;
  6938. if (mIsComptimeModule)
  6939. return;
  6940. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  6941. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  6942. // When we access classes with static constructors FROM a static constructor,
  6943. // we call that other class's static constructor first. Recursion cannot occur, since
  6944. // we simply ignore subsequent attempts to re-enter the constructor
  6945. if (!typeInstance->mHasStaticInitMethod)
  6946. return;
  6947. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  6948. return;
  6949. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  6950. return;
  6951. auto checkTypeDef = typeInstance->mTypeDef;
  6952. checkTypeDef->PopulateMemberSets();
  6953. BfMethodDef* nextMethodDef = NULL;
  6954. BfMemberSetEntry* entry;
  6955. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  6956. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6957. while (nextMethodDef != NULL)
  6958. {
  6959. auto checkMethod = nextMethodDef;
  6960. nextMethodDef = nextMethodDef->mNextWithSameName;
  6961. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  6962. if (methodModule)
  6963. {
  6964. auto methodInstance = methodModule.mMethodInstance;
  6965. if ((methodInstance != NULL) &&
  6966. (methodInstance->mMethodDef->mIsStatic) &&
  6967. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  6968. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  6969. {
  6970. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  6971. break;
  6972. }
  6973. }
  6974. }
  6975. }
  6976. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  6977. {
  6978. auto methodOwner = methodInstance->GetOwner();
  6979. auto methodDef = methodInstance->mMethodDef;
  6980. auto methodDeclaration = methodDef->GetMethodDeclaration();
  6981. if (!methodDef->mIsExtern)
  6982. return BfIRFunction();
  6983. if (methodInstance->GetCustomAttributes() == NULL)
  6984. return BfIRFunction();
  6985. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  6986. {
  6987. String typeName = TypeToString(customAttribute.mType);
  6988. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  6989. {
  6990. methodInstance->mIsIntrinsic = true;
  6991. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  6992. String error;
  6993. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  6994. {
  6995. int stringId = constant->mInt32;
  6996. auto entry = mContext->mStringObjectIdMap[stringId];
  6997. String intrinName = entry.mString;
  6998. // if (intrinName.StartsWith(":"))
  6999. // {
  7000. // SizedArray<BfIRType, 2> paramTypes;
  7001. // for (auto& param : methodInstance->mParams)
  7002. // paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  7003. // return mBfIRBuilder->GetIntrinsic(intrinName.Substring(1), mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  7004. // }
  7005. // else
  7006. {
  7007. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  7008. if (intrinId != -1)
  7009. {
  7010. if (intrinId == BfIRIntrinsic_Malloc)
  7011. {
  7012. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  7013. }
  7014. else if (intrinId == BfIRIntrinsic_Free)
  7015. {
  7016. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  7017. }
  7018. SizedArray<BfIRType, 2> paramTypes;
  7019. for (auto& param : methodInstance->mParams)
  7020. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  7021. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  7022. }
  7023. else if (reportFailure)
  7024. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  7025. }
  7026. }
  7027. else if (reportFailure)
  7028. error = "Intrinsic name must be a constant string";
  7029. if (reportFailure)
  7030. {
  7031. Fail(error, customAttribute.mRef);
  7032. }
  7033. }
  7034. }
  7035. return BfIRFunction();
  7036. }
  7037. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  7038. {
  7039. if (mBfIRBuilder->mIgnoreWrites)
  7040. return mBfIRBuilder->GetFakeFunction();
  7041. if (!mBuiltInFuncs[(int)funcTypeId])
  7042. {
  7043. SizedArray<BfIRType, 4> paramTypes;
  7044. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  7045. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  7046. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  7047. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  7048. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  7049. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  7050. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  7051. BfIRFunctionType funcType;
  7052. BfIRFunction func;
  7053. switch (funcTypeId)
  7054. {
  7055. case BfBuiltInFuncType_PrintF:
  7056. paramTypes.Add(nullPtrType);
  7057. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  7058. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  7059. break;
  7060. case BfBuiltInFuncType_Malloc:
  7061. {
  7062. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7063. {
  7064. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  7065. }
  7066. else
  7067. {
  7068. String funcName = mCompiler->mOptions.mMallocLinkName;
  7069. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  7070. funcName = "malloc";
  7071. func = mBfIRBuilder->GetFunction(funcName);
  7072. if (!func)
  7073. {
  7074. paramTypes.clear();
  7075. paramTypes.push_back(intType);
  7076. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  7077. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  7078. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  7079. }
  7080. }
  7081. }
  7082. break;
  7083. case BfBuiltInFuncType_Free:
  7084. {
  7085. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7086. {
  7087. func = GetInternalMethod("Dbg_RawFree").mFunc;
  7088. }
  7089. else
  7090. {
  7091. String funcName = mCompiler->mOptions.mFreeLinkName;
  7092. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  7093. funcName = "free";
  7094. func = mBfIRBuilder->GetFunction(funcName);
  7095. if (!func)
  7096. {
  7097. paramTypes.clear();
  7098. paramTypes.push_back(nullPtrType);
  7099. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  7100. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  7101. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  7102. }
  7103. }
  7104. }
  7105. break;
  7106. case BfBuiltInFuncType_LoadSharedLibraries:
  7107. paramTypes.clear();
  7108. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  7109. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  7110. break;
  7111. default: break;
  7112. }
  7113. mBuiltInFuncs[(int)funcTypeId] = func;
  7114. return func;
  7115. }
  7116. return mBuiltInFuncs[(int)funcTypeId];
  7117. }
  7118. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized, Array<BfTypeReference*>* deferredResolveTypes)
  7119. {
  7120. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  7121. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  7122. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  7123. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  7124. BfAutoComplete* bfAutocomplete = NULL;
  7125. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  7126. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  7127. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  7128. {
  7129. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  7130. {
  7131. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  7132. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  7133. {
  7134. String filter = nameNode->ToString();
  7135. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  7136. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  7137. if (nameIdx != 0)
  7138. {
  7139. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  7140. }
  7141. }
  7142. }
  7143. }
  7144. for (auto constraint : constraintDef->mConstraints)
  7145. {
  7146. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  7147. {
  7148. BfGenericOperatorConstraintInstance opConstraintInstance;
  7149. if (opConstraint->mLeftType != NULL)
  7150. {
  7151. if (bfAutocomplete != NULL)
  7152. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  7153. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces_All);
  7154. if (opConstraintInstance.mLeftType == NULL)
  7155. continue;
  7156. }
  7157. if (opConstraint->mRightType == NULL)
  7158. {
  7159. // We had a failure in parsing
  7160. continue;
  7161. }
  7162. if (opConstraint->mRightType != NULL)
  7163. {
  7164. if (bfAutocomplete != NULL)
  7165. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  7166. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces_All);
  7167. if (opConstraintInstance.mRightType == NULL)
  7168. continue;
  7169. }
  7170. if (opConstraint->mOpToken == NULL)
  7171. {
  7172. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  7173. continue;
  7174. }
  7175. if (opConstraint->mLeftType != NULL)
  7176. {
  7177. if (opConstraint->mRightType == NULL)
  7178. {
  7179. // Parse should have failed
  7180. continue;
  7181. }
  7182. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  7183. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  7184. {
  7185. Fail("Invalid binary operator", opConstraint->mOpToken);
  7186. continue;
  7187. }
  7188. }
  7189. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  7190. {
  7191. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  7192. }
  7193. else
  7194. {
  7195. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  7196. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  7197. {
  7198. Fail("Invalid unary operator", opConstraint->mOpToken);
  7199. continue;
  7200. }
  7201. }
  7202. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  7203. continue;
  7204. }
  7205. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  7206. if (bfAutocomplete != NULL)
  7207. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  7208. //TODO: Constraints may refer to other generic params (of either type or method)
  7209. // TO allow resolution, perhaps move this generic param initialization into GetMethodInstance (passing a genericPass bool)
  7210. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_AllowGenericMethodParamConstValue;
  7211. if (isUnspecialized)
  7212. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_DisallowComptime);
  7213. // We we have a deferredResolveTypes then we defer the generic validation, because we may have a case like
  7214. // `where T : Dictionay<TElem, int> and TElem : IHashable` and we don't want to throw the error on `T` before we build `TElem`
  7215. BfType* constraintType;
  7216. if (constraintTypeRef->IsA<BfVarTypeReference>())
  7217. constraintType = GetPrimitiveType(BfTypeCode_Var);
  7218. else
  7219. constraintType = ResolveTypeRef(constraintTypeRef, (deferredResolveTypes != NULL) ? BfPopulateType_Identity : BfPopulateType_Declaration, resolveFlags);
  7220. if (constraintType != NULL)
  7221. {
  7222. if (deferredResolveTypes != NULL)
  7223. {
  7224. PopulateType(constraintType, BfPopulateType_Declaration);
  7225. if (constraintType->IsUnspecializedTypeVariation())
  7226. deferredResolveTypes->Add(constraintTypeRef);
  7227. }
  7228. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7229. {
  7230. bool isValidTypeCode = false;
  7231. BfTypeCode typeCode = BfTypeCode_None;
  7232. if (constraintType->IsTypedPrimitive())
  7233. {
  7234. auto underlyingType = constraintType->GetUnderlyingType();
  7235. if (underlyingType->IsPrimitiveType())
  7236. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  7237. }
  7238. if (constraintType->IsPrimitiveType())
  7239. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  7240. if (constraintType->IsInstanceOf(mCompiler->mStringTypeDef))
  7241. isValidTypeCode = true;
  7242. if (constraintType->IsValueType())
  7243. isValidTypeCode = true;
  7244. if (constraintType->IsVar())
  7245. isValidTypeCode = true;
  7246. switch (typeCode)
  7247. {
  7248. case BfTypeCode_StringId:
  7249. case BfTypeCode_Boolean:
  7250. case BfTypeCode_Int8:
  7251. case BfTypeCode_UInt8:
  7252. case BfTypeCode_Int16:
  7253. case BfTypeCode_UInt16:
  7254. case BfTypeCode_Int32:
  7255. case BfTypeCode_UInt32:
  7256. case BfTypeCode_Int64:
  7257. case BfTypeCode_UInt64:
  7258. case BfTypeCode_IntPtr:
  7259. case BfTypeCode_UIntPtr:
  7260. case BfTypeCode_IntUnknown:
  7261. case BfTypeCode_UIntUnknown:
  7262. case BfTypeCode_Float:
  7263. case BfTypeCode_Double:
  7264. case BfTypeCode_Char8:
  7265. case BfTypeCode_Char16:
  7266. case BfTypeCode_Char32:
  7267. isValidTypeCode = true;
  7268. break;
  7269. default: break;
  7270. }
  7271. if (isValidTypeCode)
  7272. {
  7273. genericParamInstance->mTypeConstraint = constraintType;
  7274. }
  7275. else
  7276. {
  7277. Fail("Const constraint must be a valuetype or string", constraintTypeRef);
  7278. }
  7279. }
  7280. else
  7281. {
  7282. bool checkEquality = false;
  7283. if (constraintType->IsVar())
  7284. {
  7285. // From a `comptype` generic undef resolution. Ignore.
  7286. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_ComptypeExpr);
  7287. genericParamInstance->mComptypeConstraint.Add(constraintTypeRef);
  7288. continue;
  7289. }
  7290. else if (constraintType->IsPrimitiveType())
  7291. {
  7292. checkEquality = true;
  7293. }
  7294. if (constraintType->IsArray())
  7295. {
  7296. if (isUnspecialized)
  7297. {
  7298. 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);
  7299. continue;
  7300. }
  7301. checkEquality = true;
  7302. }
  7303. if (constraintType->IsGenericParam())
  7304. {
  7305. checkEquality = true;
  7306. }
  7307. else if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  7308. {
  7309. checkEquality = true;
  7310. }
  7311. if (checkEquality)
  7312. {
  7313. genericParamInstance->mTypeConstraint = constraintType;
  7314. }
  7315. else if (constraintType->IsInterface())
  7316. {
  7317. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  7318. }
  7319. else
  7320. {
  7321. auto constraintTypeInst = constraintType->ToTypeInstance();
  7322. if (genericParamInstance->mTypeConstraint != NULL)
  7323. {
  7324. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  7325. {
  7326. // Allow more specific type
  7327. genericParamInstance->mTypeConstraint = constraintTypeInst;
  7328. }
  7329. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  7330. {
  7331. // Silently ignore less-specific type
  7332. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  7333. {
  7334. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  7335. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Class);
  7336. }
  7337. }
  7338. else
  7339. {
  7340. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  7341. return;
  7342. }
  7343. }
  7344. else
  7345. genericParamInstance->mTypeConstraint = constraintType;
  7346. }
  7347. }
  7348. }
  7349. }
  7350. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  7351. (genericParamInstance->mTypeConstraint == NULL))
  7352. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  7353. }
  7354. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  7355. {
  7356. if (genericParamSource.mMethodInstance != NULL)
  7357. {
  7358. //auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  7359. //SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  7360. return MethodToString(genericParamSource.mMethodInstance);
  7361. }
  7362. else
  7363. {
  7364. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  7365. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  7366. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  7367. return TypeToString(typeInst);
  7368. }
  7369. }
  7370. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  7371. {
  7372. Array<String> methodParamNameOverrides;
  7373. auto _TypeToString = [&](BfType* type)
  7374. {
  7375. if (genericParamSource.mMethodInstance != NULL)
  7376. {
  7377. if (methodParamNameOverrides.IsEmpty())
  7378. {
  7379. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  7380. methodParamNameOverrides.Add(genericParam->mName);
  7381. }
  7382. return TypeToString(type, &methodParamNameOverrides);
  7383. }
  7384. return TypeToString(type);
  7385. };
  7386. bool ignoreErrors = (errorOut == NULL) ||
  7387. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  7388. BfType* origCheckArgType = checkArgType;
  7389. if (origCheckArgType->IsRef())
  7390. origCheckArgType = origCheckArgType->GetUnderlyingType();
  7391. bool argIsReferenceType = false;
  7392. int checkGenericParamFlags = 0;
  7393. if (checkArgType->IsGenericParam())
  7394. {
  7395. BfGenericParamInstance* checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  7396. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  7397. if (checkGenericParamInst->mTypeConstraint != NULL)
  7398. checkArgType = checkGenericParamInst->mTypeConstraint;
  7399. if (checkGenericParamInst->mGenericParamFlags & BfGenericParamFlag_Var)
  7400. checkArgType = GetPrimitiveType(BfTypeCode_Var);
  7401. // if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  7402. // {
  7403. // argMayBeReferenceType = false;
  7404. // }
  7405. // else
  7406. // {
  7407. // argMayBeReferenceType = true;
  7408. // }
  7409. }
  7410. if (checkArgType->IsObjectOrInterface())
  7411. argIsReferenceType = true;
  7412. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mMethodInfoEx != NULL))
  7413. {
  7414. for (int genericParamIdx = (int)mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  7415. genericParamIdx < mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  7416. {
  7417. auto genericParamInst = mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  7418. if (genericParamInst->mExternType == checkArgType)
  7419. {
  7420. checkGenericParamFlags |= genericParamInst->mGenericParamFlags;
  7421. }
  7422. }
  7423. }
  7424. BfTypeInstance* typeConstraintInst = NULL;
  7425. if (genericParamInst->mTypeConstraint != NULL)
  7426. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  7427. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  7428. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  7429. {
  7430. if ((!ignoreErrors) && (PreFail()))
  7431. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  7432. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7433. return false;
  7434. }
  7435. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  7436. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  7437. {
  7438. if ((!ignoreErrors) && (PreFail()))
  7439. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  7440. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7441. return false;
  7442. }
  7443. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  7444. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argIsReferenceType))
  7445. {
  7446. if ((!ignoreErrors) && (PreFail()))
  7447. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  7448. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7449. return false;
  7450. }
  7451. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum)
  7452. {
  7453. bool isEnum = checkArgType->IsEnum();
  7454. if ((origCheckArgType->IsGenericParam()) && (checkArgType->IsInstanceOf(mCompiler->mEnumTypeDef)))
  7455. isEnum = true;
  7456. if (((checkGenericParamFlags & (BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!isEnum))
  7457. {
  7458. if ((!ignoreErrors) && (PreFail()))
  7459. *errorOut = Fail(StrFormat("The type '%s' must be an enum type in order to use it as parameter '%s' for '%s'",
  7460. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7461. return false;
  7462. }
  7463. }
  7464. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) &&
  7465. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (checkArgType->IsInterface()))
  7466. {
  7467. if ((!ignoreErrors) && (PreFail()))
  7468. *errorOut = Fail(StrFormat("The type '%s' must be an concrete type in order to use it as parameter '%s' for '%s'",
  7469. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7470. return false;
  7471. }
  7472. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Interface) &&
  7473. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsInterface()))
  7474. {
  7475. if ((!ignoreErrors) && (PreFail()))
  7476. *errorOut = Fail(StrFormat("The type '%s' must be an interface type in order to use it as parameter '%s' for '%s'",
  7477. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7478. return false;
  7479. }
  7480. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7481. {
  7482. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  7483. {
  7484. if ((!ignoreErrors) && (PreFail()))
  7485. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  7486. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7487. return false;
  7488. }
  7489. }
  7490. else
  7491. {
  7492. if (checkArgType->IsConstExprValue())
  7493. {
  7494. if ((!ignoreErrors) && (PreFail()))
  7495. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  7496. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7497. return false;
  7498. }
  7499. }
  7500. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  7501. {
  7502. bool canDelete = false;
  7503. if (checkArgType->IsPointer())
  7504. canDelete = true;
  7505. else if (checkArgType->IsObjectOrInterface())
  7506. canDelete = true;
  7507. else if ((checkGenericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var)) != 0)
  7508. canDelete = true;
  7509. if (!canDelete)
  7510. {
  7511. if ((!ignoreErrors) && (PreFail()))
  7512. {
  7513. if (checkArgType->IsGenericParam())
  7514. *errorOut = Fail(StrFormat("Must add 'where %s : delete' constraint in order to use type as parameter '%s' for '%s'",
  7515. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7516. else
  7517. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  7518. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7519. }
  7520. return false;
  7521. }
  7522. }
  7523. if (checkArgType->IsPointer())
  7524. {
  7525. auto ptrType = (BfPointerType*)checkArgType;
  7526. checkArgType = ptrType->mElementType;
  7527. }
  7528. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  7529. {
  7530. bool canAlloc = false;
  7531. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  7532. {
  7533. if (checkTypeInst->IsObjectOrStruct())
  7534. {
  7535. checkTypeInst->mTypeDef->PopulateMemberSets();
  7536. BfMemberSetEntry* entry = NULL;
  7537. BfMethodDef* checkMethodDef = NULL;
  7538. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  7539. if (entry != NULL)
  7540. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  7541. bool hadProtected = false;
  7542. while (checkMethodDef != NULL)
  7543. {
  7544. if (!checkMethodDef->mParams.IsEmpty())
  7545. {
  7546. auto firstParam = checkMethodDef->mParams[0];
  7547. if (((firstParam->mParamKind == BfParamKind_Params) || (firstParam->mParamKind == BfParamKind_AppendIdx) || (firstParam->mParamKind == BfParamKind_VarArgs)) ||
  7548. ((firstParam->mParamDeclaration != NULL) && (firstParam->mParamDeclaration->mInitializer != NULL)))
  7549. {
  7550. // Allow all-default params
  7551. }
  7552. else
  7553. {
  7554. checkMethodDef = checkMethodDef->mNextWithSameName;
  7555. continue;
  7556. }
  7557. }
  7558. if (checkMethodDef->mProtection == BfProtection_Public)
  7559. {
  7560. canAlloc = true;
  7561. break;
  7562. }
  7563. if ((checkMethodDef->mProtection == BfProtection_Protected) || (checkMethodDef->mProtection == BfProtection_ProtectedInternal))
  7564. hadProtected = true;
  7565. checkMethodDef = checkMethodDef->mNextWithSameName;
  7566. }
  7567. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  7568. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  7569. }
  7570. }
  7571. else if (checkArgType->IsGenericParam())
  7572. {
  7573. canAlloc = (checkGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) != 0;
  7574. }
  7575. else if (checkArgType->IsPrimitiveType())
  7576. {
  7577. // Any primitive types and stuff can be allocated
  7578. canAlloc = true;
  7579. }
  7580. if (!canAlloc)
  7581. {
  7582. if ((!ignoreErrors) && (PreFail()))
  7583. {
  7584. if (checkArgType->IsGenericParam())
  7585. *errorOut = Fail(StrFormat("Must add 'where %s : new' constraint in order to use type as parameter '%s' for '%s'",
  7586. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7587. else
  7588. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  7589. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7590. }
  7591. return false;
  7592. }
  7593. }
  7594. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  7595. return true;
  7596. if (genericParamInst->mTypeConstraint != NULL)
  7597. {
  7598. bool constraintMatched = false;
  7599. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7600. {
  7601. if (checkArgType->IsConstExprValue())
  7602. {
  7603. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  7604. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  7605. {
  7606. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  7607. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  7608. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  7609. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  7610. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  7611. (primType->mTypeDef->mTypeCode != BfTypeCode_Let) &&
  7612. (primType->mTypeDef->mTypeCode != BfTypeCode_Var))
  7613. {
  7614. bool doError = true;
  7615. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  7616. {
  7617. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7618. {
  7619. if (mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue))
  7620. doError = false;
  7621. }
  7622. }
  7623. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_Float) && ((constExprValueType->mValue.mTypeCode == BfTypeCode_Double)))
  7624. {
  7625. doError = false;
  7626. }
  7627. if (doError)
  7628. {
  7629. if ((!ignoreErrors) && (PreFail()))
  7630. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7631. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7632. return false;
  7633. }
  7634. }
  7635. }
  7636. else if (genericParamInst->mTypeConstraint != constExprValueType->mType)
  7637. {
  7638. if ((!ignoreErrors) && (PreFail()))
  7639. *errorOut = Fail(StrFormat("Const generic argument '%s', declared as '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7640. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7641. return false;
  7642. }
  7643. }
  7644. }
  7645. else
  7646. {
  7647. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  7648. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  7649. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7650. if (convCheckConstraint == NULL)
  7651. return false;
  7652. if ((checkArgType->IsMethodRef()) || (checkArgType->IsFunction()))
  7653. {
  7654. if (convCheckConstraint->IsDelegate())
  7655. {
  7656. BfMethodInstance* checkMethodInstance;
  7657. if (checkArgType->IsMethodRef())
  7658. {
  7659. auto methodRefType = (BfMethodRefType*)checkArgType;
  7660. checkMethodInstance = methodRefType->mMethodRef;
  7661. }
  7662. else
  7663. {
  7664. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  7665. }
  7666. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  7667. if (checkMethodInstance->HasExplicitThis() != 0)
  7668. {
  7669. // Don't allow functions with explicit 'this'
  7670. }
  7671. else
  7672. {
  7673. BfExprEvaluator exprEvaluator(this);
  7674. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  7675. constraintMatched = true;
  7676. }
  7677. }
  7678. else if (convCheckConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef))
  7679. constraintMatched = true;
  7680. else if ((checkArgType->IsFunction()) && (convCheckConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))
  7681. constraintMatched = true;
  7682. }
  7683. else if ((checkArgType == convCheckConstraint) || (checkArgType->IsVar()) || (TypeIsSubTypeOf(checkArgType->ToTypeInstance(), convCheckConstraint->ToTypeInstance())))
  7684. {
  7685. constraintMatched = true;
  7686. }
  7687. else if (origCheckArgType->IsWrappableType())
  7688. {
  7689. if (origCheckArgType->IsSizedArray())
  7690. {
  7691. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  7692. if (convCheckConstraint->IsGenericTypeInstance())
  7693. {
  7694. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  7695. if (convCheckConstraintInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  7696. {
  7697. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  7698. {
  7699. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  7700. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  7701. constraintMatched = true;
  7702. }
  7703. }
  7704. }
  7705. }
  7706. if (!constraintMatched)
  7707. {
  7708. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7709. if ((wrappedStructType == convCheckConstraint) || (TypeIsSubTypeOf(wrappedStructType, convCheckConstraint->ToTypeInstance())))
  7710. constraintMatched = true;
  7711. }
  7712. }
  7713. if (!constraintMatched)
  7714. {
  7715. if ((!ignoreErrors) && (PreFail()))
  7716. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  7717. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  7718. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  7719. return false;
  7720. }
  7721. }
  7722. }
  7723. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  7724. {
  7725. BfType* convCheckConstraint = checkConstraint;
  7726. if (convCheckConstraint->IsUnspecializedType())
  7727. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7728. if (convCheckConstraint == NULL)
  7729. return false;
  7730. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  7731. bool implementsInterface = false;
  7732. if (origCheckArgType != checkArgType)
  7733. {
  7734. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  7735. }
  7736. if (!implementsInterface)
  7737. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  7738. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  7739. {
  7740. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7741. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7742. implementsInterface = true;
  7743. }
  7744. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  7745. {
  7746. auto underlyingType = origCheckArgType->GetUnderlyingType();
  7747. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  7748. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7749. implementsInterface = true;
  7750. }
  7751. if (!implementsInterface)
  7752. {
  7753. if ((!ignoreErrors) && (PreFail()))
  7754. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  7755. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  7756. return false;
  7757. }
  7758. }
  7759. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  7760. {
  7761. auto leftType = checkOpConstraint.mLeftType;
  7762. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  7763. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs, mCurTypeInstance);
  7764. if (leftType != NULL)
  7765. leftType = FixIntUnknown(leftType);
  7766. auto rightType = checkOpConstraint.mRightType;
  7767. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  7768. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs, mCurTypeInstance);
  7769. if (rightType != NULL)
  7770. rightType = FixIntUnknown(rightType);
  7771. BfConstraintState constraintSet;
  7772. constraintSet.mPrevState = mContext->mCurConstraintState;
  7773. constraintSet.mGenericParamInstance = genericParamInst;
  7774. constraintSet.mLeftType = leftType;
  7775. constraintSet.mRightType = rightType;
  7776. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  7777. if (!CheckConstraintState(NULL))
  7778. return false;
  7779. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  7780. {
  7781. BfExprEvaluator exprEvaluator(this);
  7782. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  7783. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7784. //
  7785. {
  7786. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7787. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7788. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  7789. }
  7790. if ((!exprEvaluator.mResult) ||
  7791. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  7792. {
  7793. if ((!ignoreErrors) && (PreFail()))
  7794. {
  7795. if (genericParamInst->mExternType != NULL)
  7796. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  7797. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  7798. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7799. ), checkArgTypeRef);
  7800. else
  7801. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  7802. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7803. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7804. ), checkArgTypeRef);
  7805. }
  7806. return false;
  7807. }
  7808. }
  7809. else
  7810. {
  7811. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7812. StringT<128> failedOpName;
  7813. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  7814. {
  7815. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7816. failedOpName = "implicit conversion from '";
  7817. }
  7818. else
  7819. {
  7820. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7821. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7822. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  7823. {
  7824. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7825. failedOpName = "explicit conversion from '";
  7826. }
  7827. else
  7828. {
  7829. BfExprEvaluator exprEvaluator(this);
  7830. exprEvaluator.mResult = rightValue;
  7831. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  7832. if ((!exprEvaluator.mResult) ||
  7833. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  7834. {
  7835. failedOpName += "unary operation '";
  7836. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  7837. }
  7838. }
  7839. }
  7840. if (!failedOpName.IsEmpty())
  7841. {
  7842. if ((!ignoreErrors) && (PreFail()))
  7843. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  7844. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7845. failedOpName.c_str(), TypeToString(rightType).c_str()
  7846. ), checkArgTypeRef);
  7847. return false;
  7848. }
  7849. }
  7850. }
  7851. return true;
  7852. }
  7853. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  7854. {
  7855. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  7856. {
  7857. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  7858. return genericParamType;
  7859. }
  7860. auto genericParamType = new BfGenericParamType();
  7861. genericParamType->mContext = mContext;
  7862. genericParamType->mGenericParamKind = paramKind;
  7863. genericParamType->mGenericParamIdx = paramIdx;
  7864. PopulateType(genericParamType);
  7865. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  7866. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  7867. BfResolvedTypeSet::LookupContext lookupCtx;
  7868. lookupCtx.mModule = this;
  7869. BfResolvedTypeSet::EntryRef typeEntry;
  7870. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  7871. BF_ASSERT(inserted);
  7872. typeEntry->mValue = genericParamType;
  7873. return genericParamType;
  7874. }
  7875. static int sValueFromExprIdx = 0;
  7876. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  7877. {
  7878. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  7879. if ((result) && (!ignoreNullable))
  7880. {
  7881. if (result.mType->IsVar())
  7882. return result;
  7883. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  7884. //TODO: Make this work, needed for 'void' and such
  7885. BfType* nullableType = NULL;
  7886. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  7887. {
  7888. BfTypeVector typeVec;
  7889. typeVec.push_back(result.mType);
  7890. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  7891. BF_ASSERT(nullableType != NULL);
  7892. }
  7893. // Go back to start and do any setup we need
  7894. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7895. BfTypedValue nullableTypedValue;
  7896. if (nullableType != NULL)
  7897. {
  7898. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  7899. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  7900. GetConstValue(nullableType->mSize), nullableType->mAlign);
  7901. }
  7902. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7903. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  7904. mBfIRBuilder->SetInsertPoint(notNullBB);
  7905. result = LoadValue(result);
  7906. if (nullableTypedValue)
  7907. {
  7908. auto elementType = nullableType->GetUnderlyingType();
  7909. if (elementType->IsVar())
  7910. {
  7911. // Do nothing
  7912. }
  7913. else if (elementType->IsValuelessType())
  7914. {
  7915. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  7916. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  7917. }
  7918. else
  7919. {
  7920. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  7921. mBfIRBuilder->CreateAlignedStore(result.mValue, ptrValue, result.mType->mAlign);
  7922. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  7923. mBfIRBuilder->CreateAlignedStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue, 1);
  7924. }
  7925. result = nullableTypedValue;
  7926. }
  7927. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7928. AddBasicBlock(pendingNullCond->mDoneBB);
  7929. if (nullableType == NULL)
  7930. {
  7931. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  7932. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  7933. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  7934. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  7935. {
  7936. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  7937. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  7938. }
  7939. result.mValue = phi;
  7940. }
  7941. }
  7942. else
  7943. {
  7944. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7945. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7946. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7947. AddBasicBlock(pendingNullCond->mDoneBB);
  7948. }
  7949. delete mCurMethodState->mPendingNullConditional;
  7950. mCurMethodState->mPendingNullConditional = NULL;
  7951. return result;
  7952. }
  7953. BF_NOINLINE void BfModule::EvaluateWithNewConditionalScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  7954. {
  7955. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  7956. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData);
  7957. if (mCurMethodState != NULL)
  7958. {
  7959. deferredLocalAssignData.mIsIfCondition = true;
  7960. deferredLocalAssignData.mIfMayBeSkipped = true;
  7961. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  7962. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  7963. mCurMethodState->mDeferredLocalAssignData = &deferredLocalAssignData;
  7964. }
  7965. BfScopeData newScope;
  7966. newScope.mOuterIsConditional = true;
  7967. newScope.mAllowTargeting = false;
  7968. if (mCurMethodState != NULL)
  7969. {
  7970. mCurMethodState->AddScope(&newScope);
  7971. NewScopeState(true, false);
  7972. }
  7973. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7974. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  7975. if (mCurMethodState != NULL)
  7976. RestoreScopeState();
  7977. }
  7978. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7979. {
  7980. //
  7981. {
  7982. BP_ZONE("CreateValueFromExpression:CheckStack");
  7983. StackHelper stackHelper;
  7984. if (!stackHelper.CanStackExpand(128 * 1024))
  7985. {
  7986. BfTypedValue result;
  7987. if (!stackHelper.Execute([&]()
  7988. {
  7989. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7990. }))
  7991. {
  7992. Fail("Expression too complex to compile", expr);
  7993. }
  7994. return result;
  7995. }
  7996. }
  7997. BP_ZONE("BfModule::CreateValueFromExpression");
  7998. if (outOrigType != NULL)
  7999. *outOrigType = NULL;
  8000. exprEvaluator.mExpectingType = wantTypeRef;
  8001. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  8002. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  8003. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  8004. {
  8005. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope->mScopeKind != BfScopeKind_StatementTarget_Conditional))
  8006. {
  8007. EvaluateWithNewConditionalScope(exprEvaluator, expr, flags);
  8008. }
  8009. else
  8010. {
  8011. SetAndRestoreValue<bool> prevIsConditional(mCurMethodState->mCurScope->mIsConditional, true);
  8012. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  8013. }
  8014. }
  8015. else
  8016. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  8017. if (!exprEvaluator.mResult)
  8018. {
  8019. if ((flags & BfEvalExprFlags_InferReturnType) != 0)
  8020. return exprEvaluator.mResult;
  8021. if (!mCompiler->mPassInstance->HasFailed())
  8022. {
  8023. if (PreFail())
  8024. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  8025. }
  8026. return BfTypedValue();
  8027. }
  8028. auto typedVal = exprEvaluator.mResult;
  8029. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  8030. {
  8031. BF_ASSERT(typedVal.mType->IsGenericParam());
  8032. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  8033. bool handled = false;
  8034. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  8035. {
  8036. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  8037. if (genericTypeConstraint != NULL)
  8038. {
  8039. auto underlyingConstraint = genericTypeConstraint;
  8040. if ((underlyingConstraint != NULL) && (underlyingConstraint->IsBoxed()))
  8041. underlyingConstraint = underlyingConstraint->GetUnderlyingType();
  8042. if (underlyingConstraint != NULL)
  8043. {
  8044. BfTypedValue result;
  8045. result.mKind = BfTypedValueKind_Value;
  8046. result.mType = genericTypeConstraint;
  8047. result.mValue = mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(underlyingConstraint));
  8048. typedVal = result;
  8049. handled = true;
  8050. }
  8051. }
  8052. }
  8053. if (!handled)
  8054. {
  8055. //Fail("Only const generic parameters can be used as values", expr);
  8056. AssertErrorState();
  8057. return BfTypedValue();
  8058. }
  8059. }
  8060. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  8061. FixIntUnknown(typedVal);
  8062. if (!mBfIRBuilder->mIgnoreWrites)
  8063. FixValueActualization(typedVal);
  8064. exprEvaluator.CheckResultForReading(typedVal);
  8065. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  8066. {
  8067. if ((flags & BfEvalExprFlags_NoCast) == 0)
  8068. {
  8069. // Only allow a 'ref' type if we have an explicit 'ref' operator
  8070. bool allowRef = false;
  8071. BfAstNode* checkExpr = expr;
  8072. while (checkExpr != NULL)
  8073. {
  8074. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  8075. checkExpr = parenExpr->mExpression;
  8076. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  8077. {
  8078. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  8079. allowRef = true;
  8080. break;
  8081. }
  8082. if (auto block = BfNodeDynCast<BfBlock>(checkExpr))
  8083. {
  8084. if (block->mChildArr.mSize == 0)
  8085. break;
  8086. checkExpr = block->mChildArr.back();
  8087. }
  8088. else
  8089. break;
  8090. }
  8091. if (!allowRef)
  8092. typedVal = RemoveRef(typedVal);
  8093. }
  8094. }
  8095. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  8096. {
  8097. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsDataIncomplete()) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  8098. {
  8099. if (typedVal.mValue.IsFake())
  8100. {
  8101. InternalError("Unexpected fakeval in CreateValueFromExpression");
  8102. typedVal = GetDefaultTypedValue(typedVal.mType);
  8103. }
  8104. }
  8105. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8106. }
  8107. if (wantTypeRef != NULL)
  8108. {
  8109. if (outOrigType != NULL)
  8110. *outOrigType = typedVal.mType;
  8111. if (((flags & BfEvalExprFlags_NoCast) == 0) && (!wantTypeRef->IsVar()))
  8112. {
  8113. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  8114. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  8115. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  8116. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  8117. if (!typedVal)
  8118. return typedVal;
  8119. }
  8120. if (exprEvaluator.mIsVolatileReference)
  8121. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8122. }
  8123. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  8124. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8125. if (auto autoComplete = mCompiler->GetAutoComplete())
  8126. autoComplete->CheckResult(expr, typedVal);
  8127. return typedVal;
  8128. }
  8129. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  8130. {
  8131. BfExprEvaluator exprEvaluator(this);
  8132. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  8133. }
  8134. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  8135. {
  8136. BfExprEvaluator exprEvaluator(this);
  8137. exprEvaluator.Evaluate(expr);
  8138. if (!exprEvaluator.mResult)
  8139. {
  8140. Fail("Invalid expression type", expr);
  8141. return BfTypedValue();
  8142. }
  8143. if (!exprEvaluator.mResult.IsAddr())
  8144. {
  8145. Fail("Cannot assign to value", expr);
  8146. return BfTypedValue();
  8147. }
  8148. return exprEvaluator.mResult;
  8149. }
  8150. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  8151. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  8152. {
  8153. auto typeInstance = typedValue.mType->ToTypeInstance();
  8154. if (zeroMemory)
  8155. {
  8156. int zeroAlign = typedValue.mType->mAlign;
  8157. if (typeInstance != NULL)
  8158. zeroAlign = typeInstance->mInstAlign;
  8159. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  8160. }
  8161. if (!typedValue.mType->IsObject())
  8162. {
  8163. return;
  8164. }
  8165. if ((scopeData == NULL) && (mCurMethodState != NULL))
  8166. return; // Handled in heap alloc funcs
  8167. auto typeDef = typeInstance->mTypeDef;
  8168. mBfIRBuilder->PopulateType(typedValue.mType);
  8169. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  8170. bool isAutocomplete = mCompiler->IsAutocomplete();
  8171. BfIRValue vDataRef;
  8172. if (!isAutocomplete)
  8173. {
  8174. vDataRef = GetClassVDataPtr(typeInstance);
  8175. }
  8176. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8177. auto ptrType = CreatePointerType(i8Type);
  8178. auto ptrPtrType = CreatePointerType(ptrType);
  8179. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  8180. PopulateType(ptrType, BfPopulateType_Declaration);
  8181. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  8182. if (!isAutocomplete)
  8183. {
  8184. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8185. {
  8186. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8187. SizedArray<BfIRValue, 4> llvmArgs;
  8188. llvmArgs.push_back(objectPtr);
  8189. llvmArgs.push_back(vDataRef);
  8190. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  8191. if (objectStackInitMethod)
  8192. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  8193. }
  8194. else
  8195. {
  8196. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  8197. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  8198. mBfIRBuilder->CreateStore(srcVal, destAddr);
  8199. }
  8200. }
  8201. }
  8202. bool BfModule::IsAllocatorAligned()
  8203. {
  8204. if (mCompiler->mOptions.mMallocLinkName == "StompAlloc")
  8205. return false;
  8206. return true;
  8207. }
  8208. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  8209. {
  8210. BfIRValue result;
  8211. BfType* ptrType;
  8212. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  8213. ptrType = type;
  8214. else
  8215. ptrType = CreatePointerType(type);
  8216. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  8217. {
  8218. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8219. SizedArray<BfExpression*, 2> argExprs;
  8220. BfTypedValueExpression typedValueExpr;
  8221. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  8222. typedValueExpr.mRefNode = refNode;
  8223. argExprs.push_back(&typedValueExpr);
  8224. BfTypedValueExpression appendSizeValueExpr;
  8225. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  8226. appendSizeValueExpr.mRefNode = refNode;
  8227. argExprs.push_back(&appendSizeValueExpr);
  8228. BfExprEvaluator exprEvaluator(this);
  8229. BfTypedValue allocResult;
  8230. if (allocTarget.mScopedInvocationTarget != NULL)
  8231. {
  8232. SizedArray<BfTypeReference*, 2> genericArgs;
  8233. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, BfMethodGenericArguments());
  8234. allocResult = LoadValue(exprEvaluator.mResult);
  8235. }
  8236. else if (allocTarget.mCustomAllocator)
  8237. {
  8238. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8239. if (customTypeInst == NULL)
  8240. {
  8241. if (allocTarget.mCustomAllocator.mType->IsStructPtr())
  8242. customTypeInst = allocTarget.mCustomAllocator.mType->GetUnderlyingType()->ToTypeInstance();
  8243. }
  8244. if (customTypeInst == NULL)
  8245. {
  8246. Fail(StrFormat("Type '%s' cannot be used as a custom allocator", TypeToString(allocTarget.mCustomAllocator.mType).c_str()), refNode);
  8247. }
  8248. else
  8249. {
  8250. BfTypedValueExpression typeValueExpr;
  8251. String allocMethodName = "Alloc";
  8252. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  8253. {
  8254. allocMethodName = "AllocTyped";
  8255. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  8256. auto typeRefVal = CreateTypeDataRef(type);
  8257. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  8258. typeValueExpr.mRefNode = refNode;
  8259. argExprs.Insert(0, &typeValueExpr);
  8260. }
  8261. if (HasMixin(customTypeInst, allocMethodName, 2))
  8262. {
  8263. BfSizedArray<BfExpression*> argExprArr;
  8264. argExprArr.mSize = (int)argExprs.size();
  8265. argExprArr.mVals = &argExprs[0];
  8266. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  8267. allocResult = exprEvaluator.GetResult();
  8268. }
  8269. else
  8270. {
  8271. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8272. BfResolvedArgs argValues(&sizedArgExprs);
  8273. exprEvaluator.ResolveArgValues(argValues);
  8274. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  8275. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, BfMethodGenericArguments());
  8276. }
  8277. }
  8278. }
  8279. if (allocResult)
  8280. {
  8281. if (allocResult.mType->IsVoidPtr())
  8282. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  8283. else
  8284. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  8285. return result;
  8286. }
  8287. }
  8288. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  8289. return result;
  8290. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8291. {
  8292. BfIRValue allocData = GetDbgRawAllocData(type);
  8293. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  8294. SizedArray<BfIRValue, 2> llvmArgs;
  8295. llvmArgs.push_back(sizeValue);
  8296. llvmArgs.push_back(allocData);
  8297. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  8298. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8299. }
  8300. BfModuleMethodInstance moduleMethodInstance;
  8301. moduleMethodInstance = GetInternalMethod("Malloc");
  8302. SizedArray<BfIRValue, 1> llvmArgs;
  8303. llvmArgs.push_back(sizeValue);
  8304. auto func = moduleMethodInstance.mFunc;
  8305. if ((!func) || (func.IsFake()))
  8306. {
  8307. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  8308. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  8309. }
  8310. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  8311. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  8312. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  8313. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8314. return result;
  8315. }
  8316. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  8317. {
  8318. if (type->IsStruct())
  8319. {
  8320. auto typeInstance = type->ToTypeInstance();
  8321. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  8322. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8323. }
  8324. else if (type->IsObjectOrInterface())
  8325. {
  8326. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8327. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  8328. BF_ASSERT(moduleMethodInst.mFunc);
  8329. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8330. }
  8331. else
  8332. {
  8333. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8334. BfExprEvaluator exprEvaluator(this);
  8335. SizedArray<BfResolvedArg, 1> resolvedArgs;
  8336. BfResolvedArg resolvedArg;
  8337. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  8338. resolvedArgs.Add(resolvedArg);
  8339. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, BfMethodGenericArguments());
  8340. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  8341. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  8342. BF_ASSERT(moduleMethodInst.mFunc);
  8343. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8344. }
  8345. return BfIRValue();
  8346. }
  8347. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  8348. {
  8349. BfIRValue allocDataValue;
  8350. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  8351. return allocDataValue;
  8352. BfIRValue markFuncPtr;
  8353. if (type->WantsGCMarking())
  8354. markFuncPtr = GetMarkFuncPtr(type);
  8355. else
  8356. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8357. BfIRValue typeDataRef = CreateTypeDataRef(type);
  8358. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  8359. BfTypeInstance* typeInstance = type->ToTypeInstance();
  8360. if (typeInstance == NULL)
  8361. {
  8362. typeInstance = GetWrappedStructType(type);
  8363. if (typeInstance != NULL)
  8364. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8365. }
  8366. if (typeInstance != NULL)
  8367. PopulateType(typeInstance);
  8368. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8369. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  8370. {
  8371. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8372. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8373. }
  8374. SizedArray<BfIRValue, 2> dataValues;
  8375. dataValues.Add(mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  8376. dataValues.Add(typeDataRef);
  8377. dataValues.Add(markFuncPtr);
  8378. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  8379. BfIRValue dataStruct = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  8380. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  8381. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  8382. return allocDataValue;
  8383. }
  8384. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  8385. {
  8386. BP_ZONE("AllocFromType");
  8387. BfScopeData* scopeData = allocTarget.mScopeData;
  8388. BF_ASSERT(!type->IsVar());
  8389. auto typeInstance = type->ToTypeInstance();
  8390. if ((typeInstance == NULL) && (type->IsGenericParam()))
  8391. typeInstance = mContext->mBfObjectType;
  8392. bool isHeapAlloc = scopeData == NULL;
  8393. bool isScopeAlloc = scopeData != NULL;
  8394. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  8395. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  8396. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  8397. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  8398. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  8399. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  8400. {
  8401. BfPointerType* ptrType = CreatePointerType(type);
  8402. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  8403. return val;
  8404. }
  8405. if (typeInstance != NULL)
  8406. mBfIRBuilder->PopulateType(typeInstance);
  8407. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  8408. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  8409. {
  8410. return mBfIRBuilder->GetFakeVal();
  8411. }
  8412. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8413. BfIRValue sizeValue;
  8414. BfIRType allocType = mBfIRBuilder->MapType(type);
  8415. int allocSize = type->mSize;
  8416. int allocAlign = type->mAlign;
  8417. if (typeInstance != NULL)
  8418. {
  8419. if ((!mBfIRBuilder->mIgnoreWrites) && (!mIsComptimeModule))
  8420. typeInstance->mHasBeenInstantiated = true;
  8421. allocSize = typeInstance->mInstSize;
  8422. allocAlign = typeInstance->mInstAlign;
  8423. //if (typeInstance->IsEnum())
  8424. //allocType = typeInstance->mIRType;
  8425. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  8426. }
  8427. if (alignOverride != -1)
  8428. allocAlign = alignOverride;
  8429. // The "dynSize" cases:
  8430. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  8431. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  8432. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  8433. // though we'd expect their stack space to be released
  8434. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  8435. {
  8436. MarkDynStack(scopeData);
  8437. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8438. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  8439. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  8440. BfType* voidPtrType = CreatePointerType(voidType);
  8441. if (!mCurMethodState->mDynStackRevIdx)
  8442. {
  8443. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  8444. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8445. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8446. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  8447. mBfIRBuilder->ClearDebugLocation(storeInst);
  8448. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8449. }
  8450. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  8451. auto bytePtrType = CreatePointerType(byteType);
  8452. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  8453. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  8454. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8455. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8456. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  8457. mBfIRBuilder->ClearDebugLocation(storeInst);
  8458. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  8459. mBfIRBuilder->ClearDebugLocation(storeInst);
  8460. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8461. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  8462. if (IsTargetingBeefBackend())
  8463. {
  8464. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  8465. // to ensure there isn't any register collision during looping is just to not allow it to
  8466. // bind to a register at all
  8467. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  8468. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  8469. }
  8470. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  8471. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  8472. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  8473. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  8474. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  8475. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  8476. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  8477. mBfIRBuilder->AddBlock(verCheckBB);
  8478. mBfIRBuilder->SetInsertPoint(verCheckBB);
  8479. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  8480. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  8481. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  8482. mBfIRBuilder->AddBlock(resizeBB);
  8483. mBfIRBuilder->SetInsertPoint(resizeBB);
  8484. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8485. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  8486. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  8487. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  8488. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  8489. mBfIRBuilder->CreateBr(endBB);
  8490. mBfIRBuilder->AddBlock(endBB);
  8491. mBfIRBuilder->SetInsertPoint(endBB);
  8492. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  8493. };
  8494. if (isScopeAlloc)
  8495. {
  8496. if (arraySize)
  8497. {
  8498. bool isConstantArraySize = arraySize.IsConst();
  8499. if (isRawArrayAlloc)
  8500. {
  8501. BfPointerType* ptrType = CreatePointerType(type);
  8502. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8503. {
  8504. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8505. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  8506. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  8507. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  8508. }
  8509. else
  8510. {
  8511. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8512. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  8513. if (!isDynAlloc)
  8514. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8515. else
  8516. {
  8517. MarkDynStack(scopeData);
  8518. SaveStackState(scopeData);
  8519. }
  8520. int typeSize = type->GetStride();
  8521. BfIRValue allocaInst;
  8522. BfIRValue result;
  8523. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  8524. {
  8525. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  8526. result = allocaInst;
  8527. }
  8528. else
  8529. {
  8530. if (typeInstance->IsStruct())
  8531. typeSize = typeInstance->GetInstStride();
  8532. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  8533. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  8534. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8535. auto ptrType = CreatePointerType(typeInstance);
  8536. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  8537. if (!isDynAlloc)
  8538. mBfIRBuilder->ClearDebugLocation(result);
  8539. }
  8540. if (!isDynAlloc)
  8541. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8542. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8543. if (!isDynAlloc)
  8544. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8545. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  8546. if (arraySize.IsConst())
  8547. {
  8548. auto constant = mBfIRBuilder->GetConstant(arraySize);
  8549. if (constant->mInt64 == 0)
  8550. noDtorCall = true;
  8551. }
  8552. if (!noDtorCall)
  8553. {
  8554. bool isConstSize = arraySize.IsConst();
  8555. BfIRBlock clearBlock;
  8556. BfIRBlock contBlock;
  8557. bool wantsDeinit = ((!IsOptimized()) && (!mIsComptimeModule) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly));
  8558. if (wantsDeinit)
  8559. {
  8560. BfIRBlock prevBlock;
  8561. if (!isConstSize)
  8562. {
  8563. clearBlock = mBfIRBuilder->CreateBlock("clear");
  8564. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  8565. prevBlock = mBfIRBuilder->GetInsertBlock();
  8566. mBfIRBuilder->AddBlock(clearBlock);
  8567. mBfIRBuilder->SetInsertPoint(clearBlock);
  8568. }
  8569. auto deferredCall = AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  8570. if (!isConstSize)
  8571. {
  8572. mBfIRBuilder->CreateBr(contBlock);
  8573. mBfIRBuilder->SetInsertPoint(prevBlock);
  8574. if (deferredCall != NULL)
  8575. {
  8576. // Zero out size args
  8577. for (int i = 1; i < deferredCall->mModuleMethodInstance.mMethodInstance->GetParamCount(); i++)
  8578. {
  8579. auto scopedArg = deferredCall->mScopeArgs[i];
  8580. if (scopedArg != deferredCall->mOrigScopeArgs[i])
  8581. mBfIRBuilder->CreateStore(GetDefaultValue(deferredCall->mModuleMethodInstance.mMethodInstance->GetParamType(i)), deferredCall->mScopeArgs[i]);
  8582. }
  8583. }
  8584. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  8585. mBfIRBuilder->AddBlock(contBlock);
  8586. mBfIRBuilder->SetInsertPoint(contBlock);
  8587. }
  8588. }
  8589. }
  8590. return result;
  8591. }
  8592. }
  8593. else
  8594. {
  8595. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8596. {
  8597. // Generate and check new size
  8598. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8599. auto firstElementField = &arrayType->mFieldInstances.back();
  8600. int arrayClassSize = firstElementField->mDataOffset;
  8601. sizeValue = GetConstValue(arrayClassSize);
  8602. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8603. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8604. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  8605. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  8606. if (!noDtorCall)
  8607. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8608. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8609. return typedVal.mValue;
  8610. }
  8611. else
  8612. {
  8613. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8614. auto firstElementField = &arrayType->mFieldInstances.back();
  8615. if (!type->IsValuelessType())
  8616. {
  8617. int arrayClassSize = firstElementField->mDataOffset;
  8618. sizeValue = GetConstValue(arrayClassSize);
  8619. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8620. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8621. }
  8622. else
  8623. sizeValue = GetConstValue(arrayType->mInstSize);
  8624. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8625. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8626. if (!isDynAlloc)
  8627. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8628. else
  8629. {
  8630. MarkDynStack(scopeData);
  8631. SaveStackState(scopeData);
  8632. }
  8633. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  8634. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8635. if (!isDynAlloc)
  8636. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8637. auto allocaBlock = mBfIRBuilder->GetInsertBlock();
  8638. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8639. BfTypedValue typedVal;
  8640. if (!isDynAlloc)
  8641. {
  8642. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8643. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8644. mBfIRBuilder->ClearDebugLocation(typedVal.mValue);
  8645. mBfIRBuilder->SetInsertPoint(prevBlock);
  8646. allocaBlock = mCurMethodState->mIRInitBlock;
  8647. }
  8648. else
  8649. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8650. if (!noDtorCall)
  8651. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true, allocaBlock);
  8652. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8653. return typedVal.mValue;
  8654. }
  8655. }
  8656. }
  8657. else if (appendSizeValue)
  8658. {
  8659. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  8660. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  8661. // use the "dynSize" version conservatively
  8662. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8663. {
  8664. // Generate and check new size
  8665. sizeValue = GetConstValue(typeInstance->mInstSize);
  8666. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8667. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  8668. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  8669. if (!noDtorCall)
  8670. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  8671. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8672. return typedVal.mValue;
  8673. }
  8674. else // stack alloc, unlooped, with append
  8675. {
  8676. sizeValue = GetConstValue(typeInstance->mInstSize);
  8677. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8678. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8679. bool wasDynAlloc = isDynAlloc;
  8680. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8681. if (!isDynAlloc)
  8682. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8683. else
  8684. {
  8685. MarkDynStack(scopeData);
  8686. SaveStackState(scopeData);
  8687. }
  8688. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  8689. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  8690. if (!isDynAlloc)
  8691. {
  8692. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8693. }
  8694. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8695. bool mayBeLarge = false;
  8696. if (sizeValue.IsConst())
  8697. {
  8698. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  8699. if (constantInt->mInt64 >= 4096)
  8700. mayBeLarge = true;
  8701. }
  8702. else
  8703. mayBeLarge = true;
  8704. if (((type->IsObject() && (!mayBeLarge))) ||
  8705. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8706. ((zeroMemory) && (!mayBeLarge)))
  8707. {
  8708. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8709. }
  8710. BfIRValue castedVal;
  8711. if (!isDynAlloc)
  8712. {
  8713. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8714. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8715. mBfIRBuilder->ClearDebugLocation(castedVal);
  8716. mBfIRBuilder->SetInsertPoint(prevBlock);
  8717. if (WantsLifetimes())
  8718. {
  8719. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8720. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8721. }
  8722. }
  8723. else
  8724. {
  8725. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8726. }
  8727. auto typedVal = BfTypedValue(castedVal, typeInstance);
  8728. if (!noDtorCall)
  8729. {
  8730. bool doCondAlloca = false;
  8731. if (!IsTargetingBeefBackend())
  8732. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  8733. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  8734. }
  8735. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8736. return typedVal.mValue;
  8737. }
  8738. }
  8739. else // "Normal" stack alloc
  8740. {
  8741. BF_ASSERT(!sizeValue);
  8742. //TODO: If sizeValue is a constant then do this in the head IR builder
  8743. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8744. if (!isLoopedAlloc)
  8745. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8746. else
  8747. {
  8748. MarkDynStack(scopeData);
  8749. SaveStackState(scopeData);
  8750. }
  8751. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  8752. if (!isLoopedAlloc)
  8753. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8754. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8755. bool mayBeLarge = allocSize >= 4096;
  8756. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  8757. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8758. ((zeroMemory) && (!mayBeLarge)))
  8759. {
  8760. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  8761. // and memset is always safe
  8762. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8763. }
  8764. auto typedVal = BfTypedValue(allocaInst, type);
  8765. if (!isLoopedAlloc)
  8766. {
  8767. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8768. mBfIRBuilder->SetInsertPoint(prevBlock);
  8769. if (WantsLifetimes())
  8770. {
  8771. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8772. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8773. }
  8774. }
  8775. if (!noDtorCall)
  8776. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8777. if (typeInstance != NULL)
  8778. {
  8779. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  8780. }
  8781. else
  8782. {
  8783. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  8784. }
  8785. return allocaInst;
  8786. }
  8787. }
  8788. else if (arraySize)
  8789. {
  8790. if (isRawArrayAlloc)
  8791. {
  8792. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8793. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  8794. }
  8795. else
  8796. {
  8797. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8798. typeInstance = arrayType;
  8799. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8800. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8801. appendSizeValue = elementDataSize;
  8802. if (!type->IsSizeAligned())
  8803. {
  8804. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  8805. }
  8806. }
  8807. }
  8808. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  8809. {
  8810. auto vDataRef = GetClassVDataPtr(typeInstance);
  8811. BfIRValue result;
  8812. bool isResultInitialized = false;
  8813. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8814. if (typeInstance->mTypeOptionsIdx != -1)
  8815. {
  8816. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8817. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8818. }
  8819. if (mIsComptimeModule)
  8820. stackCount = 0;
  8821. if (!sizeValue)
  8822. sizeValue = GetConstValue(typeInstance->mInstSize);
  8823. if (appendSizeValue)
  8824. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8825. BfIRValue origSizeValue = sizeValue;
  8826. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  8827. if (isAllocEx)
  8828. {
  8829. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  8830. if (prepareStackTraceMethod)
  8831. {
  8832. SizedArray<BfIRValue, 2> irArgs;
  8833. irArgs.Add(sizeValue);
  8834. irArgs.Add(GetConstValue(stackCount));
  8835. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  8836. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  8837. }
  8838. }
  8839. if (allocTarget.mCustomAllocator)
  8840. {
  8841. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8842. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  8843. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  8844. {
  8845. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8846. mBfIRBuilder->PopulateType(classVDataType);
  8847. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8848. mBfIRBuilder->PopulateType(typeInstType);
  8849. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  8850. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  8851. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  8852. BfTypedValueExpression typedValueExpr;
  8853. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  8854. typedValueExpr.mRefNode = allocTarget.mRefNode;
  8855. BfExprEvaluator exprEvaluator(this);
  8856. SizedArray<BfExpression*, 2> argExprs;
  8857. argExprs.push_back(&typedValueExpr);
  8858. BfTypedValueExpression sizeValueExpr;
  8859. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  8860. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  8861. argExprs.push_back(&sizeValueExpr);
  8862. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8863. BfResolvedArgs argValues(&sizedArgExprs);
  8864. exprEvaluator.ResolveArgValues(argValues);
  8865. exprEvaluator.mNoBind = true;
  8866. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, BfMethodGenericArguments());
  8867. if (allocResult)
  8868. {
  8869. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  8870. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  8871. else
  8872. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  8873. isResultInitialized = true;
  8874. }
  8875. }
  8876. }
  8877. bool wasAllocated = false;
  8878. if (!result)
  8879. {
  8880. if (hasCustomAllocator)
  8881. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  8882. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8883. {
  8884. SizedArray<BfIRValue, 4> llvmArgs;
  8885. llvmArgs.push_back(sizeValue);
  8886. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8887. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8888. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8889. wasAllocated = true;
  8890. }
  8891. }
  8892. if (result)
  8893. {
  8894. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8895. {
  8896. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  8897. SizedArray<BfIRValue, 4> llvmArgs;
  8898. llvmArgs.push_back(objectPtr);
  8899. llvmArgs.push_back(origSizeValue);
  8900. llvmArgs.push_back(vDataRef);
  8901. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  8902. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  8903. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  8904. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  8905. if (wasAllocated)
  8906. {
  8907. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  8908. auto bytePtrType = CreatePointerType(byteType);
  8909. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  8910. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  8911. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  8912. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  8913. }
  8914. }
  8915. else
  8916. {
  8917. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  8918. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8919. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  8920. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  8921. }
  8922. }
  8923. else
  8924. {
  8925. if ((mBfIRBuilder->mIgnoreWrites) ||
  8926. ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)))
  8927. {
  8928. if (mBfIRBuilder->mIgnoreWrites)
  8929. {
  8930. return GetDefaultValue(typeInstance);
  8931. }
  8932. else
  8933. {
  8934. // Fake with alloca
  8935. mBfIRBuilder->PopulateType(typeInstance);
  8936. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInstance));
  8937. }
  8938. }
  8939. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8940. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  8941. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8942. {
  8943. SizedArray<BfIRValue, 4> llvmArgs;
  8944. llvmArgs.push_back(vData);
  8945. llvmArgs.push_back(sizeValue);
  8946. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  8947. llvmArgs.push_back(GetConstValue(stackCount));
  8948. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  8949. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  8950. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8951. }
  8952. else
  8953. {
  8954. SizedArray<BfIRValue, 4> llvmArgs;
  8955. llvmArgs.push_back(sizeValue);
  8956. BfIRFunction irFunc;
  8957. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8958. {
  8959. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  8960. irFunc = moduleMethodInstance.mFunc;
  8961. }
  8962. if (!irFunc)
  8963. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8964. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8965. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  8966. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  8967. if (mIsComptimeModule)
  8968. {
  8969. vdataPtr = mBfIRBuilder->CreateBitCast(vdataPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance())));
  8970. }
  8971. mBfIRBuilder->CreateStore(vData, vdataPtr);
  8972. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8973. }
  8974. }
  8975. if ((zeroMemory) && (arraySize))
  8976. {
  8977. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8978. typeInstance = arrayType;
  8979. auto firstElementField = &arrayType->mFieldInstances.back();
  8980. int arrayClassSize = firstElementField->mDataOffset;
  8981. BfIRValue elementDataSize;
  8982. bool skipZero = false;
  8983. if (arraySize.IsConst())
  8984. {
  8985. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8986. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8987. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  8988. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  8989. if (constVal->mInt64 <= 0)
  8990. skipZero = true;
  8991. }
  8992. else
  8993. {
  8994. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  8995. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8996. }
  8997. if (!skipZero)
  8998. {
  8999. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  9000. auto ptrType = CreatePointerType(i8Type);
  9001. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  9002. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  9003. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  9004. appendSizeValue = elementDataSize;
  9005. }
  9006. }
  9007. return result;
  9008. }
  9009. else
  9010. {
  9011. if (!sizeValue)
  9012. sizeValue = GetConstValue(allocSize);
  9013. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  9014. }
  9015. }
  9016. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  9017. {
  9018. if ((type == NULL) || (refNode == NULL))
  9019. return;
  9020. auto typeInstance = type->ToTypeInstance();
  9021. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  9022. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  9023. }
  9024. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  9025. {
  9026. if (align <= 1)
  9027. return;
  9028. if (sizeMultiple == 0)
  9029. sizeMultiple = align;
  9030. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  9031. {
  9032. if (!IsAllocatorAligned())
  9033. {
  9034. // Don't align
  9035. }
  9036. else if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  9037. {
  9038. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  9039. BF_ASSERT(localVar->mName == "appendIdx");
  9040. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  9041. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9042. if (align > 1)
  9043. {
  9044. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  9045. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  9046. }
  9047. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  9048. }
  9049. else
  9050. {
  9051. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  9052. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  9053. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  9054. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  9055. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  9056. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  9057. }
  9058. }
  9059. if (mCurMethodState->mCurAppendAlign == 0)
  9060. mCurMethodState->mCurAppendAlign = sizeMultiple;
  9061. else
  9062. {
  9063. if (sizeMultiple % align == 0)
  9064. mCurMethodState->mCurAppendAlign = align;
  9065. else
  9066. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  9067. }
  9068. }
  9069. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  9070. {
  9071. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  9072. BF_ASSERT(localVar->mName == "appendIdx");
  9073. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  9074. BfIRValue retValue;
  9075. BfTypeInstance* retTypeInstance = NULL;
  9076. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  9077. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  9078. if (arraySize)
  9079. {
  9080. if (isRawArrayAlloc)
  9081. {
  9082. EmitAppendAlign(type->mAlign);
  9083. BfPointerType* ptrType = CreatePointerType(type);
  9084. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  9085. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9086. if (mSystem->mPtrSize != 4)
  9087. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  9088. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9089. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9090. if (zeroMemory)
  9091. {
  9092. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  9093. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  9094. }
  9095. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  9096. }
  9097. else
  9098. {
  9099. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  9100. EmitAppendAlign(arrayType->mAlign, type->mSize);
  9101. auto firstElementField = &arrayType->mFieldInstances.back();
  9102. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  9103. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  9104. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  9105. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  9106. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9107. if (mSystem->mPtrSize != 4)
  9108. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  9109. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9110. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9111. if (zeroMemory)
  9112. {
  9113. // Only zero out the actual elements
  9114. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  9115. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  9116. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  9117. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  9118. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  9119. }
  9120. retTypeInstance = arrayType;
  9121. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  9122. }
  9123. }
  9124. else
  9125. {
  9126. auto typeInst = type->ToTypeInstance();
  9127. BfIRValue sizeValue;
  9128. BfIRType toType;
  9129. if (typeInst != NULL)
  9130. {
  9131. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  9132. sizeValue = GetConstValue(typeInst->mInstSize);
  9133. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  9134. }
  9135. else
  9136. {
  9137. EmitAppendAlign(type->mAlign, type->mSize);
  9138. sizeValue = GetConstValue(type->mSize);
  9139. auto toPtrType = CreatePointerType(type);
  9140. toType = mBfIRBuilder->MapType(toPtrType);
  9141. }
  9142. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9143. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9144. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9145. retTypeInstance = typeInst;
  9146. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  9147. }
  9148. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  9149. {
  9150. mBfIRBuilder->PopulateType(retTypeInstance);
  9151. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  9152. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  9153. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  9154. auto curThis = GetThis();
  9155. BfIRValue newFlags;
  9156. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9157. {
  9158. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  9159. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  9160. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  9161. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  9162. }
  9163. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  9164. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  9165. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  9166. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  9167. mBfIRBuilder->CreateStore(srcVal, destAddr);
  9168. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9169. {
  9170. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  9171. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  9172. }
  9173. }
  9174. if (appendSizeValue)
  9175. {
  9176. EmitAppendAlign(appendAllocAlign);
  9177. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9178. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  9179. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9180. }
  9181. return retValue;
  9182. }
  9183. bool BfModule::IsOptimized()
  9184. {
  9185. if (mProject == NULL)
  9186. return false;
  9187. if (mIsComptimeModule)
  9188. return false;
  9189. int optLevel = GetModuleOptions().mOptLevel;
  9190. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  9191. }
  9192. bool BfModule::IsTargetingBeefBackend()
  9193. {
  9194. if (mProject == NULL)
  9195. return true;
  9196. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9197. }
  9198. bool BfModule::WantsLifetimes()
  9199. {
  9200. if (mBfIRBuilder->mIgnoreWrites)
  9201. return false;
  9202. if ((mIsComptimeModule) && (mBfIRBuilder->HasDebugLocation()))
  9203. return true;
  9204. else if (mProject == NULL)
  9205. return false;
  9206. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9207. }
  9208. bool BfModule::HasCompiledOutput()
  9209. {
  9210. return (!mSystem->mIsResolveOnly) && (mGeneratesCode) && (!mIsComptimeModule);
  9211. }
  9212. bool BfModule::HasExecutedOutput()
  9213. {
  9214. return ((!mSystem->mIsResolveOnly) && (mGeneratesCode)) || (mIsComptimeModule);
  9215. }
  9216. // We will skip the object access check for any occurrences of this value
  9217. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  9218. {
  9219. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9220. return;
  9221. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9222. return;
  9223. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  9224. return;
  9225. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  9226. }
  9227. bool BfModule::WantsObjectAccessCheck(BfType* type)
  9228. {
  9229. if ((mBfIRBuilder->mIgnoreWrites) || (!type->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9230. return false;
  9231. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9232. return false;
  9233. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9234. auto typeOptions = GetTypeOptions();
  9235. if (typeOptions != NULL)
  9236. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9237. if (!emitObjectAccessCheck)
  9238. return false;
  9239. return true;
  9240. }
  9241. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  9242. {
  9243. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9244. return;
  9245. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9246. return;
  9247. if (typedVal.mValue.IsConst())
  9248. {
  9249. int stringIdx = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  9250. if (stringIdx != -1)
  9251. return;
  9252. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  9253. if (constant->mTypeCode == BfTypeCode_NullPtr)
  9254. return;
  9255. if (constant->mConstType == BfConstType_BitCastNull)
  9256. return;
  9257. }
  9258. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9259. auto typeOptions = GetTypeOptions();
  9260. if (typeOptions != NULL)
  9261. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9262. if (!emitObjectAccessCheck)
  9263. return;
  9264. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  9265. {
  9266. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  9267. return;
  9268. }
  9269. if (typedVal.IsAddr())
  9270. typedVal = LoadValue(typedVal);
  9271. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  9272. }
  9273. bool BfModule::WantsDebugHelpers()
  9274. {
  9275. if (mBfIRBuilder->mIgnoreWrites)
  9276. return false;
  9277. if (mIsComptimeModule)
  9278. {
  9279. // Always add
  9280. }
  9281. else if ((mProject == NULL) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  9282. return false;
  9283. return true;
  9284. }
  9285. void BfModule::EmitEnsureInstructionAt()
  9286. {
  9287. if (!WantsDebugHelpers())
  9288. return;
  9289. mBfIRBuilder->CreateEnsureInstructionAt();
  9290. }
  9291. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  9292. {
  9293. if (mBfIRBuilder->mIgnoreWrites)
  9294. return; // Nothing needed here
  9295. auto irb = mBfIRBuilder;
  9296. auto checkBB = irb->CreateBlock("as.check");
  9297. auto isNull = irb->CreateIsNull(targetValue.mValue);
  9298. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  9299. if (mIsComptimeModule)
  9300. {
  9301. AddBasicBlock(checkBB);
  9302. auto callResult = mBfIRBuilder->Comptime_DynamicCastCheck(targetValue.mValue, targetType->mTypeId, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9303. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult, GetDefaultValue(mContext->mBfObjectType));
  9304. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9305. return;
  9306. }
  9307. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  9308. auto intPtrType = CreatePointerType(intType);
  9309. auto intPtrPtrType = CreatePointerType(intPtrType);
  9310. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  9311. auto int32PtrType = CreatePointerType(int32Type);
  9312. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  9313. if (mCompiler->mOptions.mAllowHotSwapping)
  9314. {
  9315. BfExprEvaluator exprEvaluator(this);
  9316. AddBasicBlock(checkBB);
  9317. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9318. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  9319. SizedArray<BfIRValue, 4> irArgs;
  9320. irArgs.push_back(objectParam);
  9321. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  9322. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  9323. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  9324. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9325. }
  9326. else
  9327. {
  9328. AddBasicBlock(checkBB);
  9329. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  9330. vDataPtr = irb->CreateLoad(vDataPtr);
  9331. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9332. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  9333. if (targetType->IsInterface())
  9334. {
  9335. auto targetTypeInst = targetType->ToTypeInstance();
  9336. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9337. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  9338. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  9339. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9340. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  9341. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  9342. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  9343. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  9344. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  9345. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9346. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  9347. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  9348. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9349. }
  9350. else
  9351. {
  9352. if (!targetType->IsTypeInstance())
  9353. targetType = GetWrappedStructType(targetType);
  9354. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9355. int inheritanceIdOfs = mSystem->mPtrSize * mCompiler->GetVDataPrefixDataCount();
  9356. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9357. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9358. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  9359. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  9360. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  9361. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  9362. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  9363. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9364. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  9365. fieldInst = &typeTypeInstance->mFieldInstances[10];
  9366. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  9367. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9368. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  9369. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  9370. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  9371. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9372. }
  9373. }
  9374. }
  9375. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  9376. {
  9377. if (mBfIRBuilder->mIgnoreWrites)
  9378. return;
  9379. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  9380. auto typeOptions = GetTypeOptions();
  9381. if (typeOptions != NULL)
  9382. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  9383. if (emitDynamicCastCheck)
  9384. {
  9385. int wantTypeId = 0;
  9386. if (!type->IsGenericParam())
  9387. wantTypeId = type->mTypeId;
  9388. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  9389. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  9390. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  9391. AddBasicBlock(failBlock);
  9392. if (mIsComptimeModule)
  9393. {
  9394. mBfIRBuilder->Comptime_Error(CeErrorKind_ObjectDynCheckFailed);
  9395. }
  9396. else
  9397. {
  9398. SizedArray<BfIRValue, 8> llvmArgs;
  9399. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9400. llvmArgs.push_back(bitAddr);
  9401. llvmArgs.push_back(GetConstValue32(wantTypeId));
  9402. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  9403. BF_ASSERT(objDynCheck);
  9404. if (objDynCheck)
  9405. {
  9406. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  9407. }
  9408. }
  9409. mBfIRBuilder->CreateBr(endBlock);
  9410. AddBasicBlock(endBlock);
  9411. }
  9412. }
  9413. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, BfCastFlags castFlags)
  9414. {
  9415. bool callDtor = (castFlags & BfCastFlags_NoBoxDtor) == 0;
  9416. bool wantConst = ((castFlags & BfCastFlags_WantsConst) != 0) && (typedVal.mValue.IsConst());
  9417. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9418. {
  9419. if (toType == mContext->mBfObjectType)
  9420. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9421. if (toType->IsBoxed())
  9422. {
  9423. BfBoxedType* boxedType = (BfBoxedType*)toType;
  9424. if (boxedType->mElementType->IsGenericParam())
  9425. {
  9426. if (typedVal.mType == boxedType->mElementType)
  9427. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9428. else
  9429. return BfTypedValue();
  9430. }
  9431. }
  9432. }
  9433. BP_ZONE("BoxValue");
  9434. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  9435. if (typedVal.mType->IsNullable())
  9436. {
  9437. typedVal = MakeAddressable(typedVal);
  9438. auto innerType = typedVal.mType->GetUnderlyingType();
  9439. if (!innerType->IsValueType())
  9440. {
  9441. if (!mIgnoreErrors)
  9442. Fail("Only value types can be boxed", srcNode);
  9443. return BfTypedValue();
  9444. }
  9445. auto boxedType = CreateBoxedType(innerType);
  9446. auto resultType = toType;
  9447. if (resultType == NULL)
  9448. resultType = boxedType;
  9449. if (mBfIRBuilder->mIgnoreWrites)
  9450. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  9451. auto prevBB = mBfIRBuilder->GetInsertBlock();
  9452. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  9453. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  9454. mBfIRBuilder->PopulateType(typedVal.mType);
  9455. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  9456. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  9457. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  9458. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9459. mBfIRBuilder->AddBlock(boxBB);
  9460. mBfIRBuilder->SetInsertPoint(boxBB);
  9461. BfScopeData newScope;
  9462. newScope.mOuterIsConditional = true;
  9463. mCurMethodState->AddScope(&newScope);
  9464. NewScopeState();
  9465. BfIRValue nullableValueAddr;
  9466. BfIRValue loadedVal;
  9467. if (innerType->IsValuelessType())
  9468. {
  9469. loadedVal = mBfIRBuilder->GetFakeVal();
  9470. }
  9471. else
  9472. {
  9473. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  9474. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  9475. }
  9476. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor ? BfCastFlags_None : BfCastFlags_NoBoxDtor);
  9477. RestoreScopeState();
  9478. if (!boxedVal)
  9479. return BfTypedValue();
  9480. mBfIRBuilder->CreateBr(endBB);
  9481. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  9482. mBfIRBuilder->AddBlock(endBB);
  9483. mBfIRBuilder->SetInsertPoint(endBB);
  9484. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  9485. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  9486. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  9487. return BfTypedValue(phi, resultType);
  9488. }
  9489. bool alreadyCheckedCast = false;
  9490. BfTypeInstance* toTypeInstance = NULL;
  9491. if (toType != NULL)
  9492. toTypeInstance = toType->ToTypeInstance();
  9493. bool isStructPtr = typedVal.mType->IsStructPtr();
  9494. if (fromStructTypeInstance == NULL)
  9495. {
  9496. auto primType = (BfPrimitiveType*)typedVal.mType;
  9497. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  9498. {
  9499. // Can always do IHashable
  9500. alreadyCheckedCast = true;
  9501. }
  9502. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  9503. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9504. else
  9505. {
  9506. auto checkStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9507. if (checkStructTypeInstance == toType->GetUnderlyingType())
  9508. fromStructTypeInstance = checkStructTypeInstance;
  9509. }
  9510. if (isStructPtr)
  9511. {
  9512. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9513. alreadyCheckedCast = true;
  9514. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  9515. }
  9516. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  9517. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9518. }
  9519. if (fromStructTypeInstance == NULL)
  9520. return BfTypedValue();
  9521. // Need to box it
  9522. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  9523. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9524. {
  9525. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9526. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  9527. auto boxedType = CreateBoxedType(typedVal.mType);
  9528. mBfIRBuilder->PopulateType(boxedType);
  9529. if (wantConst)
  9530. return BfTypedValue(mBfIRBuilder->CreateConstBox(typedVal.mValue, mBfIRBuilder->MapType(boxedType)), boxedType);
  9531. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9532. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  9533. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  9534. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  9535. if (boxedType->IsUnspecializedType())
  9536. {
  9537. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  9538. }
  9539. else
  9540. {
  9541. PopulateType(fromStructTypeInstance);
  9542. if (!fromStructTypeInstance->IsValuelessType())
  9543. {
  9544. typedVal = LoadValue(typedVal);
  9545. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  9546. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  9547. {
  9548. auto ptrType = CreatePointerType(typedVal.mType);
  9549. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  9550. }
  9551. if (typedVal.IsSplat())
  9552. {
  9553. AggregateSplatIntoAddr(typedVal, valPtr);
  9554. }
  9555. else
  9556. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr, typedVal.mType->mAlign);
  9557. }
  9558. }
  9559. if (toType == NULL)
  9560. {
  9561. return BfTypedValue(allocaInst, boxedType);
  9562. }
  9563. else
  9564. {
  9565. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  9566. return BfTypedValue(castedValue, toType);
  9567. }
  9568. }
  9569. return BfTypedValue();
  9570. }
  9571. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  9572. {
  9573. BfTypeInstance* checkTypeInst = typeInst;
  9574. while (checkTypeInst != NULL)
  9575. {
  9576. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  9577. {
  9578. if (checkProp->mName == propDef->mName)
  9579. {
  9580. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  9581. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  9582. {
  9583. propDef = checkProp;
  9584. typeInst = checkTypeInst;
  9585. return true;
  9586. }
  9587. }
  9588. }
  9589. checkTypeInst = checkTypeInst->mBaseType;
  9590. }
  9591. return false;
  9592. }
  9593. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  9594. {
  9595. if (!typeInstance->mResolvingVarField)
  9596. {
  9597. if (!typeInstance->DefineStateAllowsStaticMethods())
  9598. PopulateType(typeInstance, BfPopulateType_AllowStaticMethods);
  9599. }
  9600. else
  9601. {
  9602. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  9603. {
  9604. AssertErrorState();
  9605. return NULL;
  9606. }
  9607. }
  9608. if (assertName != NULL)
  9609. {
  9610. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9611. }
  9612. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9613. {
  9614. if (mCompiler->EnsureCeUnpaused(typeInstance))
  9615. {
  9616. InternalError("OOB in GetRawMethodInstanceAtIdx");
  9617. }
  9618. return NULL;
  9619. }
  9620. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  9621. if (methodGroup.mDefault == NULL)
  9622. {
  9623. if (!mCompiler->mIsResolveOnly)
  9624. {
  9625. // Get it from the owning module so we don't create a reference prematurely...
  9626. auto declModule = typeInstance->mModule;
  9627. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  9628. {
  9629. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9630. if (!declModule->mIsScratchModule)
  9631. declModule->mOnDemandMethodCount++;
  9632. }
  9633. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  9634. (typeInstance->mTypeFailed) || (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted));
  9635. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  9636. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9637. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified);
  9638. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9639. }
  9640. else
  9641. {
  9642. auto declModule = typeInstance->mModule;
  9643. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass);
  9644. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9645. }
  9646. }
  9647. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9648. //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
  9649. // be from a call to the NON-raw version
  9650. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  9651. // {
  9652. // methodInstance->mIsReified = mIsReified;
  9653. // if (methodInstance->mMethodProcessRequest == NULL)
  9654. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  9655. // }
  9656. return methodInstance;
  9657. }
  9658. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  9659. {
  9660. if (methodDef->mIsLocalMethod)
  9661. {
  9662. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  9663. }
  9664. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx, NULL);
  9665. }
  9666. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  9667. {
  9668. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9669. while (typeInstance != NULL)
  9670. {
  9671. typeInstance->mTypeDef->PopulateMemberSets();
  9672. BfMemberSetEntry* entry = NULL;
  9673. BfMethodDef* methodDef = NULL;
  9674. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9675. methodDef = (BfMethodDef*)entry->mMemberDef;
  9676. while (methodDef != NULL)
  9677. {
  9678. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  9679. (methodDef->mGenericParams.size() == 0) &&
  9680. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9681. return GetRawMethodInstance(typeInstance, methodDef);
  9682. methodDef = methodDef->mNextWithSameName;
  9683. }
  9684. if (!checkBase)
  9685. break;
  9686. typeInstance = typeInstance->mBaseType;
  9687. }
  9688. return NULL;
  9689. }
  9690. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  9691. {
  9692. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9693. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  9694. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  9695. if (!useUnspecializedType)
  9696. return methodInstance;
  9697. if (!owner->IsGenericTypeInstance())
  9698. return methodInstance;
  9699. if ((owner->IsDelegateFromTypeRef()) ||
  9700. (owner->IsFunctionFromTypeRef()) ||
  9701. (owner->IsTuple()))
  9702. {
  9703. return methodInstance;
  9704. }
  9705. auto genericType = (BfTypeInstance*)owner;
  9706. if ((genericType->IsUnspecializedType()) && (!genericType->IsUnspecializedTypeVariation()))
  9707. return methodInstance;
  9708. if (methodInstance->mMethodDef->mIsLocalMethod)
  9709. return methodInstance;
  9710. if (methodInstance->mMethodDef->mDeclaringType->IsEmitted())
  9711. return methodInstance;
  9712. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef->GetDefinition());
  9713. if (unspecializedType == NULL)
  9714. {
  9715. AssertErrorState();
  9716. return methodInstance;
  9717. }
  9718. if (unspecializedType == NULL)
  9719. return methodInstance;
  9720. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  9721. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  9722. }
  9723. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  9724. {
  9725. int genericCount = 0;
  9726. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  9727. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  9728. {
  9729. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  9730. if (param->IsGenericParam())
  9731. genericCount++;
  9732. }
  9733. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  9734. genericCount++;
  9735. return genericCount;
  9736. }
  9737. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  9738. {
  9739. BF_ASSERT(!mIsScratchModule);
  9740. BF_ASSERT(mIsReified);
  9741. BfModule* mainModule = this;
  9742. if (mParentModule != NULL)
  9743. mainModule = mParentModule;
  9744. BfModule* specModule = NULL;
  9745. BfModule** specModulePtr = NULL;
  9746. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  9747. {
  9748. return *specModulePtr;
  9749. }
  9750. else
  9751. {
  9752. String specModuleName = mModuleName;
  9753. for (auto bfProject : projectList)
  9754. {
  9755. specModuleName += StrFormat("@%s", bfProject->mSafeName.c_str());
  9756. }
  9757. specModule = new BfModule(mContext, specModuleName);
  9758. specModule->mProject = mainModule->mProject;
  9759. specModule->mParentModule = mainModule;
  9760. specModule->mIsSpecializedMethodModuleRoot = true;
  9761. specModule->Init();
  9762. Array<BfProject*> projList;
  9763. for (auto project : projectList)
  9764. projList.Add(project);
  9765. mainModule->mSpecializedMethodModules[projList] = specModule;
  9766. }
  9767. return specModule;
  9768. }
  9769. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  9770. {
  9771. if (IsSkippingExtraResolveChecks())
  9772. return BfIRValue();
  9773. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  9774. {
  9775. //BF_ASSERT(!methodInstance->mIRFunction);
  9776. return BfIRValue();
  9777. }
  9778. auto methodDef = methodInstance->mMethodDef;
  9779. StringT<4096> methodName;
  9780. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  9781. if (isInlined != methodInstance->mAlwaysInline)
  9782. {
  9783. if (isInlined)
  9784. methodName += "__INLINE";
  9785. else
  9786. methodName += "__NOINLINE";
  9787. }
  9788. if (tryExisting)
  9789. {
  9790. auto func = mBfIRBuilder->GetFunction(methodName);
  9791. if (func)
  9792. return func;
  9793. }
  9794. auto intrinsic = GetIntrinsic(methodInstance);
  9795. if (intrinsic)
  9796. return intrinsic;
  9797. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  9798. {
  9799. return CreateDllImportGlobalVar(methodInstance, false);
  9800. }
  9801. BfIRType returnType;
  9802. SizedArray<BfIRType, 8> paramTypes;
  9803. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  9804. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  9805. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  9806. auto callingConv = GetIRCallingConvention(methodInstance);
  9807. if (callingConv != BfIRCallingConv_CDecl)
  9808. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  9809. SetupIRMethod(methodInstance, func, isInlined);
  9810. // auto srcModule = methodInstance->GetOwner()->GetModule();
  9811. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  9812. // {
  9813. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  9814. // {
  9815. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  9816. // }
  9817. // }
  9818. return func;
  9819. }
  9820. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  9821. {
  9822. if (assertName != NULL)
  9823. {
  9824. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9825. }
  9826. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9827. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9828. return BfModuleMethodInstance();
  9829. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9830. BfMethodDef* methodDef = NULL;
  9831. BfTypeInstance* foreignType = NULL;
  9832. if (methodInstance != NULL)
  9833. {
  9834. methodDef = methodInstance->mMethodDef;
  9835. if (methodInstance->mMethodInfoEx != NULL)
  9836. foreignType = methodInstance->mMethodInfoEx->mForeignType;
  9837. }
  9838. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  9839. {
  9840. // Can't use it, not reified
  9841. methodInstance = NULL;
  9842. }
  9843. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  9844. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  9845. {
  9846. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  9847. return BfModuleMethodInstance(methodInstance, func);
  9848. }
  9849. if (foreignType != NULL)
  9850. return GetMethodInstance(typeInstance, methodDef, BfTypeVector(), (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef), foreignType);
  9851. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  9852. }
  9853. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9854. {
  9855. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9856. while (typeInstance != NULL)
  9857. {
  9858. typeInstance->mTypeDef->PopulateMemberSets();
  9859. BfMemberSetEntry* entry = NULL;
  9860. BfMethodDef* methodDef = NULL;
  9861. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9862. methodDef = (BfMethodDef*)entry->mMemberDef;
  9863. while (methodDef != NULL)
  9864. {
  9865. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9866. (methodDef->mGenericParams.size() == 0) &&
  9867. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9868. {
  9869. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9870. if (moduleMethodInstance)
  9871. return moduleMethodInstance;
  9872. }
  9873. methodDef = methodDef->mNextWithSameName;
  9874. }
  9875. if (!checkBase)
  9876. break;
  9877. typeInstance = typeInstance->mBaseType;
  9878. }
  9879. return BfModuleMethodInstance();
  9880. }
  9881. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  9882. {
  9883. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9884. while (typeInstance != NULL)
  9885. {
  9886. typeInstance->mTypeDef->PopulateMemberSets();
  9887. BfMemberSetEntry* entry = NULL;
  9888. BfMethodDef* methodDef = NULL;
  9889. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9890. methodDef = (BfMethodDef*)entry->mMemberDef;
  9891. while (methodDef != NULL)
  9892. {
  9893. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9894. (methodDef->mGenericParams.size() == 0) &&
  9895. (paramTypes.size() == methodDef->mParams.size()))
  9896. {
  9897. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9898. if (moduleMethodInstance.mMethodInstance != NULL)
  9899. {
  9900. bool matches = true;
  9901. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  9902. {
  9903. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  9904. matches = false;
  9905. }
  9906. if (matches)
  9907. return moduleMethodInstance;
  9908. }
  9909. }
  9910. methodDef = methodDef->mNextWithSameName;
  9911. }
  9912. if (!checkBase)
  9913. break;
  9914. typeInstance = typeInstance->mBaseType;
  9915. }
  9916. return BfModuleMethodInstance();
  9917. }
  9918. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  9919. {
  9920. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  9921. PopulateType(internalType);
  9922. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  9923. if (!moduleMethodInstance)
  9924. {
  9925. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  9926. }
  9927. return moduleMethodInstance;
  9928. }
  9929. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  9930. {
  9931. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  9932. typeInstance->mOperatorInfo.Add(NULL);
  9933. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  9934. {
  9935. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  9936. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  9937. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  9938. BfTypeState typeState;
  9939. typeState.mType = typeInstance;
  9940. typeState.mCurTypeDef = operatorDef->mDeclaringType;
  9941. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  9942. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  9943. if (operatorDef->mReturnTypeRef != NULL)
  9944. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  9945. if (operatorDef->mParams.size() >= 1)
  9946. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  9947. if (operatorDef->mParams.size() >= 2)
  9948. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  9949. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  9950. }
  9951. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  9952. }
  9953. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  9954. {
  9955. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  9956. if (operatorInfo == NULL)
  9957. return NULL;
  9958. if (operatorInfo->mReturnType == NULL)
  9959. return NULL;
  9960. auto castFlags = BfCastFlags_IsConstraintCheck;
  9961. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9962. castFlags = (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator);
  9963. if (lhs)
  9964. {
  9965. if (operatorInfo->mLHSType == NULL)
  9966. return NULL;
  9967. if (!CanCast(lhs, operatorInfo->mLHSType, castFlags))
  9968. return NULL;
  9969. }
  9970. if (rhs)
  9971. {
  9972. if (operatorInfo->mRHSType == NULL)
  9973. return NULL;
  9974. if (!CanCast(rhs, operatorInfo->mRHSType, castFlags))
  9975. return NULL;
  9976. }
  9977. return operatorInfo->mReturnType;
  9978. }
  9979. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9980. {
  9981. while (typeInstance != NULL)
  9982. {
  9983. typeInstance->mTypeDef->PopulateMemberSets();
  9984. BfMemberSetEntry* entry = NULL;
  9985. BfMethodDef* methodDef = NULL;
  9986. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9987. methodDef = (BfMethodDef*)entry->mMemberDef;
  9988. while (methodDef != NULL)
  9989. {
  9990. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9991. (methodDef->mGenericParams.size() == 0) &&
  9992. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9993. {
  9994. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  9995. if (!methodInstanceGroup.IsImplemented())
  9996. return false;
  9997. if (methodInstanceGroup.mDefault == NULL)
  9998. return false;
  9999. return methodInstanceGroup.mDefault->mIsReified;
  10000. }
  10001. methodDef = methodDef->mNextWithSameName;
  10002. }
  10003. if (!checkBase)
  10004. break;
  10005. typeInstance = typeInstance->mBaseType;
  10006. }
  10007. return false;
  10008. }
  10009. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  10010. {
  10011. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  10012. while (typeInstance != NULL)
  10013. {
  10014. typeInstance->mTypeDef->PopulateMemberSets();
  10015. BfMemberSetEntry* entry = NULL;
  10016. BfMethodDef* methodDef = NULL;
  10017. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10018. methodDef = (BfMethodDef*)entry->mMemberDef;
  10019. while (methodDef != NULL)
  10020. {
  10021. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  10022. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  10023. return true;
  10024. methodDef = methodDef->mNextWithSameName;
  10025. }
  10026. if (!checkBase)
  10027. break;
  10028. typeInstance = typeInstance->mBaseType;
  10029. }
  10030. return BfModuleMethodInstance();
  10031. }
  10032. String BfModule::FieldToString(BfFieldInstance* fieldInstance)
  10033. {
  10034. auto result = TypeToString(fieldInstance->mOwner);
  10035. result += ".";
  10036. auto fieldDef = fieldInstance->GetFieldDef();
  10037. if (fieldDef != NULL)
  10038. result += fieldDef->mName;
  10039. else
  10040. result += "???";
  10041. return result;
  10042. }
  10043. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* typeGenericArgs, BfTypeVector* methodGenericArgs)
  10044. {
  10045. auto methodDef = methodInst->mMethodDef;
  10046. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  10047. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10048. bool hasGenericArgs = (typeGenericArgs != NULL) || (methodGenericArgs != NULL);
  10049. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  10050. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  10051. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  10052. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  10053. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10054. if (allowResolveGenericParamNames)
  10055. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10056. StringT<128> methodName;
  10057. auto _AddTypeName = [&](BfType* type)
  10058. {
  10059. auto typeNameFlags = BfTypeNameFlags_None;
  10060. if (allowResolveGenericParamNames)
  10061. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10062. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  10063. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  10064. methodName += TypeToString(type, typeNameFlags);
  10065. };
  10066. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  10067. {
  10068. _AddTypeName(methodInst->mReturnType);
  10069. methodName += " ";
  10070. }
  10071. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  10072. {
  10073. methodName += TypeToString(type, typeNameFlags);
  10074. if (methodName == "$")
  10075. methodName = "";
  10076. else if (!methodName.IsEmpty())
  10077. methodName += ".";
  10078. }
  10079. String accessorString;
  10080. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  10081. if (methodInst->mMethodDef->mIsLocalMethod)
  10082. {
  10083. int atPos = (int)methodDefName.IndexOf('$');
  10084. methodDefName.RemoveToEnd(atPos);
  10085. methodDefName.Replace("@", ".");
  10086. }
  10087. else
  10088. {
  10089. int atPos = (int)methodDefName.IndexOf('$');
  10090. if (atPos != -1)
  10091. {
  10092. accessorString = methodDefName.Substring(0, atPos);
  10093. if ((accessorString == "get") || (accessorString == "set"))
  10094. {
  10095. methodDefName = methodDefName.Substring(atPos + 1);
  10096. }
  10097. else
  10098. accessorString = "";
  10099. }
  10100. }
  10101. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  10102. {
  10103. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10104. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10105. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10106. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  10107. methodName += ".";
  10108. }
  10109. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  10110. {
  10111. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10112. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10113. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10114. methodName += "[";
  10115. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  10116. methodName += "].";
  10117. }
  10118. if (methodDef->mMethodType == BfMethodType_Operator)
  10119. {
  10120. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  10121. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  10122. {
  10123. // Don't add explicit/implicit part, since that's not available in GCC mangling
  10124. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  10125. {
  10126. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  10127. methodName += "explicit ";
  10128. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  10129. methodName += "explicit ";
  10130. }*/
  10131. methodName += "operator ";
  10132. if (methodInst->mReturnType != NULL)
  10133. methodName += TypeToString(methodInst->mReturnType);
  10134. }
  10135. else
  10136. {
  10137. methodName += "operator";
  10138. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  10139. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  10140. }
  10141. }
  10142. else if (methodDef->mMethodType == BfMethodType_Ctor)
  10143. {
  10144. if (methodDef->mIsStatic)
  10145. methodName += "__BfStaticCtor";
  10146. else
  10147. methodName += "this";
  10148. accessorString = "";
  10149. }
  10150. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  10151. {
  10152. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10153. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10154. {
  10155. methodName += "get indexer";
  10156. }
  10157. else
  10158. {
  10159. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10160. propertyDecl->mNameNode->ToString(methodName);
  10161. methodName += " get accessor";
  10162. return methodName;
  10163. }
  10164. }
  10165. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10166. {
  10167. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10168. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10169. {
  10170. methodName += "set indexer";
  10171. }
  10172. else
  10173. {
  10174. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10175. propertyDecl->mNameNode->ToString(methodName);
  10176. methodName += " set accessor";
  10177. return methodName;
  10178. }
  10179. }
  10180. else
  10181. methodName += methodDefName;
  10182. if (methodDef->mMethodType == BfMethodType_Mixin)
  10183. methodName += "!";
  10184. BfTypeVector newMethodGenericArgs;
  10185. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  10186. {
  10187. methodName += "<";
  10188. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  10189. {
  10190. if (i > 0)
  10191. methodName += ", ";
  10192. BfTypeNameFlags typeNameFlags = BfTypeNameFlag_ShortConst;
  10193. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  10194. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10195. if (allowResolveGenericParamNames)
  10196. typeNameFlags = (BfTypeNameFlags)(typeNameFlags | BfTypeNameFlag_ResolveGenericParamNames);
  10197. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  10198. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  10199. {
  10200. bool hasEmpty = false;
  10201. for (auto arg : *methodGenericArgs)
  10202. {
  10203. if (arg == NULL)
  10204. hasEmpty = true;
  10205. }
  10206. if (hasEmpty)
  10207. {
  10208. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  10209. {
  10210. auto arg = (*methodGenericArgs)[genericIdx];
  10211. if (arg != NULL)
  10212. newMethodGenericArgs.push_back(arg);
  10213. else
  10214. {
  10215. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  10216. if (genericParamInst->mTypeConstraint != NULL)
  10217. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  10218. else
  10219. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  10220. }
  10221. }
  10222. methodGenericArgs = &newMethodGenericArgs;
  10223. }
  10224. if (type->IsUnspecializedType())
  10225. type = ResolveGenericType(type, NULL, methodGenericArgs, mCurTypeInstance);
  10226. }
  10227. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  10228. {
  10229. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  10230. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  10231. methodName += TypeToString(type, typeNameFlags);
  10232. }
  10233. else
  10234. methodName += TypeToString(type, typeNameFlags);
  10235. }
  10236. methodName += ">";
  10237. }
  10238. if (accessorString.length() == 0)
  10239. {
  10240. int dispParamIdx = 0;
  10241. methodName += "(";
  10242. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  10243. {
  10244. int paramKind = methodInst->GetParamKind(paramIdx);
  10245. if ((paramKind == BfParamKind_ImplicitCapture) || (paramKind == BfParamKind_AppendIdx))
  10246. continue;
  10247. if (dispParamIdx > 0)
  10248. methodName += ", ";
  10249. if (paramKind == BfParamKind_Params)
  10250. methodName += "params ";
  10251. BfType* type = methodInst->GetParamType(paramIdx);
  10252. _AddTypeName(type);
  10253. methodName += " ";
  10254. methodName += methodInst->GetParamName(paramIdx);
  10255. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  10256. if ((paramInitializer != NULL) && ((methodNameFlags & BfMethodNameFlag_NoAst) == 0))
  10257. {
  10258. methodName += " = ";
  10259. methodName += paramInitializer->ToString();
  10260. }
  10261. dispParamIdx++;
  10262. }
  10263. methodName += ")";
  10264. }
  10265. if (accessorString.length() != 0)
  10266. {
  10267. methodName += " ";
  10268. methodName += accessorString;
  10269. }
  10270. if ((methodNameFlags & BfMethodNameFlag_IncludeMut) != 0)
  10271. {
  10272. if ((methodDef->mIsMutating) && (methodInst->GetOwner()->IsValueType()))
  10273. methodName += " mut";
  10274. }
  10275. return methodName;
  10276. }
  10277. void BfModule::pt(BfType* type)
  10278. {
  10279. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  10280. }
  10281. void BfModule::pm(BfMethodInstance* type)
  10282. {
  10283. OutputDebugStrF("%s\n", MethodToString(type).c_str());
  10284. }
  10285. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  10286. {
  10287. if ((flagsLeft & checkFlag) == 0)
  10288. return;
  10289. if (!str.empty())
  10290. {
  10291. if (flagsLeft == checkFlag)
  10292. {
  10293. if ((int)str.IndexOf(',') != -1)
  10294. str += ", and ";
  10295. else
  10296. str += " and ";
  10297. }
  10298. else
  10299. str += ", ";
  10300. }
  10301. str += addString;
  10302. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  10303. }
  10304. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  10305. {
  10306. String resultStr;
  10307. auto flagsLeft = attrTarget;
  10308. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  10309. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  10310. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  10311. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  10312. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  10313. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  10314. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  10315. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  10316. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  10317. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  10318. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  10319. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  10320. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  10321. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  10322. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  10323. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  10324. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  10325. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  10326. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  10327. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  10328. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  10329. if (resultStr.IsEmpty())
  10330. return "<nothing>";
  10331. return resultStr;
  10332. }
  10333. BfIRType BfModule::CurrentAddToConstHolder(BfIRType irType)
  10334. {
  10335. if (irType.mKind == BfIRTypeData::TypeKind_SizedArray)
  10336. {
  10337. auto sizedArrayType = (BfConstantSizedArrayType*)mBfIRBuilder->GetConstantById(irType.mId);
  10338. return mCurTypeInstance->GetOrCreateConstHolder()->GetSizedArrayType(CurrentAddToConstHolder(sizedArrayType->mType), (int)sizedArrayType->mLength);
  10339. }
  10340. return irType;
  10341. }
  10342. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  10343. {
  10344. auto constant = mBfIRBuilder->GetConstant(irVal);
  10345. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  10346. if (stringPoolIdx != -1)
  10347. {
  10348. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  10349. return;
  10350. }
  10351. if (constant->mConstType == BfConstType_Agg)
  10352. {
  10353. auto constArray = (BfConstantAgg*)constant;
  10354. SizedArray<BfIRValue, 8> newVals;
  10355. for (auto val : constArray->mValues)
  10356. {
  10357. auto newVal = val;
  10358. CurrentAddToConstHolder(newVal);
  10359. newVals.push_back(newVal);
  10360. }
  10361. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstAgg(CurrentAddToConstHolder(constArray->mType), newVals);
  10362. return;
  10363. }
  10364. auto origConst = irVal;
  10365. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10366. {
  10367. auto bitcast = (BfConstantBitCast*)constant;
  10368. BfIRValue newVal;
  10369. if (constant->mConstType == BfConstType_BitCast)
  10370. {
  10371. newVal = BfIRValue(BfIRValueFlags_Const, bitcast->mTarget);
  10372. CurrentAddToConstHolder(newVal);
  10373. }
  10374. else
  10375. newVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstNull();
  10376. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstBitCast(newVal, CurrentAddToConstHolder(bitcast->mToType));
  10377. return;
  10378. }
  10379. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  10380. }
  10381. void BfModule::ClearConstData()
  10382. {
  10383. mBfIRBuilder->ClearConstData();
  10384. mStringObjectPool.Clear();
  10385. mStringCharPtrPool.Clear();
  10386. mStringPoolRefs.Clear();
  10387. mUnreifiedStringPoolRefs.Clear();
  10388. mStaticFieldRefs.Clear();
  10389. }
  10390. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  10391. {
  10392. switch (constant->mTypeCode)
  10393. {
  10394. case BfTypeCode_StringId:
  10395. case BfTypeCode_Boolean:
  10396. case BfTypeCode_Int8:
  10397. case BfTypeCode_UInt8:
  10398. case BfTypeCode_Int16:
  10399. case BfTypeCode_UInt16:
  10400. case BfTypeCode_Int32:
  10401. case BfTypeCode_UInt32:
  10402. case BfTypeCode_Int64:
  10403. case BfTypeCode_UInt64:
  10404. case BfTypeCode_IntPtr:
  10405. case BfTypeCode_UIntPtr:
  10406. case BfTypeCode_IntUnknown:
  10407. case BfTypeCode_UIntUnknown:
  10408. case BfTypeCode_Char8:
  10409. case BfTypeCode_Char16:
  10410. case BfTypeCode_Char32:
  10411. case BfTypeCode_Float:
  10412. case BfTypeCode_Double:
  10413. {
  10414. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10415. BfTypedValue typedValue;
  10416. bool allowUnactualized = mBfIRBuilder->mIgnoreWrites;
  10417. if (constant->mTypeCode == BfTypeCode_StringId)
  10418. {
  10419. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10420. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10421. {
  10422. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType, allowUnactualized), wantType);
  10423. return typedValue;
  10424. }
  10425. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  10426. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType, allowUnactualized), stringType);
  10427. }
  10428. if (!typedValue)
  10429. {
  10430. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10431. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  10432. }
  10433. if (typedValue.mType == wantType)
  10434. return typedValue;
  10435. if (wantType->IsTypedPrimitive())
  10436. {
  10437. if (typedValue.mType == wantType->GetUnderlyingType())
  10438. {
  10439. typedValue.mType = wantType;
  10440. return typedValue;
  10441. }
  10442. }
  10443. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  10444. if (!castedTypedValue)
  10445. return BfTypedValue();
  10446. return castedTypedValue;
  10447. }
  10448. break;
  10449. default: break;
  10450. }
  10451. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  10452. BF_ASSERT(irValue);
  10453. if (!irValue)
  10454. return BfTypedValue();
  10455. if (constant->mConstType == BfConstType_GlobalVar)
  10456. {
  10457. mBfIRBuilder->PopulateType(wantType);
  10458. auto result = BfTypedValue(irValue, wantType, true);
  10459. if (!wantType->IsComposite())
  10460. result = LoadValue(result);
  10461. return result;
  10462. }
  10463. return BfTypedValue(irValue, wantType, false);
  10464. }
  10465. bool BfModule::HasUnactializedConstant(BfConstant* constant, BfIRConstHolder* constHolder)
  10466. {
  10467. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  10468. return true;
  10469. if (constant->mTypeCode == BfTypeCode_StringId)
  10470. return true;
  10471. if (constant->mConstType == BfConstType_Agg)
  10472. {
  10473. auto constArray = (BfConstantAgg*)constant;
  10474. for (auto val : constArray->mValues)
  10475. {
  10476. if (HasUnactializedConstant(constHolder->GetConstant(val), constHolder))
  10477. return true;
  10478. }
  10479. }
  10480. return false;
  10481. }
  10482. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType, bool allowUnactualized)
  10483. {
  10484. if (constant->mTypeCode == BfTypeCode_NullPtr)
  10485. {
  10486. if ((wantType == NULL) && (constant->mIRType.mKind == BfIRTypeData::TypeKind_TypeId))
  10487. wantType = mContext->mTypes[constant->mIRType.mId];
  10488. if (wantType == NULL)
  10489. return mBfIRBuilder->CreateConstNull();
  10490. return GetDefaultValue(wantType);
  10491. }
  10492. if (constant->mTypeCode == BfTypeCode_StringId)
  10493. {
  10494. if (!allowUnactualized)
  10495. {
  10496. if ((wantType == NULL) ||
  10497. (wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10498. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10499. {
  10500. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  10501. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  10502. if ((wantType != NULL) && (wantType->IsPointer()))
  10503. return GetStringCharPtr(stringObjConst, true);
  10504. return stringObjConst;
  10505. }
  10506. }
  10507. }
  10508. if (constant->mConstType == Beefy::BfConstType_TypeOf)
  10509. {
  10510. auto constTypeOf = (BfTypeOf_Const*)constant;
  10511. if (mCurTypeInstance != NULL)
  10512. AddDependency(constTypeOf->mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10513. return CreateTypeDataRef(constTypeOf->mType, true);
  10514. }
  10515. if (constant->mConstType == BfConstType_PtrToInt)
  10516. {
  10517. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  10518. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10519. return mBfIRBuilder->CreatePtrToInt(ConstantToCurrent(fromTarget, constHolder, NULL), fromPtrToInt->mToTypeCode);
  10520. }
  10521. if (constant->mConstType == BfConstType_IntToPtr)
  10522. {
  10523. auto fromPtrToInt = (BfConstantIntToPtr*)constant;
  10524. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10525. BfIRType toIRType = fromPtrToInt->mToType;
  10526. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10527. {
  10528. auto toType = mContext->mTypes[toIRType.mId];
  10529. toIRType = mBfIRBuilder->MapType(toType);
  10530. }
  10531. return mBfIRBuilder->CreateIntToPtr(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10532. }
  10533. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10534. {
  10535. auto bitcast = (BfConstantBitCast*)constant;
  10536. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  10537. BfIRType toIRType = bitcast->mToType;
  10538. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10539. {
  10540. auto toType = mContext->mTypes[toIRType.mId];
  10541. toIRType = mBfIRBuilder->MapType(toType);
  10542. }
  10543. return mBfIRBuilder->CreateBitCast(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10544. }
  10545. if (constant->mConstType == BfConstType_Agg)
  10546. {
  10547. auto constArray = (BfConstantAgg*)constant;
  10548. if ((wantType == NULL) && (constArray->mType.mKind == BfIRTypeData::TypeKind_TypeId))
  10549. wantType = mContext->mTypes[constArray->mType.mId];
  10550. if (wantType->IsArray())
  10551. wantType = CreateSizedArrayType(wantType->GetUnderlyingType(), (int)constArray->mValues.mSize);
  10552. bool handleAsArray = false;
  10553. SizedArray<BfIRValue, 8> newVals;
  10554. if (wantType->IsSizedArray())
  10555. {
  10556. handleAsArray = true;
  10557. }
  10558. else if (wantType->IsInstanceOf(mCompiler->mSpanTypeDef))
  10559. {
  10560. auto valueType = ResolveTypeDef(mCompiler->mValueTypeTypeDef);
  10561. handleAsArray = true;
  10562. if (!constArray->mValues.IsEmpty())
  10563. {
  10564. auto firstConstant = constHolder->GetConstant(constArray->mValues[0]);
  10565. if ((firstConstant->mConstType == BfConstType_AggZero) && (firstConstant->mIRType.mKind == BfIRType::TypeKind_TypeId) &&
  10566. (firstConstant->mIRType.mId == valueType->mTypeId))
  10567. handleAsArray = false;
  10568. if (firstConstant->mConstType == BfConstType_Agg)
  10569. {
  10570. auto firstConstArray = (BfConstantAgg*)firstConstant;
  10571. if ((firstConstArray->mType.mKind == BfIRType::TypeKind_TypeId) &&
  10572. (firstConstArray->mType.mId == valueType->mTypeId))
  10573. handleAsArray = false;
  10574. }
  10575. }
  10576. }
  10577. if (handleAsArray)
  10578. {
  10579. auto elementType = wantType->GetUnderlyingType();
  10580. for (auto val : constArray->mValues)
  10581. {
  10582. newVals.Add(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  10583. }
  10584. }
  10585. else
  10586. {
  10587. auto wantTypeInst = wantType->ToTypeInstance();
  10588. if (wantTypeInst == NULL)
  10589. {
  10590. InternalError("BfModule::ConstantToCurrent typeInst error");
  10591. return BfIRValue();
  10592. }
  10593. if (wantTypeInst->mBaseType != NULL)
  10594. {
  10595. auto baseVal = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[0]), constHolder, wantTypeInst->mBaseType);
  10596. newVals.Add(baseVal);
  10597. }
  10598. if (wantType->IsUnion())
  10599. {
  10600. auto innerType = wantType->ToTypeInstance()->GetUnionInnerType();
  10601. if (!innerType->IsValuelessType())
  10602. {
  10603. auto val = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[1]), constHolder, innerType);
  10604. newVals.Add(val);
  10605. }
  10606. }
  10607. if ((!wantType->IsUnion()) || (wantType->IsPayloadEnum()))
  10608. {
  10609. for (auto& fieldInstance : wantTypeInst->mFieldInstances)
  10610. {
  10611. if (fieldInstance.mDataIdx < 0)
  10612. continue;
  10613. if (fieldInstance.mDataIdx >= constArray->mValues.mSize)
  10614. {
  10615. InternalError("BfModule::ConstantToCurrent union error");
  10616. return BfIRValue();
  10617. }
  10618. auto val = constArray->mValues[fieldInstance.mDataIdx];
  10619. BfIRValue memberVal = ConstantToCurrent(constHolder->GetConstant(val), constHolder, fieldInstance.mResolvedType);
  10620. if (fieldInstance.mDataIdx == newVals.mSize)
  10621. newVals.Add(memberVal);
  10622. else
  10623. {
  10624. while (fieldInstance.mDataIdx >= newVals.mSize)
  10625. newVals.Add(BfIRValue());
  10626. newVals[fieldInstance.mDataIdx] = memberVal;
  10627. }
  10628. }
  10629. }
  10630. for (auto& val : newVals)
  10631. {
  10632. if (!val)
  10633. val = mBfIRBuilder->CreateConstArrayZero(0);
  10634. }
  10635. }
  10636. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(wantType, BfIRPopulateType_Identity), newVals);
  10637. }
  10638. return mBfIRBuilder->CreateConst(constant, constHolder);
  10639. }
  10640. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget, bool force)
  10641. {
  10642. if (attrTarget == BfAttributeTargets_SkipValidate)
  10643. return;
  10644. for (auto& customAttribute : customAttributes->mAttributes)
  10645. {
  10646. if (!customAttribute.mAwaitingValidation)
  10647. continue;
  10648. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  10649. {
  10650. if ((customAttribute.mIsMultiUse) && (!force))
  10651. continue;
  10652. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  10653. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  10654. }
  10655. customAttribute.mAwaitingValidation = false;
  10656. }
  10657. }
  10658. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10659. {
  10660. bool allowNonConstArgs = (flags & BfGetCustomAttributesFlags_AllowNonConstArgs) != 0;
  10661. bool keepConstsInModule = (flags & BfGetCustomAttributesFlags_KeepConstsInModule) != 0;
  10662. if (!mCompiler->mHasRequiredTypes)
  10663. return;
  10664. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  10665. {
  10666. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  10667. sourceClassifier->VisitChild(attributesDirective);
  10668. }
  10669. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  10670. if (mCompiler->IsAutocomplete())
  10671. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  10672. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  10673. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  10674. BfTypeDef* activeTypeDef = GetActiveTypeDef();
  10675. BfAutoComplete* autoComplete = NULL;
  10676. if (mCompiler->mResolvePassData != NULL)
  10677. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  10678. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  10679. {
  10680. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  10681. {
  10682. if (captureInfo == NULL)
  10683. {
  10684. Fail("Capture specifiers can only be used in lambda allocations", tokenNode);
  10685. continue;
  10686. }
  10687. BfCaptureInfo::Entry captureEntry;
  10688. captureEntry.mRefNode = tokenNode;
  10689. captureEntry.mCaptureType = BfCaptureType_Copy;
  10690. if (tokenNode->mToken == BfToken_Ampersand)
  10691. captureEntry.mCaptureType = BfCaptureType_Reference;
  10692. if (tokenNode->mToken == BfToken_Question)
  10693. captureEntry.mCaptureType = BfCaptureType_Auto;
  10694. if (!attributesDirective->mArguments.IsEmpty())
  10695. {
  10696. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]))
  10697. captureEntry.mNameNode = identifierNode;
  10698. else if (auto thisExpr = BfNodeDynCast<BfThisExpression>(attributesDirective->mArguments[0]))
  10699. {
  10700. captureEntry.mNameNode = thisExpr;
  10701. }
  10702. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  10703. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  10704. }
  10705. captureInfo->mCaptures.Add(captureEntry);
  10706. continue;
  10707. }
  10708. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  10709. BfCustomAttribute customAttribute;
  10710. customAttribute.mAwaitingValidation = true;
  10711. customAttribute.mDeclaringType = activeTypeDef;
  10712. customAttribute.mRef = attributesDirective;
  10713. customAttribute.mIsMultiUse = attributesDirective->mIsMultiUse;
  10714. if (attributesDirective->mAttrOpenToken != NULL)
  10715. targetOverride = (BfAttributeTargets)0;
  10716. if (attributesDirective->mAttributeTypeRef == NULL)
  10717. {
  10718. AssertErrorState();
  10719. continue;
  10720. }
  10721. BfType* attrType;
  10722. if (mContext->mCurTypeState != NULL)
  10723. {
  10724. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10725. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10726. }
  10727. else
  10728. {
  10729. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10730. }
  10731. BfTypeDef* attrTypeDef = NULL;
  10732. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  10733. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  10734. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10735. {
  10736. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  10737. if (attrTypeDef != NULL)
  10738. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  10739. }
  10740. bool isBypassedAttr = false;
  10741. if (attrTypeDef != NULL)
  10742. {
  10743. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  10744. // We solve it by having a 'bypass' for known attributes that Object depends on
  10745. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  10746. {
  10747. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  10748. {
  10749. for (auto methodDef : attrTypeDef->mMethods)
  10750. {
  10751. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  10752. {
  10753. customAttribute.mType = attrType->ToTypeInstance();
  10754. customAttribute.mCtor = methodDef;
  10755. isBypassedAttr = true;
  10756. break;
  10757. }
  10758. }
  10759. }
  10760. }
  10761. if (isBypassedAttr)
  10762. {
  10763. customAttribute.mAwaitingValidation = false;
  10764. customAttributes->mAttributes.push_back(customAttribute);
  10765. continue;
  10766. }
  10767. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInst(mContext->mUnreifiedModule->mCurTypeInstance, mCurTypeInstance);
  10768. SetAndRestoreValue<BfMethodInstance*> prevCurMethodInst(mContext->mUnreifiedModule->mCurMethodInstance, mCurMethodInstance);
  10769. if (mContext->mCurTypeState != NULL)
  10770. {
  10771. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10772. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10773. }
  10774. else
  10775. {
  10776. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10777. }
  10778. }
  10779. BfTypeInstance* attrTypeInst = NULL;
  10780. if (attrType == NULL)
  10781. continue;
  10782. attrTypeInst = attrType->ToTypeInstance();
  10783. if ((attrTypeInst != NULL) && (attrTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting))
  10784. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  10785. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  10786. {
  10787. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  10788. continue;
  10789. }
  10790. if ((mIsReified) && (attrTypeInst->mAttributeData != NULL) && ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_ReflectAttribute) != 0))
  10791. {
  10792. // Reify attribute
  10793. PopulateType(attrTypeInst);
  10794. }
  10795. if (mCurTypeInstance != NULL)
  10796. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10797. customAttribute.mType = attrTypeInst;
  10798. bool allocatedMethodState = NULL;
  10799. defer(
  10800. {
  10801. if (allocatedMethodState)
  10802. {
  10803. delete mCurMethodState;
  10804. mCurMethodState = NULL;
  10805. }
  10806. });
  10807. if (mCurMethodState == NULL)
  10808. {
  10809. allocatedMethodState = true;
  10810. mCurMethodState = new BfMethodState();
  10811. mCurMethodState->mTempKind = BfMethodState::TempKind_Static;
  10812. }
  10813. BfConstResolver constResolver(this);
  10814. if (allowNonConstArgs)
  10815. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  10816. bool inPropSet = false;
  10817. SizedArray<BfResolvedArg, 2> argValues;
  10818. for (BfExpression* arg : attributesDirective->mArguments)
  10819. {
  10820. if (arg == NULL)
  10821. {
  10822. continue;
  10823. }
  10824. if (autoComplete != NULL)
  10825. autoComplete->mShowAttributeProperties = attrTypeInst;
  10826. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  10827. {
  10828. inPropSet = true;
  10829. if (autoComplete != NULL)
  10830. autoComplete->CheckNode(assignExpr->mLeft, true);
  10831. String findName = assignExpr->mLeft->ToString();
  10832. BfPropertyDef* bestProp = NULL;
  10833. BfTypeInstance* bestPropTypeInst = NULL;
  10834. BfFieldDef* bestField = NULL;
  10835. BfTypeInstance* bestFieldTypeInst = NULL;
  10836. auto checkTypeInst = attrTypeInst;
  10837. while (checkTypeInst != NULL)
  10838. {
  10839. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  10840. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  10841. {
  10842. if (prop->mName == findName)
  10843. {
  10844. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  10845. {
  10846. bestProp = prop;
  10847. bestPropTypeInst = checkTypeInst;
  10848. }
  10849. }
  10850. }
  10851. for (auto field : checkTypeInst->mTypeDef->mFields)
  10852. {
  10853. if (field->mName == findName)
  10854. {
  10855. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  10856. {
  10857. bestField = field;
  10858. bestFieldTypeInst = checkTypeInst;
  10859. }
  10860. }
  10861. }
  10862. if ((bestProp != NULL) || (bestField != NULL))
  10863. break;
  10864. checkTypeInst = checkTypeInst->mBaseType;
  10865. }
  10866. bool handledExpr = false;
  10867. if (bestField != NULL)
  10868. {
  10869. handledExpr = true;
  10870. if (mCompiler->mResolvePassData != NULL)
  10871. {
  10872. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  10873. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10874. {
  10875. autoComplete->mDefField = bestField;
  10876. autoComplete->mDefType = attrTypeDef;
  10877. }
  10878. }
  10879. if (bestField->mProtection != BfProtection_Public)
  10880. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10881. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10882. BfCustomAttributeSetField setField;
  10883. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  10884. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  10885. if (assignExpr->mRight != NULL)
  10886. {
  10887. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType, BfConstResolveFlag_NoActualizeValues);
  10888. if (result)
  10889. {
  10890. if (!keepConstsInModule)
  10891. CurrentAddToConstHolder(result.mValue);
  10892. setField.mParam = result;
  10893. customAttribute.mSetField.push_back(setField);
  10894. }
  10895. }
  10896. }
  10897. else if (bestProp == NULL)
  10898. {
  10899. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  10900. }
  10901. else
  10902. {
  10903. BfMethodDef* setMethod = NULL;
  10904. for (auto methodDef : bestProp->mMethods)
  10905. {
  10906. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10907. {
  10908. setMethod = methodDef;
  10909. break;
  10910. }
  10911. }
  10912. if (setMethod == NULL)
  10913. {
  10914. Fail("Property has no setter", assignExpr->mLeft);
  10915. }
  10916. else
  10917. {
  10918. if (mCompiler->mResolvePassData != NULL)
  10919. {
  10920. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  10921. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10922. {
  10923. autoComplete->mDefProp = bestProp;
  10924. autoComplete->mDefType = attrTypeDef;
  10925. }
  10926. }
  10927. handledExpr = true;
  10928. if (bestProp->mProtection != BfProtection_Public)
  10929. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10930. BfResolvedArg resolvedArg;
  10931. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10932. BfCustomAttributeSetProperty setProperty;
  10933. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  10934. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  10935. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  10936. if (methodInstance.mMethodInstance != NULL)
  10937. {
  10938. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  10939. if (assignExpr->mRight != NULL)
  10940. {
  10941. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType, BfConstResolveFlag_NoActualizeValues);
  10942. if ((result) && (!result.mType->IsVar()))
  10943. {
  10944. if (!result.mValue.IsConst())
  10945. result = GetDefaultTypedValue(result.mType);
  10946. BF_ASSERT(result.mType == propType);
  10947. if (!keepConstsInModule)
  10948. CurrentAddToConstHolder(result.mValue);
  10949. setProperty.mParam = result;
  10950. customAttribute.mSetProperties.push_back(setProperty);
  10951. }
  10952. }
  10953. }
  10954. }
  10955. }
  10956. if ((!handledExpr) && (assignExpr->mRight != NULL))
  10957. constResolver.Resolve(assignExpr->mRight, NULL, BfConstResolveFlag_NoActualizeValues);
  10958. }
  10959. else
  10960. {
  10961. if (inPropSet)
  10962. {
  10963. Fail("Named attribute argument expected", arg); // CS1016
  10964. }
  10965. BfDeferEvalChecker deferEvalChecker;
  10966. arg->Accept(&deferEvalChecker);
  10967. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  10968. BfResolvedArg resolvedArg;
  10969. resolvedArg.mExpression = arg;
  10970. if (deferParamEval)
  10971. {
  10972. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  10973. }
  10974. else
  10975. resolvedArg.mTypedValue = constResolver.Resolve(arg, NULL, BfConstResolveFlag_NoActualizeValues);
  10976. if (!inPropSet)
  10977. {
  10978. argValues.push_back(resolvedArg);
  10979. }
  10980. }
  10981. if (autoComplete != NULL)
  10982. autoComplete->mShowAttributeProperties = NULL;
  10983. }
  10984. auto wasCapturingMethodInfo = false;
  10985. if (autoComplete != NULL)
  10986. {
  10987. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  10988. if (attributesDirective->mCtorOpenParen != NULL)
  10989. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  10990. }
  10991. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, BfMethodGenericArguments());
  10992. methodMatcher.mBfEvalExprFlags = constResolver.mBfEvalExprFlags;
  10993. attrTypeDef = attrTypeInst->mTypeDef;
  10994. bool success = true;
  10995. bool isFailurePass = false;
  10996. for (int pass = 0; pass < 2; pass++)
  10997. {
  10998. bool isFailurePass = pass == 1;
  10999. for (auto checkMethod : attrTypeDef->mMethods)
  11000. {
  11001. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  11002. continue; // Don't match private default ctor if there's a user-defined one
  11003. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  11004. continue;
  11005. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  11006. continue;
  11007. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  11008. }
  11009. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  11010. break;
  11011. }
  11012. if (autoComplete != NULL)
  11013. {
  11014. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  11015. {
  11016. autoComplete->mIsCapturingMethodMatchInfo = true;
  11017. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  11018. }
  11019. else
  11020. autoComplete->mIsCapturingMethodMatchInfo = false;
  11021. }
  11022. if (methodMatcher.mBestMethodDef == NULL)
  11023. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  11024. if (methodMatcher.mBestMethodDef == NULL)
  11025. {
  11026. AssertErrorState();
  11027. continue;
  11028. }
  11029. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  11030. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  11031. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  11032. {
  11033. Fail("Custom attribute circular reference", attributesDirective);
  11034. }
  11035. if (mCurTypeInstance != NULL)
  11036. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  11037. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  11038. success = false;
  11039. for (auto& arg : argValues)
  11040. {
  11041. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  11042. {
  11043. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  11044. constResolver.Resolve(expr, NULL, BfConstResolveFlag_NoActualizeValues);
  11045. }
  11046. }
  11047. // Move all those to the constHolder
  11048. if (!keepConstsInModule)
  11049. {
  11050. for (auto& ctorArg : customAttribute.mCtorArgs)
  11051. {
  11052. if (ctorArg.IsConst())
  11053. CurrentAddToConstHolder(ctorArg);
  11054. }
  11055. }
  11056. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  11057. {
  11058. targetOverride = BfAttributeTargets_ReturnValue;
  11059. if (attrTarget != BfAttributeTargets_Method)
  11060. {
  11061. 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.",
  11062. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  11063. success = false;
  11064. }
  11065. }
  11066. if ((success) && (targetOverride != (BfAttributeTargets)0))
  11067. {
  11068. if ((mCurMethodInstance != NULL) && (targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  11069. {
  11070. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  11071. if (methodInfoEx->mMethodCustomAttributes == NULL)
  11072. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  11073. if (success)
  11074. {
  11075. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  11076. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  11077. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  11078. }
  11079. }
  11080. // Mark as failed since we don't actually want to add this to the custom attributes set
  11081. success = false;
  11082. }
  11083. if (success)
  11084. {
  11085. if ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_DisallowAllowMultiple) != 0)
  11086. {
  11087. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  11088. {
  11089. if (prevCustomAttribute.mType == attrTypeInst)
  11090. {
  11091. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToCleanAttributeString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  11092. }
  11093. }
  11094. }
  11095. }
  11096. if (success)
  11097. {
  11098. customAttributes->mAttributes.push_back(customAttribute);
  11099. }
  11100. }
  11101. ValidateCustomAttributes(customAttributes, attrTarget);
  11102. }
  11103. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  11104. {
  11105. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  11106. GetCustomAttributes(customAttributes, attributesDirective, attrType, flags, captureInfo);
  11107. return customAttributes;
  11108. }
  11109. BfCustomAttributes* BfModule::GetCustomAttributes(BfTypeDef* typeDef)
  11110. {
  11111. BF_ASSERT(mCompiler->IsAutocomplete());
  11112. BfAttributeTargets attrTarget;
  11113. if (typeDef->mIsDelegate)
  11114. attrTarget = BfAttributeTargets_Delegate;
  11115. else if (typeDef->mIsFunction)
  11116. attrTarget = BfAttributeTargets_Function;
  11117. else if (typeDef->mTypeCode == BfTypeCode_Enum)
  11118. attrTarget = BfAttributeTargets_Enum;
  11119. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  11120. attrTarget = BfAttributeTargets_Interface;
  11121. else if (typeDef->mTypeCode == BfTypeCode_Struct)
  11122. attrTarget = BfAttributeTargets_Struct;
  11123. else if (typeDef->mTypeCode == BfTypeCode_Extension)
  11124. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Struct | BfAttributeTargets_Class | BfAttributeTargets_Interface | BfAttributeTargets_Enum);
  11125. else
  11126. attrTarget = BfAttributeTargets_Class;
  11127. return GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  11128. }
  11129. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  11130. {
  11131. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  11132. Warn(0, "Unused attributes", attributeState->mSrc);
  11133. }
  11134. void BfModule::ProcessTypeInstCustomAttributes(int& packing, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  11135. {
  11136. if (mCurTypeInstance->mTypeDef->mIsAlwaysInclude)
  11137. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11138. if (mCurTypeInstance->mCustomAttributes != NULL)
  11139. {
  11140. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11141. {
  11142. String typeName = TypeToString(customAttribute.mType);
  11143. if (typeName == "System.PackedAttribute")
  11144. {
  11145. packing = 1;
  11146. if (customAttribute.mCtorArgs.size() >= 1)
  11147. {
  11148. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11149. int checkPacking = alignConstant->mInt32;
  11150. if (((checkPacking & (checkPacking - 1)) == 0) && (packing > 0) && (packing < 256))
  11151. packing = checkPacking;
  11152. else
  11153. Fail("Packing must be a power of 2", customAttribute.GetRefNode());
  11154. }
  11155. }
  11156. else if (typeName == "System.UnionAttribute")
  11157. {
  11158. isUnion = true;
  11159. }
  11160. else if (typeName == "System.CReprAttribute")
  11161. {
  11162. isCRepr = true;
  11163. isOrdered = true;
  11164. }
  11165. else if (typeName == "System.OrderedAttribute")
  11166. {
  11167. isOrdered = true;
  11168. }
  11169. else if (typeName == "System.AlwaysIncludeAttribute")
  11170. {
  11171. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11172. for (auto setProp : customAttribute.mSetProperties)
  11173. {
  11174. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  11175. if (propertyDef->mName == "AssumeInstantiated")
  11176. {
  11177. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11178. if ((constant != NULL) && (constant->mBool))
  11179. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_AssumeInstantiated);
  11180. }
  11181. else if (propertyDef->mName == "IncludeAllMethods")
  11182. {
  11183. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11184. if ((constant != NULL) && (constant->mBool))
  11185. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_IncludeAllMethods);
  11186. }
  11187. }
  11188. }
  11189. else if (typeName == "System.AlignAttribute")
  11190. {
  11191. if (customAttribute.mCtorArgs.size() >= 1)
  11192. {
  11193. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11194. int checkAlign = alignConstant->mInt32;
  11195. if ((checkAlign & (checkAlign - 1)) == 0)
  11196. alignOverride = checkAlign;
  11197. else
  11198. Fail("Alignment must be a power of 2", customAttribute.GetRefNode());
  11199. }
  11200. }
  11201. else if (typeName == "System.UnderlyingArrayAttribute")
  11202. {
  11203. if (customAttribute.mCtorArgs.size() >= 2)
  11204. {
  11205. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11206. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  11207. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  11208. {
  11209. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  11210. underlyingArraySize = sizeConstant->mInt32;
  11211. }
  11212. }
  11213. }
  11214. if (customAttribute.mType->mAttributeData == NULL)
  11215. PopulateType(customAttribute.mType);
  11216. BF_ASSERT(customAttribute.mType->mAttributeData != NULL);
  11217. if ((customAttribute.mType->mAttributeData != NULL) && ((customAttribute.mType->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0))
  11218. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | customAttribute.mType->mAttributeData->mAlwaysIncludeUser);
  11219. }
  11220. }
  11221. }
  11222. // Checking to see if we're an attribute or not
  11223. void BfModule::ProcessCustomAttributeData()
  11224. {
  11225. if (mCurTypeInstance->mAttributeData != NULL)
  11226. return;
  11227. bool isAttribute = false;
  11228. auto checkTypeInst = mCurTypeInstance->mBaseType;
  11229. while (checkTypeInst != NULL)
  11230. {
  11231. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  11232. isAttribute = true;
  11233. checkTypeInst = checkTypeInst->mBaseType;
  11234. }
  11235. if (!isAttribute)
  11236. return;
  11237. auto attributeData = new BfAttributeData();
  11238. bool hasCustomAttribute = false;
  11239. if (mCurTypeInstance->mCustomAttributes != NULL)
  11240. {
  11241. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11242. {
  11243. if (customAttribute.mType->IsInstanceOf(mCompiler->mAttributeUsageAttributeTypeDef))
  11244. {
  11245. if (customAttribute.mCtorArgs.size() > 0)
  11246. {
  11247. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11248. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11249. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11250. }
  11251. if (customAttribute.mCtorArgs.size() == 2)
  11252. {
  11253. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11254. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11255. {
  11256. attributeData->mFlags = (BfAttributeFlags)constant->mInt32;
  11257. }
  11258. }
  11259. for (auto& setProp : customAttribute.mSetProperties)
  11260. {
  11261. BfPropertyDef* propDef = setProp.mPropertyRef;
  11262. if (propDef->mName == "AllowMultiple")
  11263. {
  11264. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11265. if ((constant != NULL) && (constant->mBool))
  11266. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_DisallowAllowMultiple);
  11267. else
  11268. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_DisallowAllowMultiple);
  11269. }
  11270. else if (propDef->mName == "Inherited")
  11271. {
  11272. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11273. if ((constant != NULL) && (constant->mBool))
  11274. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_NotInherited);
  11275. else
  11276. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_NotInherited);
  11277. }
  11278. else if (propDef->mName == "ValidOn")
  11279. {
  11280. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11281. if (constant != NULL)
  11282. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11283. }
  11284. else if (propDef->mName == "AlwaysIncludeUser")
  11285. {
  11286. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11287. if (constant != NULL)
  11288. attributeData->mAlwaysIncludeUser = (BfAlwaysIncludeFlags)constant->mInt32;
  11289. }
  11290. }
  11291. hasCustomAttribute = true;
  11292. }
  11293. }
  11294. }
  11295. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  11296. {
  11297. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  11298. attributeData->mFlags = mCurTypeInstance->mBaseType->mAttributeData->mFlags;
  11299. attributeData->mAlwaysIncludeUser = mCurTypeInstance->mBaseType->mAttributeData->mAlwaysIncludeUser;
  11300. }
  11301. mCurTypeInstance->mAttributeData = attributeData;
  11302. }
  11303. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  11304. {
  11305. auto constant = constHolder->GetConstant(irValue);
  11306. if (constant == NULL)
  11307. return false;
  11308. if (constant->mTypeCode != BfTypeCode_StringId)
  11309. return false;
  11310. int stringId = constant->mInt32;
  11311. BfStringPoolEntry* entry = NULL;
  11312. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  11313. {
  11314. str += entry->mString;
  11315. }
  11316. else
  11317. {
  11318. BF_DBG_FATAL("Failed to find string by id");
  11319. }
  11320. return true;
  11321. }
  11322. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  11323. {
  11324. BfVariant variant;
  11325. variant.mTypeCode = BfTypeCode_None;
  11326. BfType* primType = NULL;
  11327. if (value.mType->IsPrimitiveType())
  11328. primType = (BfPrimitiveType*)value.mType;
  11329. else if (value.mType->IsTypedPrimitive())
  11330. primType = value.mType->GetUnderlyingType();
  11331. else if (value.mType->IsInstanceOf(mCompiler->mStringTypeDef))
  11332. primType = value.mType;
  11333. if (primType)
  11334. {
  11335. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  11336. if (constant != NULL)
  11337. {
  11338. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  11339. {
  11340. variant.mUInt64 = 0;
  11341. variant.mTypeCode = BfTypeCode_Let;
  11342. return variant;
  11343. }
  11344. if (constant->mConstType == BfConstType_GlobalVar)
  11345. {
  11346. int stringIdx = GetStringPoolIdx(value.mValue, mBfIRBuilder);
  11347. if (stringIdx != -1)
  11348. {
  11349. variant.mTypeCode = BfTypeCode_StringId;
  11350. variant.mInt64 = stringIdx;
  11351. return variant;
  11352. }
  11353. }
  11354. switch (constant->mTypeCode)
  11355. {
  11356. case BfTypeCode_Boolean:
  11357. case BfTypeCode_Int8:
  11358. case BfTypeCode_UInt8:
  11359. case BfTypeCode_Int16:
  11360. case BfTypeCode_UInt16:
  11361. case BfTypeCode_Int32:
  11362. case BfTypeCode_UInt32:
  11363. case BfTypeCode_Int64:
  11364. case BfTypeCode_UInt64:
  11365. case BfTypeCode_IntPtr:
  11366. case BfTypeCode_UIntPtr:
  11367. case BfTypeCode_IntUnknown:
  11368. case BfTypeCode_UIntUnknown:
  11369. case BfTypeCode_Double:
  11370. case BfTypeCode_Char8:
  11371. case BfTypeCode_Char16:
  11372. case BfTypeCode_Char32:
  11373. case BfTypeCode_StringId:
  11374. variant.mTypeCode = constant->mTypeCode;
  11375. if (((variant.mTypeCode == BfTypeCode_Int64) || (variant.mTypeCode == BfTypeCode_UInt64)) &&
  11376. (primType->mSize > 0) && (primType->mSize < 8) &&
  11377. (mBfIRBuilder->IsIntable(primType->GetTypeCode())))
  11378. {
  11379. // We may have an 'int unknown' that we need to downsize
  11380. variant.mTypeCode = primType->GetTypeCode();
  11381. }
  11382. variant.mInt64 = constant->mInt64;
  11383. break;
  11384. case BfTypeCode_Float:
  11385. variant.mTypeCode = constant->mTypeCode;
  11386. variant.mSingle = (float)constant->mDouble;
  11387. break;
  11388. default:
  11389. if (refNode != NULL)
  11390. Fail("Invalid const expression type", refNode);
  11391. break;
  11392. }
  11393. }
  11394. }
  11395. else
  11396. {
  11397. int allocSize = value.mType->mSize + 4;
  11398. BfVariant::StructData* structData = (BfVariant::StructData*)(new uint8[allocSize]);
  11399. memset(structData, 0, allocSize);
  11400. structData->mSize = value.mType->mSize;
  11401. mBfIRBuilder->WriteConstant(value.mValue, structData->mData, value.mType);
  11402. variant.mTypeCode = BfTypeCode_Struct;
  11403. variant.mPtr = structData;
  11404. }
  11405. return variant;
  11406. }
  11407. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue, bool makeInReadOnly)
  11408. {
  11409. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  11410. {
  11411. auto refType = (BfRefType*)typedValue.mType;
  11412. auto elementType = typedValue.mType->GetUnderlyingType();
  11413. if (typedValue.IsAddr())
  11414. {
  11415. if (elementType->IsValuelessType())
  11416. {
  11417. BF_ASSERT(!typedValue.mValue);
  11418. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11419. }
  11420. else
  11421. typedValue = BfTypedValue(mBfIRBuilder->CreateAlignedLoad(typedValue.mValue, elementType->mAlign), elementType, true);
  11422. }
  11423. else
  11424. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11425. if (typedValue.mType->IsValuelessType())
  11426. {
  11427. BF_ASSERT(typedValue.mValue.IsFake());
  11428. }
  11429. if ((refType->mRefKind == BfRefType::RefKind_In) && (makeInReadOnly))
  11430. {
  11431. if (typedValue.mKind == BfTypedValueKind_Addr)
  11432. typedValue.mKind = BfTypedValueKind_ReadOnlyAddr;
  11433. }
  11434. }
  11435. return typedValue;
  11436. }
  11437. BfTypedValue BfModule::SanitizeAddr(BfTypedValue typedValue)
  11438. {
  11439. if (!typedValue)
  11440. return typedValue;
  11441. if (typedValue.mType->IsRef())
  11442. {
  11443. typedValue = LoadValue(typedValue);
  11444. auto copiedVal = BfTypedValue(CreateAlloca(typedValue.mType), typedValue.mType, true);
  11445. mBfIRBuilder->CreateStore(typedValue.mValue, copiedVal.mValue);
  11446. return copiedVal;
  11447. }
  11448. return typedValue;
  11449. }
  11450. BfTypedValue BfModule::ToRef(BfTypedValue typedValue, BfRefType* refType)
  11451. {
  11452. if (refType == NULL)
  11453. refType = CreateRefType(typedValue.mType);
  11454. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (typedValue.mType->IsObjectOrInterface()))
  11455. {
  11456. return LoadValue(typedValue);
  11457. }
  11458. if (refType->mRefKind == BfRefType::RefKind_Mut)
  11459. refType = CreateRefType(typedValue.mType);
  11460. if (!typedValue.mType->IsValuelessNonOpaqueType())
  11461. typedValue = MakeAddressable(typedValue, false, true);
  11462. return BfTypedValue(typedValue.mValue, refType);
  11463. }
  11464. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  11465. {
  11466. if (!typedValue.IsAddr())
  11467. return typedValue;
  11468. PopulateType(typedValue.mType);
  11469. if ((typedValue.mType->IsValuelessNonOpaqueType()) || (typedValue.mType->IsVar()))
  11470. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  11471. if (typedValue.mValue.IsConst())
  11472. {
  11473. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  11474. if (constantValue != NULL)
  11475. {
  11476. if (constantValue->mConstType == BfConstType_GlobalVar)
  11477. {
  11478. auto globalVar = (BfGlobalVar*)constantValue;
  11479. if (globalVar->mName[0] == '#')
  11480. {
  11481. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  11482. if (result)
  11483. {
  11484. // We want to avoid 'unreachable code' issues from values that
  11485. // are technically constant but change depending on compilation context
  11486. if (mCurMethodState != NULL)
  11487. {
  11488. auto checkScope = mCurMethodState->mCurScope;
  11489. while (checkScope != NULL)
  11490. {
  11491. checkScope->mSupressNextUnreachable = true;
  11492. checkScope = checkScope->mPrevScope;
  11493. }
  11494. }
  11495. return result;
  11496. }
  11497. if (!mIsComptimeModule)
  11498. return GetDefaultTypedValue(typedValue.mType);
  11499. }
  11500. }
  11501. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  11502. {
  11503. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  11504. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  11505. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  11506. auto ceTypedValue = ceDebugger->GetAddr(constantValue);
  11507. if (ceTypedValue)
  11508. {
  11509. if ((typedValue.mType->IsObjectOrInterface()) || (typedValue.mType->IsPointer()) || (typedValue.mType->IsRef()))
  11510. {
  11511. void* data = ceContext->GetMemoryPtr((addr_ce)ceTypedValue.mAddr, sizeof(addr_ce));
  11512. if (data == NULL)
  11513. {
  11514. Fail("Invalid address", refNode);
  11515. return GetDefaultTypedValue(typedValue.mType);
  11516. }
  11517. uint64 dataAddr;
  11518. if (mSystem->mPtrSize == 4)
  11519. dataAddr = *(uint32*)data;
  11520. else
  11521. dataAddr = *(uint64*)data;
  11522. return BfTypedValue(mBfIRBuilder->CreateIntToPtr(
  11523. mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataAddr), mBfIRBuilder->MapType(typedValue.mType)), typedValue.mType);
  11524. }
  11525. auto constVal = ceContext->CreateConstant(this, ceContext->mMemory.mVals + ceTypedValue.mAddr, typedValue.mType);
  11526. if (!constVal)
  11527. {
  11528. Fail("Failed to create const", refNode);
  11529. return GetDefaultTypedValue(typedValue.mType);
  11530. }
  11531. return BfTypedValue(constVal, typedValue.mType);
  11532. }
  11533. }
  11534. }
  11535. }
  11536. BfIRValue loadedVal = typedValue.mValue;
  11537. if (loadedVal)
  11538. {
  11539. if (typedValue.mType->IsVar())
  11540. {
  11541. return BfTypedValue(loadedVal, typedValue.mType, false);
  11542. }
  11543. PopulateType(typedValue.mType, BfPopulateType_Data);
  11544. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile || typedValue.IsVolatile());
  11545. }
  11546. return BfTypedValue(loadedVal, typedValue.mType, false);
  11547. }
  11548. BfTypedValue BfModule::PrepareConst(BfTypedValue& typedValue)
  11549. {
  11550. if (!typedValue.mValue.IsConst())
  11551. return typedValue;
  11552. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  11553. if (constant->mTypeCode == BfTypeCode_StringId)
  11554. return GetTypedValueFromConstant(constant, mBfIRBuilder, typedValue.mType);
  11555. return typedValue;
  11556. }
  11557. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  11558. {
  11559. if (typedValue.IsSplat())
  11560. return AggregateSplat(typedValue);
  11561. if (typedValue.IsAddr())
  11562. return LoadValue(typedValue);
  11563. return typedValue;
  11564. }
  11565. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  11566. {
  11567. if (!typedValue.IsSplat())
  11568. return typedValue;
  11569. BF_ASSERT(!mIsComptimeModule);
  11570. if (typedValue.mType->IsValuelessType())
  11571. return typedValue;
  11572. int elementIdx = 0;
  11573. auto _ExtractValue = [&](BfType* checkType)
  11574. {
  11575. if (valueArrPtr != NULL)
  11576. return valueArrPtr[elementIdx++];
  11577. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  11578. };
  11579. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11580. {
  11581. if (checkType->IsStruct())
  11582. {
  11583. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11584. auto checkTypeInstance = checkType->ToTypeInstance();
  11585. if (checkTypeInstance->mBaseType != NULL)
  11586. {
  11587. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  11588. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  11589. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  11590. }
  11591. if (checkTypeInstance->mIsUnion)
  11592. {
  11593. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11594. if (!unionInnerType->IsValuelessType())
  11595. {
  11596. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  11597. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  11598. }
  11599. if (checkTypeInstance->IsEnum())
  11600. {
  11601. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11602. BfIRValue fieldValue = checkTypeLambda(dscrType);
  11603. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  11604. }
  11605. }
  11606. else
  11607. {
  11608. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11609. {
  11610. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11611. if (fieldInstance->mDataIdx >= 0)
  11612. {
  11613. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  11614. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  11615. }
  11616. }
  11617. }
  11618. return curValue;
  11619. }
  11620. else if (checkType->IsMethodRef())
  11621. {
  11622. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11623. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11624. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11625. {
  11626. BfIRValue fieldValue;
  11627. auto checkType = methodRefType->GetCaptureType(dataIdx);
  11628. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11629. {
  11630. fieldValue = checkTypeLambda(checkType);
  11631. }
  11632. else
  11633. {
  11634. fieldValue = _ExtractValue(checkType);
  11635. }
  11636. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  11637. }
  11638. return curValue;
  11639. }
  11640. else if (!checkType->IsValuelessType())
  11641. {
  11642. return _ExtractValue(checkType);
  11643. }
  11644. return BfIRValue();
  11645. };
  11646. BfIRValue value = checkTypeLambda(typedValue.mType);
  11647. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  11648. }
  11649. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  11650. {
  11651. if (!typedValue.IsSplat())
  11652. return;
  11653. if (typedValue.mType->IsValuelessType())
  11654. return;
  11655. BF_ASSERT(!mIsComptimeModule);
  11656. /*static int sCallIdx = 0;
  11657. if (!mCompiler->mIsResolveOnly)
  11658. sCallIdx++;
  11659. int callIdx = sCallIdx;*/
  11660. int elementIdx = 0;
  11661. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  11662. {
  11663. if (checkType->IsStruct())
  11664. {
  11665. auto checkTypeInstance = checkType->ToTypeInstance();
  11666. if (checkTypeInstance->mBaseType != NULL)
  11667. {
  11668. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  11669. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  11670. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  11671. }
  11672. if (checkTypeInstance->mIsUnion)
  11673. {
  11674. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11675. if (!unionInnerType->IsValuelessType())
  11676. {
  11677. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  11678. checkTypeLambda(unionInnerType, fieldAddrVal);
  11679. }
  11680. if (checkTypeInstance->IsEnum())
  11681. {
  11682. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11683. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  11684. checkTypeLambda(dscrType, fieldAddrVal);
  11685. }
  11686. }
  11687. else
  11688. {
  11689. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11690. {
  11691. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11692. if (fieldInstance->mDataIdx >= 0)
  11693. {
  11694. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  11695. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  11696. }
  11697. }
  11698. }
  11699. }
  11700. else if (checkType->IsMethodRef())
  11701. {
  11702. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11703. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11704. {
  11705. auto dataType = methodRefType->GetCaptureType(dataIdx);
  11706. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  11707. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11708. {
  11709. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  11710. }
  11711. else
  11712. {
  11713. // static int sItrCount = 0;
  11714. // sItrCount++;
  11715. // int curItr = sItrCount;
  11716. // if (curItr == 1)
  11717. // {
  11718. // NOP;
  11719. // }
  11720. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  11721. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  11722. }
  11723. }
  11724. }
  11725. else if (!checkType->IsValuelessType())
  11726. {
  11727. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  11728. mBfIRBuilder->CreateStore(val, curAddrVal);
  11729. }
  11730. };
  11731. checkTypeLambda(typedValue.mType, addrVal);
  11732. }
  11733. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal, bool forceMutable, bool forceAddressable)
  11734. {
  11735. bool wasReadOnly = typedVal.IsReadOnly();
  11736. if ((forceAddressable) ||
  11737. ((typedVal.mType->IsValueType()) &&
  11738. (!typedVal.mType->IsValuelessNonOpaqueType())))
  11739. {
  11740. wasReadOnly = true; // Any non-addr is implicitly read-only
  11741. //static int gCallIdx = 0;
  11742. FixValueActualization(typedVal);
  11743. if (typedVal.IsAddr())
  11744. return typedVal;
  11745. BfType* type = typedVal.mType;
  11746. PopulateType(type);
  11747. BfIRValue tempVar;
  11748. if (typedVal.mValue.IsFake())
  11749. tempVar = mBfIRBuilder->GetFakeVal();
  11750. else
  11751. {
  11752. tempVar = CreateAlloca(type);
  11753. if (typedVal.IsSplat())
  11754. AggregateSplatIntoAddr(typedVal, tempVar);
  11755. else
  11756. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  11757. }
  11758. if (forceMutable)
  11759. wasReadOnly = false;
  11760. return BfTypedValue(tempVar, type,
  11761. typedVal.IsThis() ?
  11762. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  11763. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  11764. }
  11765. return LoadValue(typedVal);
  11766. }
  11767. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  11768. {
  11769. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  11770. typedValue.mKind = BfTypedValueKind_Addr;
  11771. return typedValue;
  11772. }
  11773. BfTypedValue BfModule::CopyValue(const BfTypedValue& typedValue)
  11774. {
  11775. return MakeAddressable(LoadValue(typedValue), true);
  11776. }
  11777. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  11778. {
  11779. BF_ASSERT(!mIsComptimeModule);
  11780. BfIRValue val;
  11781. if (typedValue.mValue.IsArg())
  11782. {
  11783. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  11784. if (isAddr != NULL)
  11785. {
  11786. if (wantType != NULL)
  11787. *isAddr = wantType->IsComposite();
  11788. else
  11789. *isAddr = false;
  11790. }
  11791. else if (wantType->IsComposite())
  11792. val = mBfIRBuilder->CreateLoad(val);
  11793. }
  11794. if (!val)
  11795. {
  11796. auto checkMethodState = mCurMethodState;
  11797. while (checkMethodState != NULL)
  11798. {
  11799. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  11800. {
  11801. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  11802. if (decompAddr == typedValue.mValue)
  11803. {
  11804. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  11805. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  11806. {
  11807. // This is really backing for a POINTER to a composite inside a methodRef
  11808. val = mBfIRBuilder->CreateLoad(val);
  11809. }
  11810. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  11811. {
  11812. *isAddr = true;
  11813. return val;
  11814. }
  11815. else
  11816. {
  11817. val = mBfIRBuilder->CreateAlignedLoad(val, wantType->mAlign);
  11818. break;
  11819. }
  11820. }
  11821. }
  11822. if (val)
  11823. break;
  11824. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  11825. {
  11826. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  11827. return mBfIRBuilder->GetFakeVal();
  11828. }
  11829. checkMethodState = checkMethodState->mPrevMethodState;
  11830. }
  11831. }
  11832. if (val)
  11833. {
  11834. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  11835. {
  11836. BF_ASSERT(wantType != NULL);
  11837. if (wantType != NULL)
  11838. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  11839. }
  11840. return val;
  11841. }
  11842. BFMODULE_FATAL(this, "Splat not found");
  11843. return BfIRValue();
  11844. }
  11845. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  11846. {
  11847. int useFieldIdx = fieldIdx;
  11848. BfType* fieldType = NULL;
  11849. if (fieldInstance != NULL)
  11850. {
  11851. fieldType = fieldInstance->mResolvedType;
  11852. if (typedValue.mType->IsUnion())
  11853. {
  11854. if (fieldIdx == 1)
  11855. {
  11856. if (typedValue.IsSplat())
  11857. {
  11858. bool isAddr = false;
  11859. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  11860. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  11861. }
  11862. }
  11863. }
  11864. }
  11865. else
  11866. {
  11867. if (typedValue.mType->IsPayloadEnum())
  11868. {
  11869. auto typeInst = typedValue.mType->ToTypeInstance();
  11870. if (fieldIdx == 1)
  11871. fieldType = typeInst->GetUnionInnerType();
  11872. else if (fieldIdx == 2)
  11873. {
  11874. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  11875. }
  11876. }
  11877. else if (typedValue.mType->IsUnion())
  11878. {
  11879. if (fieldIdx == 1)
  11880. {
  11881. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  11882. if (typedValue.IsSplat())
  11883. {
  11884. bool isAddr = false;
  11885. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  11886. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  11887. }
  11888. }
  11889. }
  11890. }
  11891. BF_ASSERT(typedValue.mType->IsStruct());
  11892. if (typedValue.IsSplat())
  11893. {
  11894. if (typedValue.mType->IsPayloadEnum())
  11895. {
  11896. if (fieldIdx == 1)
  11897. {
  11898. // Payload
  11899. auto typeInst = typedValue.mType->ToTypeInstance();
  11900. auto unionInnerType = typeInst->GetUnionInnerType();
  11901. bool isAddr = false;
  11902. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  11903. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  11904. }
  11905. if (fieldIdx == 2)
  11906. {
  11907. // Discriminator
  11908. auto typeInst = typedValue.mType->ToTypeInstance();
  11909. auto unionInnerType = typeInst->GetUnionInnerType();
  11910. auto dscrType = typeInst->GetDiscriminatorType();
  11911. int argIdx = typedValue.mValue.mId;
  11912. int componentIdx = 0;
  11913. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  11914. bool isAddr;
  11915. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  11916. return BfTypedValue(irVal, dscrType, isAddr);
  11917. }
  11918. }
  11919. int componentIdx = 0;
  11920. BfTypedValue retVal;
  11921. BfFieldInstance* wantFieldInstance = fieldInstance;
  11922. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11923. {
  11924. if (checkType->IsStruct())
  11925. {
  11926. auto checkTypeInstance = checkType->ToTypeInstance();
  11927. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  11928. {
  11929. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  11930. fieldType = checkTypeInstance->GetUnionInnerType();
  11931. checkTypeLambda(fieldType);
  11932. if (checkType->IsEnum())
  11933. {
  11934. // Past discriminator...
  11935. componentIdx++;
  11936. }
  11937. return;
  11938. }
  11939. if (checkTypeInstance->mBaseType != NULL)
  11940. checkTypeLambda(checkTypeInstance->mBaseType);
  11941. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11942. {
  11943. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11944. if (fieldInstance == wantFieldInstance)
  11945. {
  11946. if (fieldInstance->mResolvedType->IsValuelessType())
  11947. {
  11948. retVal = GetDefaultTypedValue(fieldInstance->mResolvedType);
  11949. break;
  11950. }
  11951. bool isAddr = false;
  11952. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  11953. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  11954. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  11955. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  11956. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  11957. {
  11958. retVal = LoadValue(retVal);
  11959. }
  11960. break;
  11961. }
  11962. if (fieldInstance->mDataIdx >= 0)
  11963. checkTypeLambda(fieldInstance->GetResolvedType());
  11964. }
  11965. }
  11966. else if (!checkType->IsValuelessType())
  11967. {
  11968. componentIdx++;
  11969. //argIdx++;
  11970. }
  11971. };
  11972. checkTypeLambda(typedValue.mType);
  11973. BF_ASSERT(retVal);
  11974. return retVal;
  11975. }
  11976. if (typedValue.IsAddr())
  11977. {
  11978. BF_ASSERT(fieldType != NULL);
  11979. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  11980. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  11981. }
  11982. else
  11983. {
  11984. BF_ASSERT(fieldType != NULL);
  11985. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  11986. }
  11987. }
  11988. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  11989. {
  11990. if (typedValue.IsAddr())
  11991. {
  11992. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  11993. return mBfIRBuilder->CreateAlignedLoad(addrVal, typedValue.mType->mAlign);
  11994. }
  11995. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  11996. }
  11997. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  11998. {
  11999. if (isElementIndex)
  12000. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  12001. else
  12002. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  12003. // if (elementType->IsSizeAligned())
  12004. // {
  12005. // if (isElementIndex)
  12006. // return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  12007. // else
  12008. // return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  12009. // }
  12010. //
  12011. // auto ptrType = CreatePointerType(elementType);
  12012. // auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  12013. // auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  12014. // auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  12015. // BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  12016. // BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  12017. // return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  12018. }
  12019. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  12020. {
  12021. if (elementType->IsSizeAligned())
  12022. {
  12023. if (isElementIndex)
  12024. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  12025. else
  12026. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  12027. }
  12028. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  12029. }
  12030. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  12031. {
  12032. if (modifyType == NULL)
  12033. modifyType = "modify";
  12034. if (typedValue.mType->IsVar())
  12035. return true;
  12036. if (typedValue.IsReadOnly())
  12037. {
  12038. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  12039. return false;
  12040. }
  12041. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  12042. {
  12043. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  12044. return false;
  12045. }
  12046. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  12047. {
  12048. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  12049. return false;
  12050. }
  12051. return true;
  12052. }
  12053. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  12054. {
  12055. // If one is an interface and the other is an impl, B is the impl
  12056. auto implOwner = methodB->GetOwner();
  12057. if (methodA->mMethodDef->mIsLocalMethod)
  12058. {
  12059. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  12060. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  12061. if (sepPosA != sepPosB)
  12062. return false;
  12063. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  12064. return false;
  12065. }
  12066. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  12067. return false;
  12068. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  12069. return false;
  12070. if (methodA->mMethodDef->mHasComptime != methodB->mMethodDef->mHasComptime)
  12071. return false;
  12072. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  12073. return false;
  12074. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  12075. {
  12076. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  12077. return false;
  12078. }
  12079. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  12080. {
  12081. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  12082. return false;
  12083. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  12084. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  12085. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  12086. return false;
  12087. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  12088. return false;
  12089. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  12090. return false;
  12091. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  12092. {
  12093. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  12094. return false;
  12095. }
  12096. }
  12097. int implicitParamCountA = methodA->GetImplicitParamCount();
  12098. int implicitParamCountB = methodB->GetImplicitParamCount();
  12099. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  12100. return false;
  12101. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  12102. return false;
  12103. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  12104. {
  12105. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  12106. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  12107. return false;
  12108. }
  12109. // Compare generic params. Generic params are part of the method signature here
  12110. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  12111. return false;
  12112. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  12113. {
  12114. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  12115. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  12116. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  12117. return false;
  12118. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  12119. return false;
  12120. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  12121. return false;
  12122. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  12123. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  12124. return false;
  12125. }
  12126. return true;
  12127. }
  12128. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  12129. {
  12130. if (!CompareMethodSignatures(methodA, methodB))
  12131. return false;
  12132. if (methodA->mReturnType != methodB->mReturnType)
  12133. return false;
  12134. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  12135. return false;
  12136. return true;
  12137. }
  12138. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  12139. {
  12140. if ((iMethodInst->GetNumGenericParams() != 0) || (methodInstance->GetNumGenericParams() != 0))
  12141. return false;
  12142. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  12143. return false;
  12144. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  12145. return false;
  12146. if (iMethodInst->mMethodDef->mIsOperator)
  12147. {
  12148. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  12149. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  12150. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  12151. return false;
  12152. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  12153. return false;
  12154. }
  12155. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  12156. return false;
  12157. auto selfType = methodInstance->GetOwner();
  12158. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  12159. {
  12160. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  12161. return false;
  12162. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  12163. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  12164. iParamType = ResolveSelfType(iParamType, selfType);
  12165. methodParamType = ResolveSelfType(methodParamType, selfType);
  12166. if (!iParamType->IsGenericParam())
  12167. {
  12168. if (methodParamType != iParamType)
  12169. return false;
  12170. }
  12171. else
  12172. {
  12173. if (!methodParamType->IsGenericParam())
  12174. return false;
  12175. auto genericParamType = (BfGenericParamType*)methodParamType;
  12176. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  12177. return false;
  12178. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12179. bool hadInterface = false;
  12180. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  12181. if (interfaceConstraint == iParamType)
  12182. hadInterface = true;
  12183. if (!hadInterface)
  12184. return false;
  12185. }
  12186. }
  12187. return true;
  12188. }
  12189. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  12190. {
  12191. BfMethodInstance* methodInstance = methodRef;
  12192. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  12193. {
  12194. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  12195. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  12196. {
  12197. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  12198. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  12199. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12200. BfMethodRef methodRef = methodInstance;
  12201. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  12202. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  12203. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  12204. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  12205. (mIsReified))
  12206. {
  12207. specializedMethodRefInfo->mHasReifiedRef = true;
  12208. }
  12209. }
  12210. }
  12211. }
  12212. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  12213. {
  12214. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  12215. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12216. if (mBfIRBuilder == NULL)
  12217. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12218. if (methodInstance->GetOwner()->IsFunction())
  12219. {
  12220. // No actual ref needed- not an actual generated function
  12221. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12222. }
  12223. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  12224. if (!isGenFunction)
  12225. AddMethodReference(methodInstance, flags);
  12226. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  12227. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  12228. if (IsSkippingExtraResolveChecks())
  12229. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12230. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  12231. {
  12232. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12233. }
  12234. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12235. if ((methodInstance->mIsIntrinsic) || (methodInstance->mMethodDef->mIsExtern))
  12236. isInlined = false;
  12237. BfMethodRef methodRef = methodInstance;
  12238. if (isInlined)
  12239. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  12240. else
  12241. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  12242. if (!isGenFunction)
  12243. {
  12244. BfIRValue* irFuncPtr = NULL;
  12245. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  12246. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  12247. }
  12248. if (mAwaitingInitFinish)
  12249. FinishInit();
  12250. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  12251. if (!isGenFunction)
  12252. {
  12253. BF_ASSERT(func || methodInstance->mMethodInstanceGroup->mOwner->IsInterface());
  12254. mFuncReferences[methodRef] = func;
  12255. }
  12256. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  12257. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12258. {
  12259. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  12260. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  12261. // type instance
  12262. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  12263. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  12264. for (auto ownedTypeInst : mOwnedTypeInstances)
  12265. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  12266. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  12267. {
  12268. mIncompleteMethodCount++;
  12269. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12270. inlineMethodRequest->mType = methodInstance->GetOwner();
  12271. inlineMethodRequest->mFromModule = this;
  12272. inlineMethodRequest->mFunc = func;
  12273. inlineMethodRequest->mFromModuleRevision = mRevision;
  12274. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  12275. inlineMethodRequest->mMethodInstance = methodInstance;
  12276. BF_ASSERT(mIsModuleMutable);
  12277. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12278. }
  12279. }
  12280. return BfModuleMethodInstance(methodInstance, func);
  12281. }
  12282. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  12283. {
  12284. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  12285. if (mBfIRBuilder == NULL)
  12286. {
  12287. // To allow for custom attribute data
  12288. PrepareForIRWriting(typeInst);
  12289. }
  12290. BfModule* declareModule = this;
  12291. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  12292. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  12293. declareModule = declareModule->mParentModule;
  12294. // Check for attributes
  12295. if (typeInst == mContext->mBfObjectType)
  12296. {
  12297. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  12298. if (methodDecl != NULL)
  12299. {
  12300. auto attributesDirective = methodDecl->mAttributes;
  12301. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  12302. {
  12303. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  12304. sourceClassifier->VisitChild(attributesDirective);
  12305. }
  12306. }
  12307. }
  12308. else
  12309. {
  12310. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  12311. GetMethodCustomAttributes(methodInstance);
  12312. }
  12313. BF_ASSERT(mModuleOptions == NULL);
  12314. if (methodInstance->GetCustomAttributes() != NULL)
  12315. {
  12316. auto project = typeInst->mTypeDef->mProject;
  12317. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  12318. BfModuleOptions wantOptions = moduleOptions;
  12319. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  12320. if (typeOptions != NULL)
  12321. {
  12322. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  12323. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  12324. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  12325. }
  12326. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  12327. {
  12328. StringT<128> attrName;
  12329. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  12330. {
  12331. attrName.Clear();
  12332. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  12333. Array<int>* arrPtr;
  12334. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  12335. {
  12336. for (auto optionsIdx : *arrPtr)
  12337. {
  12338. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  12339. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  12340. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  12341. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  12342. }
  12343. }
  12344. }
  12345. }
  12346. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  12347. {
  12348. auto lastCheckModule = this;
  12349. auto checkModule = this->mNextAltModule;
  12350. while (checkModule != NULL)
  12351. {
  12352. if (*checkModule->mModuleOptions == wantOptions)
  12353. {
  12354. declareModule = checkModule;
  12355. break;
  12356. }
  12357. lastCheckModule = checkModule;
  12358. checkModule = checkModule->mNextAltModule;
  12359. }
  12360. // Not found?
  12361. if (declareModule == this)
  12362. {
  12363. String specModuleName = mModuleName + "@@";
  12364. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  12365. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  12366. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  12367. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  12368. declareModule = new BfModule(mContext, specModuleName);
  12369. declareModule->mProject = project;
  12370. declareModule->mModuleOptions = new BfModuleOptions();
  12371. *declareModule->mModuleOptions = wantOptions;
  12372. declareModule->mParentModule = lastCheckModule;
  12373. declareModule->Init();
  12374. lastCheckModule->mNextAltModule = declareModule;
  12375. }
  12376. }
  12377. }
  12378. declareModule->PrepareForIRWriting(typeInst);
  12379. return declareModule;
  12380. }
  12381. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType, BfModule* referencingModule)
  12382. {
  12383. if (methodDef->mMethodType == BfMethodType_Init)
  12384. return BfModuleMethodInstance();
  12385. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  12386. {
  12387. // Don't bother inlining for resolve-only
  12388. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12389. }
  12390. if (methodDef->mIsExtern)
  12391. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12392. bool processNow = false;
  12393. bool keepInCurrentModule = false;
  12394. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  12395. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  12396. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  12397. {
  12398. return BfModuleMethodInstance();
  12399. }
  12400. if (methodDef->mIsLocalMethod)
  12401. {
  12402. auto rootMethodState = mCurMethodState->GetRootMethodState();
  12403. BfLocalMethod* localMethod;
  12404. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  12405. {
  12406. // Handle the def in the correct method state
  12407. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  12408. }
  12409. BFMODULE_FATAL(this, "Cannot find local method");
  12410. return BfModuleMethodInstance();
  12411. }
  12412. #ifdef _DEBUG
  12413. for (auto arg : methodGenericArguments)
  12414. BF_ASSERT(!arg->IsVar());
  12415. #endif
  12416. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  12417. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  12418. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  12419. // a FinishInit
  12420. if ((typeInst->IsIncomplete()) &&
  12421. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  12422. {
  12423. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  12424. // for resolve-only because we don't differentiate between reified/unreified there
  12425. if ((methodDef->mIsStatic) /*&& (mIsComptimeModule)*/)
  12426. {
  12427. if (!typeInst->DefineStateAllowsStaticMethods())
  12428. PopulateType(typeInst, BfPopulateType_AllowStaticMethods);
  12429. }
  12430. else
  12431. PopulateType(typeInst, BfPopulateType_Full);
  12432. if (typeInst->mDefineState < BfTypeDefineState_Defined)
  12433. {
  12434. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12435. {
  12436. BfLogSysM("GetMethodInstance (DefineState < BfTypeDefineState_Defined)) bailing due to IsCePaused\n");
  12437. return BfModuleMethodInstance();
  12438. }
  12439. }
  12440. }
  12441. bool tryModuleMethodLookup = false;
  12442. BfModuleMethodInstance moduleMethodInst;
  12443. BfModule* instModule = typeInst->mModule;
  12444. if (keepInCurrentModule)
  12445. {
  12446. // Stay here
  12447. instModule = this;
  12448. }
  12449. if (this == mContext->mUnreifiedModule)
  12450. {
  12451. // Stay in this 'resolve only' module here
  12452. }
  12453. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  12454. {
  12455. BF_ASSERT(this == mContext->mUnreifiedModule);
  12456. }
  12457. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  12458. {
  12459. BF_ASSERT(instModule == mParentModule);
  12460. }
  12461. else if (instModule != this)
  12462. {
  12463. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12464. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  12465. if ((!mIsComptimeModule) && (!mIsReified) && (instModule->mIsReified))
  12466. {
  12467. BF_ASSERT(!mCompiler->mIsResolveOnly);
  12468. // A resolve-only module is specializing a method from a type in a reified module,
  12469. // we need to take care that this doesn't cause anything new to become reified
  12470. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  12471. if (!moduleMethodInstance)
  12472. return moduleMethodInstance;
  12473. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  12474. return moduleMethodInstance;
  12475. }
  12476. else
  12477. {
  12478. if ((!mIsComptimeModule) && (mIsReified) && (!instModule->mIsReified))
  12479. {
  12480. if (!typeInst->IsUnspecializedType())
  12481. {
  12482. if (!instModule->mReifyQueued)
  12483. {
  12484. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  12485. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  12486. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  12487. mContext->mReifyModuleWorkList.Add(instModule);
  12488. instModule->mReifyQueued = true;
  12489. }
  12490. BfLogSysM("REIFIED(GetMethodInstance QueueSpecializationRequest): %s %s MethodDef:%p RefModule:%s RefMethod:%p\n", TypeToString(typeInst).c_str(), methodDef->mName.c_str(), methodDef, mModuleName.c_str(), mCurMethodInstance);
  12491. // This ensures that the method will actually be created when it gets reified
  12492. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  12493. specializationRequest->mFromModule = typeInst->mModule;
  12494. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  12495. specializationRequest->Init(typeInst, foreignType, methodDef);
  12496. //specializationRequest->mMethodDef = methodDef;
  12497. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  12498. specializationRequest->mType = typeInst;
  12499. specializationRequest->mFlags = flags;
  12500. }
  12501. }
  12502. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12503. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoReference);
  12504. if (mIsComptimeModule)
  12505. {
  12506. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12507. if (!mCompiler->mIsResolveOnly)
  12508. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification | BfGetMethodInstanceFlag_Unreified | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12509. }
  12510. // Not extern
  12511. // Create the instance in the proper module and then create a reference in this one
  12512. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType, this);
  12513. if (!moduleMethodInst)
  12514. return moduleMethodInst;
  12515. tryModuleMethodLookup = true;
  12516. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  12517. {
  12518. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  12519. }
  12520. }
  12521. }
  12522. if (tryModuleMethodLookup)
  12523. {
  12524. SetMethodDependency(moduleMethodInst.mMethodInstance);
  12525. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  12526. }
  12527. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  12528. {
  12529. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  12530. if (moduleMethodInstance)
  12531. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  12532. return moduleMethodInst;
  12533. }
  12534. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  12535. bool hadConcreteInterfaceGenericArgument = false;
  12536. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  12537. isReified = false;
  12538. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  12539. {
  12540. isReified = false;
  12541. }
  12542. BfTypeVector sanitizedMethodGenericArguments;
  12543. SizedArray<BfProject*, 4> projectList;
  12544. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  12545. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  12546. isUnspecializedPass = false;
  12547. // 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
  12548. bool isExternalExtensionMethod = false;
  12549. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  12550. {
  12551. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) &&
  12552. (methodDef->mDeclaringType != NULL) &&
  12553. (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  12554. {
  12555. auto specProject = methodDef->mDeclaringType->mProject;
  12556. isExternalExtensionMethod = true;
  12557. if (typeInst->IsGenericTypeInstance())
  12558. {
  12559. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12560. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12561. genericTypeInst->GenerateProjectsReferenced();
  12562. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  12563. {
  12564. // This is a generic type where a generic param is already confined to the project in question
  12565. isExternalExtensionMethod = false;
  12566. }
  12567. }
  12568. if (isExternalExtensionMethod)
  12569. {
  12570. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  12571. projectList.push_back(methodDef->mDeclaringType->mProject);
  12572. }
  12573. }
  12574. }
  12575. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  12576. {
  12577. int typeProjectsCounts = 0;
  12578. if (typeInst->IsGenericTypeInstance())
  12579. {
  12580. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12581. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12582. genericTypeInst->GenerateProjectsReferenced();
  12583. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  12584. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  12585. }
  12586. else
  12587. {
  12588. typeProjectsCounts = 1;
  12589. projectList.Insert(0, typeInst->mTypeDef->mProject);
  12590. }
  12591. isUnspecializedPass = true;
  12592. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  12593. {
  12594. auto genericArgType = methodGenericArguments[genericArgIdx];
  12595. //BF_ASSERT(!genericArgType->IsRef());
  12596. if (genericArgType->IsConcreteInterfaceType())
  12597. {
  12598. hadConcreteInterfaceGenericArgument = true;
  12599. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  12600. genericArgType = concreteInterfaceType->mInterface;
  12601. }
  12602. if (genericArgType->IsGenericParam())
  12603. {
  12604. auto genericParam = (BfGenericParamType*) genericArgType;
  12605. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  12606. isUnspecializedPass = false;
  12607. }
  12608. else
  12609. {
  12610. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  12611. isUnspecializedPass = false;
  12612. }
  12613. sanitizedMethodGenericArguments.push_back(genericArgType);
  12614. }
  12615. if ((int)projectList.size() > typeProjectsCounts)
  12616. {
  12617. // Just leave the new items
  12618. projectList.RemoveRange(0, typeProjectsCounts);
  12619. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  12620. {
  12621. return lhs->mName < rhs->mName;
  12622. });
  12623. }
  12624. else
  12625. {
  12626. projectList.Clear();
  12627. }
  12628. }
  12629. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  12630. BfMethodInstanceGroup* methodInstGroup = NULL;
  12631. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12632. {
  12633. BF_ASSERT(!typeInst->IsInterface());
  12634. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  12635. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  12636. {
  12637. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  12638. // if (checkGroup.mDefault == NULL)
  12639. // {
  12640. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  12641. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  12642. // methodInstGroup = &checkGroup;
  12643. // break;
  12644. // }
  12645. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  12646. {
  12647. methodInstGroup = &checkGroup;
  12648. break;
  12649. }
  12650. }
  12651. if (methodInstGroup == NULL)
  12652. {
  12653. if (lookupMethodGenericArguments.size() != 0)
  12654. {
  12655. BF_ASSERT((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0);
  12656. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12657. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12658. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12659. }
  12660. else
  12661. {
  12662. // Allocate a new entry
  12663. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  12664. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  12665. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  12666. methodInstGroup->mOwner = typeInst;
  12667. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12668. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12669. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  12670. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12671. else
  12672. {
  12673. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  12674. if (!mIsScratchModule)
  12675. mOnDemandMethodCount++;
  12676. }
  12677. }
  12678. }
  12679. }
  12680. else
  12681. {
  12682. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  12683. }
  12684. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12685. {
  12686. if (typeInst->mDefineState > BfTypeDefineState_DefinedAndMethodsSlotted)
  12687. {
  12688. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  12689. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12690. }
  12691. }
  12692. BfIRFunction prevIRFunc;
  12693. bool doingRedeclare = false;
  12694. BfMethodInstance* methodInstance = NULL;
  12695. auto _SetReified = [&]()
  12696. {
  12697. if (!mCompiler->mIsResolveOnly)
  12698. BF_ASSERT(mCompiler->mCompileState <= BfCompiler::CompileState_Normal);
  12699. methodInstance->mIsReified = true;
  12700. };
  12701. if (lookupMethodGenericArguments.size() == 0)
  12702. {
  12703. methodInstance = methodInstGroup->mDefault;
  12704. if ((methodInstance != NULL) && ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0))
  12705. return methodInstance;
  12706. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  12707. {
  12708. MarkDerivedDirty(typeInst);
  12709. if (!HasCompiledOutput())
  12710. {
  12711. BfLogSysM("Marking non-compiled-output module method instance as reified: %p\n", methodInstance);
  12712. _SetReified();
  12713. CheckHotMethod(methodInstance, "");
  12714. }
  12715. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  12716. {
  12717. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  12718. // the specializations to handle that for us
  12719. return BfModuleMethodInstance(methodInstance);
  12720. }
  12721. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  12722. {
  12723. if (methodDef->mIsAbstract)
  12724. {
  12725. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12726. _SetReified();
  12727. }
  12728. else
  12729. {
  12730. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12731. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  12732. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  12733. doingRedeclare = true;
  12734. mOnDemandMethodCount++;
  12735. VerifyOnDemandMethods();
  12736. }
  12737. }
  12738. else
  12739. {
  12740. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  12741. // We haven't processed it yet
  12742. _SetReified();
  12743. CheckHotMethod(methodInstance, "");
  12744. if (methodInstance->mDeclModule == this)
  12745. {
  12746. if (methodInstance->mMethodProcessRequest != NULL)
  12747. {
  12748. // Disconnect method process request
  12749. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  12750. }
  12751. }
  12752. else
  12753. {
  12754. if (methodInstance->mMethodProcessRequest != NULL)
  12755. {
  12756. // Disconnect method process request
  12757. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  12758. methodInstance->mMethodProcessRequest = NULL;
  12759. }
  12760. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  12761. {
  12762. // Add new request in proper module
  12763. methodInstance->mDeclModule = this;
  12764. }
  12765. else
  12766. {
  12767. if (methodInstance->mDeclModule == NULL)
  12768. {
  12769. //
  12770. }
  12771. else if (methodInstance->mDeclModule != this)
  12772. {
  12773. // Is from specialized module?
  12774. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  12775. }
  12776. }
  12777. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12778. {
  12779. methodInstance->mIRFunction = BfIRFunction();
  12780. if (!mIsModuleMutable)
  12781. StartExtension();
  12782. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  12783. {
  12784. StringT<512> mangledName;
  12785. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  12786. bool isIntrinsic = false;
  12787. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  12788. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  12789. }
  12790. }
  12791. AddMethodToWorkList(methodInstance);
  12792. }
  12793. }
  12794. }
  12795. }
  12796. else
  12797. {
  12798. if (methodInstGroup->mDefault == NULL)
  12799. {
  12800. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12801. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12802. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12803. }
  12804. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  12805. if (methodInstGroup->mMethodSpecializationMap == NULL)
  12806. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  12807. BfMethodInstance** methodInstancePtr = NULL;
  12808. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  12809. {
  12810. methodInstance = *methodInstancePtr;
  12811. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  12812. return methodInstance;
  12813. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  12814. {
  12815. BfLogSysM("Setting mRequestedByAutocomplete=false for method instance %p\n", methodInstance);
  12816. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  12817. if (methodInstance->mMethodProcessRequest == NULL)
  12818. AddMethodToWorkList(methodInstance);
  12819. methodInstance->mRequestedByAutocomplete = false;
  12820. }
  12821. if ((isReified) && (!methodInstance->mIsReified))
  12822. {
  12823. MarkDerivedDirty(typeInst);
  12824. if (methodInstance->mHasBeenProcessed)
  12825. {
  12826. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  12827. delete methodInstance;
  12828. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12829. methodInstance = NULL;
  12830. }
  12831. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12832. {
  12833. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  12834. delete methodInstance;
  12835. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12836. methodInstance = NULL;
  12837. }
  12838. else
  12839. {
  12840. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  12841. // We haven't processed it yet
  12842. _SetReified();
  12843. CheckHotMethod(methodInstance, "");
  12844. if (methodInstance->mMethodProcessRequest == NULL)
  12845. AddMethodToWorkList(methodInstance);
  12846. }
  12847. }
  12848. }
  12849. }
  12850. auto _CheckDllImport = [&]()
  12851. {
  12852. auto declModule = methodInstance->mDeclModule;
  12853. if ((!methodInstance->mIRFunction) && (declModule->mIsModuleMutable) && (!declModule->mBfIRBuilder->mIgnoreWrites))
  12854. {
  12855. auto importKind = methodInstance->GetImportCallKind();
  12856. if (importKind != BfImportCallKind_None)
  12857. {
  12858. BfLogSysM("DllImportGlobalVar creating %p in module %p from module %p\n", methodInstance, declModule, this);
  12859. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  12860. auto func = declModule->CreateDllImportGlobalVar(methodInstance, true);
  12861. BF_ASSERT(func);
  12862. declModule->mFuncReferences[methodInstance] = func;
  12863. }
  12864. }
  12865. };
  12866. if ((methodInstance != NULL) && (!doingRedeclare))
  12867. {
  12868. SetMethodDependency(methodInstance);
  12869. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  12870. {
  12871. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  12872. BF_ASSERT(!methodInstance->mIsReified);*/
  12873. if ((!mCompiler->mIsResolveOnly) && (isReified))
  12874. {
  12875. auto refModule = referencingModule;
  12876. if (refModule == NULL)
  12877. refModule = this;
  12878. BfLogSysM("REIFIED(GetMethodInstance Reference): %s MethodDef:%p MethodInst:%p RefModule:%s RefMethod:%p\n", methodInstance->mMethodDef->mName.c_str(), methodDef, methodInstance, refModule->mModuleName.c_str(), refModule->mCurMethodInstance);
  12879. }
  12880. if (methodInstance->mIsReified != isReified)
  12881. {
  12882. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  12883. }
  12884. if ((!isReified) &&
  12885. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  12886. {
  12887. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  12888. methodInstance->mIRFunction = BfIRFunction();
  12889. }
  12890. methodInstance->mIsReified = isReified;
  12891. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  12892. {
  12893. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  12894. }
  12895. if (!methodInstance->mMethodDef->mIsAbstract)
  12896. {
  12897. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  12898. {
  12899. // Wait until unreified
  12900. }
  12901. else
  12902. AddMethodToWorkList(methodInstance);
  12903. }
  12904. else
  12905. {
  12906. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  12907. auto owningModule = methodInstance->GetOwner()->mModule;
  12908. if (!owningModule->mIsScratchModule)
  12909. {
  12910. owningModule->mOnDemandMethodCount--;
  12911. owningModule->VerifyOnDemandMethods();
  12912. }
  12913. }
  12914. }
  12915. if (mExtensionCount > 0)
  12916. {
  12917. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  12918. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  12919. {
  12920. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  12921. if (mAwaitingInitFinish)
  12922. FinishInit();
  12923. // We need to refer to a function that was defined in a prior module
  12924. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12925. if (methodInstance->mIsIntrinsic)
  12926. isInlined = false;
  12927. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  12928. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  12929. methodInstance->mDeclModule = this;
  12930. // Add this inlined def to ourselves
  12931. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12932. {
  12933. mIncompleteMethodCount++;
  12934. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12935. inlineMethodRequest->mType = typeInst;
  12936. inlineMethodRequest->mFromModule = this;
  12937. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  12938. inlineMethodRequest->mFromModuleRevision = mRevision;
  12939. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  12940. inlineMethodRequest->mMethodInstance = methodInstance;
  12941. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12942. BF_ASSERT(mIsModuleMutable);
  12943. }
  12944. }
  12945. }
  12946. if (IsSkippingExtraResolveChecks())
  12947. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12948. else
  12949. {
  12950. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12951. return methodInstance;
  12952. if (methodInstance->mDeclModule != this)
  12953. return ReferenceExternalMethodInstance(methodInstance, flags);
  12954. _CheckDllImport();
  12955. return BfModuleMethodInstance(methodInstance);
  12956. }
  12957. }
  12958. if (!doingRedeclare)
  12959. {
  12960. BfModule* specModule = NULL;
  12961. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  12962. {
  12963. specModule = GetSpecializedMethodModule(projectList);
  12964. }
  12965. if ((specModule != NULL) && (specModule != this))
  12966. {
  12967. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  12968. if (mAwaitingInitFinish)
  12969. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  12970. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12971. return specMethodInstance.mMethodInstance;
  12972. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  12973. }
  12974. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  12975. {
  12976. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  12977. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  12978. }
  12979. }
  12980. if (methodInstance == NULL)
  12981. {
  12982. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12983. {
  12984. BfLogSysM("GetMethodInstance (methodInstance == NULL) bailing due to IsCePaused\n");
  12985. return BfModuleMethodInstance();
  12986. }
  12987. if (lookupMethodGenericArguments.size() == 0)
  12988. {
  12989. BF_ASSERT(methodInstGroup->mDefault == NULL);
  12990. methodInstance = new BfMethodInstance();
  12991. methodInstGroup->mDefault = methodInstance;
  12992. BF_ASSERT(typeInst->mDefineState > BfTypeDefineState_Declared);
  12993. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  12994. }
  12995. else
  12996. {
  12997. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  12998. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12999. depthExceeded = true;
  13000. if (depthExceeded)
  13001. {
  13002. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  13003. return BfModuleMethodInstance();
  13004. }
  13005. BfMethodInstance** methodInstancePtr = NULL;
  13006. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  13007. BF_ASSERT(added);
  13008. methodInstance = new BfMethodInstance();
  13009. *methodInstancePtr = methodInstance;
  13010. if (mCompiler->IsAutocomplete())
  13011. methodInstance->mRequestedByAutocomplete = true;
  13012. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  13013. }
  13014. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  13015. methodInstance->mIRFunction = prevIRFunc; // Take it over
  13016. }
  13017. methodInstance->mMethodDef = methodDef;
  13018. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  13019. methodInstance->mMethodInstanceGroup = methodInstGroup;
  13020. methodInstance->mIsReified = isReified;
  13021. SetupMethodIdHash(methodInstance);
  13022. if (hadConcreteInterfaceGenericArgument)
  13023. methodInstance->mIgnoreBody = true;
  13024. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  13025. {
  13026. methodInstance->mIsForeignMethodDef = true;
  13027. BF_ASSERT(foreignType != NULL);
  13028. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  13029. }
  13030. if ((typeInst->IsInstanceOf(mCompiler->mValueTypeTypeDef)) && (methodDef->mName == BF_METHODNAME_EQUALS))
  13031. {
  13032. if (!lookupMethodGenericArguments.empty())
  13033. {
  13034. auto compareType = lookupMethodGenericArguments[0];
  13035. PopulateType(compareType, BfPopulateType_Data);
  13036. if (compareType->IsSplattable())
  13037. methodInstance->mAlwaysInline = true;
  13038. }
  13039. }
  13040. if (methodDef->mMethodType == BfMethodType_Init)
  13041. {
  13042. methodInstance->mMangleWithIdx = true;
  13043. }
  13044. BF_ASSERT(typeInst == methodInstance->GetOwner());
  13045. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13046. if (isUnspecializedPass)
  13047. {
  13048. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  13049. {
  13050. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  13051. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  13052. }
  13053. }
  13054. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  13055. {
  13056. if (!sanitizedMethodGenericArguments.IsEmpty())
  13057. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  13058. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  13059. {
  13060. Fail("Internal error");
  13061. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  13062. return NULL;
  13063. }
  13064. for (auto genericArg : sanitizedMethodGenericArguments)
  13065. {
  13066. if (genericArg->IsPrimitiveType())
  13067. genericArg = GetWrappedStructType(genericArg);
  13068. if (genericArg != NULL)
  13069. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  13070. }
  13071. }
  13072. // Generic constraints
  13073. if (!methodDef->mGenericParams.IsEmpty())
  13074. {
  13075. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  13076. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  13077. {
  13078. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  13079. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  13080. }
  13081. }
  13082. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  13083. {
  13084. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  13085. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  13086. }
  13087. bool addToWorkList = !processNow;
  13088. if (mCompiler->GetAutoComplete() != NULL)
  13089. {
  13090. if (typeInst->IsSpecializedByAutoCompleteMethod())
  13091. addToWorkList = false;
  13092. if (methodInstance->mRequestedByAutocomplete)
  13093. addToWorkList = false;
  13094. }
  13095. BfModule* declareModule;
  13096. //
  13097. {
  13098. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13099. declareModule = GetOrCreateMethodModule(methodInstance);
  13100. }
  13101. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  13102. declareModule = methodInstance->mDeclModule;
  13103. BF_ASSERT(declareModule != NULL);
  13104. methodInstance->mDeclModule = declareModule;
  13105. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  13106. {
  13107. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  13108. // of a reified module -
  13109. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  13110. // BUT if we don't reify it then we have to remove the body after processing.
  13111. // 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
  13112. // the proper reified module.
  13113. declareModule = mContext->mUnreifiedModule;
  13114. }
  13115. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  13116. {
  13117. if (!methodInstance->mIsReified)
  13118. {
  13119. declareModule = mContext->mUnreifiedModule;
  13120. }
  13121. else
  13122. {
  13123. declareModule->PrepareForIRWriting(methodInstance->GetOwner());
  13124. }
  13125. }
  13126. SetMethodDependency(methodInstance);
  13127. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  13128. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  13129. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  13130. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  13131. {
  13132. // For mixins we only process the unspecialized version
  13133. addToWorkList = false;
  13134. }
  13135. if (((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0) && (methodInstGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  13136. {
  13137. addToWorkList = false;
  13138. }
  13139. // if ((flags & BfGetMethodInstanceFlag_NoReference) != 0)
  13140. // addToWorkList = false;
  13141. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  13142. if (processNow)
  13143. {
  13144. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  13145. ProcessMethod(methodInstance);
  13146. }
  13147. if (IsSkippingExtraResolveChecks())
  13148. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  13149. if (methodInstance->mDeclModule != this)
  13150. return ReferenceExternalMethodInstance(methodInstance, flags);
  13151. if (doingRedeclare)
  13152. {
  13153. _CheckDllImport();
  13154. }
  13155. return BfModuleMethodInstance(methodInstance);
  13156. }
  13157. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  13158. {
  13159. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  13160. if (methodInstance->mIsForeignMethodDef)
  13161. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  13162. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  13163. }
  13164. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  13165. {
  13166. if (!methodInstance->mMethodDef->mIsLocalMethod)
  13167. return NULL;
  13168. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  13169. if (outerLocal == NULL)
  13170. return NULL;
  13171. BfTypeVector genericArgs;
  13172. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  13173. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  13174. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  13175. }
  13176. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  13177. {
  13178. HashContext hashCtx;
  13179. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  13180. {
  13181. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  13182. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  13183. if (methodInstance->GetNumGenericArguments() != 0)
  13184. {
  13185. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  13186. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13187. hashCtx.Mixin(methodGenericArg->mTypeId);
  13188. }
  13189. };
  13190. _MixinMethodInstance(methodInstance);
  13191. if (methodInstance->mMethodDef->mIsLocalMethod)
  13192. {
  13193. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  13194. if (outmostMethodInstance != NULL)
  13195. {
  13196. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  13197. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  13198. }
  13199. }
  13200. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  13201. }
  13202. bool BfModule::CheckUseMethodInstance(BfMethodInstance* methodInstance, BfAstNode* refNode)
  13203. {
  13204. if (methodInstance->mHasBeenDeclared)
  13205. return true;
  13206. Fail(StrFormat("Circular reference in method instance '%s'", MethodToString(methodInstance).c_str()), refNode);
  13207. return false;
  13208. }
  13209. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  13210. {
  13211. BfIRValue globalValue;
  13212. BfIRValue* globalValuePtr = NULL;
  13213. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  13214. {
  13215. globalValue = *globalValuePtr;
  13216. }
  13217. if (!globalValue)
  13218. {
  13219. // This is necessary to reify the interface type
  13220. PopulateType(ifaceType);
  13221. StringT<512> slotVarName;
  13222. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  13223. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  13224. BfIRValue value;
  13225. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  13226. {
  13227. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  13228. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  13229. int virtSlotIdx = ifaceType->mSlotNum + 1;
  13230. value = GetConstValue32(virtSlotIdx);*/
  13231. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  13232. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  13233. }
  13234. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  13235. mInterfaceSlotRefs[ifaceType] = globalValue;
  13236. // Make sure we reify
  13237. PopulateType(ifaceType, BfPopulateType_Declaration);
  13238. AddDependency(ifaceType, mCurTypeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  13239. }
  13240. return mBfIRBuilder->CreateAlignedLoad(globalValue/*, "slotOfs"*/, 4);
  13241. }
  13242. void BfModule::HadSlotCountDependency()
  13243. {
  13244. if (mCompiler->mIsResolveOnly)
  13245. return;
  13246. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  13247. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  13248. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  13249. }
  13250. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  13251. {
  13252. if (str == "#IsComptime")
  13253. {
  13254. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsComptimeModule ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13255. }
  13256. if (str == "#IsBuilding")
  13257. {
  13258. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (!mCompiler->mIsResolveOnly) ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13259. }
  13260. if (str == "#IsReified")
  13261. {
  13262. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsReified ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13263. }
  13264. if (str == "#CompileRev")
  13265. {
  13266. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mRevision), GetPrimitiveType(BfTypeCode_Int32));
  13267. }
  13268. if (str == "#NextId")
  13269. {
  13270. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)++mCompiler->mUniqueId), GetPrimitiveType(BfTypeCode_Int32));
  13271. }
  13272. if (str == "#ModuleName")
  13273. {
  13274. return BfTypedValue(GetStringObjectValue(mModuleName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13275. }
  13276. if (str == "#ProjectName")
  13277. {
  13278. if (mProject != NULL)
  13279. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13280. }
  13281. if (str == "#AllocStackCount")
  13282. {
  13283. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mOptions.mAllocStackCount), GetPrimitiveType(BfTypeCode_Int32));
  13284. }
  13285. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  13286. {
  13287. if (str == "#CallerLineNum")
  13288. {
  13289. return BfTypedValue(GetConstValue(mCurMethodState->mMixinState->mInjectFilePosition.mCurLine + 1), GetPrimitiveType(BfTypeCode_Int32));
  13290. }
  13291. else if (str == "#CallerFilePath")
  13292. {
  13293. String filePath = "";
  13294. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13295. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13296. return BfTypedValue(GetStringObjectValue(filePath), ResolveTypeDef(mCompiler->mStringTypeDef));
  13297. }
  13298. else if (str == "#CallerFileName")
  13299. {
  13300. String filePath = "";
  13301. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13302. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13303. return BfTypedValue(GetStringObjectValue(GetFileName(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13304. }
  13305. else if (str == "#CallerFileDir")
  13306. {
  13307. String filePath = "";
  13308. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13309. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13310. return BfTypedValue(GetStringObjectValue(GetFileDir(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13311. }
  13312. else if (str == "#CallerTypeName")
  13313. {
  13314. String typeName = "";
  13315. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13316. typeName = TypeToString(mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner());
  13317. return BfTypedValue(GetStringObjectValue(typeName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13318. }
  13319. else if (str == "#CallerType")
  13320. {
  13321. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  13322. BfType* type = NULL;
  13323. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13324. type = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  13325. if (type != NULL)
  13326. {
  13327. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  13328. return BfTypedValue(CreateTypeDataRef(type), typeType);
  13329. }
  13330. }
  13331. else if (str == "#CallerMemberName")
  13332. {
  13333. String memberName = "";
  13334. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13335. memberName = MethodToString(mCurMethodState->mMixinState->mMixinMethodInstance);
  13336. return BfTypedValue(GetStringObjectValue(memberName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13337. }
  13338. else if (str == "#CallerProject")
  13339. {
  13340. BfProject* project = NULL;
  13341. project = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mProject;
  13342. if (project != NULL)
  13343. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13344. }
  13345. }
  13346. if (str == "#TimeLocal")
  13347. {
  13348. time_t rawtime;
  13349. time(&rawtime);
  13350. tm* timeinfo = localtime(&rawtime);
  13351. char result[32];
  13352. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  13353. 1900 + timeinfo->tm_year,
  13354. timeinfo->tm_mon + 1,
  13355. timeinfo->tm_mday,
  13356. timeinfo->tm_hour,
  13357. timeinfo->tm_min,
  13358. timeinfo->tm_sec);
  13359. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  13360. }
  13361. return BfTypedValue();
  13362. }
  13363. BfTypedValue BfModule::GetCompilerFieldValue(BfTypedValue typedValue)
  13364. {
  13365. if (!typedValue.IsAddr())
  13366. return BfTypedValue();
  13367. if (typedValue.mValue.IsConst())
  13368. {
  13369. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  13370. if (constantValue != NULL)
  13371. {
  13372. if (constantValue->mConstType == BfConstType_GlobalVar)
  13373. {
  13374. auto globalVar = (BfGlobalVar*)constantValue;
  13375. if (globalVar->mName[0] == '#')
  13376. {
  13377. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  13378. return result;
  13379. }
  13380. }
  13381. }
  13382. }
  13383. return BfTypedValue();
  13384. }
  13385. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  13386. {
  13387. BfIRValue globalValue;
  13388. auto fieldDef = fieldInstance->GetFieldDef();
  13389. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  13390. {
  13391. if (fieldInstance->mConstIdx != -1)
  13392. {
  13393. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  13394. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  13395. }
  13396. else
  13397. {
  13398. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  13399. }
  13400. }
  13401. if ((mIsScratchModule) && (mCompiler->mIsResolveOnly) && (!fieldInstance->mOwner->IsInstanceOf(mCompiler->mCompilerTypeDef)))
  13402. {
  13403. // Just fake it for the extern and unspecialized modules
  13404. // We can't do this for compilation because unreified methods with default params need to get actual global variable refs
  13405. return BfTypedValue(mBfIRBuilder->CreateConstNull(), fieldInstance->GetResolvedType(), true);
  13406. }
  13407. BfIRValue* globalValuePtr = NULL;
  13408. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  13409. {
  13410. globalValue = *globalValuePtr;
  13411. BF_ASSERT(globalValue);
  13412. auto globalVar = (BfGlobalVar*)mBfIRBuilder->GetConstant(globalValue);
  13413. if ((globalVar->mStreamId == -1) && (!mBfIRBuilder->mIgnoreWrites))
  13414. {
  13415. mBfIRBuilder->MapType(fieldInstance->mResolvedType);
  13416. mBfIRBuilder->CreateGlobalVariable(globalValue);
  13417. }
  13418. }
  13419. else
  13420. {
  13421. StringT<512> staticVarName;
  13422. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  13423. auto typeType = fieldInstance->GetResolvedType();
  13424. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  13425. {
  13426. typeType = typeType->GetUnderlyingType();
  13427. }
  13428. if (mIsComptimeModule)
  13429. {
  13430. mCompiler->mCeMachine->QueueStaticField(fieldInstance, staticVarName);
  13431. }
  13432. PopulateType(typeType);
  13433. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  13434. {
  13435. BfIRType irType = mBfIRBuilder->MapType(typeType);
  13436. if (fieldInstance->IsAppendedObject())
  13437. irType = mBfIRBuilder->MapTypeInst(typeType->ToTypeInstance());
  13438. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  13439. globalValue = mBfIRBuilder->CreateGlobalVariable(
  13440. irType,
  13441. false,
  13442. BfIRLinkageType_External,
  13443. BfIRValue(),
  13444. staticVarName,
  13445. IsThreadLocal(fieldInstance));
  13446. BF_ASSERT(globalValue);
  13447. mStaticFieldRefs[fieldInstance] = globalValue;
  13448. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  13449. }
  13450. }
  13451. auto type = fieldInstance->GetResolvedType();
  13452. if (type->IsValuelessType())
  13453. return BfTypedValue(globalValue, type);
  13454. if (fieldDef->mIsVolatile)
  13455. return BfTypedValue(globalValue, type, BfTypedValueKind_VolatileAddr);
  13456. return BfTypedValue(globalValue, type, !fieldDef->mIsConst && !fieldInstance->IsAppendedObject());
  13457. }
  13458. BfFieldInstance* BfModule::GetFieldInstance(BfTypeInstance* typeInst, int fieldIdx, const char* fieldName)
  13459. {
  13460. if (typeInst->IsDataIncomplete())
  13461. PopulateType(typeInst);
  13462. if (fieldIdx >= typeInst->mFieldInstances.mSize)
  13463. {
  13464. Fail(StrFormat("Invalid field data in type '%s'", TypeToString(typeInst).c_str()));
  13465. return 0;
  13466. }
  13467. return &typeInst->mFieldInstances[fieldIdx];
  13468. }
  13469. void BfModule::MarkUsingThis()
  13470. {
  13471. auto useMethodState = mCurMethodState;
  13472. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13473. {
  13474. useMethodState = useMethodState->mPrevMethodState;
  13475. }
  13476. if ((useMethodState != NULL) && (!useMethodState->mLocals.IsEmpty()))
  13477. {
  13478. auto localVar = useMethodState->mLocals[0];
  13479. if (localVar->mIsThis)
  13480. localVar->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13481. }
  13482. }
  13483. BfTypedValue BfModule::GetThis(bool markUsing)
  13484. {
  13485. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  13486. {
  13487. if (mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis)
  13488. return mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis;
  13489. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  13490. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  13491. if ((activeFrame != NULL) && (activeFrame->mFunction->mDbgInfo != NULL))
  13492. {
  13493. for (auto& dbgVar : activeFrame->mFunction->mDbgInfo->mVariables)
  13494. {
  13495. if (dbgVar.mName == "this")
  13496. return BfTypedValue(mBfIRBuilder->CreateConstAggCE(mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs), dbgVar.mType,
  13497. dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  13498. }
  13499. }
  13500. return BfTypedValue();
  13501. }
  13502. auto useMethodState = mCurMethodState;
  13503. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13504. {
  13505. useMethodState = useMethodState->mPrevMethodState;
  13506. }
  13507. if (useMethodState != NULL)
  13508. {
  13509. // Fake a 'this' for var field resolution
  13510. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  13511. {
  13512. auto thisType = mCurTypeInstance;
  13513. if (thisType->IsValueType())
  13514. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  13515. else
  13516. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  13517. }
  13518. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  13519. {
  13520. return BfTypedValue();
  13521. }
  13522. }
  13523. else
  13524. {
  13525. //TODO: Do we allow useMethodState to be NULL anymore?
  13526. return BfTypedValue();
  13527. }
  13528. // Check mixin state for 'this'
  13529. {
  13530. auto checkMethodState = mCurMethodState;
  13531. while (checkMethodState != NULL)
  13532. {
  13533. if (checkMethodState->mMixinState != NULL)
  13534. {
  13535. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  13536. if (thisValue.HasType())
  13537. {
  13538. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13539. if (!thisValue.mType->IsValueType())
  13540. thisValue = LoadValue(thisValue);
  13541. return thisValue;
  13542. }
  13543. }
  13544. checkMethodState = checkMethodState->mPrevMethodState;
  13545. }
  13546. }
  13547. auto curMethodInstance = mCurMethodInstance;
  13548. if (useMethodState->mMethodInstance != NULL)
  13549. curMethodInstance = useMethodState->mMethodInstance;
  13550. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  13551. {
  13552. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  13553. {
  13554. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  13555. if (constLocal.mIsThis)
  13556. {
  13557. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  13558. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  13559. }
  13560. }
  13561. return BfTypedValue();
  13562. }
  13563. if (useMethodState->mLocals.IsEmpty())
  13564. {
  13565. // 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
  13566. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  13567. return BfTypedValue();
  13568. }
  13569. auto thisLocal = useMethodState->mLocals[0];
  13570. BF_ASSERT(thisLocal->mIsThis);
  13571. bool preferValue = !IsTargetingBeefBackend();
  13572. if (!thisLocal->mAddr)
  13573. preferValue = true;
  13574. bool usedVal = false;
  13575. BfIRValue thisValue;
  13576. if ((preferValue) && (!thisLocal->mIsLowered))
  13577. {
  13578. thisValue = thisLocal->mValue;
  13579. usedVal = true;
  13580. }
  13581. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  13582. thisValue = thisLocal->mAddr;
  13583. else
  13584. thisValue = mBfIRBuilder->CreateAlignedLoad(thisLocal->mAddr, thisLocal->mResolvedType->mAlign);
  13585. if (markUsing)
  13586. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13587. if (useMethodState->mClosureState != NULL)
  13588. {
  13589. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  13590. if (closureTypeInst != NULL)
  13591. {
  13592. if (closureTypeInst->mFieldInstances.size() > 0)
  13593. {
  13594. auto& field = closureTypeInst->mFieldInstances[0];
  13595. auto fieldDef = field.GetFieldDef();
  13596. if (fieldDef->mName == "__this")
  13597. {
  13598. if (mCurMethodState->mClosureState->mCapturing)
  13599. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  13600. // This is a captured 'this'
  13601. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  13602. if (field.mResolvedType->IsRef())
  13603. {
  13604. auto refType = (BfRefType*)field.mResolvedType;
  13605. auto underlyingType = refType->GetUnderlyingType();
  13606. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  13607. }
  13608. if (field.mResolvedType->IsObject())
  13609. {
  13610. result = LoadValue(result);
  13611. result.mKind = BfTypedValueKind_ThisValue;
  13612. }
  13613. else
  13614. {
  13615. if (fieldDef->mIsReadOnly)
  13616. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  13617. else
  13618. result.mKind = BfTypedValueKind_ThisAddr;
  13619. }
  13620. return result;
  13621. }
  13622. }
  13623. return BfTypedValue();
  13624. }
  13625. if (useMethodState->mClosureState->mCapturing)
  13626. {
  13627. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  13628. if (thisType->IsValueType())
  13629. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  13630. else
  13631. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  13632. }
  13633. }
  13634. if (mCurMethodInstance == NULL)
  13635. return BfTypedValue();
  13636. auto localDef = useMethodState->mLocals[0];
  13637. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  13638. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  13639. {
  13640. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  13641. {
  13642. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  13643. }
  13644. if (localDef->mIsSplat)
  13645. {
  13646. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  13647. }
  13648. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  13649. }
  13650. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  13651. }
  13652. BfLocalVariable* BfModule::GetThisVariable()
  13653. {
  13654. if (mCurMethodState == NULL)
  13655. return NULL;
  13656. auto methodState = mCurMethodState->GetNonCaptureState();
  13657. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  13658. return methodState->mLocals[0];
  13659. return NULL;
  13660. }
  13661. bool BfModule::IsInGeneric()
  13662. {
  13663. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  13664. }
  13665. bool BfModule::InDefinitionSection()
  13666. {
  13667. if (mCurTypeInstance != NULL)
  13668. {
  13669. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  13670. return false;
  13671. }
  13672. return !IsInSpecializedSection();
  13673. }
  13674. bool BfModule::IsInSpecializedGeneric()
  13675. {
  13676. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  13677. return true;
  13678. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  13679. return false;
  13680. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  13681. }
  13682. bool BfModule::IsInSpecializedSection()
  13683. {
  13684. return IsInSpecializedGeneric() ||
  13685. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  13686. }
  13687. bool BfModule::IsInUnspecializedGeneric()
  13688. {
  13689. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  13690. return true;
  13691. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedType()))
  13692. return true;
  13693. return false;
  13694. }
  13695. //////////////////////////////////////////////////////////////////////////
  13696. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  13697. {
  13698. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  13699. if (type->IsValuelessType())
  13700. return mBfIRBuilder->GetFakeVal();
  13701. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  13702. if ((!doLifetimeEnd) && (WantsLifetimes()))
  13703. {
  13704. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  13705. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  13706. }
  13707. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  13708. auto typeOptions = GetTypeOptions();
  13709. if (typeOptions != NULL)
  13710. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  13711. // Local variable inits are implicitly handled in the Beef Backend
  13712. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  13713. {
  13714. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13715. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13716. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  13717. mBfIRBuilder->ClearDebugLocation(storeInst);
  13718. mBfIRBuilder->SetInsertPoint(prevBlock);
  13719. }
  13720. return allocaInst;
  13721. }
  13722. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  13723. {
  13724. while (localVar->mName.StartsWith('@'))
  13725. {
  13726. localVar->mNamePrefixCount++;
  13727. localVar->mName.Remove(0);
  13728. }
  13729. if (mCurMethodState->mLocals.mAllocSize == 0)
  13730. {
  13731. mCurMethodState->mLocals.Reserve(16);
  13732. mCurMethodState->mLocalVarSet.Reserve(16);
  13733. }
  13734. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  13735. mCurMethodState->mLocals.push_back(localVar);
  13736. BfLocalVarEntry* localVarEntryPtr;
  13737. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  13738. {
  13739. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  13740. localVarEntryPtr->mLocalVar = localVar;
  13741. }
  13742. }
  13743. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13744. {
  13745. if (localVarDef->mResolvedType->IsVar())
  13746. return;
  13747. if ((mBfIRBuilder->DbgHasInfo()) &&
  13748. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  13749. (mHasFullDebugInfo) &&
  13750. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  13751. {
  13752. auto varType = localVarDef->mResolvedType;
  13753. if (localVarDef->mResolvedType->IsValuelessType())
  13754. {
  13755. }
  13756. else
  13757. {
  13758. bool isByAddr = false;
  13759. auto diValue = localVarDef->mValue;
  13760. if (localVarDef->mConstValue)
  13761. diValue = localVarDef->mConstValue;
  13762. else if (localVarDef->mAddr)
  13763. {
  13764. diValue = localVarDef->mAddr;
  13765. isByAddr = true;
  13766. }
  13767. if (diValue.IsConst())
  13768. {
  13769. auto constant = mBfIRBuilder->GetConstant(diValue);
  13770. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  13771. {
  13772. // Ignore for now
  13773. return;
  13774. }
  13775. }
  13776. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  13777. bool didConstToMem = false;
  13778. bool isConstant = false;
  13779. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  13780. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13781. else if (localVarDef->mConstValue)
  13782. {
  13783. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  13784. isConstant =
  13785. (constant->mConstType < BfConstType_GlobalVar) ||
  13786. (constant->mConstType == BfConstType_AggZero) ||
  13787. (constant->mConstType == BfConstType_Agg);
  13788. if (isConstant)
  13789. {
  13790. if (localVarDef->mResolvedType->IsComposite())
  13791. {
  13792. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  13793. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  13794. // if (IsTargetingBeefBackend())
  13795. // {
  13796. // diValue = mBfIRBuilder->CreateAliasValue(constMem);
  13797. // didConstToMem = true;
  13798. //
  13799. // diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13800. // }
  13801. //else
  13802. {
  13803. isByAddr = true;
  13804. mBfIRBuilder->SaveDebugLocation();
  13805. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13806. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13807. mBfIRBuilder->ClearDebugLocation();
  13808. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  13809. auto addrVal = CreateAlloca(ptrType);
  13810. mBfIRBuilder->CreateStore(constMem, addrVal);
  13811. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13812. diValue = addrVal;
  13813. didConstToMem = true;
  13814. mBfIRBuilder->SetInsertPoint(prevBlock);
  13815. mBfIRBuilder->RestoreDebugLocation();
  13816. }
  13817. }
  13818. if (mCompiler->mOptions.IsCodeView())
  13819. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13820. }
  13821. }
  13822. if (!mBfIRBuilder->mIgnoreWrites)
  13823. {
  13824. if ((localVarDef->mIsStatic) && (localVarDef->mAddr) && (!localVarDef->mResolvedType->IsValuelessType()))
  13825. {
  13826. auto refType = CreateRefType(localVarDef->mResolvedType);
  13827. diType = mBfIRBuilder->DbgGetType(refType);
  13828. auto refAlloca = CreateAlloca(refType);
  13829. mBfIRBuilder->CreateStore(localVarDef->mAddr, refAlloca);
  13830. diValue = refAlloca;
  13831. }
  13832. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13833. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  13834. localVarDef->mDbgVarInst = diVariable;
  13835. if (mBfIRBuilder->HasDebugLocation())
  13836. {
  13837. if ((isConstant) && (!didConstToMem))
  13838. {
  13839. BfTypedValue result(localVarDef->mConstValue, localVarDef->mResolvedType);
  13840. FixValueActualization(result);
  13841. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(result.mValue, diVariable);
  13842. }
  13843. else
  13844. {
  13845. if ((IsTargetingBeefBackend()) && (doAliasValue) && (!mIsComptimeModule))
  13846. {
  13847. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  13848. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  13849. }
  13850. if (isByAddr)
  13851. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  13852. else if (diValue)
  13853. {
  13854. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  13855. }
  13856. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  13857. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  13858. }
  13859. }
  13860. }
  13861. }
  13862. }
  13863. }
  13864. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13865. {
  13866. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  13867. {
  13868. if ((!localVarDef->mValue.IsConst()) &&
  13869. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  13870. {
  13871. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  13872. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  13873. }
  13874. }
  13875. if (addDebugInfo)
  13876. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  13877. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  13878. DoAddLocalVariable(localVarDef);
  13879. auto rootMethodState = mCurMethodState->GetRootMethodState();
  13880. if (localVarDef->mLocalVarId == -1)
  13881. {
  13882. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  13883. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  13884. }
  13885. bool checkLocal = true;
  13886. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  13887. {
  13888. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(mCurMethodInstance->mMethodDef->mMethodDeclaration))
  13889. checkLocal = false;
  13890. }
  13891. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!mIsComptimeModule) && (checkLocal))
  13892. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  13893. if (((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL)) && (checkLocal))
  13894. {
  13895. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  13896. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL) && (rootMethodState->mMethodInstance != NULL) && (!mIsComptimeModule))
  13897. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  13898. }
  13899. return localVarDef;
  13900. }
  13901. void BfModule::CreateDIRetVal()
  13902. {
  13903. if (!WantsDebugInfo())
  13904. return;
  13905. /*if (!mCurMethodState->mRetVal)
  13906. {
  13907. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  13908. return;
  13909. }*/
  13910. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  13911. {
  13912. BfType* dbgType = mCurMethodInstance->mReturnType;
  13913. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  13914. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13915. {
  13916. BF_ASSERT(mCurMethodState->mRetValAddr);
  13917. dbgType = CreatePointerType(dbgType);
  13918. dbgValue = mCurMethodState->mRetValAddr;
  13919. }
  13920. else
  13921. {
  13922. BF_ASSERT(!mCurMethodState->mRetValAddr);
  13923. }
  13924. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13925. "@return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  13926. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  13927. }
  13928. }
  13929. BfTypedValue BfModule::CreateTuple(const Array<BfTypedValue>& values, const Array<String>& fieldNames)
  13930. {
  13931. BfTypeVector fieldTypes;
  13932. for (auto arg : values)
  13933. fieldTypes.Add(arg.mType);
  13934. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  13935. auto tupleTypedValue = BfTypedValue(CreateAlloca(tupleType), tupleType, true);
  13936. for (int fieldIdx = 0; fieldIdx < tupleType->mFieldInstances.size(); fieldIdx++)
  13937. {
  13938. auto& fieldInstance = tupleType->mFieldInstances[fieldIdx];
  13939. if (fieldInstance.mDataIdx <= 0)
  13940. continue;
  13941. auto typedVal = values[fieldIdx];
  13942. typedVal = LoadOrAggregateValue(typedVal);
  13943. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, mBfIRBuilder->CreateInBoundsGEP(tupleTypedValue.mValue, 0, fieldInstance.mDataIdx), typedVal.mType->mAlign);
  13944. }
  13945. return tupleTypedValue;
  13946. }
  13947. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  13948. {
  13949. if (variableDef->mName.IsEmpty())
  13950. return;
  13951. BfLocalVarEntry* localVarEntryPtr = NULL;
  13952. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  13953. {
  13954. auto checkLocal = localVarEntryPtr->mLocalVar;
  13955. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  13956. {
  13957. BfError* error;
  13958. if (checkLocal->mIsImplicitParam)
  13959. return; // Ignore 'redefinition'
  13960. if (checkLocal->IsParam())
  13961. {
  13962. if (variableDef->IsParam())
  13963. error = Fail(StrFormat("A parameter named '%s' has already been declared", variableDef->mName.c_str()), variableDef->mNameNode);
  13964. else
  13965. error = Fail(StrFormat("The name '%s' is already used by a parameter. Consider declaring 'var %s;' if you wish to make a mutable copy of that parameter.", variableDef->mName.c_str(), variableDef->mName.c_str()), variableDef->mNameNode);
  13966. }
  13967. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  13968. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13969. else
  13970. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13971. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  13972. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  13973. return;
  13974. }
  13975. }
  13976. }
  13977. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  13978. {
  13979. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  13980. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  13981. {
  13982. if (tokenNode->GetToken() == BfToken_Colon)
  13983. {
  13984. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  13985. {
  13986. Fail("Cannot access method scope across deferred block boundary", scopeName);
  13987. return NULL;
  13988. }
  13989. return &mCurMethodState->mHeadScope;
  13990. }
  13991. else if (tokenNode->GetToken() == BfToken_Mixin)
  13992. {
  13993. if (fromMixinState == NULL)
  13994. {
  13995. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  13996. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  13997. return mCurMethodState->mCurScope;
  13998. }
  13999. fromMixinState->mUsedInvocationScope = true;
  14000. return fromMixinState->mTargetScope;
  14001. }
  14002. else if (tokenNode->GetToken() == BfToken_New)
  14003. return NULL;
  14004. }
  14005. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  14006. {
  14007. auto findLabel = scopeName->ToString();
  14008. bool crossedDeferredBlock = false;
  14009. auto checkScope = mCurMethodState->mCurScope;
  14010. while (checkScope != NULL)
  14011. {
  14012. if (checkScope->mIsDeferredBlock)
  14013. crossedDeferredBlock = true;
  14014. if (checkScope->mLabel == findLabel)
  14015. {
  14016. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  14017. {
  14018. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  14019. return NULL;
  14020. }
  14021. return checkScope;
  14022. }
  14023. checkScope = checkScope->mPrevScope;
  14024. }
  14025. if (!inMixinDecl)
  14026. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  14027. }
  14028. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  14029. {
  14030. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  14031. }
  14032. return mCurMethodState->mCurScope;
  14033. }
  14034. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  14035. {
  14036. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  14037. }
  14038. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  14039. {
  14040. auto scopeData = FindScope(scopeName, false);
  14041. if (scopeData == NULL)
  14042. return NULL;
  14043. int scopeDepth = scopeData->GetDepth();
  14044. // Find the first break data that is at or below the depth of our requested scope
  14045. auto breakData = mCurMethodState->mBreakData;
  14046. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  14047. {
  14048. if (breakData->mScope->mIsConditional)
  14049. return NULL;
  14050. breakData = breakData->mPrevBreakData;
  14051. }
  14052. return breakData;
  14053. }
  14054. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  14055. {
  14056. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  14057. if (!IsTargetingBeefBackend())
  14058. return;
  14059. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  14060. {
  14061. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14062. }
  14063. }
  14064. void BfModule::ClearLifetimeEnds()
  14065. {
  14066. auto scopeData = mCurMethodState->mCurScope;
  14067. while (scopeData != NULL)
  14068. {
  14069. scopeData->mDeferredLifetimeEnds.Clear();
  14070. scopeData = scopeData->mPrevScope;
  14071. }
  14072. }
  14073. bool BfModule::WantsDebugInfo()
  14074. {
  14075. if ((mCurMethodInstance != NULL) &&
  14076. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  14077. return false;
  14078. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  14079. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  14080. }
  14081. BfTypeOptions* BfModule::GetTypeOptions()
  14082. {
  14083. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  14084. return mCurMethodState->mMethodTypeOptions;
  14085. if (mCurMethodInstance == NULL)
  14086. return NULL;
  14087. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  14088. }
  14089. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  14090. {
  14091. BfReflectKind reflectKind = BfReflectKind_None;
  14092. if (attrType->mCustomAttributes != NULL)
  14093. {
  14094. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  14095. {
  14096. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  14097. {
  14098. for (auto& prop : customAttr.mSetProperties)
  14099. {
  14100. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  14101. if (propDef->mName == "ReflectUser")
  14102. {
  14103. if (prop.mParam.mValue.IsConst())
  14104. {
  14105. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  14106. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  14107. }
  14108. }
  14109. }
  14110. // Check for Flags arg
  14111. if (customAttr.mCtorArgs.size() < 2)
  14112. continue;
  14113. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  14114. if (constant == NULL)
  14115. continue;
  14116. if (constant->mTypeCode == BfTypeCode_Boolean)
  14117. continue;
  14118. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  14119. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  14120. }
  14121. }
  14122. }
  14123. return reflectKind;
  14124. }
  14125. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  14126. {
  14127. auto checkTypeInstance = typeInstance;
  14128. while (checkTypeInstance != NULL)
  14129. {
  14130. if (checkTypeInstance->mCustomAttributes != NULL)
  14131. {
  14132. auto checkReflectKind = BfReflectKind_None;
  14133. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  14134. {
  14135. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  14136. {
  14137. if (customAttr.mCtorArgs.size() > 0)
  14138. {
  14139. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  14140. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  14141. }
  14142. else
  14143. {
  14144. checkReflectKind = BfReflectKind_All;
  14145. }
  14146. }
  14147. else
  14148. {
  14149. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  14150. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  14151. }
  14152. }
  14153. if ((checkTypeInstance == typeInstance) ||
  14154. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  14155. {
  14156. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  14157. }
  14158. }
  14159. for (auto ifaceEntry : typeInstance->mInterfaces)
  14160. {
  14161. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  14162. {
  14163. auto iface = ifaceEntry.mInterfaceType;
  14164. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  14165. if (customAttr != NULL)
  14166. {
  14167. for (auto& prop : customAttr->mSetProperties)
  14168. {
  14169. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  14170. if (propDef->mName == "ReflectImplementer")
  14171. {
  14172. if (prop.mParam.mValue.IsConst())
  14173. {
  14174. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  14175. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  14176. }
  14177. }
  14178. }
  14179. }
  14180. }
  14181. }
  14182. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  14183. }
  14184. return reflectKind;
  14185. }
  14186. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  14187. {
  14188. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14189. while (checkScope != NULL)
  14190. {
  14191. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  14192. return true;
  14193. if (checkScope == scope)
  14194. break;
  14195. checkScope = checkScope->mPrevScope;
  14196. }
  14197. return false;
  14198. }
  14199. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  14200. {
  14201. // Is there anything we need to do here?
  14202. if (mBfIRBuilder->mIgnoreWrites)
  14203. {
  14204. // Just visit deferred blocks
  14205. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14206. while (checkScope != NULL)
  14207. {
  14208. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14209. while (deferredCallEntry != NULL)
  14210. {
  14211. if (deferredCallEntry->mDeferredBlock != NULL)
  14212. {
  14213. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14214. if (checkScope == &mCurMethodState->mHeadScope)
  14215. CreateRetValLocal();
  14216. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry->mEmitRefNode);
  14217. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  14218. }
  14219. deferredCallEntry = deferredCallEntry->mNext;
  14220. }
  14221. if (checkScope == scopeData)
  14222. break;
  14223. checkScope = checkScope->mPrevScope;
  14224. }
  14225. return;
  14226. }
  14227. // Why did we want to do SetIllegalSrcPos here?
  14228. // Don't we always want to step onto these instances?
  14229. // Find a case where we don't and perhaps only do it there.
  14230. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  14231. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  14232. //SetIllegalSrcPos();
  14233. bool setSrcPos = false;
  14234. bool wantsNop = true;
  14235. BfAstNode* deferCloseNode = NULL;
  14236. if (mCurMethodState->mInPostReturn)
  14237. {
  14238. // These won't get used, they are post-return
  14239. return;
  14240. }
  14241. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  14242. BfScopeData* scopeJumpBlock = NULL;
  14243. bool hadExtraDeferredLifetimeEnds = false;
  14244. auto _FlushLifetimeEnds = [&]()
  14245. {
  14246. for (auto lifetimeEnd : deferredLifetimeEnds)
  14247. {
  14248. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14249. mBfIRBuilder->ClearDebugLocation_Last();
  14250. }
  14251. deferredLifetimeEnds.clear();
  14252. };
  14253. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14254. while (checkScope != NULL)
  14255. {
  14256. if (checkScope->mCloseNode != NULL)
  14257. deferCloseNode = checkScope->mCloseNode;
  14258. if (doneBlock)
  14259. {
  14260. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  14261. for (auto& checkHandler : checkScope->mDeferredHandlers)
  14262. {
  14263. if (checkHandler.mDoneBlock == doneBlock)
  14264. {
  14265. scopeJumpBlock = checkScope;
  14266. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  14267. mBfIRBuilder->ClearDebugLocation_Last();
  14268. _FlushLifetimeEnds();
  14269. break;
  14270. }
  14271. }
  14272. if (scopeJumpBlock != NULL)
  14273. break;
  14274. }
  14275. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  14276. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  14277. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  14278. if (hasWork)
  14279. {
  14280. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  14281. if (deferCloseNode != NULL)
  14282. {
  14283. UpdateSrcPos(deferCloseNode);
  14284. }
  14285. if (checkScope == &mCurMethodState->mHeadScope)
  14286. CreateRetValLocal();
  14287. if (doneBlock)
  14288. {
  14289. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  14290. String blockName = "deferredCalls";
  14291. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  14292. BfDeferredHandler deferredHandler;
  14293. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  14294. {
  14295. mBfIRBuilder->SaveDebugLocation();
  14296. mBfIRBuilder->ClearDebugLocation();
  14297. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  14298. mBfIRBuilder->RestoreDebugLocation();
  14299. }
  14300. else
  14301. {
  14302. // Definitely chain
  14303. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  14304. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  14305. mBfIRBuilder->ClearDebugLocation_Last();
  14306. _FlushLifetimeEnds();
  14307. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  14308. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  14309. }
  14310. deferredHandler.mDoneBlock = doneBlock;
  14311. if (!mBfIRBuilder->mIgnoreWrites)
  14312. checkScope->mDeferredHandlers.push_back(deferredHandler);
  14313. if (checkScope == &mCurMethodState->mHeadScope)
  14314. {
  14315. if (!mCurMethodState->mDIRetVal)
  14316. {
  14317. // 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
  14318. // be scoped to the physical method
  14319. /*if (deferCloseNode != NULL)
  14320. {
  14321. UpdateSrcPos(deferCloseNode);
  14322. }*/
  14323. CreateDIRetVal();
  14324. }
  14325. }
  14326. if (checkScope != mCurMethodState->mTailScope)
  14327. {
  14328. if (deferredHandler.mHandlerBlock.IsFake())
  14329. {
  14330. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14331. }
  14332. if (!mBfIRBuilder->mIgnoreWrites)
  14333. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  14334. }
  14335. }
  14336. HashSet<BfDeferredCallEntry*> handledSet;
  14337. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14338. while (deferredCallEntry != NULL)
  14339. {
  14340. BfDeferredCallEmitState deferredCallEmitState;
  14341. deferredCallEmitState.mCloseNode = deferCloseNode;
  14342. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  14343. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  14344. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14345. if (deferCloseNode != NULL)
  14346. {
  14347. UpdateSrcPos(deferCloseNode);
  14348. }
  14349. if (wantsNop)
  14350. EmitEnsureInstructionAt();
  14351. wantsNop = false;
  14352. if (deferredCallEntry->mDeferredBlock != NULL)
  14353. {
  14354. BfDeferredCallEntry** entryPtr = NULL;
  14355. if (!handledSet.TryAdd(deferredCallEntry, &entryPtr))
  14356. {
  14357. // Already handled, can happen if we defer again within the block
  14358. deferredCallEntry = deferredCallEntry->mNext;
  14359. continue;
  14360. }
  14361. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  14362. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14363. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  14364. {
  14365. // The list changed, start over and ignore anything we've already handled
  14366. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14367. }
  14368. else
  14369. deferredCallEntry = deferredCallEntry->mNext;
  14370. }
  14371. else
  14372. {
  14373. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14374. deferredCallEntry = deferredCallEntry->mNext;
  14375. }
  14376. }
  14377. if (checkScope->mSavedStack)
  14378. {
  14379. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  14380. if (mCurMethodState->mDynStackRevIdx)
  14381. {
  14382. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  14383. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  14384. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  14385. }
  14386. }
  14387. }
  14388. if (!checkScope->mIsScopeHead)
  14389. {
  14390. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  14391. if (!IsTargetingBeefBackend())
  14392. {
  14393. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14394. {
  14395. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14396. }
  14397. }
  14398. else
  14399. {
  14400. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14401. {
  14402. deferredLifetimeEnds.Add(lifetimeEnd);
  14403. }
  14404. }
  14405. }
  14406. if (checkScope == scopeData)
  14407. break;
  14408. checkScope = checkScope->mPrevScope;
  14409. }
  14410. if ((doneBlock) && (scopeJumpBlock == NULL))
  14411. {
  14412. mBfIRBuilder->CreateBr(doneBlock);
  14413. mBfIRBuilder->ClearDebugLocation_Last();
  14414. }
  14415. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  14416. // may have been created when other scope lifetimes were available
  14417. _FlushLifetimeEnds();
  14418. // Emit lifetimeEnds after the branch for Beef
  14419. /*if (IsTargetingBeefBackend())
  14420. {
  14421. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  14422. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14423. while (checkScope != NULL)
  14424. {
  14425. if (checkScope == scopeJumpBlock)
  14426. break;
  14427. if (!checkScope->mIsScopeHead)
  14428. {
  14429. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14430. {
  14431. if (needsEnsureInst)
  14432. {
  14433. needsEnsureInst = false;
  14434. }
  14435. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14436. }
  14437. }
  14438. if (checkScope == scopeData)
  14439. break;
  14440. checkScope = checkScope->mPrevScope;
  14441. }
  14442. }*/
  14443. }
  14444. void BfModule::MarkScopeLeft(BfScopeData* scopeData, bool isNoReturn)
  14445. {
  14446. if ((mCurMethodState->mDeferredLocalAssignData != NULL) && (!isNoReturn))
  14447. {
  14448. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  14449. while (deferredLocalAssignData != NULL)
  14450. {
  14451. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  14452. break;
  14453. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  14454. deferredLocalAssignData->mIsUnconditional = false;
  14455. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  14456. }
  14457. }
  14458. // When we leave a scope, mark those as assigned for deferred assignment purposes
  14459. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  14460. {
  14461. auto localDef = mCurMethodState->mLocals[localIdx];
  14462. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  14463. {
  14464. bool hadAssignment = false;
  14465. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  14466. {
  14467. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  14468. if (entry.mLocalVar == localDef)
  14469. hadAssignment = true;
  14470. }
  14471. if (!hadAssignment)
  14472. {
  14473. if (!isNoReturn)
  14474. localDef->mHadExitBeforeAssign = true;
  14475. mCurMethodState->LocalDefined(localDef);
  14476. }
  14477. }
  14478. }
  14479. }
  14480. void BfModule::CreateReturn(BfIRValue val)
  14481. {
  14482. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14483. {
  14484. // Store to sret
  14485. BF_ASSERT(val);
  14486. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14487. mBfIRBuilder->CreateRetVoid();
  14488. return;
  14489. }
  14490. if (mCurMethodInstance->mReturnType->IsVar())
  14491. return;
  14492. if (mCurMethodInstance->mReturnType->IsValuelessType())
  14493. {
  14494. mBfIRBuilder->CreateRetVoid();
  14495. return;
  14496. }
  14497. if (mCurMethodInstance->mReturnType->IsStruct())
  14498. {
  14499. BfTypeCode loweredReturnType = BfTypeCode_None;
  14500. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  14501. if (!mIsComptimeModule)
  14502. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  14503. if (loweredReturnType != BfTypeCode_None)
  14504. {
  14505. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  14506. mBfIRBuilder->CreateStore(val, retVal);
  14507. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  14508. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  14509. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  14510. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  14511. mBfIRBuilder->CreateRet(loadedReturnValue);
  14512. return;
  14513. }
  14514. }
  14515. BF_ASSERT(val);
  14516. mBfIRBuilder->CreateRet(val);
  14517. }
  14518. void BfModule::EmitReturn(const BfTypedValue& val)
  14519. {
  14520. if (mCurMethodState->mIRExitBlock)
  14521. {
  14522. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  14523. {
  14524. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  14525. {
  14526. if ((mCurMethodState->mRetValAddr) || (mCurMethodState->mRetVal))
  14527. {
  14528. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  14529. if (!mCurMethodState->mRetVal)
  14530. retVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetValAddr, mCurMethodInstance->mReturnType->mAlign);
  14531. mBfIRBuilder->CreateAlignedStore(val.mValue, retVal, mCurMethodInstance->mReturnType->mAlign);
  14532. }
  14533. else if (mIsComptimeModule)
  14534. {
  14535. if (!val.mType->IsValuelessType())
  14536. mBfIRBuilder->CreateSetRet(val.mValue, val.mType->mTypeId);
  14537. else
  14538. mBfIRBuilder->CreateSetRet(BfIRValue(), val.mType->mTypeId);
  14539. }
  14540. else
  14541. {
  14542. // Just ignore
  14543. BF_ASSERT(mCurMethodInstance->mReturnType->IsVar());
  14544. }
  14545. }
  14546. }
  14547. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14548. }
  14549. else
  14550. {
  14551. EmitDeferredScopeCalls(false, NULL);
  14552. if (val)
  14553. {
  14554. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14555. }
  14556. }
  14557. mCurMethodState->SetHadReturn(true);
  14558. mCurMethodState->mLeftBlockUncond = true;
  14559. }
  14560. void BfModule::EmitDefaultReturn()
  14561. {
  14562. if (mCurMethodState->mInDeferredBlock)
  14563. return;
  14564. if (mCurMethodState->mIRExitBlock)
  14565. {
  14566. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14567. }
  14568. else
  14569. {
  14570. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mReturnType->IsVar()))
  14571. {
  14572. // Ignore
  14573. }
  14574. else if (mCurMethodInstance->mReturnType->IsVoid())
  14575. mBfIRBuilder->CreateRetVoid();
  14576. else if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == -1))
  14577. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  14578. }
  14579. mCurMethodState->SetHadReturn(true);
  14580. mCurMethodState->mLeftBlockUncond = true;
  14581. }
  14582. void BfModule::AssertErrorState()
  14583. {
  14584. if (mIgnoreErrors)
  14585. return;
  14586. if (mHadBuildError)
  14587. return;
  14588. if (mCurTypeInstance != NULL)
  14589. {
  14590. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  14591. return;
  14592. }
  14593. if (mCurMethodInstance != NULL)
  14594. {
  14595. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  14596. return;
  14597. if (mCurMethodInstance->mHasFailed)
  14598. return;
  14599. }
  14600. // We want the module to be marked as failed even if it's just an error in the parser
  14601. if (mCurMethodInstance != NULL)
  14602. mCurMethodInstance->mHasFailed = true;
  14603. mHadBuildError = true;
  14604. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  14605. if (mCurTypeInstance != NULL)
  14606. {
  14607. if (mCurTypeInstance->mTypeFailed)
  14608. return;
  14609. if ((mCurTypeInstance->mTypeDef->GetDefinition()->mSource != NULL) && (mCurTypeInstance->mTypeDef->GetDefinition()->mSource->mParsingFailed))
  14610. return;
  14611. }
  14612. if (mCurMethodInstance != NULL)
  14613. {
  14614. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) &&
  14615. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14616. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14617. return;
  14618. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) &&
  14619. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14620. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14621. return;
  14622. }
  14623. if (mCompiler->IsAutocomplete())
  14624. return;
  14625. if (mCompiler->mPassInstance->HasFailed())
  14626. return;
  14627. InternalError("Compiler in invalid state but AssertErrorState failed to prior error");
  14628. }
  14629. void BfModule::AssertParseErrorState()
  14630. {
  14631. if (mCompiler->mRevision == 1)
  14632. AssertErrorState();
  14633. }
  14634. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  14635. {
  14636. BF_ASSERT(delegateType->IsDelegateOrFunction());
  14637. auto typeInst = delegateType->ToTypeInstance();
  14638. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  14639. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  14640. if (invokeMethodInstance == NULL)
  14641. return GetPrimitiveType(BfTypeCode_Var);
  14642. return invokeMethodInstance->mReturnType;
  14643. }
  14644. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  14645. {
  14646. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  14647. }
  14648. void BfModule::CreateDelegateInvokeMethod()
  14649. {
  14650. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  14651. //mBfIRBuilder->ClearDebugLocation();
  14652. SetIllegalSrcPos();
  14653. auto typeInstance = mCurTypeInstance;
  14654. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  14655. SizedArray<BfIRType, 4> staticParamTypes;
  14656. SizedArray<BfIRValue, 4> staticFuncArgs;
  14657. SizedArray<BfIRValue, 4> memberFuncArgs;
  14658. auto multicastDelegateType = typeInstance->mBaseType;
  14659. if (multicastDelegateType->mFieldInstances.size() != 2)
  14660. {
  14661. AssertErrorState();
  14662. return;
  14663. }
  14664. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  14665. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  14666. auto fieldVal = mBfIRBuilder->CreateAlignedLoad(fieldPtr, mSystem->mPtrSize);
  14667. BfExprEvaluator exprEvaluator(this);
  14668. SizedArray<BfIRType, 8> origParamTypes;
  14669. BfIRType origReturnType;
  14670. BfIRType staticReturnType;
  14671. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  14672. if (mCurMethodInstance->mReturnType->IsValueType())
  14673. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  14674. if ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() != 0))
  14675. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14676. int thisIdx = 0;
  14677. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14678. {
  14679. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  14680. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14681. }
  14682. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14683. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14684. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == 0))
  14685. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14686. mCurMethodInstance->GetIRFunctionInfo(this, staticReturnType, staticParamTypes, true);
  14687. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14688. {
  14689. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  14690. exprEvaluator.PushArg(localVal, staticFuncArgs);
  14691. exprEvaluator.PushArg(localVal, memberFuncArgs);
  14692. }
  14693. auto staticFunc = mBfIRBuilder->CreateFunctionType(staticReturnType, staticParamTypes, false);
  14694. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  14695. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  14696. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  14697. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  14698. auto doneBB = mBfIRBuilder->CreateBlock("done");
  14699. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  14700. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  14701. BfIRValue nonStaticResult;
  14702. BfIRValue staticResult;
  14703. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  14704. auto trueEndBB = trueBB;
  14705. /// Non-static invocation
  14706. {
  14707. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  14708. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  14709. mBfIRBuilder->SetInsertPoint(trueBB);
  14710. BfIRValue numVal;
  14711. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule) && (mCompiler->mSystem->mPtrSize == 8))
  14712. {
  14713. numVal = mBfIRBuilder->CreatePtrToInt(fieldVal, BfTypeCode_UInt64);
  14714. auto andVal = mBfIRBuilder->CreateAnd(numVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)~0x8000000000000000ULL));
  14715. fieldVal = mBfIRBuilder->CreateIntToPtr(andVal, mBfIRBuilder->MapType(mContext->mBfObjectType));
  14716. }
  14717. if ((WantsObjectAccessCheck(mContext->mBfObjectType) && (mCompiler->mSystem->mPtrSize == 8)))
  14718. {
  14719. auto oacDoBB = mBfIRBuilder->CreateBlock("oac.do", true);
  14720. auto oacDoneBB = mBfIRBuilder->CreateBlock("oac.done");
  14721. auto checkGTE = mBfIRBuilder->CreateCmpGTE(numVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)0x8000000000000000ULL), false);
  14722. mBfIRBuilder->CreateCondBr(checkGTE, oacDoBB, oacDoneBB);
  14723. mBfIRBuilder->SetInsertPoint(oacDoBB);
  14724. mBfIRBuilder->CreateObjectAccessCheck(fieldVal, !IsOptimized());
  14725. mBfIRBuilder->CreateBr(oacDoneBB);
  14726. mBfIRBuilder->AddBlock(oacDoneBB);
  14727. mBfIRBuilder->SetInsertPoint(oacDoneBB);
  14728. trueEndBB = oacDoneBB;
  14729. }
  14730. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  14731. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14732. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  14733. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14734. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  14735. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14736. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  14737. if (callingConv != BfIRCallingConv_CDecl)
  14738. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  14739. mCurMethodState->SetHadReturn(false);
  14740. mCurMethodState->mLeftBlockUncond = false;
  14741. mCurMethodState->mLeftBlockCond = false;
  14742. mBfIRBuilder->CreateBr(doneBB);
  14743. }
  14744. // Static invocation
  14745. {
  14746. mBfIRBuilder->AddBlock(falseBB);
  14747. mBfIRBuilder->SetInsertPoint(falseBB);
  14748. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14749. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  14750. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14751. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  14752. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14753. {
  14754. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  14755. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  14756. }
  14757. // We had a sret for the non-static but no sret for the static (because we have a lowered return type there)
  14758. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1) && (mCurMethodInstance->GetStructRetIdx(true) == -1))
  14759. {
  14760. auto sretToType = mBfIRBuilder->GetPointerTo(staticReturnType);
  14761. auto sretCastedPtr = mBfIRBuilder->CreateBitCast(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), sretToType);
  14762. mBfIRBuilder->CreateStore(staticResult, sretCastedPtr);
  14763. }
  14764. if (callingConv == BfIRCallingConv_ThisCall)
  14765. callingConv = BfIRCallingConv_CDecl;
  14766. if (callingConv != BfIRCallingConv_CDecl)
  14767. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  14768. mCurMethodState->SetHadReturn(false);
  14769. mCurMethodState->mLeftBlockUncond = false;
  14770. mCurMethodState->mLeftBlockCond = false;
  14771. mBfIRBuilder->CreateBr(doneBB);
  14772. }
  14773. mBfIRBuilder->AddBlock(doneBB);
  14774. mBfIRBuilder->SetInsertPoint(doneBB);
  14775. if (mCurMethodInstance->mReturnType->IsVar())
  14776. {
  14777. // Do nothing
  14778. }
  14779. else if ((mCurMethodInstance->mReturnType->IsValuelessType()) ||
  14780. ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1)))
  14781. {
  14782. mBfIRBuilder->CreateRetVoid();
  14783. }
  14784. else
  14785. {
  14786. BfIRType loweredIRReturnType;
  14787. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14788. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14789. if ((!mIsComptimeModule) && (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2)))
  14790. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  14791. else
  14792. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  14793. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  14794. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueEndBB);
  14795. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  14796. mBfIRBuilder->CreateRet(phi);
  14797. }
  14798. }
  14799. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  14800. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  14801. {
  14802. auto typeDef = typeInstance->mTypeDef;
  14803. auto methodDeclaration = methodDef->mMethodDeclaration;
  14804. if (!mCompiler->mIsResolveOnly)
  14805. return true;
  14806. if (typeInstance->IsGenericTypeInstance())
  14807. {
  14808. // We only really want to process the unspecialized type for autocompletion
  14809. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  14810. return false;
  14811. }
  14812. BfAstNode* checkNode = methodDeclaration;
  14813. if (methodDeclaration == NULL)
  14814. checkNode = methodDef->mBody;
  14815. if ((!mCompiler->mResolvePassData->mParsers.IsEmpty()) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParsers[0])))
  14816. {
  14817. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  14818. return true;
  14819. }
  14820. return false;
  14821. }
  14822. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  14823. {
  14824. methodInst->mAppendAllocAlign = 1;
  14825. }
  14826. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args, bool force)
  14827. {
  14828. BP_ZONE("BfModule::TryConstCalcAppend");
  14829. BF_ASSERT(methodInst->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  14830. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (!force))
  14831. return BfTypedValue();
  14832. // We want to regenerate all ctor calls when the method internals change
  14833. {
  14834. auto checkTypeInst = methodInst->GetOwner();
  14835. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  14836. {
  14837. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  14838. checkTypeInst = GetBaseType(checkTypeInst);
  14839. }
  14840. }
  14841. if (!methodInst->mMayBeConst)
  14842. return BfTypedValue();
  14843. // Do we need to iterate in order to resolve mAppendAllocAlign?
  14844. bool isFirstRun = methodInst->mEndingAppendAllocAlign < 0;
  14845. bool wasAllConst = true;
  14846. int argIdx = 0;
  14847. int paramIdx = 0;
  14848. while (true)
  14849. {
  14850. if (argIdx >= (int)args.size())
  14851. break;
  14852. auto paramType = methodInst->GetParamType(paramIdx);
  14853. PopulateType(paramType);
  14854. int argCount = 0;
  14855. if (!paramType->IsValuelessType())
  14856. {
  14857. if ((!mIsComptimeModule) && (methodInst->GetParamIsSplat(paramIdx)))
  14858. argCount = paramType->GetSplatCount();
  14859. else
  14860. argCount = 1;
  14861. for (int argOfs = 0; argOfs < argCount; argOfs++)
  14862. {
  14863. auto arg = args[argIdx + argOfs];
  14864. if (!arg.IsConst())
  14865. {
  14866. wasAllConst = false;
  14867. if (!isFirstRun)
  14868. {
  14869. auto& param = methodInst->mParams[argIdx];
  14870. if (param.mReferencedInConstPass)
  14871. {
  14872. // If this param is required as part of the const calculation then
  14873. // we require that it be const...
  14874. return BfTypedValue();
  14875. }
  14876. }
  14877. }
  14878. }
  14879. }
  14880. paramIdx++;
  14881. argIdx += argCount;
  14882. }
  14883. auto methodDef = methodInst->mMethodDef;
  14884. auto methodDecl = methodDef->GetMethodDeclaration();
  14885. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14886. if (methodDeclBlock == NULL)
  14887. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  14888. BfTypedValue constValue;
  14889. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  14890. auto checkState = mCurMethodState->mConstResolveState;
  14891. while (checkState != NULL)
  14892. {
  14893. if (checkState->mMethodInstance == methodInst)
  14894. {
  14895. return BfTypedValue();
  14896. }
  14897. checkState = checkState->mPrevConstResolveState;
  14898. }
  14899. //auto accumValue = GetConstValue(0);
  14900. bool failed = false;
  14901. //
  14902. {
  14903. BfConstResolveState constResolveState;
  14904. constResolveState.mMethodInstance = methodInst;
  14905. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  14906. constResolveState.mInCalcAppend = true;
  14907. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14908. BfMethodState methodState;
  14909. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  14910. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  14911. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  14912. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  14913. methodState.mConstResolveState = &constResolveState;
  14914. int argIdx = 0;
  14915. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14916. {
  14917. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  14918. continue;
  14919. auto paramType = methodInst->GetParamType(paramIdx);
  14920. // Fix this after we allow structs to be consts
  14921. //BF_ASSERT(!paramType->IsSplattable());
  14922. BfLocalVariable* localVar = new BfLocalVariable();
  14923. localVar->mName = methodInst->GetParamName(paramIdx);
  14924. localVar->mResolvedType = paramType;
  14925. localVar->mConstValue = args[argIdx];
  14926. localVar->mParamIdx = paramIdx;
  14927. AddLocalVariableDef(localVar);
  14928. argIdx++;
  14929. }
  14930. AppendAllocVisitor appendAllocVisitor;
  14931. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  14932. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  14933. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  14934. if (baseCtorAppendValue)
  14935. {
  14936. if (baseCtorAppendValue.mValue.IsFake())
  14937. appendAllocVisitor.mFailed = true;
  14938. else
  14939. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  14940. }
  14941. appendAllocVisitor.mModule = this;
  14942. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14943. if (constResolveState.mFailed)
  14944. appendAllocVisitor.mFailed = true;
  14945. if (!appendAllocVisitor.mFailed)
  14946. constValue = appendAllocVisitor.mConstAccum;
  14947. if (isFirstRun)
  14948. {
  14949. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  14950. if (mCurMethodInstance->mAppendAllocAlign <= 0)
  14951. mCurMethodInstance->mAppendAllocAlign = 1;
  14952. }
  14953. if (isFirstRun)
  14954. {
  14955. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14956. {
  14957. auto localVar = mCurMethodState->mLocals[paramIdx];
  14958. if (localVar->mReadFromId != -1)
  14959. {
  14960. auto& param = methodInst->mParams[paramIdx];
  14961. param.mReferencedInConstPass = true;
  14962. }
  14963. }
  14964. }
  14965. }
  14966. mBfIRBuilder->SetInsertPoint(prevBlock);
  14967. if (!constValue)
  14968. {
  14969. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  14970. // all-const args
  14971. if (wasAllConst)
  14972. {
  14973. methodInst->mMayBeConst = false;
  14974. }
  14975. }
  14976. return constValue;
  14977. }
  14978. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  14979. {
  14980. // Any errors should only be shown in the actual CTOR call
  14981. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  14982. auto methodDef = mCurMethodInstance->mMethodDef;
  14983. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  14984. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  14985. BfCustomAttributes* customAttributes = NULL;
  14986. defer(delete customAttributes);
  14987. BfInvocationExpression* ctorInvocation = NULL;
  14988. if (ctorDeclaration != NULL)
  14989. {
  14990. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  14991. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  14992. {
  14993. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  14994. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  14995. }
  14996. }
  14997. BfTypeInstance* targetType = NULL;
  14998. if (ctorInvocation != NULL)
  14999. {
  15000. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15001. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15002. }
  15003. else
  15004. targetType = mCurTypeInstance->mBaseType;
  15005. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  15006. return NULL;
  15007. auto targetRefNode = methodDef->GetRefNode();
  15008. BfType* targetThisType = targetType;
  15009. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  15010. BfExprEvaluator exprEvaluator(this);
  15011. BfResolvedArgs argValues;
  15012. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15013. {
  15014. argValues.Init(&ctorInvocation->mArguments);
  15015. }
  15016. //
  15017. {
  15018. }
  15019. BfFunctionBindResult bindResult;
  15020. bindResult.mSkipThis = true;
  15021. bindResult.mWantsArgs = true;
  15022. {
  15023. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15024. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15025. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  15026. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), true);
  15027. }
  15028. if (bindResult.mMethodInstance == NULL)
  15029. {
  15030. AssertErrorState();
  15031. return BfTypedValue();
  15032. }
  15033. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  15034. {
  15035. return BfTypedValue();
  15036. }
  15037. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  15038. bindResult.mIRArgs.RemoveAt(0);
  15039. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  15040. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs, true);
  15041. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  15042. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  15043. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  15044. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  15045. if (appendSizeTypedValue)
  15046. return appendSizeTypedValue;
  15047. if (constOnly)
  15048. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  15049. bool needsRecalc = false;
  15050. for (auto irArg : bindResult.mIRArgs)
  15051. {
  15052. if (irArg.IsFake())
  15053. needsRecalc = true;
  15054. }
  15055. auto calcAppendArgs = bindResult.mIRArgs;
  15056. if (needsRecalc)
  15057. {
  15058. // Do it again, but without mIgnoreWrites set
  15059. BfResolvedArgs argValues;
  15060. argValues.Init(&ctorInvocation->mArguments);
  15061. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15062. BfFunctionBindResult bindResult;
  15063. bindResult.mSkipThis = true;
  15064. bindResult.mWantsArgs = true;
  15065. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  15066. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), true);
  15067. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  15068. bindResult.mIRArgs.RemoveAt(0);
  15069. calcAppendArgs = bindResult.mIRArgs;
  15070. }
  15071. if (mBfIRBuilder->mIgnoreWrites)
  15072. {
  15073. appendSizeTypedValue = GetFakeTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  15074. }
  15075. else
  15076. {
  15077. BF_ASSERT(calcAppendMethodModule.mFunc);
  15078. appendSizeTypedValue = exprEvaluator.CreateCall(NULL, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  15079. }
  15080. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  15081. return appendSizeTypedValue;
  15082. }
  15083. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  15084. void BfModule::EmitCtorCalcAppend()
  15085. {
  15086. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  15087. return;
  15088. auto methodDef = mCurMethodInstance->mMethodDef;
  15089. auto methodDecl = methodDef->GetMethodDeclaration();
  15090. Array<BfAstNode*> deferredNodeList;
  15091. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  15092. if (methodDeclBlock == NULL)
  15093. return;
  15094. AppendAllocVisitor appendAllocVisitor;
  15095. auto baseCalcAppend = CallBaseCtorCalc(false);
  15096. if (baseCalcAppend)
  15097. {
  15098. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  15099. }
  15100. appendAllocVisitor.mModule = this;
  15101. appendAllocVisitor.VisitChild(methodDecl->mBody);
  15102. }
  15103. void BfModule::CreateStaticCtor()
  15104. {
  15105. auto typeDef = mCurTypeInstance->mTypeDef;
  15106. auto methodDef = mCurMethodInstance->mMethodDef;
  15107. BfIRBlock exitBB;
  15108. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15109. {
  15110. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  15111. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  15112. mBfIRBuilder->MapType(boolType),
  15113. false,
  15114. BfIRLinkageType_Internal,
  15115. GetDefaultValue(boolType),
  15116. "didStaticInit");
  15117. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  15118. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15119. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  15120. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  15121. mBfIRBuilder->SetInsertPoint(initBB);
  15122. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  15123. }
  15124. // Do DLL imports
  15125. if (!mDllImportEntries.empty())
  15126. {
  15127. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  15128. PopulateType(internalType);
  15129. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  15130. if (!getSharedProcAddressInstance)
  15131. {
  15132. if (!mCompiler->mPassInstance->HasFailed())
  15133. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  15134. }
  15135. }
  15136. // Fill in initializer values
  15137. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15138. {
  15139. for (auto fieldDef : typeDef->mFields)
  15140. {
  15141. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic))
  15142. {
  15143. // For extensions, only handle these fields in the appropriate extension
  15144. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15145. continue;
  15146. auto initializer = fieldDef->GetInitializer();
  15147. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15148. if (!fieldInst->mFieldIncluded)
  15149. continue;
  15150. if (fieldInst->mResolvedType->IsVar())
  15151. {
  15152. continue;
  15153. }
  15154. if (fieldInst->IsAppendedObject())
  15155. {
  15156. AppendedObjectInit(fieldInst);
  15157. }
  15158. else if (initializer != NULL)
  15159. {
  15160. UpdateSrcPos(initializer);
  15161. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  15162. }
  15163. }
  15164. }
  15165. auto _CheckInitBlock = [&](BfAstNode* node)
  15166. {
  15167. };
  15168. EmitInitBlocks(_CheckInitBlock);
  15169. }
  15170. else
  15171. {
  15172. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15173. {
  15174. if (tempTypeDef->mFullName == typeDef->mFullName)
  15175. {
  15176. for (auto fieldDef : tempTypeDef->mFields)
  15177. {
  15178. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  15179. {
  15180. if (fieldDef->GetInitializer() != NULL)
  15181. {
  15182. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDef->GetInitializer()))
  15183. {
  15184. sourceClassifier->SetElementType(fieldDef->GetInitializer(), BfSourceElementType_Normal);
  15185. sourceClassifier->VisitChildNoRef(fieldDef->GetInitializer());
  15186. }
  15187. BfType* wantType = NULL;
  15188. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  15189. {
  15190. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  15191. }
  15192. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  15193. if (fieldDef->mIsAppend)
  15194. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  15195. CreateValueFromExpression(fieldDef->GetInitializer(), wantType, exprFlags);
  15196. }
  15197. }
  15198. }
  15199. }
  15200. }
  15201. }
  15202. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15203. CallChainedMethods(mCurMethodInstance, false);
  15204. }
  15205. void BfModule::EmitDtorBody()
  15206. {
  15207. if (!mCurMethodState->mIRExitBlock)
  15208. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15209. if (mCurTypeInstance->IsClosure())
  15210. {
  15211. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  15212. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  15213. auto thisVal = GetThis();
  15214. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  15215. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  15216. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  15217. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  15218. SizedArray<BfIRValue, 1> args;
  15219. args.push_back(thisVal.mValue);
  15220. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  15221. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15222. // Fall through to Object::~this call
  15223. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  15224. if (mIsComptimeModule)
  15225. mCompiler->mCeMachine->QueueMethod(dtorFunc.mMethodInstance, dtorFunc.mFunc);
  15226. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  15227. SizedArray<BfIRValue, 1> vals = { basePtr };
  15228. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  15229. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  15230. mBfIRBuilder->SetTailCall(result);
  15231. return;
  15232. }
  15233. auto typeDef = mCurTypeInstance->mTypeDef;
  15234. auto methodDef = mCurMethodInstance->mMethodDef;
  15235. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15236. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15237. CallChainedMethods(mCurMethodInstance, true);
  15238. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15239. {
  15240. VisitEmbeddedStatement(bodyBlock);
  15241. if (bodyBlock->mCloseBrace != NULL)
  15242. {
  15243. UpdateSrcPos(bodyBlock->mCloseBrace);
  15244. }
  15245. }
  15246. else
  15247. {
  15248. if (methodDeclaration != NULL)
  15249. UpdateSrcPos(methodDeclaration);
  15250. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15251. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  15252. else if (typeDef->mTypeDeclaration != NULL)
  15253. UpdateSrcPos(typeDef->mTypeDeclaration);
  15254. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  15255. {
  15256. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  15257. }
  15258. }
  15259. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15260. {
  15261. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  15262. {
  15263. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  15264. auto fieldDef = fieldInst->GetFieldDef();
  15265. BfFieldDeclaration* fieldDecl = NULL;
  15266. if (fieldDef != NULL)
  15267. fieldDecl = fieldDef->GetFieldDeclaration();
  15268. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDecl != NULL) && (fieldDecl->mFieldDtor != NULL))
  15269. {
  15270. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15271. {
  15272. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15273. continue;
  15274. }
  15275. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  15276. {
  15277. Fail("Structs cannot have field destructors", fieldDecl->mFieldDtor->mTildeToken, true);
  15278. }
  15279. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  15280. auto fieldDtor = fieldDecl->mFieldDtor;
  15281. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  15282. continue;
  15283. UpdateSrcPos(fieldDtor);
  15284. BfScopeData scopeData;
  15285. mCurMethodState->AddScope(&scopeData);
  15286. NewScopeState();
  15287. UpdateSrcPos(fieldDtor);
  15288. bool hasDbgInfo = (!fieldDef->mIsConst);
  15289. if (hasDbgInfo)
  15290. {
  15291. mBfIRBuilder->SaveDebugLocation();
  15292. mBfIRBuilder->ClearDebugLocation();
  15293. }
  15294. BfIRValue value;
  15295. if (fieldDef->mIsStatic)
  15296. {
  15297. value = ReferenceStaticField(fieldInst).mValue;
  15298. }
  15299. else
  15300. {
  15301. PopulateType(fieldInst->mResolvedType);
  15302. if (fieldInst->mResolvedType->IsValuelessType())
  15303. {
  15304. value = mBfIRBuilder->GetFakeVal();
  15305. }
  15306. else if (!mCurTypeInstance->IsValueType())
  15307. {
  15308. auto thisValue = GetThis();
  15309. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  15310. }
  15311. else
  15312. {
  15313. AssertErrorState();
  15314. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15315. }
  15316. }
  15317. BfIRValue staticVal;
  15318. if (hasDbgInfo)
  15319. {
  15320. BfIRValue dbgShowValue = value;
  15321. BfLocalVariable* localDef = new BfLocalVariable();
  15322. localDef->mName = "_";
  15323. localDef->mResolvedType = fieldInst->mResolvedType;
  15324. if (fieldInst->IsAppendedObject())
  15325. {
  15326. localDef->mValue = mBfIRBuilder->CreateBitCast(value, mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15327. }
  15328. else
  15329. {
  15330. localDef->mAddr = value;
  15331. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  15332. {
  15333. // Create another pointer indirection, a ref to the gep
  15334. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  15335. auto allocaInst = CreateAlloca(refFieldType);
  15336. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  15337. localDef->mResolvedType = refFieldType;
  15338. localDef->mAddr = allocaInst;
  15339. }
  15340. }
  15341. mBfIRBuilder->RestoreDebugLocation();
  15342. auto defLocalVar = AddLocalVariableDef(localDef, true);
  15343. if (!fieldInst->IsAppendedObject())
  15344. {
  15345. // Put back so we actually modify the correct value*/
  15346. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  15347. defLocalVar->mAddr = value;
  15348. }
  15349. }
  15350. while (fieldDtor != NULL)
  15351. {
  15352. if (mCompiler->mResolvePassData != NULL)
  15353. {
  15354. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15355. {
  15356. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15357. sourceClassifier->VisitChild(fieldDtor);
  15358. }
  15359. }
  15360. UpdateSrcPos(fieldDtor);
  15361. VisitEmbeddedStatement(fieldDtor->mBody);
  15362. fieldDtor = fieldDtor->mNextFieldDtor;
  15363. }
  15364. RestoreScopeState();
  15365. }
  15366. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldInst->IsAppendedObject()))
  15367. {
  15368. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15369. {
  15370. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15371. continue;
  15372. }
  15373. auto refNode = fieldDef->GetRefNode();
  15374. UpdateSrcPos(refNode);
  15375. auto objectType = mContext->mBfObjectType;
  15376. BfTypeInstance* checkTypeInst = mCurTypeInstance->ToTypeInstance();
  15377. BfTypedValue val;
  15378. if (fieldDef->mIsStatic)
  15379. val = ReferenceStaticField(fieldInst);
  15380. else
  15381. {
  15382. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  15383. val = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  15384. }
  15385. bool allowPrivate = checkTypeInst == mCurTypeInstance;
  15386. bool allowProtected = allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst);
  15387. while (checkTypeInst != NULL)
  15388. {
  15389. auto dtorMethodDef = checkTypeInst->mTypeDef->GetMethodByName("~this");
  15390. if (dtorMethodDef)
  15391. {
  15392. if (!CheckProtection(dtorMethodDef->mProtection, checkTypeInst->mTypeDef, allowProtected, allowPrivate))
  15393. {
  15394. auto error = Fail(StrFormat("'%s.~this()' is inaccessible due to its protection level", TypeToString(checkTypeInst).c_str()), refNode); // CS0122
  15395. }
  15396. }
  15397. checkTypeInst = checkTypeInst->mBaseType;
  15398. allowPrivate = false;
  15399. }
  15400. // call dtor
  15401. BfExprEvaluator expressionEvaluator(this);
  15402. PopulateType(val.mType);
  15403. PopulateType(objectType, BfPopulateType_DataAndMethods);
  15404. if (objectType->mVirtualMethodTable.size() == 0)
  15405. {
  15406. if (!mCompiler->IsAutocomplete())
  15407. AssertErrorState();
  15408. }
  15409. else if (!IsSkippingExtraResolveChecks())
  15410. {
  15411. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  15412. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  15413. SizedArray<BfIRValue, 4> llvmArgs;
  15414. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  15415. expressionEvaluator.CreateCall(refNode, methodInstance, mBfIRBuilder->GetFakeVal(), false, llvmArgs);
  15416. }
  15417. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  15418. {
  15419. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  15420. auto int8PtrVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(int8PtrType));
  15421. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  15422. }
  15423. }
  15424. }
  15425. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15426. {
  15427. auto checkBaseType = mCurTypeInstance->mBaseType;
  15428. while (checkBaseType != NULL)
  15429. {
  15430. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15431. {
  15432. if (bodyBlock->mCloseBrace != NULL)
  15433. UpdateSrcPos(bodyBlock->mCloseBrace);
  15434. }
  15435. else
  15436. {
  15437. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  15438. }
  15439. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  15440. if (dtorMethodDef != NULL)
  15441. {
  15442. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  15443. if (IsSkippingExtraResolveChecks())
  15444. {
  15445. // Nothing
  15446. }
  15447. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  15448. {
  15449. if ((!IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  15450. {
  15451. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  15452. SizedArray<BfIRValue, 1> vals = { basePtr };
  15453. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  15454. if (mIsComptimeModule)
  15455. mCompiler->mCeMachine->QueueMethod(dtorMethodInstance.mMethodInstance, dtorMethodInstance.mFunc);
  15456. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  15457. }
  15458. }
  15459. else
  15460. {
  15461. // Invalid base dtor declaration
  15462. AssertErrorState();
  15463. }
  15464. break;
  15465. }
  15466. checkBaseType = checkBaseType->mBaseType;
  15467. }
  15468. }
  15469. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15470. }
  15471. else
  15472. {
  15473. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15474. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15475. // resolve pass, NOT the autocomplete expression
  15476. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15477. {
  15478. if (tempTypeDef->mFullName == typeDef->mFullName)
  15479. {
  15480. for (auto fieldDef : tempTypeDef->mFields)
  15481. {
  15482. auto fieldDecl = fieldDef->GetFieldDeclaration();
  15483. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  15484. (fieldDecl->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  15485. {
  15486. BfType* fieldType = NULL;
  15487. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  15488. {
  15489. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  15490. auto curFieldDef = curFieldInstance->GetFieldDef();
  15491. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  15492. fieldType = curFieldInstance->GetResolvedType();
  15493. }
  15494. if (fieldType == NULL)
  15495. fieldType = GetPrimitiveType(BfTypeCode_Var);
  15496. auto fieldDtor = fieldDecl->mFieldDtor;
  15497. BfScopeData scopeData;
  15498. mCurMethodState->AddScope(&scopeData);
  15499. NewScopeState();
  15500. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  15501. if (fieldType != NULL)
  15502. {
  15503. BfLocalVariable* localDef = new BfLocalVariable();
  15504. localDef->mName = "_";
  15505. localDef->mResolvedType = fieldType;
  15506. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  15507. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15508. AddLocalVariableDef(localDef);
  15509. }
  15510. while (fieldDtor != NULL)
  15511. {
  15512. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15513. {
  15514. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15515. sourceClassifier->VisitChild(fieldDtor);
  15516. }
  15517. UpdateSrcPos(fieldDtor);
  15518. VisitEmbeddedStatement(fieldDtor->mBody);
  15519. fieldDtor = fieldDtor->mNextFieldDtor;
  15520. }
  15521. RestoreScopeState();
  15522. }
  15523. }
  15524. }
  15525. }
  15526. }
  15527. }
  15528. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  15529. {
  15530. BF_ASSERT(methodInstance->mIsReified);
  15531. auto typeInstance = methodInstance->GetOwner();
  15532. bool foundDllImportAttr = false;
  15533. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  15534. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  15535. {
  15536. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  15537. {
  15538. foundDllImportAttr = true;
  15539. }
  15540. }
  15541. if (!foundDllImportAttr)
  15542. {
  15543. AssertErrorState();
  15544. return BfIRValue();
  15545. }
  15546. StringT<512> name = "bf_hs_preserve@";
  15547. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  15548. name += "__imp";
  15549. BfIRType returnType;
  15550. SizedArray<BfIRType, 8> paramTypes;
  15551. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  15552. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  15553. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  15554. BfIRValue initVal;
  15555. if (define)
  15556. {
  15557. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  15558. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  15559. }
  15560. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  15561. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  15562. {
  15563. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15564. auto ptrType = CreatePointerType(voidType);
  15565. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  15566. }
  15567. return globalVar;
  15568. }
  15569. void BfModule::CreateDllImportMethod()
  15570. {
  15571. if (mBfIRBuilder->mIgnoreWrites)
  15572. return;
  15573. auto globalVar = mFuncReferences[mCurMethodInstance];
  15574. if (!globalVar)
  15575. return;
  15576. bool allowTailCall = true;
  15577. mBfIRBuilder->ClearDebugLocation();
  15578. bool isHotCompile = mCompiler->IsHotCompile();
  15579. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  15580. if (isHotCompile)
  15581. {
  15582. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  15583. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  15584. }
  15585. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  15586. BfIRType returnType;
  15587. SizedArray<BfIRType, 8> paramTypes;
  15588. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15589. SizedArray<BfIRValue, 8> args;
  15590. for (int i = 0; i < (int)paramTypes.size(); i++)
  15591. args.push_back(mBfIRBuilder->GetArgument(i));
  15592. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15593. if (isHotCompile)
  15594. {
  15595. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  15596. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  15597. if (callingConvention == BfIRCallingConv_StdCall)
  15598. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  15599. else if (callingConvention == BfIRCallingConv_FastCall)
  15600. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  15601. else
  15602. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15603. if (allowTailCall)
  15604. mBfIRBuilder->SetTailCall(result);
  15605. CreateReturn(result);
  15606. mCurMethodState->mHadReturn = true;
  15607. }
  15608. if (HasCompiledOutput())
  15609. {
  15610. BfDllImportEntry dllImportEntry;
  15611. dllImportEntry.mFuncVar = globalVar;
  15612. dllImportEntry.mMethodInstance = mCurMethodInstance;
  15613. mDllImportEntries.push_back(dllImportEntry);
  15614. }
  15615. }
  15616. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  15617. {
  15618. auto methodDef = methodInstance->mMethodDef;
  15619. BfTypeInstance* owner = NULL;
  15620. if (!methodDef->mIsStatic)
  15621. owner = methodInstance->GetThisType()->ToTypeInstance();
  15622. if (owner == NULL)
  15623. owner = methodInstance->GetOwner();
  15624. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  15625. return BfIRCallingConv_CDecl;
  15626. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  15627. return BfIRCallingConv_StdCall;
  15628. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  15629. return BfIRCallingConv_FastCall;
  15630. if (!methodDef->mIsStatic)
  15631. {
  15632. if (owner->mIsCRepr)
  15633. return BfIRCallingConv_ThisCall;
  15634. if ((!owner->IsValuelessType()) &&
  15635. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  15636. return BfIRCallingConv_ThisCall;
  15637. }
  15638. return BfIRCallingConv_CDecl;
  15639. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  15640. }
  15641. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  15642. {
  15643. BfMethodDef* methodDef = NULL;
  15644. if (methodInstance != NULL)
  15645. methodDef = methodInstance->mMethodDef;
  15646. if (!func)
  15647. return;
  15648. if (mCompiler->mOptions.mNoFramePointerElim)
  15649. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  15650. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  15651. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  15652. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  15653. if (methodInstance == NULL)
  15654. return;
  15655. if (methodInstance->mReturnType->IsVar())
  15656. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_VarRet);
  15657. if (methodDef->mImportKind == BfImportKind_Export)
  15658. {
  15659. if (methodDef->mDeclaringType->mProject->mTargetType != BfTargetType_BeefLib_StaticLib)
  15660. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  15661. }
  15662. if (methodDef->mIsNoReturn)
  15663. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  15664. auto callingConv = GetIRCallingConvention(methodInstance);
  15665. if (callingConv != BfIRCallingConv_CDecl)
  15666. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  15667. if (isInlined)
  15668. {
  15669. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15670. }
  15671. int argIdx = 0;
  15672. int paramIdx = 0;
  15673. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  15674. paramIdx = -1;
  15675. int argCount = methodInstance->GetIRFunctionParamCount(this);
  15676. while (argIdx < argCount)
  15677. {
  15678. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  15679. {
  15680. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  15681. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  15682. argIdx++;
  15683. continue;
  15684. }
  15685. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  15686. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  15687. paramIdx++;
  15688. BfType* resolvedTypeRef = NULL;
  15689. BfType* resolvedTypeRef2 = NULL;
  15690. String paramName;
  15691. bool isSplattable = false;
  15692. bool tryLowering = !mIsComptimeModule;
  15693. if (isThis)
  15694. {
  15695. paramName = "this";
  15696. if (methodInstance->mIsClosure)
  15697. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  15698. else
  15699. resolvedTypeRef = methodInstance->GetThisType();
  15700. isSplattable = (!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(-1));
  15701. tryLowering = (!mIsComptimeModule) && (methodInstance->AllowsSplatting(-1));
  15702. }
  15703. else
  15704. {
  15705. paramName = methodInstance->GetParamName(paramIdx);
  15706. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  15707. if (resolvedTypeRef->IsMethodRef())
  15708. isSplattable = true;
  15709. else if ((!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(paramIdx)))
  15710. {
  15711. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15712. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15713. {
  15714. // crepr splat is always splattable
  15715. isSplattable = true;
  15716. }
  15717. else
  15718. {
  15719. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15720. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15721. isSplattable = true;
  15722. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  15723. isSplattable = true;
  15724. }
  15725. }
  15726. }
  15727. if (tryLowering)
  15728. {
  15729. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15730. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15731. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  15732. {
  15733. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  15734. argIdx++;
  15735. if (loweredTypeCode2 != BfTypeCode_None)
  15736. {
  15737. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  15738. argIdx++;
  15739. }
  15740. paramIdx++;
  15741. continue;
  15742. }
  15743. }
  15744. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  15745. {
  15746. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  15747. int addDeref = -1;
  15748. if (resolvedTypeRef->IsRef())
  15749. {
  15750. auto refType = (BfRefType*)resolvedTypeRef;
  15751. auto elementType = refType->mElementType;
  15752. PopulateType(elementType, BfPopulateType_Data);
  15753. addDeref = elementType->mSize;
  15754. if ((addDeref <= 0) && (!elementType->IsValuelessType()) && (!elementType->IsOpaque()))
  15755. AssertErrorState();
  15756. }
  15757. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  15758. {
  15759. if (isThis)
  15760. {
  15761. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  15762. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  15763. addDeref = resolvedTypeRef->mSize;
  15764. }
  15765. else if (methodInstance->WantsStructsAttribByVal(resolvedTypeRef))
  15766. {
  15767. mBfIRBuilder->PopulateType(resolvedTypeRef, BfIRPopulateType_Full);
  15768. BF_ASSERT(resolvedTypeRef->mAlign > 0);
  15769. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  15770. }
  15771. }
  15772. else if (resolvedTypeRef->IsPrimitiveType())
  15773. {
  15774. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  15775. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  15776. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  15777. }
  15778. if (addDeref >= 0)
  15779. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  15780. argIdx++;
  15781. };
  15782. if (isSplattable)
  15783. {
  15784. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  15785. {
  15786. if (checkType->IsStruct())
  15787. {
  15788. auto checkTypeInstance = checkType->ToTypeInstance();
  15789. if (checkTypeInstance->mBaseType != NULL)
  15790. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  15791. if (checkTypeInstance->mIsUnion)
  15792. {
  15793. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  15794. checkTypeLambda(unionInnerType, curName + "_data");
  15795. }
  15796. else
  15797. {
  15798. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  15799. {
  15800. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  15801. auto fieldDef = fieldInstance->GetFieldDef();
  15802. if (fieldInstance->mDataIdx >= 0)
  15803. {
  15804. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  15805. }
  15806. }
  15807. }
  15808. if (checkTypeInstance->IsEnum())
  15809. {
  15810. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  15811. argIdx++;
  15812. }
  15813. }
  15814. else if (checkType->IsMethodRef())
  15815. {
  15816. auto methodRefType = (BfMethodRefType*)checkType;
  15817. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  15818. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  15819. {
  15820. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  15821. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  15822. {
  15823. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  15824. }
  15825. else
  15826. {
  15827. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  15828. }
  15829. }
  15830. }
  15831. else if (!checkType->IsValuelessType())
  15832. {
  15833. _SetupParam(curName, checkType);
  15834. }
  15835. };
  15836. checkTypeLambda(resolvedTypeRef, paramName);
  15837. paramIdx++;
  15838. continue;
  15839. }
  15840. _SetupParam(paramName, resolvedTypeRef);
  15841. if (resolvedTypeRef2 != NULL)
  15842. _SetupParam(paramName, resolvedTypeRef2);
  15843. paramIdx++;
  15844. }
  15845. }
  15846. void BfModule::EmitInitBlocks(const std::function<void(BfAstNode*)>& initBlockCallback)
  15847. {
  15848. auto methodDef = mCurMethodInstance->mMethodDef;
  15849. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  15850. BfMemberSetEntry* entry = NULL;
  15851. BfMethodDef* initMethodDef = NULL;
  15852. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  15853. if (entry != NULL)
  15854. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  15855. SizedArray<BfAstNode*, 8> initBodies;
  15856. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  15857. {
  15858. if (initMethodDef->mDeclaringType->GetDefinition() != methodDef->mDeclaringType->GetDefinition())
  15859. continue;
  15860. if (initMethodDef->mMethodType != BfMethodType_Init)
  15861. continue;
  15862. if (initMethodDef->mIsStatic != methodDef->mIsStatic)
  15863. continue;
  15864. initBodies.Insert(0, initMethodDef->mBody);
  15865. }
  15866. for (auto body : initBodies)
  15867. {
  15868. initBlockCallback(body);
  15869. VisitEmbeddedStatement(body);
  15870. }
  15871. }
  15872. void BfModule::EmitCtorBody(bool& skipBody)
  15873. {
  15874. auto methodInstance = mCurMethodInstance;
  15875. auto methodDef = methodInstance->mMethodDef;
  15876. auto methodDeclaration = methodDef->mMethodDeclaration;
  15877. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  15878. auto typeDef = mCurTypeInstance->mTypeDef;
  15879. BfCustomAttributes* customAttributes = NULL;
  15880. defer(delete customAttributes);
  15881. BfInvocationExpression* ctorInvocation = NULL;
  15882. BfAttributeState attributeState;
  15883. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  15884. if (ctorDeclaration != NULL)
  15885. {
  15886. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  15887. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  15888. {
  15889. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  15890. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  15891. }
  15892. }
  15893. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  15894. // Prologue
  15895. mBfIRBuilder->ClearDebugLocation();
  15896. bool hadThisInitializer = false;
  15897. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15898. {
  15899. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15900. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15901. if (targetToken->GetToken() == BfToken_This)
  15902. {
  15903. hadThisInitializer = true;
  15904. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  15905. mCurMethodState->LocalDefined(GetThisVariable());
  15906. }
  15907. }
  15908. // Zero out memory for default ctor
  15909. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()) && (!mCurTypeInstance->IsAnonymousInitializerType()) && (methodInstance->mChainType != BfMethodChainType_ChainMember) &&
  15910. (!mCurMethodState->mLocals.IsEmpty()))
  15911. {
  15912. if (mCurTypeInstance->IsTypedPrimitive())
  15913. {
  15914. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15915. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  15916. }
  15917. else if (mCurTypeInstance->mInstSize > 0)
  15918. {
  15919. BfIRValue fillValue = GetConstValue8(0);
  15920. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  15921. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15922. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  15923. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  15924. }
  15925. }
  15926. BfAstNode* baseCtorNode = NULL;
  15927. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  15928. baseCtorNode = ctorInvocation->mTarget;
  15929. else if (methodDef->mBody != NULL)
  15930. baseCtorNode = methodDef->mBody;
  15931. else if (ctorDeclaration != NULL)
  15932. baseCtorNode = ctorDeclaration;
  15933. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15934. baseCtorNode = methodDef->mDeclaringType->GetRefNode();
  15935. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15936. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  15937. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  15938. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  15939. else
  15940. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  15941. bool calledCtorNoBody = false;
  15942. if ((mCurTypeInstance->IsTypedPrimitive()) && (!mCurTypeInstance->IsValuelessType()))
  15943. {
  15944. // Zero out typed primitives in ctor
  15945. mBfIRBuilder->CreateAlignedStore(GetDefaultValue(mCurTypeInstance->GetUnderlyingType()), mBfIRBuilder->GetArgument(0), mCurTypeInstance->mAlign);
  15946. }
  15947. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  15948. {
  15949. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  15950. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  15951. {
  15952. BfMethodDef* defaultCtor = NULL;
  15953. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  15954. {
  15955. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  15956. {
  15957. defaultCtor = methodDef;
  15958. }
  15959. }
  15960. if (defaultCtor != NULL)
  15961. {
  15962. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  15963. SetIllegalSrcPos();
  15964. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  15965. BfExprEvaluator exprEvaluator(this);
  15966. SizedArray<BfIRValue, 1> irArgs;
  15967. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  15968. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  15969. if (mIsComptimeModule)
  15970. mCompiler->mCeMachine->QueueMethod(moduleMethodInstance);
  15971. calledCtorNoBody = true;
  15972. }
  15973. }
  15974. }
  15975. // Initialize fields (if applicable)
  15976. if (mCurTypeInstance->IsBoxed())
  15977. {
  15978. skipBody = true;
  15979. }
  15980. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  15981. {
  15982. // Field initializers occur in CtorNoBody methods for extensions
  15983. }
  15984. else if (!hadThisInitializer)
  15985. {
  15986. // If we had a 'this' initializer, that other ctor will have initialized our fields
  15987. //auto
  15988. if ((!mCompiler->mIsResolveOnly) ||
  15989. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  15990. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  15991. {
  15992. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  15993. // to properly set the assigned flags
  15994. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  15995. bool hadInlineInitBlock = false;
  15996. BfScopeData scopeData;
  15997. scopeData.mInInitBlock = true;
  15998. auto _CheckInitBlock = [&](BfAstNode* node)
  15999. {
  16000. if (!hadInlineInitBlock)
  16001. {
  16002. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  16003. {
  16004. UpdateSrcPos(baseCtorNode);
  16005. if (methodDef->mBody == NULL)
  16006. SetIllegalSrcPos();
  16007. // 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
  16008. EmitEnsureInstructionAt();
  16009. BfType* thisType = mCurTypeInstance;
  16010. if (thisType->IsValueType())
  16011. thisType = CreateRefType(thisType);
  16012. SizedArray<BfIRMDNode, 1> diParamTypes;
  16013. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  16014. mCurMethodState->AddScope(&scopeData);
  16015. NewScopeState();
  16016. int flags = 0;
  16017. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  16018. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  16019. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  16020. String linkageName;
  16021. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mCurBuilder != NULL))
  16022. linkageName = StrFormat("%d", mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(mCurMethodInstance, "$initFields"));
  16023. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", linkageName, mCurFilePosition.mFileInstance->mDIFile,
  16024. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  16025. UpdateSrcPos(node);
  16026. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  16027. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  16028. //
  16029. {
  16030. auto loadedThis = GetThis();
  16031. // LLVM can't handle two variables pointing to the same value
  16032. BfIRValue copiedThisPtr;
  16033. copiedThisPtr = CreateAlloca(thisType);
  16034. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  16035. mBfIRBuilder->ClearDebugLocation(storeInst);
  16036. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  16037. }
  16038. hadInlineInitBlock = true;
  16039. }
  16040. else
  16041. {
  16042. // Just do a simple one
  16043. mCurMethodState->AddScope(&scopeData);
  16044. NewScopeState();
  16045. hadInlineInitBlock = true;
  16046. }
  16047. }
  16048. UpdateSrcPos(node);
  16049. };
  16050. for (auto fieldDef : typeDef->mFields)
  16051. {
  16052. // For extensions, only handle these fields in the appropriate extension
  16053. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16054. continue;
  16055. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  16056. {
  16057. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  16058. if (!fieldInst->mFieldIncluded)
  16059. continue;
  16060. if (fieldInst->mDataIdx < 0)
  16061. continue;
  16062. auto initializer = fieldDef->GetInitializer();
  16063. if (fieldInst->IsAppendedObject())
  16064. {
  16065. UpdateSrcPos(fieldDef->GetNameNode());
  16066. AppendedObjectInit(fieldInst);
  16067. continue;
  16068. }
  16069. if (initializer == NULL)
  16070. {
  16071. continue;
  16072. // if (fieldDef->mProtection != BfProtection_Hidden)
  16073. // continue;
  16074. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  16075. // continue;
  16076. }
  16077. if (fieldInst->mResolvedType == NULL)
  16078. {
  16079. BF_ASSERT(mHadBuildError);
  16080. continue;
  16081. }
  16082. if (initializer != NULL)
  16083. {
  16084. _CheckInitBlock(initializer);
  16085. }
  16086. BfIRValue fieldAddr;
  16087. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  16088. {
  16089. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  16090. }
  16091. else
  16092. {
  16093. // Failed
  16094. }
  16095. auto assignValue = GetFieldInitializerValue(fieldInst);
  16096. if (mCurTypeInstance->IsUnion())
  16097. {
  16098. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  16099. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  16100. }
  16101. if ((fieldAddr) && (assignValue))
  16102. mBfIRBuilder->CreateAlignedStore(assignValue.mValue, fieldAddr, fieldInst->mResolvedType->mAlign);
  16103. }
  16104. }
  16105. EmitInitBlocks(_CheckInitBlock);
  16106. if (hadInlineInitBlock)
  16107. {
  16108. RestoreScopeState();
  16109. // This gets set to false because of AddScope but we actually are still in the head block
  16110. mCurMethodState->mInHeadScope = true;
  16111. // Make sure we emit a return even if we had a NoReturn call or return inside ourselves
  16112. mCurMethodState->mHadReturn = false;
  16113. mCurMethodState->mLeftBlockUncond = false;
  16114. }
  16115. }
  16116. else // Autocomplete case
  16117. {
  16118. BfScopeData scopeData;
  16119. scopeData.mInInitBlock = true;
  16120. mCurMethodState->AddScope(&scopeData);
  16121. NewScopeState();
  16122. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  16123. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  16124. // resolve pass, NOT the autocomplete expression
  16125. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  16126. {
  16127. if (tempTypeDef->mFullName == typeDef->mFullName)
  16128. {
  16129. for (auto fieldDef : tempTypeDef->mFields)
  16130. {
  16131. auto initializer = fieldDef->GetInitializer();
  16132. if ((!fieldDef->mIsStatic) && (initializer != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  16133. {
  16134. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  16135. {
  16136. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  16137. sourceClassifier->VisitChild(initializer);
  16138. }
  16139. BfType* wantType = NULL;
  16140. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) &&
  16141. (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  16142. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowInferredSizedArray);
  16143. if ((wantType != NULL) &&
  16144. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  16145. wantType = NULL;
  16146. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  16147. if (fieldDef->mIsAppend)
  16148. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  16149. CreateValueFromExpression(initializer, wantType, exprFlags);
  16150. }
  16151. }
  16152. tempTypeDef->PopulateMemberSets();
  16153. BfMemberSetEntry* entry = NULL;
  16154. BfMethodDef* initMethodDef = NULL;
  16155. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  16156. if (entry != NULL)
  16157. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  16158. SizedArray<BfAstNode*, 8> initBodies;
  16159. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  16160. {
  16161. if (initMethodDef->mMethodType != BfMethodType_Init)
  16162. continue;
  16163. initBodies.Insert(0, initMethodDef->mBody);
  16164. }
  16165. for (auto body : initBodies)
  16166. VisitEmbeddedStatement(body);
  16167. }
  16168. }
  16169. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  16170. for (auto fieldDef : typeDef->mFields)
  16171. {
  16172. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->GetInitializer() != NULL))
  16173. {
  16174. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  16175. if (fieldDef->GetInitializer() != NULL)
  16176. MarkFieldInitialized(fieldInst);
  16177. }
  16178. }
  16179. RestoreScopeState();
  16180. }
  16181. }
  16182. if (!methodInstance->mIsAutocompleteMethod)
  16183. {
  16184. if (auto autoDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  16185. {
  16186. BfExprEvaluator exprEvaluator(this);
  16187. for (int paramIdx = 0; paramIdx < methodDef->mParams.mSize; paramIdx++)
  16188. {
  16189. auto paramDef = methodDef->mParams[paramIdx];
  16190. auto& fieldInstance = mCurTypeInstance->mFieldInstances[paramIdx];
  16191. BF_ASSERT(paramDef->mName == fieldInstance.GetFieldDef()->mName);
  16192. if (fieldInstance.mDataIdx < 0)
  16193. continue;
  16194. if (paramDef->mParamKind != BfParamKind_Normal)
  16195. continue;
  16196. auto localVar = mCurMethodState->mLocals[paramIdx + 1];
  16197. BF_ASSERT(localVar->mName == paramDef->mName);
  16198. auto localVal = exprEvaluator.LoadLocal(localVar);
  16199. localVal = LoadOrAggregateValue(localVal);
  16200. if (!localVal.mType->IsVar())
  16201. {
  16202. auto thisVal = GetThis();
  16203. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance.mDataIdx);
  16204. if (mCurTypeInstance->IsUnion())
  16205. fieldPtr = mBfIRBuilder->CreateBitCast(fieldPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInstance.mResolvedType)));
  16206. mBfIRBuilder->CreateAlignedStore(localVal.mValue, fieldPtr, localVar->mResolvedType->mAlign);
  16207. }
  16208. MarkFieldInitialized(&fieldInstance);
  16209. }
  16210. }
  16211. }
  16212. // Call base ctor (if applicable)
  16213. BfTypeInstance* targetType = NULL;
  16214. BfAstNode* targetRefNode = NULL;
  16215. if (ctorDeclaration != NULL)
  16216. targetRefNode = ctorDeclaration->mInitializer;
  16217. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  16218. targetRefNode = invocationExpr->mTarget;
  16219. if (targetRefNode == NULL)
  16220. targetRefNode = mCurTypeInstance->mTypeDef->GetRefNode();
  16221. if (baseCtorNode != NULL)
  16222. {
  16223. UpdateSrcPos(baseCtorNode);
  16224. if (methodDef->mBody == NULL)
  16225. SetIllegalSrcPos();
  16226. }
  16227. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16228. {
  16229. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  16230. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  16231. }
  16232. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()) && (methodDef->mMethodType != BfMethodType_CtorNoBody))
  16233. {
  16234. auto baseType = mCurTypeInstance->mBaseType;
  16235. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  16236. ((baseType->mTypeDef != mCompiler->mValueTypeTypeDef) || (!mContext->mCanSkipValueTypeCtor)) &&
  16237. ((baseType->mTypeDef != mCompiler->mBfObjectTypeDef) || (!mContext->mCanSkipObjectCtor)))
  16238. {
  16239. // Try to find a ctor without any params first
  16240. BfMethodDef* matchedMethod = NULL;
  16241. bool hadCtorWithAllDefaults = false;
  16242. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  16243. for (int pass = 0; pass < 2; pass++)
  16244. {
  16245. baseType->mTypeDef->PopulateMemberSets();
  16246. BfMemberSetEntry* entry = NULL;
  16247. BfMethodDef* checkMethodDef = NULL;
  16248. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  16249. if (entry != NULL)
  16250. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  16251. while (checkMethodDef != NULL)
  16252. {
  16253. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  16254. if (isHiddenGenerated)
  16255. {
  16256. // Allow calling of the default base ctor if it is implicitly defined
  16257. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  16258. allowMethod = true;
  16259. }
  16260. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  16261. {
  16262. if (checkMethodDef->mParams.size() == 0)
  16263. {
  16264. if (matchedMethod != NULL)
  16265. {
  16266. // Has multiple matched methods - can happen from extensions
  16267. matchedMethod = NULL;
  16268. break;
  16269. }
  16270. matchedMethod = checkMethodDef;
  16271. }
  16272. else if (isHiddenGenerated)
  16273. {
  16274. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  16275. hadCtorWithAllDefaults = true;
  16276. }
  16277. }
  16278. checkMethodDef = checkMethodDef->mNextWithSameName;
  16279. }
  16280. if (matchedMethod != NULL)
  16281. break;
  16282. }
  16283. if ((HasExecutedOutput()) && (matchedMethod != NULL))
  16284. {
  16285. SizedArray<BfIRValue, 1> args;
  16286. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  16287. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  16288. {
  16289. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  16290. args.push_back(basePtr);
  16291. }
  16292. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  16293. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  16294. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  16295. if (callingConv != BfIRCallingConv_CDecl)
  16296. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  16297. if (mIsComptimeModule)
  16298. mCompiler->mCeMachine->QueueMethod(ctorBodyMethodInstance);
  16299. }
  16300. if (matchedMethod == NULL)
  16301. {
  16302. targetType = mCurTypeInstance->mBaseType;
  16303. if (ctorDeclaration != NULL)
  16304. targetRefNode = ctorDeclaration->mThisToken;
  16305. else if ((typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mNameNode != NULL))
  16306. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  16307. }
  16308. }
  16309. }
  16310. if (methodDef->mHasAppend)
  16311. {
  16312. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  16313. }
  16314. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  16315. {
  16316. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  16317. {
  16318. if (targetType == mCurTypeInstance)
  16319. {
  16320. auto thisVariable = GetThisVariable();
  16321. if (thisVariable != NULL)
  16322. {
  16323. thisVariable->mUnassignedFieldFlags = 0;
  16324. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16325. }
  16326. }
  16327. targetType = NULL;
  16328. }
  16329. }
  16330. auto autoComplete = mCompiler->GetAutoComplete();
  16331. if ((targetType != NULL) && (!mCurTypeInstance->IsAnonymousInitializerType()))
  16332. {
  16333. BfAstNode* refNode = methodDeclaration;
  16334. if (refNode == NULL)
  16335. refNode = typeDef->mTypeDeclaration;
  16336. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  16337. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  16338. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16339. {
  16340. auto invocationExpr = ctorInvocation;
  16341. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  16342. }
  16343. BfType* targetThisType = targetType;
  16344. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  16345. BfExprEvaluator exprEvaluator(this);
  16346. BfResolvedArgs argValues;
  16347. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16348. {
  16349. argValues.Init(&ctorInvocation->mArguments);
  16350. if (gDebugStuff)
  16351. {
  16352. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  16353. }
  16354. }
  16355. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  16356. BfTypedValue appendIdxVal;
  16357. if (methodDef->mHasAppend)
  16358. {
  16359. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  16360. BF_ASSERT(localVar->mName == "appendIdx");
  16361. auto intRefType = localVar->mResolvedType;
  16362. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  16363. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  16364. }
  16365. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), methodDef->mHasAppend, &appendIdxVal);
  16366. if (autoComplete != NULL)
  16367. {
  16368. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  16369. {
  16370. if (autoComplete->mMethodMatchInfo != NULL)
  16371. autoComplete->mIsCapturingMethodMatchInfo = true;
  16372. else
  16373. autoComplete->mIsCapturingMethodMatchInfo = false;
  16374. }
  16375. else
  16376. autoComplete->mIsCapturingMethodMatchInfo = false;
  16377. }
  16378. }
  16379. auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration);
  16380. if ((autoComplete != NULL) && (autoComplete->CheckFixit(methodDeclaration)) && (methodDeclaration != NULL) && (autoCtorDecl != NULL))
  16381. {
  16382. auto typeDecl = methodDef->mDeclaringType->mTypeDeclaration;
  16383. BfParserData* parser = typeDecl->GetSourceData()->ToParserData();
  16384. if (parser != NULL)
  16385. {
  16386. String fixitStr = "Expand auto constructor\t";
  16387. int insertPos = typeDecl->mSrcStart;
  16388. bool needsBlock = false;
  16389. if (auto defBlock = BfNodeDynCast<BfBlock>(typeDecl->mDefineNode))
  16390. {
  16391. insertPos = defBlock->mOpenBrace->mSrcStart + 1;
  16392. }
  16393. else if (auto tokenNode = BfNodeDynCast<BfTokenNode>(typeDecl->mDefineNode))
  16394. {
  16395. insertPos = tokenNode->mSrcStart;
  16396. fixitStr += StrFormat("delete|%s-%d|\x01",
  16397. autoComplete->FixitGetLocation(parser, tokenNode->mSrcStart).c_str(), tokenNode->mSrcEnd - tokenNode->mSrcStart);
  16398. needsBlock = true;
  16399. }
  16400. int srcStart = methodDeclaration->mSrcStart;
  16401. if ((autoCtorDecl->mPrefix == NULL) && (typeDecl->mColonToken != NULL))
  16402. srcStart = typeDecl->mColonToken->mSrcStart;
  16403. while ((srcStart > 0) && (::isspace((uint8)parser->mSrc[srcStart - 1])))
  16404. srcStart--;
  16405. fixitStr += StrFormat("expand|%s|%d|",
  16406. parser->mFileName.c_str(), insertPos);
  16407. if (needsBlock)
  16408. fixitStr += "\t";
  16409. else
  16410. fixitStr += "\f";
  16411. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16412. {
  16413. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16414. paramStr.Replace('\n', '\r');
  16415. fixitStr += "public ";
  16416. fixitStr += paramStr;
  16417. fixitStr += ";\r";
  16418. }
  16419. fixitStr += "\rpublic this(";
  16420. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16421. {
  16422. if (paramIdx > 0)
  16423. fixitStr += ", ";
  16424. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16425. paramStr.Replace('\n', '\r');
  16426. fixitStr += paramStr;
  16427. }
  16428. fixitStr += ")\t";
  16429. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16430. {
  16431. if (paramIdx > 0)
  16432. fixitStr += "\r";
  16433. auto nameNode = autoCtorDecl->mParams[paramIdx]->mNameNode;
  16434. if (nameNode == NULL)
  16435. continue;
  16436. String nameStr = nameNode->ToString();
  16437. fixitStr += "this.";
  16438. fixitStr += nameStr;
  16439. fixitStr += " = ";
  16440. fixitStr += nameStr;
  16441. fixitStr += ";";
  16442. }
  16443. fixitStr += "\b";
  16444. if (needsBlock)
  16445. fixitStr += "\b";
  16446. fixitStr += StrFormat("\x01""delete|%s-%d|",
  16447. autoComplete->FixitGetLocation(parser, srcStart).c_str(), autoCtorDecl->mSrcEnd - srcStart);
  16448. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", fixitStr.c_str()));
  16449. }
  16450. }
  16451. }
  16452. void BfModule::EmitEnumToStringBody()
  16453. {
  16454. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16455. auto strVal = CreateAlloca(stringType);
  16456. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  16457. BfExprEvaluator exprEvaluator(this);
  16458. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16459. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  16460. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  16461. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  16462. BfType* discriminatorType = NULL;
  16463. BfTypedValue rawPayload;
  16464. BfIRValue enumVal;
  16465. if (mCurTypeInstance->IsPayloadEnum())
  16466. {
  16467. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  16468. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  16469. enumTypedValue = LoadValue(enumTypedValue);
  16470. enumVal = enumTypedValue.mValue;
  16471. rawPayload = ExtractValue(GetThis(), NULL, 1);
  16472. }
  16473. else
  16474. enumVal = mBfIRBuilder->GetArgument(0);
  16475. Array<BfType*> paramTypes;
  16476. paramTypes.Add(stringType);
  16477. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16478. BfIRValue switchVal;
  16479. if (!mCurTypeInstance->IsValuelessType())
  16480. switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  16481. HashSet<int64> handledCases;
  16482. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16483. {
  16484. if (fieldInstance.mIsEnumPayloadCase)
  16485. {
  16486. int tagId = -fieldInstance.mDataIdx - 1;
  16487. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16488. mBfIRBuilder->AddBlock(caseBlock);
  16489. mBfIRBuilder->SetInsertPoint(caseBlock);
  16490. BF_ASSERT(discriminatorType->IsPrimitiveType());
  16491. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  16492. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16493. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16494. auto stringDestVal = LoadValue(stringDestAddr);
  16495. SizedArray<BfIRValue, 2> args;
  16496. args.Add(stringDestVal.mValue);
  16497. args.Add(caseStr);
  16498. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16499. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  16500. BF_ASSERT(payloadType->IsTuple());
  16501. if (payloadType->mFieldInstances.size() != 0)
  16502. {
  16503. auto payload = rawPayload;
  16504. if (payload.mType != payloadType)
  16505. {
  16506. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  16507. }
  16508. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  16509. SizedArray<BfIRValue, 2> irArgs;
  16510. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  16511. stringDestVal = LoadValue(stringDestAddr);
  16512. irArgs.Add(stringDestVal.mValue);
  16513. exprEvaluator.CreateCall(NULL, toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  16514. }
  16515. mBfIRBuilder->CreateBr(endBlock);
  16516. continue;
  16517. }
  16518. if (fieldInstance.mConstIdx == -1)
  16519. continue;
  16520. // Only allow compact 'ValA, ValB' enum declaration fields through
  16521. auto fieldDef = fieldInstance.GetFieldDef();
  16522. auto fieldDecl = fieldDef->mFieldDeclaration;
  16523. if ((fieldDecl == NULL) || (fieldDef->mTypeRef != NULL))
  16524. continue;
  16525. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  16526. if (!handledCases.TryAdd(constant->mInt64, NULL))
  16527. {
  16528. // Duplicate
  16529. continue;
  16530. }
  16531. if (switchVal)
  16532. {
  16533. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16534. mBfIRBuilder->AddBlock(caseBlock);
  16535. mBfIRBuilder->SetInsertPoint(caseBlock);
  16536. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  16537. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16538. }
  16539. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16540. mBfIRBuilder->CreateStore(caseStr, strVal);
  16541. mBfIRBuilder->CreateBr(appendBlock);
  16542. }
  16543. mBfIRBuilder->AddBlock(appendBlock);
  16544. mBfIRBuilder->SetInsertPoint(appendBlock);
  16545. SizedArray<BfIRValue, 2> args;
  16546. auto stringDestVal = LoadValue(stringDestAddr);
  16547. args.Add(stringDestVal.mValue);
  16548. args.Add(mBfIRBuilder->CreateLoad(strVal));
  16549. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16550. if (switchVal)
  16551. {
  16552. mBfIRBuilder->CreateBr(endBlock);
  16553. mBfIRBuilder->AddBlock(noMatchBlock);
  16554. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  16555. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  16556. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  16557. args.clear();
  16558. args.Add(int64Val);
  16559. stringDestVal = LoadValue(stringDestAddr);
  16560. args.Add(stringDestVal.mValue);
  16561. exprEvaluator.CreateCall(NULL, toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  16562. mBfIRBuilder->CreateBr(endBlock);
  16563. mBfIRBuilder->AddBlock(endBlock);
  16564. mBfIRBuilder->SetInsertPoint(endBlock);
  16565. }
  16566. }
  16567. void BfModule::EmitTupleToStringBody()
  16568. {
  16569. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16570. BfExprEvaluator exprEvaluator(this);
  16571. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16572. Array<BfType*> paramTypes;
  16573. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  16574. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16575. paramTypes.Clear();
  16576. paramTypes.Add(stringType);
  16577. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16578. auto _AppendChar = [&](char c)
  16579. {
  16580. SizedArray<BfIRValue, 2> args;
  16581. auto stringDestVal = LoadValue(stringDestRef);
  16582. args.Add(stringDestVal.mValue);
  16583. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  16584. exprEvaluator.CreateCall(NULL, appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  16585. };
  16586. int fieldIdx = 0;
  16587. auto thisValue = GetThis();
  16588. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  16589. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  16590. BfIRValue commaStr;
  16591. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  16592. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  16593. _AppendChar('(');
  16594. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16595. {
  16596. if (fieldInstance.mDataIdx == -1)
  16597. continue;
  16598. if (fieldIdx > 0)
  16599. {
  16600. if (!commaStr)
  16601. commaStr = GetStringObjectValue(", ");
  16602. SizedArray<BfIRValue, 2> args;
  16603. auto stringDestVal = LoadValue(stringDestRef);
  16604. args.Add(stringDestVal.mValue);
  16605. args.Add(commaStr);
  16606. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16607. }
  16608. fieldIdx++;
  16609. if (fieldInstance.mResolvedType->IsValuelessType())
  16610. continue;
  16611. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  16612. if (fieldValue.mType->IsWrappableType())
  16613. {
  16614. auto wrappedType = GetWrappedStructType(fieldValue.mType);
  16615. if ((wrappedType->IsTypedPrimitive()) || (wrappedType->IsValuelessType()))
  16616. {
  16617. fieldValue.mType = wrappedType;
  16618. }
  16619. else
  16620. {
  16621. fieldValue = MakeAddressable(fieldValue);
  16622. fieldValue.mType = wrappedType;
  16623. fieldValue.mValue = mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapTypeInstPtr(fieldValue.mType->ToTypeInstance()));
  16624. if (!wrappedType->IsValuelessType())
  16625. fieldValue.mKind = BfTypedValueKind_Addr;
  16626. }
  16627. }
  16628. auto typeInstance = fieldValue.mType->ToTypeInstance();
  16629. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  16630. {
  16631. BfExprEvaluator exprEvaluator(this);
  16632. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16633. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16634. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  16635. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  16636. methodMatcher.TryDevirtualizeCall(fieldValue);
  16637. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16638. BfResolvedArg resolvedArg;
  16639. auto stringDestVal = LoadValue(stringDestRef);
  16640. resolvedArg.mTypedValue = stringDestVal;
  16641. resolvedArg.mResolvedType = stringDestVal.mType;
  16642. resolvedArgs.Add(resolvedArg);
  16643. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16644. continue;
  16645. }
  16646. if (fieldValue.mType->IsObjectOrInterface())
  16647. {
  16648. fieldValue = LoadValue(fieldValue);
  16649. BF_ASSERT(!fieldValue.IsAddr());
  16650. SizedArray<BfIRValue, 2> args;
  16651. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16652. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16653. stringDestVal = LoadValue(stringDestVal);
  16654. args.Add(stringDestVal.mValue);
  16655. exprEvaluator.CreateCall(NULL, toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  16656. continue;
  16657. }
  16658. BfExprEvaluator exprEvaluator(this);
  16659. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16660. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16661. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  16662. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  16663. methodMatcher.TryDevirtualizeCall(fieldValue);
  16664. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  16665. {
  16666. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  16667. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  16668. // Just append the type name
  16669. String typeName = TypeToString(fieldInstance.mResolvedType);
  16670. auto strVal = GetStringObjectValue(typeName);
  16671. SizedArray<BfIRValue, 2> args;
  16672. auto stringDestVal = LoadValue(stringDestRef);
  16673. args.Add(stringDestVal.mValue);
  16674. args.Add(strVal);
  16675. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16676. continue;
  16677. }
  16678. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16679. BfResolvedArg resolvedArg;
  16680. auto stringDestVal = LoadValue(stringDestRef);
  16681. resolvedArg.mTypedValue = stringDestVal;
  16682. resolvedArg.mResolvedType = stringDestVal.mType;
  16683. resolvedArgs.Add(resolvedArg);
  16684. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16685. }
  16686. _AppendChar(')');
  16687. }
  16688. void BfModule::EmitIteratorBlock(bool& skipBody)
  16689. {
  16690. auto methodInstance = mCurMethodInstance;
  16691. auto methodDef = methodInstance->mMethodDef;
  16692. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16693. auto typeDef = mCurTypeInstance->mTypeDef;
  16694. BfType* innerRetType = NULL;
  16695. BfTypeInstance* usingInterface = NULL;
  16696. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  16697. if (retTypeInst != NULL)
  16698. {
  16699. if ((retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef)) ||
  16700. (retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumeratorTypeDef)))
  16701. {
  16702. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  16703. }
  16704. }
  16705. if (innerRetType == NULL)
  16706. {
  16707. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  16708. return;
  16709. }
  16710. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  16711. if (blockBody == NULL)
  16712. return;
  16713. }
  16714. void BfModule::EmitGCMarkAppended(BfTypedValue markVal)
  16715. {
  16716. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  16717. if (gcType == NULL)
  16718. return;
  16719. BfModuleMethodInstance markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "MarkAppendedObject", 1);
  16720. if (!markFromGCThreadMethodInstance)
  16721. return;
  16722. SizedArray<BfIRValue, 1> args;
  16723. args.push_back(mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16724. BfExprEvaluator exprEvaluator(this);
  16725. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16726. }
  16727. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  16728. {
  16729. auto fieldType = markVal.mType;
  16730. auto fieldTypeInst = fieldType->ToTypeInstance();
  16731. if (fieldType == NULL)
  16732. return;
  16733. if (!markVal.mType->IsComposite())
  16734. markVal = LoadValue(markVal);
  16735. BfExprEvaluator exprEvaluator(this);
  16736. PopulateType(markVal.mType, BfPopulateType_Data);
  16737. if (markVal.mType->IsObjectOrInterface())
  16738. {
  16739. BfIRValue val = markVal.mValue;
  16740. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  16741. SizedArray<BfIRValue, 1> args;
  16742. args.push_back(val);
  16743. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16744. }
  16745. else if (fieldType->IsSizedArray())
  16746. {
  16747. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)fieldType;
  16748. if (sizedArrayType->mElementType->WantsGCMarking())
  16749. {
  16750. BfTypedValue arrayValue = markVal;
  16751. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  16752. auto itr = CreateAlloca(intPtrType);
  16753. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  16754. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  16755. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  16756. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  16757. mBfIRBuilder->CreateBr(loopBB);
  16758. mBfIRBuilder->SetInsertPoint(loopBB);
  16759. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  16760. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  16761. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  16762. mBfIRBuilder->SetInsertPoint(bodyBB);
  16763. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16764. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16765. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  16766. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16767. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16768. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  16769. mBfIRBuilder->CreateStore(incValue, itr);
  16770. mBfIRBuilder->CreateBr(loopBB);
  16771. mBfIRBuilder->SetInsertPoint(doneBB);
  16772. }
  16773. }
  16774. else if ((fieldType->IsComposite()) && (!fieldType->IsTypedPrimitive()) && (fieldTypeInst != NULL))
  16775. {
  16776. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  16777. if (markMemberMethodInstance)
  16778. {
  16779. SizedArray<BfIRValue, 1> args;
  16780. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  16781. if (markVal.mType != methodOwner)
  16782. markVal = Cast(NULL, markVal, methodOwner);
  16783. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  16784. exprEvaluator.CreateCall(NULL, markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  16785. }
  16786. }
  16787. }
  16788. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  16789. {
  16790. Array<BfMethodInstance*> methodInstances;
  16791. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  16792. {
  16793. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  16794. auto chainedMethodInst = methodInstGroup.mDefault;
  16795. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  16796. {
  16797. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  16798. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  16799. {
  16800. methodInstances.push_back(chainedMethodInst);
  16801. }
  16802. }
  16803. }
  16804. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  16805. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  16806. {
  16807. bool isBetter;
  16808. bool isWorse;
  16809. CompareDeclTypes(mCurTypeInstance, lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  16810. if (isBetter == isWorse)
  16811. {
  16812. return false;
  16813. }
  16814. return isWorse;
  16815. });
  16816. if (reverse)
  16817. std::reverse(methodInstances.begin(), methodInstances.end());
  16818. for (auto chainedMethodInst : methodInstances)
  16819. {
  16820. auto declModule = this;
  16821. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  16822. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  16823. BfExprEvaluator exprEvaluator(this);
  16824. SizedArray<BfIRValue, 1> args;
  16825. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  16826. exprEvaluator.CreateCall(NULL, moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  16827. }
  16828. }
  16829. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  16830. {
  16831. BF_ASSERT(mCurMethodInstance->mIsReified);
  16832. if (mCurTypeInstance->mHotTypeData == NULL)
  16833. {
  16834. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  16835. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  16836. }
  16837. auto hotMethod = mCurMethodInstance->mHotMethod;
  16838. for (auto depData : hotMethod->mReferences)
  16839. {
  16840. // Only virtual decls are allowed to already be there
  16841. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  16842. }
  16843. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  16844. int prevSize = (int)hotMethod->mReferences.size();
  16845. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  16846. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  16847. refCount++;
  16848. hotMethod->mReferences.Reserve(refCount);
  16849. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  16850. {
  16851. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  16852. hotThis->mRefCount++;
  16853. hotMethod->mReferences.Insert(0, hotThis);
  16854. prevSize++;
  16855. }
  16856. for (auto val : builder->mAllocatedData)
  16857. {
  16858. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  16859. hotMethod->mReferences.Add(hotAllocation);
  16860. }
  16861. for (auto val : builder->mUsedData)
  16862. hotMethod->mReferences.Add(val);
  16863. for (auto val : builder->mCalledMethods)
  16864. hotMethod->mReferences.Add(val);
  16865. for (auto val : builder->mDevirtualizedCalledMethods)
  16866. {
  16867. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  16868. hotMethod->mReferences.Add(devirtualizedMethod);
  16869. }
  16870. for (auto val : builder->mFunctionPtrs)
  16871. {
  16872. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  16873. hotMethod->mReferences.Add(funcRef);
  16874. }
  16875. for (auto val : builder->mInnerMethods)
  16876. {
  16877. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  16878. hotMethod->mReferences.Add(innerMethod);
  16879. }
  16880. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  16881. {
  16882. auto depData = hotMethod->mReferences[refIdx];
  16883. BF_ASSERT(depData != NULL);
  16884. depData->mRefCount++;
  16885. }
  16886. }
  16887. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  16888. {
  16889. auto methodDef = methodInstance->mMethodDef;
  16890. auto methodDeclaration = methodDef->mMethodDeclaration;
  16891. bool isThisStruct = false;
  16892. if (thisType != NULL)
  16893. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  16894. int argIdx = 0;
  16895. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16896. argIdx++;
  16897. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16898. if (!methodDef->mIsStatic)
  16899. {
  16900. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16901. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16902. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  16903. paramVar->mIsBumpAlloc = true;
  16904. paramVar->mResolvedType = thisType;
  16905. paramVar->mName.Reference("this");
  16906. if (!thisType->IsValuelessType())
  16907. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16908. else
  16909. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  16910. if ((!mIsComptimeModule) && (thisType->IsSplattable()) && (methodInstance->AllowsSplatting(-1)))
  16911. {
  16912. if (!thisType->IsTypedPrimitive())
  16913. paramVar->mIsSplat = true;
  16914. }
  16915. else if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  16916. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  16917. auto thisTypeInst = thisType->ToTypeInstance();
  16918. paramVar->mIsStruct = isThisStruct;
  16919. paramVar->mAddr = BfIRValue();
  16920. paramVar->mIsThis = true;
  16921. paramVar->mParamIdx = -1;
  16922. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  16923. {
  16924. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  16925. }
  16926. else
  16927. {
  16928. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16929. }
  16930. paramVar->mReadFromId = -1;
  16931. paramVar->Init();
  16932. if (methodDeclaration == NULL)
  16933. UseDefaultSrcPos();
  16934. AddLocalVariableDef(paramVar);
  16935. if (!thisType->IsValuelessType())
  16936. {
  16937. if (wantsDIData)
  16938. {
  16939. BfType* thisPtrType = thisType;
  16940. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  16941. if (!thisType->IsValueType())
  16942. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  16943. else if (!paramVar->mIsSplat)
  16944. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  16945. diParams->push_back(diType);
  16946. }
  16947. if (paramVar->mIsSplat)
  16948. {
  16949. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16950. }
  16951. else
  16952. {
  16953. argIdx++;
  16954. if (loweredTypeCode2 != BfTypeCode_None)
  16955. argIdx++;
  16956. }
  16957. }
  16958. }
  16959. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16960. argIdx++;
  16961. bool hadParams = false;
  16962. bool hasDefault = false;
  16963. int compositeVariableIdx = -1;
  16964. int paramIdx = 0;
  16965. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16966. {
  16967. // We already issues a type error for this param if we had one in declaration processing
  16968. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  16969. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  16970. paramVar->mIsBumpAlloc = true;
  16971. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16972. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16973. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  16974. auto resolvedType = methodInstance->GetParamType(paramIdx);
  16975. if (resolvedType == NULL)
  16976. {
  16977. AssertErrorState();
  16978. paramVar->mParamFailed = true;
  16979. }
  16980. prevIgnoreErrors.Restore();
  16981. PopulateType(resolvedType, BfPopulateType_Declaration);
  16982. paramVar->mResolvedType = resolvedType;
  16983. int namePrefixCount = 0;
  16984. methodInstance->GetParamName(paramIdx, paramVar->mName, namePrefixCount);
  16985. paramVar->mNamePrefixCount = (uint8)namePrefixCount;
  16986. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  16987. if (!isParamSkipped)
  16988. {
  16989. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16990. if (resolvedType->IsMethodRef())
  16991. {
  16992. paramVar->mIsSplat = true;
  16993. }
  16994. else if ((!mIsComptimeModule) && (resolvedType->IsComposite()) && (resolvedType->IsSplattable()))
  16995. {
  16996. if (methodInstance->AllowsSplatting(paramIdx))
  16997. {
  16998. auto resolveTypeInst = resolvedType->ToTypeInstance();
  16999. if ((resolveTypeInst != NULL) && (resolveTypeInst->mIsCRepr))
  17000. paramVar->mIsSplat = true;
  17001. else
  17002. {
  17003. int splatCount = resolvedType->GetSplatCount();
  17004. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  17005. paramVar->mIsSplat = true;
  17006. }
  17007. }
  17008. }
  17009. }
  17010. else
  17011. {
  17012. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  17013. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  17014. }
  17015. paramVar->mIsLowered = (!mIsComptimeModule) && resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  17016. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  17017. paramVar->mParamIdx = paramIdx;
  17018. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  17019. paramVar->mReadFromId = 0;
  17020. if (resolvedType->IsRef())
  17021. {
  17022. auto refType = (BfRefType*)resolvedType;
  17023. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  17024. if (refType->mRefKind == BfRefType::RefKind_In)
  17025. {
  17026. paramVar->mIsReadOnly = true;
  17027. }
  17028. }
  17029. else
  17030. {
  17031. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  17032. if (methodDef->mMethodType != BfMethodType_Mixin)
  17033. paramVar->mIsReadOnly = true;
  17034. }
  17035. if (paramVar->mResolvedType->IsGenericParam())
  17036. {
  17037. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  17038. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  17039. {
  17040. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  17041. paramVar->mResolvedType = typedVal.mType;
  17042. paramVar->mConstValue = typedVal.mValue;
  17043. }
  17044. }
  17045. if (paramVar->mResolvedType->IsConstExprValue())
  17046. {
  17047. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  17048. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  17049. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  17050. BF_ASSERT(unspecParamType->IsGenericParam());
  17051. if (unspecParamType->IsGenericParam())
  17052. {
  17053. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  17054. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  17055. {
  17056. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  17057. if (genericParamInst->mTypeConstraint != NULL)
  17058. {
  17059. BfExprEvaluator exprEvaluator(this);
  17060. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  17061. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  17062. auto checkType = genericParamInst->mTypeConstraint;
  17063. if (checkType->IsTypedPrimitive())
  17064. checkType = checkType->GetUnderlyingType();
  17065. auto typedVal = exprEvaluator.mResult;
  17066. if ((typedVal) && (typedVal.mType != checkType))
  17067. typedVal = Cast(NULL, typedVal, checkType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  17068. if ((typedVal.mType == checkType) && (typedVal.mValue.IsConst()))
  17069. {
  17070. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  17071. paramVar->mConstValue = typedVal.mValue;
  17072. BF_ASSERT(paramVar->mConstValue.IsConst());
  17073. paramVar->mIsConst = true;
  17074. }
  17075. else
  17076. {
  17077. AssertErrorState();
  17078. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  17079. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  17080. paramVar->mIsConst = true;
  17081. }
  17082. if (paramVar->mResolvedType->IsObject())
  17083. {
  17084. BfTypedValue typedVal(paramVar->mConstValue, paramVar->mResolvedType);
  17085. FixValueActualization(typedVal);
  17086. if (typedVal.mValue.IsConst())
  17087. paramVar->mConstValue = typedVal.mValue;
  17088. }
  17089. }
  17090. }
  17091. }
  17092. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  17093. if (paramVar->mResolvedType->IsConstExprValue())
  17094. {
  17095. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  17096. //AssertErrorState();
  17097. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  17098. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  17099. paramVar->mIsConst = true;
  17100. }
  17101. }
  17102. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  17103. {
  17104. if (compositeVariableIdx == -1)
  17105. {
  17106. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  17107. BfLocalVariable* localVar = new BfLocalVariable();
  17108. auto paramInst = &methodInstance->mParams[paramIdx];
  17109. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  17110. localVar->mName = paramDef->mName;
  17111. localVar->mNamePrefixCount = paramDef->mNamePrefixCount;
  17112. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  17113. localVar->mCompositeCount = 0;
  17114. DoAddLocalVariable(localVar);
  17115. }
  17116. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  17117. paramVar->mIsImplicitParam = true;
  17118. }
  17119. if (!mCurTypeInstance->IsDelegateOrFunction())
  17120. CheckVariableDef(paramVar);
  17121. paramVar->Init();
  17122. AddLocalVariableDef(paramVar);
  17123. if (!isParamSkipped)
  17124. {
  17125. if (wantsDIData)
  17126. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  17127. if (paramVar->mIsSplat)
  17128. {
  17129. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17130. }
  17131. else
  17132. {
  17133. argIdx++;
  17134. }
  17135. if (loweredTypeCode2 != BfTypeCode_None)
  17136. argIdx++;
  17137. }
  17138. }
  17139. // Try to find an ending delegate params composite
  17140. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  17141. {
  17142. auto paramDef = methodDef->mParams.back();
  17143. if (paramDef->mParamKind == BfParamKind_Params)
  17144. {
  17145. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  17146. if (paramsType == NULL)
  17147. {
  17148. // Had error or 'var'
  17149. }
  17150. else if (paramsType->IsGenericParam())
  17151. {
  17152. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  17153. if (genericParamInstance->mTypeConstraint != NULL)
  17154. {
  17155. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  17156. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  17157. ((typeInstConstraint != NULL) &&
  17158. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  17159. {
  17160. BfLocalVariable* localVar = new BfLocalVariable();
  17161. localVar->mName = paramDef->mName;
  17162. localVar->mResolvedType = paramsType;
  17163. localVar->mCompositeCount = 0;
  17164. DoAddLocalVariable(localVar);
  17165. }
  17166. }
  17167. }
  17168. else if (paramsType->IsDelegate())
  17169. {
  17170. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  17171. if (invokeMethodInstance != NULL)
  17172. {
  17173. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  17174. // and wasn't cleared by the preceding loop
  17175. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  17176. BfLocalVariable* localVar = new BfLocalVariable();
  17177. localVar->mName = paramDef->mName;
  17178. localVar->mResolvedType = paramsType;
  17179. localVar->mCompositeCount = 0;
  17180. DoAddLocalVariable(localVar);
  17181. }
  17182. }
  17183. }
  17184. }
  17185. }
  17186. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  17187. {
  17188. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  17189. // return;
  17190. auto startMethodState = mCurMethodState;
  17191. auto _ClearState = [&]()
  17192. {
  17193. mCurMethodState->mLocalMethods.Clear();
  17194. for (auto& local : mCurMethodState->mLocals)
  17195. {
  17196. if (local->mIsBumpAlloc)
  17197. local->~BfLocalVariable();
  17198. else
  17199. delete local;
  17200. }
  17201. mCurMethodState->mLocals.Clear();
  17202. mCurMethodState->mLocalVarSet.Clear();
  17203. };
  17204. while (true)
  17205. {
  17206. bool didWork = false;
  17207. // 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
  17208. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  17209. // however (compiler bug), so this is the safest way
  17210. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  17211. {
  17212. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  17213. {
  17214. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  17215. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  17216. if (!mHadBuildError)
  17217. {
  17218. // Process as a closure - that allows us to look back and see the const locals and stuff
  17219. BfClosureState closureState;
  17220. mCurMethodState->mClosureState = &closureState;
  17221. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17222. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  17223. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  17224. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  17225. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  17226. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17227. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  17228. _ClearState();
  17229. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  17230. {
  17231. auto localVar = new BfLocalVariable();
  17232. *localVar = constLocal;
  17233. DoAddLocalVariable(localVar);
  17234. }
  17235. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  17236. bool doProcess = !mCompiler->mCanceling;
  17237. if (doProcess)
  17238. {
  17239. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  17240. ProcessMethod(deferredLocalMethod->mMethodInstance);
  17241. }
  17242. }
  17243. delete deferredLocalMethod;
  17244. mContext->CheckLockYield();
  17245. didWork = true;
  17246. }
  17247. mCurMethodState->mDeferredLocalMethods.Clear();
  17248. }
  17249. for (auto& kv : mCurMethodState->mLocalMethodCache)
  17250. {
  17251. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  17252. }
  17253. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  17254. {
  17255. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  17256. {
  17257. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  17258. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  17259. BfClosureState closureState;
  17260. mCurMethodState->mClosureState = &closureState;
  17261. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17262. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  17263. if (lambdaInstance->mClosureTypeInstance != NULL)
  17264. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  17265. else
  17266. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  17267. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17268. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  17269. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  17270. _ClearState();
  17271. for (auto& constLocal : lambdaInstance->mConstLocals)
  17272. {
  17273. //if (constLocal.mIsThis)
  17274. {
  17275. // Valueless 'this'
  17276. closureState.mConstLocals.Add(constLocal);
  17277. }
  17278. /*else
  17279. {
  17280. auto localVar = new BfLocalVariable();
  17281. *localVar = constLocal;
  17282. DoAddLocalVariable(localVar);
  17283. }*/
  17284. }
  17285. BfMethodInstanceGroup methodInstanceGroup;
  17286. methodInstanceGroup.mOwner = mCurTypeInstance;
  17287. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  17288. bool doProcess = !mCompiler->mCanceling;
  17289. if (doProcess)
  17290. {
  17291. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  17292. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17293. ProcessMethod(lambdaInstance->mMethodInstance);
  17294. lambdaInstance->mMethodInstance->mMethodInstanceGroup = NULL;
  17295. if (lambdaInstance->mDtorMethodInstance != NULL)
  17296. {
  17297. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17298. auto startMethodState2 = mCurMethodState;
  17299. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  17300. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = NULL;
  17301. }
  17302. }
  17303. didWork = true;
  17304. }
  17305. mContext->CheckLockYield();
  17306. mCurMethodState->mDeferredLambdaInstances.Clear();
  17307. }
  17308. if (!didWork)
  17309. break;
  17310. }
  17311. }
  17312. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance, bool isAppendObject)
  17313. {
  17314. if (checkType->IsComposite())
  17315. PopulateType(checkType, BfPopulateType_Data);
  17316. if (!checkType->WantsGCMarking())
  17317. return;
  17318. auto typeInstance = checkType->ToTypeInstance();
  17319. bool callMarkMethod = false;
  17320. // Call the actual marking method
  17321. if (memberDepth == 0)
  17322. {
  17323. // Don't call marking method on self
  17324. }
  17325. else if (checkType->IsObjectOrInterface())
  17326. {
  17327. if (!objectOffsets.Add(curOffset))
  17328. {
  17329. return;
  17330. }
  17331. callMarkMethod = true;
  17332. }
  17333. else if (checkType->IsSizedArray())
  17334. {
  17335. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  17336. if (sizedArrayType->mElementType->WantsGCMarking())
  17337. {
  17338. BfTypedValue arrayValue = thisValue;
  17339. if (thisValue.mType != checkType)
  17340. {
  17341. BfIRValue srcValue = thisValue.mValue;
  17342. if (curOffset != 0)
  17343. {
  17344. if (!thisValue.mType->IsPointer())
  17345. {
  17346. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17347. auto int8PtrType = CreatePointerType(int8Type);
  17348. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  17349. }
  17350. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  17351. }
  17352. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  17353. }
  17354. if (sizedArrayType->mElementCount > 6)
  17355. {
  17356. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  17357. auto itr = CreateAlloca(intPtrType);
  17358. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  17359. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  17360. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  17361. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  17362. mBfIRBuilder->CreateBr(loopBB);
  17363. mBfIRBuilder->SetInsertPoint(loopBB);
  17364. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  17365. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  17366. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  17367. mBfIRBuilder->SetInsertPoint(bodyBB);
  17368. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17369. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17370. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  17371. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17372. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17373. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  17374. mBfIRBuilder->CreateStore(incValue, itr);
  17375. mBfIRBuilder->CreateBr(loopBB);
  17376. mBfIRBuilder->SetInsertPoint(doneBB);
  17377. }
  17378. else
  17379. {
  17380. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  17381. {
  17382. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17383. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17384. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  17385. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17386. HashSet<int> objectOffsets;
  17387. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17388. }
  17389. }
  17390. }
  17391. }
  17392. else if (typeInstance != NULL)
  17393. {
  17394. typeInstance->mTypeDef->PopulateMemberSets();
  17395. BfMemberSetEntry* entry = NULL;
  17396. BfMethodDef* methodDef = NULL;
  17397. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  17398. {
  17399. methodDef = (BfMethodDef*)entry->mMemberDef;
  17400. if (methodDef->HasBody())
  17401. {
  17402. callMarkMethod = true;
  17403. }
  17404. }
  17405. }
  17406. if (callMarkMethod)
  17407. {
  17408. BfTypedValue markValue;
  17409. auto memberType = checkType;
  17410. if (memberType->IsObjectOrInterface())
  17411. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  17412. auto memberPtrType = CreatePointerType(memberType);
  17413. if (curOffset == 0)
  17414. {
  17415. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17416. }
  17417. else
  17418. {
  17419. if (!thisValue.mType->IsPointer())
  17420. {
  17421. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17422. auto int8PtrType = CreatePointerType(int8Type);
  17423. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  17424. }
  17425. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  17426. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17427. }
  17428. if (isAppendObject)
  17429. EmitGCMarkAppended(markValue);
  17430. else
  17431. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17432. return;
  17433. }
  17434. auto methodDef = mCurMethodInstance->mMethodDef;
  17435. if (checkType->IsPayloadEnum())
  17436. {
  17437. for (auto& fieldInst : typeInstance->mFieldInstances)
  17438. {
  17439. if (!fieldInst.mIsEnumPayloadCase)
  17440. continue;
  17441. auto fieldDef = fieldInst.GetFieldDef();
  17442. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17443. }
  17444. return;
  17445. }
  17446. if (typeInstance == NULL)
  17447. return;
  17448. for (auto& fieldInst : typeInstance->mFieldInstances)
  17449. {
  17450. auto fieldDef = fieldInst.GetFieldDef();
  17451. if (fieldDef == NULL)
  17452. continue;
  17453. if (fieldDef->mIsStatic)
  17454. continue;
  17455. if (typeInstance == mCurTypeInstance)
  17456. {
  17457. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  17458. // we may be marking member values that can never contain a value anyway, but this is benign
  17459. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17460. continue;
  17461. }
  17462. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance, fieldInst.IsAppendedObject());
  17463. }
  17464. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  17465. {
  17466. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17467. }
  17468. }
  17469. void BfModule::EmitGCMarkMembers()
  17470. {
  17471. auto methodDef = mCurMethodInstance->mMethodDef;
  17472. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  17473. BfModuleMethodInstance markFromGCThreadMethodInstance;
  17474. if (gcType != NULL)
  17475. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  17476. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  17477. {
  17478. if (mCurTypeInstance->IsBoxed())
  17479. {
  17480. // This already gets filled in by the normal boxed forwarding
  17481. }
  17482. else
  17483. {
  17484. auto thisValue = GetThis();
  17485. if (thisValue.IsSplat())
  17486. {
  17487. BfIRFunction func = mCurMethodInstance->mIRFunction;
  17488. int argIdx = 0;
  17489. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  17490. {
  17491. if (checkType->IsStruct())
  17492. {
  17493. auto checkTypeInstance = checkType->ToTypeInstance();
  17494. if (checkTypeInstance->mBaseType != NULL)
  17495. checkTypeLambda(checkTypeInstance->mBaseType);
  17496. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  17497. {
  17498. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  17499. if (fieldInstance->mDataIdx >= 0)
  17500. checkTypeLambda(fieldInstance->GetResolvedType());
  17501. }
  17502. }
  17503. else if (checkType->IsMethodRef())
  17504. {
  17505. BFMODULE_FATAL(this, "Not handled");
  17506. }
  17507. else if (checkType->WantsGCMarking())
  17508. {
  17509. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  17510. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17511. argIdx++;
  17512. }
  17513. };
  17514. checkTypeLambda(thisValue.mType);
  17515. }
  17516. else if (!methodDef->mIsStatic)
  17517. {
  17518. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  17519. {
  17520. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  17521. if (moduleMethodInst)
  17522. {
  17523. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  17524. bool wantsBaseMarking = true;
  17525. if (methodBaseType == mContext->mBfObjectType)
  17526. {
  17527. wantsBaseMarking = false;
  17528. PopulateType(methodBaseType);
  17529. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  17530. {
  17531. if ((fieldInstance.GetFieldDef()->mDeclaringType->IsExtension()) &&
  17532. (fieldInstance.mResolvedType->WantsGCMarking()))
  17533. wantsBaseMarking = true;
  17534. }
  17535. }
  17536. if (wantsBaseMarking)
  17537. {
  17538. auto thisValue = GetThis();
  17539. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  17540. SizedArray<BfIRValue, 1> args;
  17541. if ((!mIsComptimeModule) && (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1)))
  17542. {
  17543. BfExprEvaluator exprEvaluator(this);
  17544. exprEvaluator.SplatArgs(baseValue, args);
  17545. }
  17546. else
  17547. {
  17548. args.push_back(baseValue.mValue);
  17549. }
  17550. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  17551. }
  17552. }
  17553. }
  17554. }
  17555. if (!methodDef->mIsStatic)
  17556. {
  17557. HashSet<int> objectOffsets;
  17558. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  17559. }
  17560. else
  17561. {
  17562. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17563. {
  17564. if (thisValue.IsSplat())
  17565. break;
  17566. auto fieldDef = fieldInst.GetFieldDef();
  17567. if (fieldDef == NULL)
  17568. continue;
  17569. if (IsThreadLocal(&fieldInst))
  17570. continue;
  17571. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  17572. {
  17573. // For extensions, only handle these fields in the appropriate extension
  17574. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17575. continue;
  17576. if (!fieldInst.mFieldIncluded)
  17577. continue;
  17578. auto fieldType = fieldInst.mResolvedType;
  17579. auto fieldDef = fieldInst.GetFieldDef();
  17580. BfTypedValue markVal;
  17581. if (fieldDef->mIsConst)
  17582. continue;
  17583. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17584. continue;
  17585. mBfIRBuilder->PopulateType(fieldType);
  17586. if (fieldType->IsValuelessType())
  17587. continue;
  17588. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  17589. {
  17590. StringT<512> staticVarName;
  17591. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  17592. if (staticVarName.StartsWith('#'))
  17593. continue;
  17594. markVal = ReferenceStaticField(&fieldInst);
  17595. }
  17596. else if (!fieldDef->mIsStatic)
  17597. {
  17598. if (fieldInst.IsAppendedObject())
  17599. {
  17600. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst.mDataIdx);
  17601. auto val = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  17602. markVal = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst.mResolvedType)), fieldInst.mResolvedType);
  17603. }
  17604. else
  17605. {
  17606. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  17607. }
  17608. }
  17609. if (markVal)
  17610. {
  17611. if (fieldInst.IsAppendedObject())
  17612. EmitGCMarkAppended(markVal);
  17613. else
  17614. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  17615. }
  17616. }
  17617. }
  17618. }
  17619. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17620. CallChainedMethods(mCurMethodInstance, false);
  17621. }
  17622. }
  17623. }
  17624. void BfModule::EmitGCFindTLSMembers()
  17625. {
  17626. auto methodDef = mCurMethodInstance->mMethodDef;
  17627. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  17628. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  17629. BF_ASSERT(reportTLSMark);
  17630. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17631. {
  17632. auto fieldDef = fieldInst.GetFieldDef();
  17633. if (fieldDef == NULL)
  17634. continue;
  17635. if (!IsThreadLocal(&fieldInst))
  17636. continue;
  17637. // For extensions, only handle these fields in the appropriate extension
  17638. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17639. continue;
  17640. if (!fieldInst.mFieldIncluded)
  17641. continue;
  17642. if (fieldDef->mIsConst)
  17643. continue;
  17644. auto fieldType = fieldInst.mResolvedType;
  17645. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17646. continue;
  17647. if (fieldType->IsValuelessType())
  17648. continue;
  17649. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  17650. if (markVal)
  17651. {
  17652. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  17653. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  17654. SizedArray<BfIRValue, 2> llvmArgs;
  17655. llvmArgs.push_back(fieldRefPtr);
  17656. llvmArgs.push_back(markFuncPtr);
  17657. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  17658. }
  17659. }
  17660. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17661. CallChainedMethods(mCurMethodInstance, false);
  17662. }
  17663. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup, bool forceIRWrites)
  17664. {
  17665. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  17666. if (mIsComptimeModule)
  17667. {
  17668. BF_ASSERT(!mCompiler->IsAutocomplete());
  17669. }
  17670. if (mAwaitingInitFinish)
  17671. FinishInit();
  17672. if ((methodInstance->mIsReified) && (!mCompiler->mIsResolveOnly))
  17673. {
  17674. BfLogSysM("REIFIED(ProcessMethod): %s %p Module: %s\n", methodInstance->mMethodDef->mName.c_str(), methodInstance, mModuleName.c_str());
  17675. }
  17676. // Reify types that are actually used - they don't get reified during method declaration
  17677. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  17678. {
  17679. auto _CheckType = [&](BfType* type)
  17680. {
  17681. if (!type->IsReified())
  17682. PopulateType(type, BfPopulateType_Declaration);
  17683. };
  17684. _CheckType(methodInstance->mReturnType);
  17685. for (auto& param : methodInstance->mParams)
  17686. {
  17687. _CheckType(param.mResolvedType);
  17688. }
  17689. }
  17690. if (!methodInstance->mIsReified)
  17691. BF_ASSERT(!mIsReified);
  17692. BF_ASSERT((!methodInstance->GetOwner()->IsUnspecializedTypeVariation()) || (mIsComptimeModule));
  17693. if (methodInstance->mMethodInfoEx != NULL)
  17694. {
  17695. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  17696. {
  17697. if (methodGenericArg->IsMethodRef())
  17698. {
  17699. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  17700. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  17701. }
  17702. }
  17703. }
  17704. if (mBfIRBuilder == NULL)
  17705. {
  17706. BfLogSysM("ProcessMethod %p calling EnsureIRBuilder\n", methodInstance);
  17707. EnsureIRBuilder();
  17708. }
  17709. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, (mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized) && (!forceIRWrites));
  17710. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  17711. {
  17712. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  17713. }
  17714. SetAndRestoreValue<bool> prevIsClassifying;
  17715. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  17716. (mCompiler->mResolvePassData != NULL))
  17717. {
  17718. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  17719. prevIsClassifying.Init(mCompiler->mResolvePassData->mIsClassifying, false);
  17720. }
  17721. if (methodInstance->mHasBeenProcessed)
  17722. {
  17723. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  17724. return;
  17725. }
  17726. if (methodInstance->mFailedConstraints)
  17727. {
  17728. // The only way this should be able to happen is if we fail our generic param check
  17729. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  17730. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  17731. methodInstance->mHasBeenProcessed = true;
  17732. return;
  17733. }
  17734. if (HasExecutedOutput())
  17735. {
  17736. BF_ASSERT(mIsModuleMutable);
  17737. }
  17738. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  17739. if (!mIsComptimeModule)
  17740. {
  17741. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  17742. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  17743. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  17744. {
  17745. auto owningModule = methodInstance->GetOwner()->mModule;
  17746. if (owningModule->mIsScratchModule)
  17747. {
  17748. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  17749. }
  17750. else
  17751. {
  17752. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  17753. if (owningModule->mOnDemandMethodCount > 0)
  17754. owningModule->mOnDemandMethodCount--;
  17755. }
  17756. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  17757. VerifyOnDemandMethods();
  17758. }
  17759. }
  17760. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  17761. // self-referencing append allocations in ctor@calcAppend
  17762. methodInstance->mHasBeenProcessed = true;
  17763. mIncompleteMethodCount--;
  17764. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  17765. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  17766. auto methodDef = methodInstance->mMethodDef;
  17767. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17768. if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  17769. mBfIRBuilder->mIgnoreWrites = true;
  17770. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  17771. {
  17772. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  17773. // so we get the new vdata for it
  17774. methodInstance->GetOwner()->mDirty = true;
  17775. }
  17776. int dependentGenericStartIdx = 0;
  17777. if ((methodDef->mIsLocalMethod) && (mCurMethodState != NULL)) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  17778. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  17779. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  17780. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  17781. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  17782. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  17783. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  17784. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors);
  17785. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, mIsComptimeModule);
  17786. if ((!mIsComptimeModule) && (methodInstance->mIsReified) &&
  17787. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  17788. {
  17789. mCurTypeInstance->mHasBeenInstantiated = true;
  17790. }
  17791. // Warnings are shown in the capture phase
  17792. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  17793. mIgnoreWarnings = true;
  17794. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  17795. UseDefaultSrcPos();
  17796. if ((mIsComptimeModule) && (methodDef->mIsStatic))
  17797. {
  17798. PopulateType(mCurTypeInstance, BfPopulateType_AllowStaticMethods);
  17799. }
  17800. else
  17801. {
  17802. // We may not actually be populated in relatively rare autocompelte cases
  17803. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  17804. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  17805. }
  17806. BfAstNode* nameNode = NULL;
  17807. if (methodDeclaration != NULL)
  17808. {
  17809. nameNode = methodDeclaration->mNameNode;
  17810. if (nameNode == NULL)
  17811. {
  17812. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  17813. nameNode = ctorDeclaration->mThisToken;
  17814. }
  17815. }
  17816. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  17817. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) &&
  17818. (methodDef->mIdx >= 0) && (!methodInstance->mIsForeignMethodDef))
  17819. {
  17820. if (methodInstance->GetExplicitInterface() == NULL)
  17821. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  17822. else
  17823. {
  17824. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  17825. {
  17826. auto ifaceInst = ifaceEntry.mInterfaceType;
  17827. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  17828. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17829. if (methodInstance->GetExplicitInterface() != ifaceInst)
  17830. continue;
  17831. ifaceInst->mTypeDef->PopulateMemberSets();
  17832. BfMethodDef* nextMethod = NULL;
  17833. BfMemberSetEntry* entry = NULL;
  17834. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17835. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17836. while (nextMethod != NULL)
  17837. {
  17838. auto checkMethod = nextMethod;
  17839. nextMethod = nextMethod->mNextWithSameName;
  17840. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  17841. if (implMethodInst == methodInstance)
  17842. {
  17843. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  17844. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  17845. }
  17846. }
  17847. }
  17848. }
  17849. if (methodDef->mIsOverride)
  17850. {
  17851. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  17852. {
  17853. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  17854. if (ventry.mDeclaringMethod.mMethodNum == -1)
  17855. continue;
  17856. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  17857. if (virtMethod != NULL)
  17858. {
  17859. if (virtMethod == methodInstance)
  17860. {
  17861. // Is matching method
  17862. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  17863. {
  17864. auto baseType = mCurTypeInstance->mBaseType;
  17865. if (baseType != NULL)
  17866. {
  17867. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  17868. baseType = baseType->mBaseType;
  17869. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  17870. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  17871. }
  17872. }
  17873. break;
  17874. }
  17875. }
  17876. }
  17877. }
  17878. }
  17879. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d Incomplete:%d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified, mIncompleteMethodCount);
  17880. int importStrNum = -1;
  17881. auto importKind = methodInstance->GetImportKind();
  17882. if ((!mCompiler->mIsResolveOnly) &&
  17883. ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic)))
  17884. {
  17885. if (auto customAttr = methodInstance->GetCustomAttributes()->Get(mCompiler->mImportAttributeTypeDef))
  17886. {
  17887. if (customAttr->mCtorArgs.size() == 1)
  17888. {
  17889. auto fileNameArg = customAttr->mCtorArgs[0];
  17890. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  17891. if (constant != NULL)
  17892. {
  17893. if (!constant->IsNull())
  17894. importStrNum = constant->mInt32;
  17895. }
  17896. else
  17897. {
  17898. importStrNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  17899. }
  17900. if (importStrNum != -1)
  17901. {
  17902. if (!mStringPoolRefs.Contains(importStrNum))
  17903. mStringPoolRefs.Add(importStrNum);
  17904. }
  17905. }
  17906. }
  17907. }
  17908. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  17909. {
  17910. if (mBfIRBuilder->mIgnoreWrites)
  17911. return;
  17912. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  17913. if (!methodInstance->mIRFunction)
  17914. {
  17915. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  17916. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  17917. BF_ASSERT(dllImportGlobalVar || methodInstance->mHasFailed);
  17918. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  17919. }
  17920. if (HasCompiledOutput())
  17921. {
  17922. BfDllImportEntry dllImportEntry;
  17923. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  17924. dllImportEntry.mMethodInstance = mCurMethodInstance;
  17925. mDllImportEntries.push_back(dllImportEntry);
  17926. }
  17927. return;
  17928. }
  17929. StringT<512> mangledName;
  17930. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  17931. if (!methodInstance->mIRFunction)
  17932. {
  17933. bool isIntrinsic = false;
  17934. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  17935. }
  17936. if (methodInstance->mIsIntrinsic)
  17937. return;
  17938. if (mCurTypeInstance->IsFunction())
  17939. return;
  17940. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  17941. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  17942. if (methodDef->mBody != NULL)
  17943. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17944. else if (methodDeclaration != NULL)
  17945. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17946. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17947. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  17948. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17949. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17950. if ((mCurMethodState == NULL) && (!IsInSpecializedSection())) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  17951. {
  17952. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()))
  17953. {
  17954. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(methodDef->mBody))
  17955. {
  17956. SetAndRestoreValue<bool> prevSkipAnonTypes(sourceClassifier->mSkipAnonymousTypes, true);
  17957. sourceClassifier->VisitChildNoRef(methodDef->mBody);
  17958. }
  17959. }
  17960. }
  17961. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  17962. BfMethodState methodState;
  17963. if (mCurMethodState != NULL)
  17964. methodState.mClosureState = mCurMethodState->mClosureState;
  17965. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  17966. {
  17967. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  17968. if (methodInstance->mHotMethod == NULL)
  17969. CheckHotMethod(methodInstance, mangledName);
  17970. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  17971. }
  17972. methodState.mPrevMethodState = mCurMethodState;
  17973. methodState.mMethodInstance = methodInstance;
  17974. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17975. if (methodInstance->GetCustomAttributes() != NULL)
  17976. {
  17977. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  17978. if (typeOptionsIdx != -1)
  17979. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  17980. }
  17981. BfTypeState typeState(mCurTypeInstance);
  17982. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  17983. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  17984. BfMethodInstance* unspecializedMethodInstance = NULL;
  17985. if ((prevMethodState.mPrevVal != NULL) &&
  17986. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  17987. {
  17988. // This is 'inner' (probably a closure) - use binding from outer function
  17989. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  17990. }
  17991. else if ((methodInstance->mIsUnspecialized) ||
  17992. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  17993. {
  17994. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17995. }
  17996. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  17997. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation || mIsComptimeModule) && (!methodInstance->mMethodDef->mIsLocalMethod) && (!methodInstance->mMethodDef->mDeclaringType->IsEmitted()))))
  17998. {
  17999. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  18000. if ((mIsComptimeModule) && (!unspecializedMethodInstance->mHasBeenProcessed))
  18001. {
  18002. // This will have already been populated by CeMachine
  18003. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  18004. }
  18005. else
  18006. {
  18007. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  18008. if (!unspecializedMethodInstance->mHasBeenProcessed)
  18009. {
  18010. // Make sure the unspecialized method is processed so we can take its bindings
  18011. // Clear mCurMethodState so we don't think we're in a local method
  18012. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  18013. if (unspecializedMethodInstance->mMethodProcessRequest == NULL)
  18014. unspecializedMethodInstance->mDeclModule->mIncompleteMethodCount++;
  18015. mContext->ProcessMethod(unspecializedMethodInstance);
  18016. }
  18017. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  18018. }
  18019. }
  18020. if (methodDef->mMethodType == BfMethodType_Operator)
  18021. {
  18022. auto operatorDef = (BfOperatorDef*) methodDef;
  18023. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  18024. auto paramErrorRefNode = refNode;
  18025. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  18026. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  18027. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  18028. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  18029. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  18030. {
  18031. if (methodDef->mParams.size() != 2)
  18032. {
  18033. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  18034. }
  18035. else
  18036. {
  18037. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18038. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18039. checkParam0 = checkParam0->GetUnderlyingType();
  18040. auto checkParam1 = mCurMethodInstance->GetParamType(1);
  18041. if ((checkParam1->IsRef()) && (!checkParam1->IsOut()))
  18042. checkParam1 = checkParam1->GetUnderlyingType();
  18043. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  18044. (checkParam1 != mCurTypeInstance) && (!checkParam1->IsSelf()))
  18045. {
  18046. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  18047. }
  18048. }
  18049. BfType* wantType = NULL;
  18050. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  18051. {
  18052. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  18053. }
  18054. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  18055. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  18056. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  18057. }
  18058. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  18059. {
  18060. if (methodDef->mIsStatic)
  18061. {
  18062. if (methodDef->mParams.size() != 1)
  18063. {
  18064. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  18065. }
  18066. else
  18067. {
  18068. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18069. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18070. checkParam0 = checkParam0->GetUnderlyingType();
  18071. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()))
  18072. {
  18073. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  18074. }
  18075. }
  18076. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  18077. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  18078. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  18079. {
  18080. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  18081. }
  18082. }
  18083. else
  18084. {
  18085. if (methodDef->mParams.size() != 0)
  18086. {
  18087. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  18088. }
  18089. if (!mCurMethodInstance->mReturnType->IsVoid())
  18090. {
  18091. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  18092. }
  18093. }
  18094. }
  18095. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  18096. {
  18097. if (methodDef->mParams.size() != 1)
  18098. {
  18099. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  18100. }
  18101. if (!mCurMethodInstance->mReturnType->IsVoid())
  18102. {
  18103. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  18104. }
  18105. }
  18106. else // Conversion
  18107. {
  18108. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  18109. {
  18110. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  18111. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  18112. }
  18113. if (methodDef->mParams.size() != 1)
  18114. {
  18115. auto refNode = paramErrorRefNode;
  18116. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  18117. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  18118. Fail("Conversion operators must declare one parameter", refNode);
  18119. }
  18120. else if ((methodInstance->mMethodInfoEx == NULL) ||
  18121. (methodInstance->mMethodInfoEx->mMethodGenericArguments.IsEmpty()) ||
  18122. ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation)))
  18123. {
  18124. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18125. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18126. checkParam0 = checkParam0->GetUnderlyingType();
  18127. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  18128. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  18129. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  18130. if (checkParam0 == mCurMethodInstance->mReturnType)
  18131. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  18132. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  18133. // happened here
  18134. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (checkParam0 != mContext->mBfObjectType)))
  18135. {
  18136. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  18137. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, checkParam0->ToTypeInstance());
  18138. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  18139. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  18140. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  18141. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  18142. }
  18143. }
  18144. }
  18145. }
  18146. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mBfIRBuilder->mIgnoreWrites) && (mHasFullDebugInfo);
  18147. if (methodDef->mMethodType == BfMethodType_Mixin)
  18148. wantsDIData = false;
  18149. if (mCurTypeInstance->IsUnspecializedType())
  18150. wantsDIData = false;
  18151. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  18152. wantsDIData = false;
  18153. bool wantsDIVariables = wantsDIData;
  18154. if (methodDef->mIsExtern)
  18155. wantsDIVariables = false;
  18156. SizedArray<BfIRMDNode, 8> diParams;
  18157. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  18158. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  18159. BfType* thisType = NULL;
  18160. if (!methodDef->mIsStatic)
  18161. {
  18162. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  18163. thisType = methodState.mClosureState->mClosureType;
  18164. else
  18165. thisType = mCurTypeInstance;
  18166. }
  18167. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  18168. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  18169. //////////////////////////////////////////////////////////////////////////
  18170. //
  18171. {
  18172. if (methodDeclaration != NULL)
  18173. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18174. else if (methodDef->mBody != NULL)
  18175. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18176. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18177. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  18178. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18179. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18180. }
  18181. BfIRMDNode diFunction;
  18182. if (wantsDIData)
  18183. {
  18184. BP_ZONE("BfModule::DoMethodDeclaration.DISetup");
  18185. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  18186. int defLine = mCurFilePosition.mCurLine;
  18187. if (mDICompileUnit)
  18188. {
  18189. int flags = 0;
  18190. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  18191. if (methodDef->mProtection == BfProtection_Public)
  18192. flags = llvm::DINode::FlagPublic;
  18193. else if (methodDef->mProtection == BfProtection_Protected)
  18194. flags = llvm::DINode::FlagProtected;
  18195. else
  18196. flags = llvm::DINode::FlagPrivate;
  18197. if (methodDef->mIsOverride)
  18198. {
  18199. //flags |= llvm::DINode::FlagVirtual;
  18200. }
  18201. else if (methodDef->mIsVirtual)
  18202. flags |= llvm::DINode::FlagIntroducedVirtual;
  18203. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  18204. flags |= llvm::DINode::FlagStaticMember;
  18205. else
  18206. {
  18207. if ((mCurTypeInstance->IsValuelessType()) ||
  18208. ((!mIsComptimeModule) && (mCurTypeInstance->IsSplattable())))
  18209. flags |= llvm::DINode::FlagStaticMember;
  18210. }
  18211. flags |= llvm::DINode::FlagPrototyped;
  18212. if (methodDef->mMethodType == BfMethodType_Ctor)
  18213. {
  18214. flags |= llvm::DINode::FlagArtificial;
  18215. }
  18216. auto llvmFunction = methodInstance->mIRFunction;
  18217. SizedArray<BfIRMDNode, 1> genericArgs;
  18218. SizedArray<BfIRValue, 1> genericConstValueArgs;
  18219. String methodName;
  18220. if (methodInstance->GetForeignType() != NULL)
  18221. {
  18222. methodName += TypeToString(methodInstance->GetForeignType());
  18223. methodName += ".";
  18224. }
  18225. if (methodInstance->GetExplicitInterface() != NULL)
  18226. {
  18227. methodName += TypeToString(methodInstance->GetExplicitInterface());
  18228. methodName += ".";
  18229. }
  18230. methodName += methodDef->mName;
  18231. if (methodInstance->GetNumGenericArguments() != 0)
  18232. {
  18233. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  18234. {
  18235. if (genericArg->IsConstExprValue())
  18236. {
  18237. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  18238. while (genericConstValueArgs.size() < genericArgs.size())
  18239. genericConstValueArgs.push_back(BfIRValue());
  18240. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  18241. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  18242. }
  18243. else
  18244. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  18245. }
  18246. methodName += "<";
  18247. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  18248. {
  18249. if (i > 0)
  18250. methodName += ", ";
  18251. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  18252. methodName += TypeToString(type);
  18253. }
  18254. methodName += ">";
  18255. }
  18256. if ((methodName.empty()) && (methodDeclaration != NULL))
  18257. {
  18258. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18259. {
  18260. methodName += "operator";
  18261. if (operatorDecl->mIsConvOperator)
  18262. {
  18263. methodName += " ";
  18264. methodName += TypeToString(methodInstance->mReturnType);
  18265. }
  18266. else if (operatorDecl->mOpTypeToken != NULL)
  18267. methodName += operatorDecl->mOpTypeToken->ToString();
  18268. }
  18269. }
  18270. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  18271. methodName += "$CHK";
  18272. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  18273. methodName += "$UCHK";
  18274. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18275. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18276. // defLine + 1, diFuncType, false, true,
  18277. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  18278. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  18279. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18280. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18281. defLine + 1, diFuncType, false, true,
  18282. llvm::dwarf::DW_VIRTUALITY_none,
  18283. 0,
  18284. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18285. }
  18286. else
  18287. {
  18288. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18289. }
  18290. }
  18291. //////////////////////////////////////////////////////////////////////////
  18292. // Head and Init get rolled into Entry afterwards.
  18293. methodState.mIRFunction = methodInstance->mIRFunction;
  18294. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  18295. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  18296. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  18297. methodState.mCurScope->mDIScope = diFunction;
  18298. auto llvmEntryBlock = methodState.mIREntryBlock;
  18299. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  18300. if (methodDef->mName == "__MALFORMED")
  18301. {
  18302. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  18303. mBfIRBuilder->SetInsertPoint(newBlock);
  18304. }
  18305. if (methodDef->mBody != NULL)
  18306. {
  18307. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18308. }
  18309. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  18310. {
  18311. // We want to be able to step into delegate invokes -- we actually step over them
  18312. if (methodDef->mName != "Invoke")
  18313. {
  18314. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18315. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  18316. }
  18317. }
  18318. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18319. mBfIRBuilder->ClearDebugLocation();
  18320. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  18321. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  18322. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  18323. {
  18324. int localIdx = 0;
  18325. int argIdx = 0;
  18326. Array<BfIRValue> splatAddrValues;
  18327. for ( ; argIdx < irParamCount; localIdx++)
  18328. {
  18329. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18330. if ((isThis) && (thisType->IsValuelessNonOpaqueType()))
  18331. isThis = false;
  18332. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() == argIdx))
  18333. {
  18334. argIdx++;
  18335. if (argIdx == irParamCount)
  18336. break;
  18337. }
  18338. BfLocalVariable* paramVar = NULL;
  18339. while (true)
  18340. {
  18341. BF_ASSERT(localIdx < methodState.mLocals.size());
  18342. paramVar = methodState.mLocals[localIdx];
  18343. if ((paramVar->mCompositeCount == -1) &&
  18344. (!paramVar->mIsConst) &&
  18345. ((!paramVar->mResolvedType->IsValuelessNonOpaqueType()) || (paramVar->mResolvedType->IsMethodRef())))
  18346. break;
  18347. localIdx++;
  18348. }
  18349. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  18350. {
  18351. paramVar->mIsReadOnly = true;
  18352. }
  18353. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) ||
  18354. ((!mIsComptimeModule) && (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter)));
  18355. if (paramVar->mResolvedType->IsMethodRef())
  18356. wantsAddr = false;
  18357. // if ((methodDef->mHasAppend) && (argIdx == 1))
  18358. // {
  18359. // BF_ASSERT(paramVar->mName == "appendIdx");
  18360. // wantsAddr = true;
  18361. // }
  18362. if (paramVar->mIsSplat)
  18363. {
  18364. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18365. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18366. BfTypeUtils::SplatIterate([&](BfType* checkType)
  18367. {
  18368. BfIRType splatIRType;
  18369. if (checkType->IsComposite())
  18370. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  18371. else
  18372. splatIRType = mBfIRBuilder->MapType(checkType);
  18373. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  18374. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  18375. if (!paramVar->mAddr)
  18376. paramVar->mAddr = allocaInst;
  18377. if (WantsLifetimes())
  18378. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18379. splatAddrValues.push_back(allocaInst);
  18380. }, paramVar->mResolvedType);
  18381. mBfIRBuilder->SetInsertPoint(prevInsert);
  18382. }
  18383. else if (isThis)
  18384. {
  18385. if (wantsAddr)
  18386. {
  18387. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18388. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18389. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  18390. if (paramVar->mIsSplat)
  18391. {
  18392. //
  18393. }
  18394. else
  18395. {
  18396. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  18397. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  18398. wantPtr = true;
  18399. if (wantPtr)
  18400. {
  18401. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  18402. }
  18403. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  18404. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18405. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  18406. paramVar->mAddr = allocaInst;
  18407. if (WantsLifetimes())
  18408. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18409. }
  18410. mBfIRBuilder->SetInsertPoint(prevInsert);
  18411. }
  18412. }
  18413. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  18414. {
  18415. // Address doesn't change so we don't have to alloca it
  18416. BfIRType allocType;
  18417. int alignSize = mSystem->mPtrSize;
  18418. if (paramVar->mResolvedType->IsRef())
  18419. {
  18420. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18421. }
  18422. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  18423. {
  18424. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18425. alignSize = paramVar->mResolvedType->mAlign;
  18426. }
  18427. else
  18428. {
  18429. paramVar->mHasLocalStructBacking = true;
  18430. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  18431. if (typeInst != NULL)
  18432. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  18433. else
  18434. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  18435. }
  18436. if (wantsAddr)
  18437. {
  18438. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18439. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18440. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18441. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  18442. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18443. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  18444. paramVar->mAddr = allocaInst;
  18445. mBfIRBuilder->SetInsertPoint(prevInsert);
  18446. if (WantsLifetimes())
  18447. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18448. }
  18449. }
  18450. else if (wantsAddr)
  18451. {
  18452. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  18453. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18454. paramVar->mAddr = allocaInst;
  18455. }
  18456. if (paramVar->mIsSplat)
  18457. {
  18458. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18459. }
  18460. else if (paramVar->mIsLowered)
  18461. {
  18462. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18463. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18464. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18465. argIdx++;
  18466. if (loweredTypeCode2 != BfTypeCode_None)
  18467. argIdx++;
  18468. }
  18469. else
  18470. {
  18471. argIdx++;
  18472. }
  18473. }
  18474. if (methodDef->mBody != NULL)
  18475. UpdateSrcPos(methodDef->mBody);
  18476. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18477. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18478. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18479. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  18480. localIdx = 0;
  18481. argIdx = 0;
  18482. int splatAddrIdx = 0;
  18483. while (localIdx < (int)methodState.mLocals.size())
  18484. {
  18485. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  18486. argIdx++;
  18487. int curLocalIdx = localIdx++;
  18488. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  18489. if (paramVar->mIsConst)
  18490. continue;
  18491. if (!paramVar->IsParam())
  18492. continue;
  18493. if (paramVar->mCompositeCount != -1)
  18494. continue;
  18495. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18496. if ((isThis) && (thisType->IsValuelessNonOpaqueType()))
  18497. isThis = false;
  18498. if (paramVar->mValue.IsArg())
  18499. BF_ASSERT(paramVar->mValue.mId == argIdx);
  18500. BfIRMDNode diVariable;
  18501. if (wantsDIData)
  18502. {
  18503. String paramName = paramVar->mName;
  18504. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18505. if (isThis)
  18506. {
  18507. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  18508. paramName = "__closure";
  18509. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18510. {
  18511. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18512. bool wantRef = paramVar->mResolvedType->IsComposite();
  18513. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  18514. wantRef = true;
  18515. if (wantRef)
  18516. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18517. }
  18518. else if (!paramVar->mResolvedType->IsValueType())
  18519. {
  18520. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  18521. }
  18522. }
  18523. else
  18524. {
  18525. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18526. {
  18527. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18528. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18529. diType = mBfIRBuilder->DbgCreateConstType(diType);
  18530. }
  18531. }
  18532. if (!paramVar->mIsSplat)
  18533. {
  18534. if ((paramVar->mParamIdx >= 0) && (paramVar->mParamIdx < methodInstance->mDefaultValues.mSize))
  18535. {
  18536. auto defaultValue = methodInstance->mDefaultValues[paramVar->mParamIdx];
  18537. auto constant = mCurTypeInstance->mConstHolder->GetConstant(defaultValue.mValue);
  18538. if ((constant != NULL) &&
  18539. ((BfIRConstHolder::IsIntable(constant->mTypeCode)) || (BfIRConstHolder::IsFloat(constant->mTypeCode))))
  18540. {
  18541. int64 writeVal = constant->mInt64;
  18542. if (constant->mTypeCode == BfTypeCode_Float)
  18543. {
  18544. // We need to do this because Singles are stored in mDouble, so we need to reduce here
  18545. float floatVal = (float)constant->mDouble;
  18546. writeVal = *(uint32*)&floatVal;
  18547. }
  18548. if (writeVal < 0)
  18549. paramName += StrFormat("$_%llu", -writeVal);
  18550. else
  18551. paramName += StrFormat("$%llu", writeVal);
  18552. }
  18553. }
  18554. if (paramVar->mResolvedType->IsValuelessNonOpaqueType())
  18555. {
  18556. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  18557. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18558. }
  18559. else if (paramVar->mIsImplicitParam)
  18560. {
  18561. // Annotate this specially?
  18562. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18563. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18564. }
  18565. else
  18566. {
  18567. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18568. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18569. }
  18570. paramVar->mDbgVarInst = diVariable;
  18571. }
  18572. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  18573. {
  18574. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  18575. // {
  18576. // // Only add this placeholder if we don't have any values
  18577. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  18578. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18579. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  18580. // }
  18581. }
  18582. }
  18583. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  18584. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  18585. {
  18586. // Write our argument value into the .addr
  18587. mBfIRBuilder->ClearDebugLocation();
  18588. if (paramVar->mIsSplat)
  18589. {
  18590. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18591. //
  18592. }
  18593. else
  18594. {
  18595. bool handled = false;
  18596. if (paramVar->mIsLowered)
  18597. {
  18598. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18599. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18600. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  18601. {
  18602. BfIRValue targetAddr = paramVar->mAddr;
  18603. bool isTempTarget = false;
  18604. int loweredSize = mBfIRBuilder->GetSize(loweredTypeCode) + mBfIRBuilder->GetSize(loweredTypeCode2);
  18605. if (paramVar->mResolvedType->mSize < loweredSize)
  18606. {
  18607. isTempTarget = true;
  18608. targetAddr = CreateAlloca(GetPrimitiveType(BfTypeCode_Int8), true, NULL, GetConstValue(loweredSize));
  18609. mBfIRBuilder->SetAllocaAlignment(targetAddr,
  18610. BF_MAX(paramVar->mResolvedType->mAlign,
  18611. BF_MAX(mBfIRBuilder->GetSize(loweredTypeCode), mBfIRBuilder->GetSize(loweredTypeCode2))));
  18612. }
  18613. // We have a lowered type coming in, so we have to cast the .addr before storing
  18614. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  18615. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  18616. auto primPtrVal = mBfIRBuilder->CreateBitCast(targetAddr, primPtrType);
  18617. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, mCurTypeInstance->mAlign);
  18618. if (loweredTypeCode2 != BfTypeCode_None)
  18619. {
  18620. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  18621. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  18622. BfIRValue primPtrVal2;
  18623. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  18624. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  18625. else
  18626. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  18627. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  18628. }
  18629. if (isTempTarget)
  18630. {
  18631. auto castedTempPtr = mBfIRBuilder->CreateBitCast(targetAddr, mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType)));
  18632. auto tempVal = mBfIRBuilder->CreateAlignedLoad(castedTempPtr, paramVar->mResolvedType->mAlign);
  18633. mBfIRBuilder->CreateAlignedStore(tempVal, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  18634. }
  18635. // We don't want to allow directly using value
  18636. paramVar->mValue = BfIRValue();
  18637. handled = true;
  18638. }
  18639. else
  18640. {
  18641. BF_ASSERT("Expected lowered");
  18642. }
  18643. }
  18644. if (!handled)
  18645. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  18646. }
  18647. }
  18648. if (methodDef->mBody != NULL)
  18649. UpdateSrcPos(methodDef->mBody);
  18650. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  18651. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  18652. else if (methodDeclaration == NULL)
  18653. UseDefaultSrcPos();
  18654. // Write our argument value into the .addr
  18655. if (paramVar->mIsSplat)
  18656. {
  18657. int splatComponentIdx = 0;
  18658. auto curArgIdx = argIdx;
  18659. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  18660. {
  18661. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  18662. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  18663. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  18664. mBfIRBuilder->ClearDebugLocation(storeInst);
  18665. if (wantsDIData)
  18666. {
  18667. BfIRMDNode diType;
  18668. if (checkType->IsComposite())
  18669. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  18670. else
  18671. diType = mBfIRBuilder->DbgGetType(checkType);
  18672. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18673. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18674. if (wantsDIVariables)
  18675. {
  18676. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  18677. }
  18678. }
  18679. curArgIdx++;
  18680. splatComponentIdx++;
  18681. };
  18682. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  18683. {
  18684. if (checkType->IsStruct())
  18685. {
  18686. auto checkTypeInstance = checkType->ToTypeInstance();
  18687. if (checkTypeInstance->mBaseType != NULL)
  18688. {
  18689. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  18690. }
  18691. if (checkTypeInstance->mIsUnion)
  18692. {
  18693. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  18694. if (!unionInnerType->IsValuelessType())
  18695. {
  18696. _FinishSplatsIterate(unionInnerType, name + "$u");
  18697. }
  18698. if (checkTypeInstance->IsEnum())
  18699. {
  18700. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  18701. _FinishSplatsIterate(dscrType, name + "$d");
  18702. }
  18703. }
  18704. else
  18705. {
  18706. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  18707. {
  18708. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  18709. auto fieldDef = fieldInstance->GetFieldDef();
  18710. if (fieldInstance->mDataIdx >= 0)
  18711. {
  18712. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  18713. }
  18714. }
  18715. }
  18716. }
  18717. else if (checkType->IsMethodRef())
  18718. {
  18719. auto methodRefType = (BfMethodRefType*)checkType;
  18720. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  18721. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  18722. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  18723. // {
  18724. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  18725. // if (!paramType->IsValuelessType())
  18726. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  18727. // }
  18728. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  18729. {
  18730. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  18731. String paramName = methodInstance->GetParamName(paramIdx);
  18732. if (paramName == "this")
  18733. paramName = "__this";
  18734. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  18735. {
  18736. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  18737. }
  18738. else
  18739. {
  18740. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  18741. }
  18742. }
  18743. }
  18744. else if (!checkType->IsValuelessType())
  18745. {
  18746. _FinishSplats(checkType, name);
  18747. }
  18748. };
  18749. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18750. if (!paramVar->mConstValue)
  18751. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  18752. }
  18753. BfIRValue declareCall;
  18754. if (diVariable)
  18755. {
  18756. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  18757. {
  18758. if (!paramVar->mAddr)
  18759. {
  18760. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  18761. {
  18762. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  18763. {
  18764. // We don't need to set the location for this
  18765. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  18766. }
  18767. }
  18768. else
  18769. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  18770. }
  18771. else
  18772. {
  18773. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  18774. }
  18775. }
  18776. }
  18777. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  18778. {
  18779. // We don't allow actually assignment to "this", so we just do a single load
  18780. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  18781. // we need to store it in the stack frame for debugging purposes
  18782. auto loadedThis = mBfIRBuilder->CreateAlignedLoad(paramVar->mAddr/*, "this"*/, paramVar->mResolvedType->mAlign);
  18783. mBfIRBuilder->ClearDebugLocation(loadedThis);
  18784. paramVar->mValue = loadedThis;
  18785. }
  18786. if ((wantsDIData) && (declareCall))
  18787. mBfIRBuilder->UpdateDebugLocation(declareCall);
  18788. if (paramVar->mIsSplat)
  18789. {
  18790. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18791. }
  18792. else if (paramVar->mIsLowered)
  18793. {
  18794. argIdx++;
  18795. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18796. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18797. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18798. if (loweredTypeCode2 != BfTypeCode_None)
  18799. argIdx++;
  18800. }
  18801. else if (!paramVar->mResolvedType->IsValuelessNonOpaqueType())
  18802. {
  18803. argIdx++;
  18804. }
  18805. }
  18806. if (wantsDIData)
  18807. {
  18808. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  18809. }
  18810. }
  18811. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  18812. {
  18813. auto paramVar = mCurMethodState->mLocals[varIdx];
  18814. // 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
  18815. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  18816. // if (paramVar->mIsSplat)
  18817. // {
  18818. // if (wantsDIVariables)
  18819. // {
  18820. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  18821. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  18822. // }
  18823. // }
  18824. if (paramVar->mResolvedType->IsValuelessType())
  18825. {
  18826. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  18827. {
  18828. // Only add this placeholder if we don't have any values
  18829. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18830. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  18831. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18832. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  18833. }
  18834. }
  18835. }
  18836. if (IsTargetingBeefBackend())
  18837. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  18838. if (methodState.mClosureState != NULL)
  18839. {
  18840. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  18841. {
  18842. BfLocalVariable* localVar = new BfLocalVariable();
  18843. *localVar = constLocal;
  18844. localVar->mIsBumpAlloc = false;
  18845. AddLocalVariableDef(localVar, true);
  18846. }
  18847. }
  18848. bool wantsRemoveBody = false;
  18849. bool skipBody = false;
  18850. bool skipUpdateSrcPos = false;
  18851. bool skipEndChecks = false;
  18852. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  18853. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18854. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  18855. hasExternSpecifier = true;
  18856. // Allocate, clear, set classVData
  18857. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  18858. {
  18859. CreateStaticCtor();
  18860. }
  18861. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  18862. {
  18863. skipBody = true;
  18864. skipEndChecks = true;
  18865. if (HasExecutedOutput())
  18866. {
  18867. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18868. mBfIRBuilder->ClearDebugLocation();
  18869. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  18870. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  18871. PopulateType(innerType, BfPopulateType_DataAndMethods);
  18872. mBfIRBuilder->PopulateType(mCurTypeInstance);
  18873. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  18874. if (methodInstance->mIsForeignMethodDef)
  18875. {
  18876. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  18877. }
  18878. BfTypeVector methodGenericArguments;
  18879. if (methodInstance->mMethodInfoEx != NULL)
  18880. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  18881. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  18882. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  18883. {
  18884. if (!methodInstance->mReturnType->IsValuelessType())
  18885. {
  18886. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  18887. CreateReturn(retVal);
  18888. }
  18889. else
  18890. mBfIRBuilder->CreateRetVoid();
  18891. }
  18892. else
  18893. {
  18894. auto innerMethodDef = innerMethodInstance.mMethodInstance->mMethodDef;
  18895. if ((innerMethodDef == methodDef != NULL) && (!CompareMethodSignatures(methodInstance, innerMethodInstance.mMethodInstance)))
  18896. {
  18897. InternalError("Boxing method passthrough error");
  18898. }
  18899. else
  18900. {
  18901. SizedArray<BfIRValue, 8> innerParams;
  18902. BfExprEvaluator exprEvaluator(this);
  18903. if (!innerType->IsValuelessType())
  18904. {
  18905. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  18906. BfTypedValue innerVal(thisValue, innerType, true);
  18907. if (boxedType->IsBoxedStructPtr())
  18908. {
  18909. innerVal = LoadValue(innerVal);
  18910. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  18911. }
  18912. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  18913. }
  18914. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  18915. {
  18916. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  18917. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  18918. exprEvaluator.PushArg(localVal, innerParams);
  18919. }
  18920. if (!innerMethodInstance.mFunc)
  18921. {
  18922. BF_ASSERT(innerType->IsUnspecializedType());
  18923. }
  18924. else if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  18925. {
  18926. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  18927. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  18928. exprEvaluator.mReceivingValue = &returnType;
  18929. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  18930. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  18931. mBfIRBuilder->CreateRetVoid();
  18932. }
  18933. else
  18934. {
  18935. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  18936. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  18937. if (mCurMethodInstance->mReturnType->IsValueType())
  18938. retVal = LoadValue(retVal);
  18939. CreateReturn(retVal.mValue);
  18940. }
  18941. }
  18942. }
  18943. }
  18944. mCurMethodState->SetHadReturn(true);
  18945. mCurMethodState->mLeftBlockUncond = true;
  18946. }
  18947. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  18948. {
  18949. SetIllegalSrcPos();
  18950. mBfIRBuilder->ClearDebugLocation();
  18951. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  18952. auto thisVal = GetThis();
  18953. int prevSize = 0;
  18954. if ((mContext->mBfObjectType != NULL) && (mCurTypeInstance->IsObject()))
  18955. {
  18956. prevSize = mContext->mBfObjectType->mInstSize;
  18957. PopulateType(mContext->mBfObjectType);
  18958. // If we have object extensions, clear out starting at the extension
  18959. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  18960. {
  18961. if (fieldInstance.GetFieldDef()->mDeclaringType->IsExtension())
  18962. {
  18963. prevSize = fieldInstance.mDataOffset;
  18964. break;
  18965. }
  18966. }
  18967. }
  18968. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  18969. int curSize = mCurTypeInstance->mInstSize;
  18970. if (curSize > prevSize)
  18971. {
  18972. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  18973. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  18974. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  18975. }
  18976. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  18977. {
  18978. auto useThis = mCurMethodState->mLocals[0]->mValue;
  18979. auto useThisType = mCurTypeInstance;
  18980. auto checkTypeInst = mCurTypeInstance;
  18981. while (checkTypeInst != NULL)
  18982. {
  18983. for (auto& fieldInstance : checkTypeInst->mFieldInstances)
  18984. {
  18985. auto fieldDef = fieldInstance.GetFieldDef();
  18986. if ((fieldDef == NULL) || (fieldDef->mIsStatic))
  18987. continue;
  18988. if (fieldInstance.IsAppendedObject())
  18989. {
  18990. if (checkTypeInst != useThisType)
  18991. {
  18992. useThis = mBfIRBuilder->CreateBitCast(useThis, mBfIRBuilder->MapType(checkTypeInst));
  18993. useThisType = checkTypeInst;
  18994. }
  18995. BfIRValue fieldAddr = mBfIRBuilder->CreateInBoundsGEP(useThis, 0, fieldInstance.mDataIdx);
  18996. auto int8PtrVal = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(int8PtrType));
  18997. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  18998. }
  18999. }
  19000. checkTypeInst = checkTypeInst->mBaseType;
  19001. }
  19002. }
  19003. skipUpdateSrcPos = true;
  19004. }
  19005. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  19006. {
  19007. EmitCtorBody(skipBody);
  19008. }
  19009. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  19010. {
  19011. EmitDtorBody();
  19012. skipBody = true;
  19013. }
  19014. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  19015. {
  19016. EmitIteratorBlock(skipBody);
  19017. }
  19018. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  19019. {
  19020. // We need to be able to mark deleted objects
  19021. mCurMethodState->mIgnoreObjectAccessCheck = true;
  19022. }
  19023. auto customAttributes = methodInstance->GetCustomAttributes();
  19024. if (customAttributes != NULL)
  19025. {
  19026. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  19027. mCurMethodState->mIgnoreObjectAccessCheck = true;
  19028. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  19029. mCurMethodState->mDisableChecks = true;
  19030. }
  19031. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  19032. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  19033. {
  19034. // We chain even non-default ctors to the default ctors
  19035. auto defaultCtor = methodInstance;
  19036. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  19037. CallChainedMethods(defaultCtor, false);
  19038. }
  19039. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  19040. if (!mCompiler->mHasRequiredTypes)
  19041. {
  19042. // Skip processing to avoid errors
  19043. }
  19044. else if (methodDef->mBody == NULL)
  19045. {
  19046. if (methodDeclaration != NULL)
  19047. {
  19048. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  19049. {
  19050. if (operatorDeclaration->mIsConvOperator)
  19051. wantsRemoveBody = true;
  19052. }
  19053. }
  19054. bool isDllImport = false;
  19055. if ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic))
  19056. {
  19057. if (importStrNum != -1)
  19058. {
  19059. if (importKind == BfImportKind_Import_Static)
  19060. {
  19061. if (!mImportFileNames.Contains(importStrNum))
  19062. {
  19063. mImportFileNames.Add(importStrNum);
  19064. }
  19065. }
  19066. }
  19067. }
  19068. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  19069. {
  19070. CreateDllImportMethod();
  19071. }
  19072. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  19073. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  19074. {
  19075. if (mCurTypeInstance->mTypeDef->mIsFunction)
  19076. {
  19077. // Emit nothing
  19078. }
  19079. else
  19080. {
  19081. CreateDelegateInvokeMethod();
  19082. mCurMethodState->SetHadReturn(true);
  19083. mCurMethodState->mLeftBlockUncond = true;
  19084. }
  19085. }
  19086. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  19087. {
  19088. if (mCurTypeInstance->IsObject())
  19089. {
  19090. CreateDynamicCastMethod();
  19091. }
  19092. else
  19093. {
  19094. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  19095. mCurMethodState->mHadReturn = true;
  19096. }
  19097. }
  19098. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  19099. {
  19100. BfIRValue ret;
  19101. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  19102. {
  19103. // This can happen if we provide an invalid name
  19104. AssertErrorState();
  19105. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  19106. }
  19107. else
  19108. {
  19109. // Unfortunate DebugLoc shenanigans-
  19110. // 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,
  19111. // so we only set the loc on the CreateRet which gets inlined out
  19112. mBfIRBuilder->SaveDebugLocation();
  19113. mBfIRBuilder->ClearDebugLocation();
  19114. BfIRValue fromBool;
  19115. if ((!mCurTypeInstance->IsTypedPrimitive()) || (mCurTypeInstance->IsValuelessType()))
  19116. {
  19117. fromBool = GetDefaultValue(methodInstance->mReturnType);
  19118. }
  19119. else
  19120. {
  19121. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  19122. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  19123. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  19124. }
  19125. mBfIRBuilder->RestoreDebugLocation();
  19126. ret = mBfIRBuilder->CreateRet(fromBool);
  19127. //ExtendLocalLifetimes(0);
  19128. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19129. }
  19130. mCurMethodState->SetHadReturn(true);
  19131. mCurMethodState->mLeftBlockUncond = true;
  19132. }
  19133. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  19134. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  19135. {
  19136. BfIRValue ret;
  19137. // Unfortunate DebugLoc shenanigans-
  19138. // 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,
  19139. // so we only set the loc on the CreateRet which gets inlined out
  19140. mBfIRBuilder->SaveDebugLocation();
  19141. mBfIRBuilder->ClearDebugLocation();
  19142. BfIRValue fromBool;
  19143. mBfIRBuilder->RestoreDebugLocation();
  19144. if (!mCompiler->mIsResolveOnly)
  19145. {
  19146. if (!mCurTypeInstance->IsValuelessType())
  19147. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  19148. else
  19149. mBfIRBuilder->CreateRetVoid();
  19150. }
  19151. //ExtendLocalLifetimes(0);
  19152. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19153. mCurMethodState->SetHadReturn(true);
  19154. mCurMethodState->mLeftBlockUncond = true;
  19155. }
  19156. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  19157. {
  19158. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  19159. if (HasExecutedOutput())
  19160. {
  19161. EmitEnumToStringBody();
  19162. }
  19163. mBfIRBuilder->CreateRetVoid();
  19164. mCurMethodState->SetHadReturn(true);
  19165. mCurMethodState->mLeftBlockUncond = true;
  19166. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19167. }
  19168. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  19169. {
  19170. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  19171. if (HasExecutedOutput())
  19172. {
  19173. EmitTupleToStringBody();
  19174. }
  19175. mBfIRBuilder->CreateRetVoid();
  19176. mCurMethodState->SetHadReturn(true);
  19177. mCurMethodState->mLeftBlockUncond = true;
  19178. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19179. }
  19180. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  19181. {
  19182. CreateValueTypeEqualsMethod(false);
  19183. skipBody = true;
  19184. skipEndChecks = true;
  19185. }
  19186. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  19187. {
  19188. CreateValueTypeEqualsMethod(true);
  19189. skipBody = true;
  19190. skipEndChecks = true;
  19191. }
  19192. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef->GetDefinition() == mCompiler->mValueTypeTypeDef))
  19193. {
  19194. CreateValueTypeEqualsMethod(false);
  19195. skipBody = true;
  19196. skipEndChecks = true;
  19197. }
  19198. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (mCurTypeInstance->IsDelegate()))
  19199. {
  19200. CreateDelegateEqualsMethod();
  19201. skipBody = true;
  19202. skipEndChecks = true;
  19203. }
  19204. else
  19205. {
  19206. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  19207. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  19208. {
  19209. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  19210. Fail("Body expected", methodDef->GetRefNode());
  19211. }
  19212. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  19213. {
  19214. if ((methodInstance->mReturnType->IsRef()) && (!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  19215. Fail("Auto-implemented ref property getters must declare 'mut'", methodInstance->mMethodDef->GetRefNode());
  19216. if (methodInstance->mReturnType->IsValuelessType())
  19217. {
  19218. mBfIRBuilder->CreateRetVoid();
  19219. }
  19220. else if (HasExecutedOutput())
  19221. {
  19222. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19223. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19224. BfFieldDef* fieldDef = NULL;
  19225. if (fieldInstance != NULL)
  19226. fieldDef = fieldInstance->GetFieldDef();
  19227. BfType* retType = methodInstance->mReturnType;
  19228. if (retType->IsRef())
  19229. retType = retType->GetUnderlyingType();
  19230. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  19231. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19232. {
  19233. BfTypedValue lookupValue;
  19234. if (fieldDef->IsNonConstStatic())
  19235. lookupValue = ReferenceStaticField(fieldInstance);
  19236. else if (mCurTypeInstance->IsObject())
  19237. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  19238. else
  19239. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  19240. if (methodInstance->mReturnType->IsRef())
  19241. {
  19242. if ((!lookupValue.IsAddr()) && (!lookupValue.mType->IsValuelessType()))
  19243. lookupValue = MakeAddressable(lookupValue);
  19244. }
  19245. else
  19246. lookupValue = LoadOrAggregateValue(lookupValue);
  19247. CreateReturn(lookupValue.mValue);
  19248. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19249. }
  19250. else
  19251. {
  19252. // This can happen if we have two properties with the same name but different types
  19253. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19254. EmitDefaultReturn();
  19255. }
  19256. }
  19257. else
  19258. {
  19259. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19260. EmitDefaultReturn();
  19261. }
  19262. mCurMethodState->SetHadReturn(true);
  19263. }
  19264. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  19265. {
  19266. if ((!methodDef->mIsMutating) && (!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  19267. {
  19268. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  19269. }
  19270. else if (!mCompiler->IsAutocomplete())
  19271. {
  19272. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19273. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19274. auto fieldDef = fieldInstance->GetFieldDef();
  19275. auto& lastParam = mCurMethodState->mLocals.back();
  19276. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  19277. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19278. {
  19279. BfIRValue lookupAddr;
  19280. if (fieldDef->IsNonConstStatic())
  19281. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  19282. else
  19283. {
  19284. auto thisValue = GetThis();
  19285. if (thisValue.IsSplat())
  19286. {
  19287. BFMODULE_FATAL(this, "Should not happen");
  19288. }
  19289. if (mCurTypeInstance->IsObject())
  19290. thisValue = LoadValue(thisValue);
  19291. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  19292. }
  19293. BfExprEvaluator exprEvaluator(this);
  19294. auto localVal = exprEvaluator.LoadLocal(lastParam);
  19295. localVal = LoadOrAggregateValue(localVal);
  19296. if (!localVal.mType->IsValuelessType())
  19297. mBfIRBuilder->CreateAlignedStore(localVal.mValue, lookupAddr, localVal.mType->mAlign);
  19298. }
  19299. else if (!fieldInstance->mResolvedType->IsValuelessType())
  19300. {
  19301. // This can happen if we have two properties with the same name but different types
  19302. AssertErrorState();
  19303. }
  19304. }
  19305. }
  19306. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  19307. {
  19308. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19309. {
  19310. if (HasCompiledOutput())
  19311. EmitGCMarkMembers();
  19312. }
  19313. else if (!mCurTypeInstance->IsObject())
  19314. {
  19315. }
  19316. }
  19317. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  19318. {
  19319. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19320. {
  19321. if (HasCompiledOutput())
  19322. EmitGCFindTLSMembers();
  19323. }
  19324. }
  19325. }
  19326. }
  19327. else if (!skipBody)
  19328. {
  19329. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  19330. bool wantsRetVal = true;
  19331. if ((mIsComptimeModule) && (methodDef->mMethodType != BfMethodType_CtorCalcAppend))
  19332. wantsRetVal = false;
  19333. else if (mCurMethodInstance->mReturnType->IsVar())
  19334. wantsRetVal = false;
  19335. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  19336. {
  19337. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  19338. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  19339. {
  19340. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  19341. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  19342. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst, mCurMethodInstance->mReturnType->mAlign);
  19343. mBfIRBuilder->ClearDebugLocation(storeInst);
  19344. mCurMethodState->mRetValAddr = allocaInst;
  19345. }
  19346. else if (wantsRetVal)
  19347. {
  19348. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  19349. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  19350. }
  19351. }
  19352. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19353. {
  19354. mBfIRBuilder->CreateAlignedStore(GetConstValue(0), mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19355. BfGetSymbolReferenceKind prevSymbolKind;
  19356. BfAutoComplete* prevAutoComplete;
  19357. if (mCompiler->mResolvePassData != NULL)
  19358. {
  19359. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  19360. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19361. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  19362. }
  19363. EmitCtorCalcAppend();
  19364. if (mCompiler->mResolvePassData != NULL)
  19365. {
  19366. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  19367. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  19368. }
  19369. }
  19370. else if (!isEmptyBodied)
  19371. {
  19372. if (!mCurMethodState->mIRExitBlock)
  19373. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  19374. bool isExpressionBody = false;
  19375. if (methodDeclaration != NULL)
  19376. {
  19377. if (methodDeclaration->mFatArrowToken != NULL)
  19378. isExpressionBody = true;
  19379. }
  19380. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  19381. {
  19382. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  19383. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  19384. isExpressionBody = true;
  19385. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  19386. {
  19387. isExpressionBody = true;
  19388. }
  19389. }
  19390. else
  19391. {
  19392. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  19393. {
  19394. if (!block->mChildArr.IsEmpty())
  19395. {
  19396. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  19397. {
  19398. if (exprStmt->mTrailingSemicolon == NULL)
  19399. isExpressionBody = true;
  19400. }
  19401. }
  19402. }
  19403. else
  19404. isExpressionBody = true;
  19405. }
  19406. DoCEEmit(methodInstance);
  19407. if (methodInstance->mCeCancelled)
  19408. mIgnoreErrors = true;
  19409. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  19410. {
  19411. while (fieldDtorBody != NULL)
  19412. {
  19413. VisitEmbeddedStatement(fieldDtorBody->mBody);
  19414. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  19415. }
  19416. }
  19417. else if (!isExpressionBody)
  19418. {
  19419. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  19420. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  19421. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  19422. VisitCodeBlock(bodyBlock);
  19423. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  19424. }
  19425. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  19426. {
  19427. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  19428. // {
  19429. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  19430. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  19431. // }
  19432. auto expectingType = mCurMethodInstance->mReturnType;
  19433. // What was this error for?
  19434. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  19435. // {
  19436. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  19437. // }
  19438. BfEvalExprFlags exprEvalFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_IsExpressionBody);
  19439. if (expectingType->IsVoid())
  19440. {
  19441. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  19442. bool wasReturnGenericParam = false;
  19443. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  19444. {
  19445. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  19446. }
  19447. else
  19448. {
  19449. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  19450. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  19451. wasReturnGenericParam = true;
  19452. }
  19453. // If we the void return was from a generic specialization, allow us to return a void result,
  19454. // otherwise treat expression as though it must be a statement
  19455. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  19456. if (isStatement)
  19457. expectingType = NULL;
  19458. }
  19459. BfExprEvaluator exprEvaluator(this);
  19460. if (mCurMethodInstance->mMethodDef->mIsReadOnly)
  19461. exprEvaluator.mAllowReadOnlyReference = true;
  19462. UpdateSrcPos(expressionBody);
  19463. auto retVal = CreateValueFromExpression(exprEvaluator, expressionBody, expectingType, exprEvalFlags);
  19464. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  19465. {
  19466. mCurMethodState->mHadReturn = true;
  19467. if (!mCurMethodState->mLeftBlockUncond)
  19468. {
  19469. retVal = LoadOrAggregateValue(retVal);
  19470. EmitReturn(retVal);
  19471. }
  19472. }
  19473. }
  19474. }
  19475. }
  19476. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  19477. if (skipUpdateSrcPos)
  19478. {
  19479. // Skip
  19480. }
  19481. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19482. UpdateSrcPos(bodyBlock->mCloseBrace);
  19483. else if (methodDef->mBody != NULL)
  19484. UpdateSrcPos(methodDef->mBody);
  19485. else if (methodDeclaration != NULL)
  19486. UpdateSrcPos(methodDeclaration);
  19487. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  19488. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  19489. else
  19490. UseDefaultSrcPos();
  19491. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19492. {
  19493. if (mCurMethodState->mRetVal)
  19494. {
  19495. mCurMethodState->SetHadReturn(true);
  19496. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  19497. mBfIRBuilder->CreateRet(retVal);
  19498. }
  19499. else
  19500. AssertErrorState();
  19501. }
  19502. mCurMethodState->mHeadScope.mDone = true;
  19503. if (!mCurMethodState->mHadReturn)
  19504. {
  19505. // Clear off the stackallocs that have occurred after a scopeData break
  19506. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  19507. }
  19508. EmitDeferredCallProcessorInstances(&mCurMethodState->mHeadScope);
  19509. if (mCurMethodState->mIRExitBlock)
  19510. {
  19511. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  19512. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  19513. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  19514. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  19515. if ((!mCurMethodState->mDIRetVal) && (wantsDIData))
  19516. CreateDIRetVal();
  19517. }
  19518. for (auto localVar : mCurMethodState->mLocals)
  19519. {
  19520. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  19521. {
  19522. //
  19523. }
  19524. else if ((skipEndChecks) || (methodDef->mBody == NULL))
  19525. break;
  19526. LocalVariableDone(localVar, true);
  19527. }
  19528. if (mCurMethodState->mIRExitBlock)
  19529. {
  19530. if ((mCurMethodState->mRetVal) &&
  19531. ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() == -1)))
  19532. {
  19533. auto loadedVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19534. CreateReturn(loadedVal);
  19535. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19536. if (mCurMethodState->mDIRetVal)
  19537. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19538. }
  19539. else
  19540. {
  19541. // Have something on the last line to step onto
  19542. if (mHasFullDebugInfo)
  19543. {
  19544. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19545. UpdateSrcPos(bodyBlock->mCloseBrace);
  19546. EmitEnsureInstructionAt();
  19547. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19548. {
  19549. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19550. mBfIRBuilder->EnsureFunctionPatchable();
  19551. }
  19552. }
  19553. mBfIRBuilder->CreateRetVoid();
  19554. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19555. if (mCurMethodState->mDIRetVal)
  19556. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19557. }
  19558. }
  19559. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  19560. {
  19561. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  19562. {
  19563. if ((!mIsComptimeModule) && (irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19564. {
  19565. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19566. mBfIRBuilder->EnsureFunctionPatchable();
  19567. }
  19568. mBfIRBuilder->CreateRetVoid();
  19569. }
  19570. }
  19571. else
  19572. {
  19573. if (!mCurMethodState->mHadReturn)
  19574. {
  19575. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  19576. if (bodyBlock != NULL)
  19577. {
  19578. if (bodyBlock->mCloseBrace != NULL)
  19579. {
  19580. BfAstNode* target = bodyBlock->mCloseBrace;
  19581. if (!mCompiler->mHasRequiredTypes)
  19582. {
  19583. AddFailType(mCurTypeInstance);
  19584. mHadBuildError = true;
  19585. }
  19586. else
  19587. Fail("Method must return value", target);
  19588. }
  19589. else
  19590. {
  19591. // It's possible to not have a closing brace if the method ends in an EOF
  19592. AssertErrorState();
  19593. }
  19594. }
  19595. }
  19596. }
  19597. // Move 'init' into 'entry'
  19598. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  19599. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  19600. if (((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType())) &&
  19601. (!mIsComptimeModule))
  19602. {
  19603. // Don't keep instructions for unspecialized types
  19604. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19605. }
  19606. // Avoid linking any internal funcs that were just supposed to be comptime-accessible
  19607. /*if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  19608. wantsRemoveBody = true;*/
  19609. if ((hasExternSpecifier) && (!skipBody))
  19610. {
  19611. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  19612. // incase it gets called later by some hot-loaded coded
  19613. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()) && (mCurTypeInstance != mContext->mBfObjectType))
  19614. {
  19615. if (!mCurMethodInstance->mMethodDef->mName.StartsWith("Comptime_"))
  19616. CreateFakeCallerMethod(mangledName);
  19617. }
  19618. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19619. }
  19620. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  19621. {
  19622. // We only need the DLL stub when we may be hot swapping
  19623. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19624. }
  19625. else if (wantsRemoveBody)
  19626. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19627. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  19628. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  19629. // unspecialized types
  19630. if (((mCurTypeInstance->IsUnspecializedType()) && (!mIsComptimeModule)) ||
  19631. (mCurTypeInstance->IsInterface()))
  19632. {
  19633. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  19634. methodInstance->mIRFunction = BfIRFunction();
  19635. }
  19636. CheckAddFailType();
  19637. if (mHadBuildError)
  19638. prevHadBuildError.CancelRestore();
  19639. if (mHadBuildWarning)
  19640. prevHadWarning.CancelRestore();
  19641. if (!methodDef->mIsLocalMethod)
  19642. ProcessMethod_ProcessDeferredLocals();
  19643. prevIgnoreWrites.Restore();
  19644. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  19645. if (methodState.mHotDataReferenceBuilder != NULL)
  19646. {
  19647. AddHotDataReferences(&hotDataReferenceBuilder);
  19648. }
  19649. else
  19650. {
  19651. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  19652. {
  19653. // Remove the hot method data
  19654. auto hotMethod = methodInstance->mHotMethod;
  19655. auto prevMethod = hotMethod->mPrevVersion;
  19656. if (prevMethod != NULL)
  19657. {
  19658. // If there's a prev method then pull its data into the main HotMethod.
  19659. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  19660. // over to the main HotMethod definition to keep the HotMethod address
  19661. // invariant
  19662. for (auto ref : hotMethod->mReferences)
  19663. ref->Deref();
  19664. hotMethod->mReferences.Clear();
  19665. BF_ASSERT(prevMethod->mRefCount == 1);
  19666. hotMethod->mReferences = prevMethod->mReferences;
  19667. if (hotMethod->mSrcTypeVersion != NULL)
  19668. hotMethod->mSrcTypeVersion->Deref();
  19669. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  19670. prevMethod->mSrcTypeVersion = NULL;
  19671. prevMethod->mReferences.Clear();
  19672. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  19673. prevMethod->mPrevVersion = NULL;
  19674. prevMethod->Deref();
  19675. }
  19676. hotMethod->Deref();
  19677. methodInstance->mHotMethod = NULL;
  19678. }
  19679. }
  19680. }
  19681. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  19682. {
  19683. String name;
  19684. bool found = false;
  19685. auto checkMethodState = mCurMethodState;
  19686. while (checkMethodState != NULL)
  19687. {
  19688. if (checkMethodState->mClosureState == NULL)
  19689. break;
  19690. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  19691. {
  19692. found = true;
  19693. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  19694. break;
  19695. }
  19696. checkMethodState = checkMethodState->mPrevMethodState;
  19697. }
  19698. if (!found)
  19699. name += mCurMethodInstance->mMethodDef->mName;
  19700. int prevSepPos = (int)name.LastIndexOf('$');
  19701. if (prevSepPos != -1)
  19702. {
  19703. name.RemoveToEnd(prevSepPos);
  19704. }
  19705. name += "@";
  19706. name += baseName;
  19707. HashContext hashCtx;
  19708. if (anchorNode != NULL)
  19709. {
  19710. hashCtx.Mixin(anchorNode->GetStartCharId());
  19711. }
  19712. //
  19713. {
  19714. auto checkMethodState = declMethodState;
  19715. auto checkMixinState = declMixinState;
  19716. while (checkMethodState != NULL)
  19717. {
  19718. if (checkMixinState != NULL)
  19719. {
  19720. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  19721. }
  19722. checkMethodState = checkMethodState->mPrevMethodState;
  19723. if (checkMethodState != NULL)
  19724. checkMixinState = checkMethodState->mMixinState;
  19725. }
  19726. }
  19727. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19728. if ((rootMethodState != NULL) && (rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19729. {
  19730. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  19731. {
  19732. StringT<512> genericTypeName;
  19733. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  19734. hashCtx.MixinStr(genericTypeName);
  19735. }
  19736. }
  19737. uint64 hashVal = hashCtx.Finish64();
  19738. name += "$";
  19739. name += BfTypeUtils::HashEncode64(hashVal);
  19740. return name;
  19741. }
  19742. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  19743. {
  19744. if (localMethod->mMethodDef != NULL)
  19745. return localMethod->mMethodDef;
  19746. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19747. auto declMethodState = localMethod->mDeclMethodState;
  19748. auto declMixinState = localMethod->mDeclMixinState;
  19749. auto typeInst = mCurTypeInstance;
  19750. BfAstNode* body = NULL;
  19751. BfAstNode* anchorNode = NULL;
  19752. auto _AllocDirectTypeRef = [&](BfType* type)
  19753. {
  19754. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  19755. directTypeRef->Init(type);
  19756. return directTypeRef;
  19757. };
  19758. auto methodDeclaration = localMethod->mMethodDeclaration;
  19759. if (methodDeclaration != NULL)
  19760. {
  19761. body = methodDeclaration->mBody;
  19762. anchorNode = methodDeclaration->mOpenParen;
  19763. }
  19764. else
  19765. {
  19766. body = localMethod->mLambdaBindExpr->mBody;
  19767. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  19768. }
  19769. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  19770. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  19771. BfMethodDef* methodDef;
  19772. BfMethodDef* outerMethodDef = NULL;
  19773. if (localMethod->mOuterLocalMethod != NULL)
  19774. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  19775. else if (rootMethodState->mMethodInstance != NULL)
  19776. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  19777. if (methodDeclaration != NULL)
  19778. {
  19779. BfDefBuilder defBuilder(mCompiler->mSystem);
  19780. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  19781. defBuilder.mPassInstance = mCompiler->mPassInstance;
  19782. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  19783. defBuilder.mCurDeclaringTypeDef = defBuilder.mCurTypeDef;
  19784. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  19785. }
  19786. else
  19787. {
  19788. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  19789. methodDef = new BfMethodDef();
  19790. methodDef->mName = localMethod->mMethodName;
  19791. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  19792. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  19793. methodDef->mBody = body;
  19794. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  19795. {
  19796. auto paramType = invokeMethod->GetParamType(paramIdx);
  19797. String paramName;
  19798. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  19799. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  19800. else
  19801. paramName = invokeMethod->GetParamName(paramIdx);
  19802. auto paramDef = new BfParameterDef();
  19803. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  19804. paramDef->mName = paramName;
  19805. methodDef->mParams.Add(paramDef);
  19806. }
  19807. if (outerMethodDef != NULL)
  19808. {
  19809. for (auto genericParam : outerMethodDef->mGenericParams)
  19810. {
  19811. auto* copiedGenericParamDef = new BfGenericParamDef();
  19812. *copiedGenericParamDef = *genericParam;
  19813. methodDef->mGenericParams.Add(copiedGenericParamDef);
  19814. }
  19815. }
  19816. }
  19817. methodDef->mIdx = ~methodLocalIdx;
  19818. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  19819. methodDef->mName = localMethod->mExpectedFullName;
  19820. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  19821. //
  19822. // if (!localMethod->mExpectedFullName.IsEmpty())
  19823. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  19824. methodDef->mIsStatic = true;
  19825. methodDef->mIsLocalMethod = true;
  19826. methodDef->mIsVirtual = false;
  19827. localMethod->mMethodDef = methodDef;
  19828. auto methodInstanceGroup = new BfMethodInstanceGroup();
  19829. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  19830. methodInstanceGroup->mMethodIdx = -1;
  19831. methodInstanceGroup->mOwner = mCurTypeInstance;
  19832. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  19833. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  19834. {
  19835. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  19836. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  19837. }
  19838. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  19839. {
  19840. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  19841. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19842. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  19843. {
  19844. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  19845. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  19846. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  19847. autoComplete->mDefType = typeInst->mTypeDef;
  19848. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  19849. autoComplete->mReplaceLocalId = methodLocalIdx;
  19850. }
  19851. }
  19852. return localMethod->mMethodDef;
  19853. }
  19854. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  19855. {
  19856. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  19857. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  19858. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19859. auto declMethodState = localMethod->mDeclMethodState;
  19860. auto declMixinState = localMethod->mDeclMixinState;
  19861. auto callerMethodState = mCurMethodState;
  19862. auto typeInst = mCurTypeInstance;
  19863. if (mCurMethodState->mMixinState != NULL)
  19864. {
  19865. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  19866. }
  19867. auto methodDef = GetLocalMethodDef(localMethod);
  19868. BfAstNode* body = NULL;
  19869. auto methodDeclaration = localMethod->mMethodDeclaration;
  19870. if (methodDeclaration != NULL)
  19871. {
  19872. body = methodDeclaration->mBody;
  19873. }
  19874. else
  19875. {
  19876. body = localMethod->mLambdaBindExpr->mBody;
  19877. }
  19878. bool hadConcreteInterfaceGenericArgument = false;
  19879. BfTypeVector sanitizedMethodGenericArguments;
  19880. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  19881. // version of this method for this pass through the outermost method
  19882. int dependentGenericStartIdx = 0;
  19883. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19884. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  19885. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  19886. if (methodGenericArguments.size() == 0)
  19887. {
  19888. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19889. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  19890. }
  19891. else
  19892. {
  19893. int genericArgIdx = 0;
  19894. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  19895. // {
  19896. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  19897. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  19898. // }
  19899. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  19900. {
  19901. auto genericArgType = methodGenericArguments[genericArgIdx];
  19902. BF_ASSERT(!genericArgType->IsRef());
  19903. if (genericArgType->IsConcreteInterfaceType())
  19904. {
  19905. hadConcreteInterfaceGenericArgument = true;
  19906. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  19907. genericArgType = concreteInterfaceType->mInterface;
  19908. }
  19909. sanitizedMethodGenericArguments.push_back(genericArgType);
  19910. }
  19911. }
  19912. bool wantPrematureMethodInstance = false;
  19913. if (!force)
  19914. {
  19915. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  19916. }
  19917. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  19918. bool isDefaultPass = true;
  19919. BfTypeVector lookupMethodGenericArguments;
  19920. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  19921. {
  19922. auto genericArgType = methodGenericArguments[genericArgIdx];
  19923. BF_ASSERT(!genericArgType->IsRef());
  19924. lookupMethodGenericArguments.Add(genericArgType);
  19925. if (genericArgType->IsGenericParam())
  19926. {
  19927. auto genericParam = (BfGenericParamType*)genericArgType;
  19928. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  19929. isDefaultPass = false;
  19930. }
  19931. else
  19932. {
  19933. isDefaultPass = false;
  19934. }
  19935. }
  19936. bool hadExistingMethodInstance = false;
  19937. if (methodInstance != NULL)
  19938. {
  19939. hadExistingMethodInstance = true;
  19940. }
  19941. else
  19942. {
  19943. if (isDefaultPass)
  19944. {
  19945. methodInstance = methodInstGroup->mDefault;
  19946. if (methodInstance != NULL)
  19947. {
  19948. hadExistingMethodInstance = true;
  19949. }
  19950. else
  19951. {
  19952. methodInstance = new BfMethodInstance();
  19953. methodInstGroup->mDefault = methodInstance;
  19954. }
  19955. }
  19956. else
  19957. {
  19958. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  19959. if (methodInstGroup->mMethodSpecializationMap == NULL)
  19960. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  19961. BfMethodInstance** methodInstancePtr = NULL;
  19962. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  19963. {
  19964. methodInstance = *methodInstancePtr;
  19965. hadExistingMethodInstance = true;
  19966. }
  19967. else
  19968. {
  19969. methodInstance = new BfMethodInstance();
  19970. *methodInstancePtr = methodInstance;
  19971. }
  19972. }
  19973. }
  19974. if (hadExistingMethodInstance)
  19975. {
  19976. if ((!methodInstance->mDisallowCalling) ||
  19977. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  19978. return BfModuleMethodInstance(methodInstance);
  19979. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  19980. }
  19981. else
  19982. {
  19983. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  19984. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  19985. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  19986. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  19987. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  19988. methodInstance->mMethodDef = methodDef;
  19989. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  19990. if (hadConcreteInterfaceGenericArgument)
  19991. methodInstance->mIgnoreBody = true;
  19992. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  19993. for (auto genericArg : sanitizedMethodGenericArguments)
  19994. {
  19995. if (genericArg->IsPrimitiveType())
  19996. genericArg = GetWrappedStructType(genericArg);
  19997. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  19998. }
  19999. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  20000. {
  20001. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  20002. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  20003. }
  20004. SetupMethodIdHash(methodInstance);
  20005. }
  20006. auto _SetupMethodInstance = [&]()
  20007. {
  20008. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  20009. // Generic constraints
  20010. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  20011. {
  20012. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  20013. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  20014. }
  20015. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  20016. {
  20017. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  20018. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  20019. }
  20020. };
  20021. //////////////////////////////////////////////////////////////////////////
  20022. auto _VisitLambdaBody = [&]()
  20023. {
  20024. if (localMethod->mDeclOnly)
  20025. return;
  20026. if (mCompiler->mCanceling)
  20027. return;
  20028. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  20029. {
  20030. VisitCodeBlock(blockBody);
  20031. }
  20032. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  20033. {
  20034. BfType* expectType = NULL;
  20035. if (!methodInstance->mReturnType->IsVoid())
  20036. expectType = methodInstance->mReturnType;
  20037. CreateValueFromExpression(bodyExpr, expectType, BfEvalExprFlags_AllowRefExpr);
  20038. }
  20039. };
  20040. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  20041. {
  20042. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  20043. auto result = ResolveTypeRef(typeRef);
  20044. if (result == NULL)
  20045. result = mContext->mBfObjectType;
  20046. return result;
  20047. };
  20048. BfTypeInstance* outerClosure = NULL;
  20049. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  20050. outerClosure = declMethodState->mClosureState->mClosureType;
  20051. BfMethodState methodState;
  20052. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  20053. BfIRFunctionType funcType;
  20054. auto voidType = GetPrimitiveType(BfTypeCode_None);
  20055. SizedArray<BfIRType, 0> paramTypes;
  20056. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  20057. mBfIRBuilder->SaveDebugLocation();
  20058. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  20059. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  20060. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  20061. BfDeferredLocalAssignData deferredLocalAssignData;
  20062. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  20063. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  20064. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  20065. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  20066. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  20067. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  20068. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  20069. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  20070. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  20071. methodState.mIRFunction = declMethodState->mIRFunction;
  20072. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  20073. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  20074. {
  20075. methodState.mCurScope->mAstBlock = blockBody;
  20076. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  20077. }
  20078. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  20079. BfClosureState closureState;
  20080. if (methodDef->mMethodType == BfMethodType_Mixin)
  20081. {
  20082. if (declMethodState != NULL)
  20083. {
  20084. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  20085. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  20086. else if (declMethodState->mMethodInstance != NULL)
  20087. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  20088. }
  20089. }
  20090. if (closureState.mReturnType == NULL)
  20091. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  20092. closureState.mCapturing = true;
  20093. closureState.mLocalMethod = localMethod;
  20094. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  20095. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  20096. methodState.mClosureState = &closureState;
  20097. closureState.mClosureType = outerClosure;
  20098. int outerLocalsCount = (int)methodState.mLocals.size();
  20099. if (!hadExistingMethodInstance)
  20100. {
  20101. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  20102. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  20103. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  20104. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  20105. auto declareModule = this;
  20106. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  20107. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  20108. BF_ASSERT(declareModule != NULL);
  20109. methodInstance->mDeclModule = declareModule;
  20110. _SetupMethodInstance();
  20111. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  20112. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  20113. }
  20114. if (wantPrematureMethodInstance)
  20115. {
  20116. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  20117. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  20118. // its true method instance
  20119. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  20120. //BF_ASSERT(moduleMethodInstance);
  20121. return BfModuleMethodInstance(methodInstance);
  20122. }
  20123. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  20124. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  20125. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  20126. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  20127. closureState.mClosureMethodDef = methodDef;
  20128. bool wantsVisitBody = true;
  20129. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  20130. wantsVisitBody = false;
  20131. if (methodInstance->IsOrInUnspecializedVariation())
  20132. wantsVisitBody = false;
  20133. bool allowCapture = (methodDeclaration == NULL) || (methodDeclaration->mStaticSpecifier == NULL);
  20134. if (wantsVisitBody)
  20135. {
  20136. BP_ZONE("VisitLambdaBody");
  20137. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  20138. // this capture stage for each of those times
  20139. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  20140. /*
  20141. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  20142. // that will not occur during the actual lambda method generation, for example: returning a value
  20143. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  20144. // our AST nodes will still be visited
  20145. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  20146. */
  20147. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20148. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  20149. mBfIRBuilder->SaveDebugLocation();
  20150. closureState.mCaptureVisitingBody = true;
  20151. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  20152. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  20153. methodState.mMethodInstance = methodInstance;
  20154. NewScopeState();
  20155. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  20156. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  20157. {
  20158. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  20159. for (auto localDef : methodState.mLocals)
  20160. {
  20161. if (localDef->mResolvedType->IsVar())
  20162. continue;
  20163. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  20164. }
  20165. }
  20166. // Keep outs from being marked as assigned
  20167. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20168. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  20169. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  20170. auto prevDLA = rootMethodState->mDeferredLocalAssignData;
  20171. while ((prevDLA != NULL) && (prevDLA->mIsChained))
  20172. prevDLA = prevDLA->mChainedAssignData;
  20173. if (prevDLA != NULL)
  20174. {
  20175. deferredLocalAssignData.mAssignedLocals = prevDLA->mAssignedLocals;
  20176. deferredLocalAssignData.mLeftBlockUncond = prevDLA->mLeftBlockUncond;
  20177. }
  20178. SetAndRestoreValue<BfDeferredLocalAssignData*> sarDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  20179. if (!mIgnoreErrors)
  20180. localMethod->mDidBodyErrorPass = true;
  20181. _VisitLambdaBody();
  20182. RestoreScopeState();
  20183. closureState.mCaptureVisitingBody = false;
  20184. mBfIRBuilder->RestoreDebugLocation();
  20185. }
  20186. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  20187. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  20188. {
  20189. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  20190. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  20191. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  20192. }
  20193. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  20194. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  20195. closureState.mClosureMethodDef = NULL;
  20196. for (auto methodInstance : closureState.mLocalMethodRefs)
  20197. {
  20198. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  20199. }
  20200. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  20201. prevIgnoreWrites.Restore();
  20202. std::multiset<BfClosureCapturedEntry> capturedEntries;
  20203. //
  20204. {
  20205. auto varMethodState = declMethodState;
  20206. while (varMethodState != NULL)
  20207. {
  20208. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  20209. {
  20210. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  20211. methodDef->mIsStatic = false;
  20212. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20213. methodDef->mIsMutating = true;
  20214. }
  20215. bool copyOuterCaptures = false;
  20216. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  20217. {
  20218. auto localVar = varMethodState->mLocals[localIdx];
  20219. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20220. {
  20221. if (!allowCapture)
  20222. {
  20223. if ((!localVar->mIsStatic) && (!localVar->mConstValue))
  20224. continue;
  20225. }
  20226. if (localVar->mIsThis)
  20227. {
  20228. // We can only set mutating if our owning type is mutating
  20229. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  20230. {
  20231. if (typeInst->IsValueType())
  20232. {
  20233. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20234. methodDef->mIsMutating = true;
  20235. }
  20236. }
  20237. methodDef->mIsStatic = false;
  20238. continue;
  20239. }
  20240. if ((localVar->mIsThis) && (outerClosure != NULL))
  20241. {
  20242. continue;
  20243. }
  20244. if ((localVar->mConstValue) || (localVar->mIsStatic) || (localVar->mResolvedType->IsValuelessType()))
  20245. {
  20246. closureState.mConstLocals.push_back(*localVar);
  20247. continue;
  20248. }
  20249. BfClosureCapturedEntry capturedEntry;
  20250. auto capturedType = localVar->mResolvedType;
  20251. bool captureByRef = false;
  20252. if (!capturedType->IsRef())
  20253. {
  20254. if (localVar->mIsThis)
  20255. {
  20256. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  20257. captureByRef = true;
  20258. }
  20259. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20260. captureByRef = true;
  20261. }
  20262. else
  20263. {
  20264. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  20265. {
  20266. capturedType = ((BfRefType*)capturedType)->mElementType;
  20267. }
  20268. }
  20269. if (captureByRef)
  20270. {
  20271. //capturedEntry.mIsByReference = true;
  20272. capturedType = CreateRefType(capturedType);
  20273. }
  20274. else
  20275. {
  20276. //capturedEntry.mIsByReference = false;
  20277. }
  20278. capturedEntry.mNameNode = localVar->mNameNode;
  20279. capturedEntry.mType = capturedType;
  20280. capturedEntry.mName = localVar->mName;
  20281. //capturedEntry.mLocalVarDef = localVar;
  20282. capturedEntries.insert(capturedEntry);
  20283. }
  20284. }
  20285. varMethodState = varMethodState->mPrevMethodState;
  20286. if ((varMethodState == NULL) ||
  20287. (varMethodState->mMixinState != NULL) ||
  20288. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  20289. break;
  20290. }
  20291. }
  20292. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  20293. {
  20294. auto fieldDef = copyField->GetFieldDef();
  20295. BfClosureCapturedEntry capturedEntry;
  20296. capturedEntry.mName = copyField->GetFieldDef()->mName;
  20297. capturedEntry.mType = copyField->mResolvedType;
  20298. if (capturedEntry.mType->IsRef())
  20299. {
  20300. // Keep by ref
  20301. }
  20302. else if (!fieldDef->mIsReadOnly)
  20303. {
  20304. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  20305. }
  20306. capturedEntries.insert(capturedEntry);
  20307. }
  20308. int captureIdx = 0;
  20309. for (auto& capturedEntry : capturedEntries)
  20310. {
  20311. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  20312. }
  20313. /*if (isDefaultPass)
  20314. {
  20315. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  20316. int captureIdx = 0;
  20317. for (auto& capturedEntry : capturedEntries)
  20318. {
  20319. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  20320. BfParameterDef* paramDef = new BfParameterDef();
  20321. paramDef->mName = capturedEntry.mName;
  20322. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  20323. directTypeRef->mType = capturedEntry.mType;
  20324. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  20325. paramDef->mTypeRef = directTypeRef;
  20326. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  20327. methodDef->mParams.Insert(captureIdx, paramDef);
  20328. captureIdx++;
  20329. }
  20330. }
  20331. else
  20332. {
  20333. auto defaultMethodInstance = methodInstGroup->mDefault;
  20334. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  20335. }*/
  20336. methodState.Reset();
  20337. closureState.mCapturing = false;
  20338. //////////////////////////////////////////////////////////////////////////
  20339. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  20340. if (methodInstance->mReturnType != NULL)
  20341. {
  20342. BF_ASSERT(methodInstance->mDisallowCalling);
  20343. // We did a premature declaration (without captures)
  20344. methodInstance->UndoDeclaration();
  20345. methodInstance->mDisallowCalling = false;
  20346. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  20347. }
  20348. auto declareModule = this;
  20349. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  20350. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  20351. BF_ASSERT(declareModule != NULL);
  20352. methodInstance->mDeclModule = declareModule;
  20353. _SetupMethodInstance();
  20354. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  20355. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  20356. closureState.mReturnType = methodInstance->mReturnType;
  20357. mCompiler->mStats.mMethodsQueued++;
  20358. mCompiler->UpdateCompletion();
  20359. declareModule->mIncompleteMethodCount++;
  20360. mCompiler->mStats.mMethodsProcessed++;
  20361. if (!methodInstance->mIsReified)
  20362. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  20363. auto deferMethodState = rootMethodState;
  20364. // 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)
  20365. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  20366. (methodDef->mMethodType != BfMethodType_Mixin) &&
  20367. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)) &&
  20368. (!mCompiler->IsDataResolvePass()))
  20369. {
  20370. BP_ZONE("BfDeferredLocalMethod:create");
  20371. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  20372. deferredLocalMethod->mLocalMethod = localMethod;
  20373. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  20374. deferredLocalMethod->mMethodInstance = methodInstance;
  20375. auto checkMethodState = declMethodState;
  20376. while (checkMethodState != NULL)
  20377. {
  20378. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  20379. {
  20380. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  20381. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20382. }
  20383. if (checkMethodState->mMixinState != NULL)
  20384. {
  20385. BfMixinRecord mixinRecord;
  20386. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  20387. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20388. }
  20389. checkMethodState = checkMethodState->mPrevMethodState;
  20390. }
  20391. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  20392. }
  20393. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  20394. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  20395. mBfIRBuilder->RestoreDebugLocation();
  20396. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  20397. {
  20398. auto checkMethodState = mCurMethodState;
  20399. while (checkMethodState != NULL)
  20400. {
  20401. BfLocalMethod* nextLocalMethod = NULL;
  20402. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  20403. {
  20404. while (nextLocalMethod != NULL)
  20405. {
  20406. auto checkLocalMethod = nextLocalMethod;
  20407. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  20408. if (checkLocalMethod == localMethod)
  20409. continue;
  20410. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  20411. continue;
  20412. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  20413. if (checkMethodInstance == NULL)
  20414. continue; // Not generated yet
  20415. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  20416. {
  20417. String error = "Method already declared with the same parameter types";
  20418. auto bfError = Fail(error, methodInstance->mMethodDef->GetRefNode(), true);
  20419. if ((bfError != NULL) && (methodInstance->mMethodDef->GetRefNode() != checkMethodInstance->mMethodDef->GetRefNode()))
  20420. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  20421. }
  20422. }
  20423. }
  20424. checkMethodState = checkMethodState->mPrevMethodState;
  20425. }
  20426. }
  20427. return BfModuleMethodInstance(methodInstance);
  20428. }
  20429. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  20430. {
  20431. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  20432. return 0;
  20433. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20434. int rootMethodGenericParamCount = 0;
  20435. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  20436. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  20437. if (mCurMethodInstance == NULL)
  20438. return rootMethodGenericParamCount;
  20439. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  20440. return rootMethodGenericParamCount;
  20441. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  20442. if (callerLocalMethod == NULL)
  20443. return rootMethodGenericParamCount;
  20444. BfLocalMethod* calledLocalMethod = NULL;
  20445. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  20446. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  20447. {
  20448. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  20449. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  20450. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  20451. }
  20452. return rootMethodGenericParamCount;
  20453. }
  20454. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  20455. {
  20456. auto methodDef = methodInstance->mMethodDef;
  20457. auto customAttributes = methodInstance->GetCustomAttributes();
  20458. if (customAttributes != NULL)
  20459. return;
  20460. auto methodDeclaration = methodDef->GetMethodDeclaration();
  20461. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  20462. auto typeInstance = methodInstance->GetOwner();
  20463. if (typeInstance->IsInstanceOf(mCompiler->mValueTypeTypeDef))
  20464. return;
  20465. BfTypeState typeState(typeInstance);
  20466. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20467. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  20468. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20469. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  20470. BfAttributeDirective* attributeDirective = NULL;
  20471. if (methodDeclaration != NULL)
  20472. attributeDirective = methodDeclaration->mAttributes;
  20473. else if (propertyMethodDeclaration != NULL)
  20474. {
  20475. attributeDirective = propertyMethodDeclaration->mAttributes;
  20476. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  20477. {
  20478. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  20479. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  20480. }
  20481. }
  20482. if (attributeDirective != NULL)
  20483. {
  20484. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20485. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20486. if ((methodInstance == methodInstance->mMethodInstanceGroup->mDefault) && (methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes != NULL))
  20487. {
  20488. // Take over previously-generated custom attributes
  20489. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes;
  20490. methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes = NULL;
  20491. }
  20492. else
  20493. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  20494. }
  20495. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mPropertyDeclaration->mAttributes != NULL) && ((attrTarget & BfAttributeTargets_Property) == 0))
  20496. {
  20497. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes != NULL)
  20498. {
  20499. GetCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20500. }
  20501. else
  20502. {
  20503. methodInstance->GetMethodInfoEx()->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20504. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20505. }
  20506. }
  20507. if (methodDeclaration != NULL)
  20508. {
  20509. if (auto inlineTypeRef = BfNodeDynCast<BfInlineTypeReference>(methodDeclaration->mReturnType))
  20510. {
  20511. if (inlineTypeRef->mTypeDeclaration->mAttributes != NULL)
  20512. {
  20513. // Apply multiuse attributes from anonymous return type
  20514. auto returnType = ResolveTypeRef(inlineTypeRef);
  20515. if ((returnType != NULL) && (returnType->ToTypeInstance()))
  20516. {
  20517. auto returnTypeInst = returnType->ToTypeInstance();
  20518. if ((returnTypeInst->IsAnonymous()) && (returnTypeInst->mCustomAttributes != NULL))
  20519. {
  20520. bool hasPendingAttributes = false;
  20521. for (const auto& customAttribute : returnTypeInst->mCustomAttributes->mAttributes)
  20522. {
  20523. if (customAttribute.mAwaitingValidation)
  20524. {
  20525. hasPendingAttributes = true;
  20526. break;
  20527. }
  20528. }
  20529. if (hasPendingAttributes)
  20530. {
  20531. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20532. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20533. if (methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes == NULL)
  20534. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = new BfCustomAttributes();
  20535. for (const auto& customAttribute : returnTypeInst->mCustomAttributes->mAttributes)
  20536. {
  20537. if (!customAttribute.mAwaitingValidation)
  20538. continue;
  20539. BfCustomAttribute copiedCustomAttribute = customAttribute;
  20540. copiedCustomAttribute.mIsMultiUse = false;
  20541. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes.Add(copiedCustomAttribute);
  20542. }
  20543. ValidateCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, attrTarget);
  20544. }
  20545. }
  20546. }
  20547. }
  20548. }
  20549. }
  20550. customAttributes = methodInstance->GetCustomAttributes();
  20551. if (customAttributes == NULL)
  20552. {
  20553. auto owner = methodInstance->GetOwner();
  20554. if ((owner->IsDelegate()) || (owner->IsFunction()))
  20555. customAttributes = owner->mCustomAttributes;
  20556. }
  20557. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  20558. if (customAttributes != NULL)
  20559. {
  20560. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  20561. if (linkNameAttr != NULL)
  20562. {
  20563. if (linkNameAttr->mCtorArgs.size() == 1)
  20564. {
  20565. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  20566. if (constant != NULL)
  20567. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  20568. }
  20569. }
  20570. if (methodDef->mHasComptime)
  20571. methodInstance->mComptimeFlags = BfComptimeFlag_Comptime;
  20572. auto comptimeAttr = customAttributes->Get(mCompiler->mComptimeAttributeTypeDef);
  20573. if (comptimeAttr != NULL)
  20574. {
  20575. for (auto setProp : comptimeAttr->mSetProperties)
  20576. {
  20577. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  20578. if (propertyDef->mName == "OnlyFromComptime")
  20579. {
  20580. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  20581. if ((constant != NULL) && (constant->mBool))
  20582. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_OnlyFromComptime);
  20583. }
  20584. else if (propertyDef->mName == "ConstEval")
  20585. {
  20586. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  20587. if ((constant != NULL) && (constant->mBool))
  20588. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_ConstEval);
  20589. }
  20590. }
  20591. }
  20592. }
  20593. auto delegateInfo = typeInstance->GetDelegateInfo();
  20594. if ((delegateInfo != NULL) && (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) && (methodInstance->mMethodDef->mName == "Invoke"))
  20595. methodInstance->mCallingConvention = delegateInfo->mCallingConvention;
  20596. }
  20597. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  20598. {
  20599. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  20600. {
  20601. // Don't create a func
  20602. return;
  20603. }
  20604. auto typeInstance = methodInstance->GetOwner();
  20605. auto methodDef = methodInstance->mMethodDef;
  20606. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  20607. if (isTemporaryFunc)
  20608. {
  20609. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  20610. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  20611. mangledName = "autocomplete_tmp";
  20612. }
  20613. if (!mBfIRBuilder->mIgnoreWrites)
  20614. {
  20615. BfIRFunction prevFunc;
  20616. // Remove old version (if we have one)
  20617. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  20618. if (prevFunc)
  20619. {
  20620. if ((methodDef->mIsOverride) && (mCurTypeInstance->mTypeDef->mIsCombinedPartial))
  20621. {
  20622. bool takeover = false;
  20623. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  20624. BfMethodDef* nextMethod = NULL;
  20625. BfMemberSetEntry* entry = NULL;
  20626. if (mCurTypeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  20627. nextMethod = (BfMethodDef*)entry->mMemberDef;
  20628. while (nextMethod != NULL)
  20629. {
  20630. auto checkMethod = nextMethod;
  20631. nextMethod = nextMethod->mNextWithSameName;
  20632. if (checkMethod == methodDef)
  20633. continue;
  20634. if (checkMethod->mIsOverride)
  20635. {
  20636. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20637. if (checkMethodInstance == NULL)
  20638. continue;
  20639. if ((checkMethodInstance->mIRFunction == prevFunc) &&
  20640. (checkMethodInstance->mMethodDef->mMethodDeclaration != NULL) &&
  20641. (checkMethodInstance->mVirtualTableIdx < 0))
  20642. {
  20643. BfAstNode* refNode = methodDef->GetRefNode();
  20644. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  20645. refNode = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  20646. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  20647. refNode = methodDeclaration->mVirtualSpecifier;
  20648. auto error = Fail(StrFormat("Conflicting extension override method '%s'", MethodToString(mCurMethodInstance).c_str()), refNode);
  20649. if (error != NULL)
  20650. mCompiler->mPassInstance->MoreInfo("See previous override", checkMethod->GetRefNode());
  20651. takeover = false;
  20652. break;
  20653. }
  20654. }
  20655. if (!checkMethod->mIsExtern)
  20656. continue;
  20657. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20658. if (checkMethodInstance == NULL)
  20659. continue;
  20660. if (!CompareMethodSignatures(checkMethodInstance, mCurMethodInstance))
  20661. continue;
  20662. // Take over function
  20663. takeover = true;
  20664. }
  20665. if (takeover)
  20666. mCurMethodInstance->mIRFunction = prevFunc;
  20667. if (!mCurMethodInstance->mIRFunction)
  20668. {
  20669. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  20670. if (!mIsComptimeModule)
  20671. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  20672. }
  20673. }
  20674. else if (methodDef->mIsExtern)
  20675. {
  20676. // Allow this
  20677. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  20678. }
  20679. else if (typeInstance->IsIRFuncUsed(prevFunc))
  20680. {
  20681. // We can have a collision of names when we have generic methods that differ only in
  20682. // their constraints, but they should only collide in their unspecialized form
  20683. // since only one will be chosen for a given concrete type
  20684. if (!mIsComptimeModule)
  20685. mCurMethodInstance->mMangleWithIdx = true;
  20686. mangledName.Clear();
  20687. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  20688. BfLogSysM("Function collision forced mangleWithIdx for %p: %d GenericArgs: %d Unspecialized: %d\n", methodInstance, prevFunc.mId, methodInstance->GetNumGenericArguments(), methodInstance->mIsUnspecialized);
  20689. }
  20690. else
  20691. {
  20692. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  20693. if (!mIsComptimeModule)
  20694. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  20695. }
  20696. }
  20697. }
  20698. if (typeInstance != mContext->mBfObjectType)
  20699. {
  20700. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  20701. GetMethodCustomAttributes(methodInstance);
  20702. }
  20703. // if (prevFunc)
  20704. // {
  20705. // if (methodDef->mIsExtern)
  20706. // {
  20707. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  20708. // methodInstance->mIRFunction = prevFunc;
  20709. // }
  20710. // else
  20711. // {
  20712. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  20713. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  20714. // {
  20715. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  20716. // BfLogSysM("Ignoring function name collision\n");
  20717. // }
  20718. // else
  20719. // {
  20720. // if (methodDef->mMethodDeclaration == NULL)
  20721. // {
  20722. // AssertErrorState();
  20723. // }
  20724. // else
  20725. // {
  20726. // BF_ASSERT(mIsSpecialModule);
  20727. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  20728. // {
  20729. // // We shouldn't have name collisions on the first run!
  20730. // AssertErrorState();
  20731. // }
  20732. // }
  20733. // }
  20734. // BfLogSysM("Before erase\n");
  20735. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  20736. // }
  20737. // }
  20738. bool isIntrinsic = false;
  20739. if (!methodInstance->mIRFunction)
  20740. {
  20741. BfIRFunction func;
  20742. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType() || (mIsComptimeModule)) &&
  20743. (!methodDef->IsEmptyPartial())) && (funcType);
  20744. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  20745. {
  20746. if (!mIsReified)
  20747. wantsLLVMFunc = false;
  20748. }*/
  20749. if (wantsLLVMFunc)
  20750. {
  20751. func = GetIntrinsic(methodInstance, true);
  20752. if (func)
  20753. {
  20754. isIntrinsic = true;
  20755. }
  20756. else
  20757. {
  20758. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  20759. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  20760. if (methodInstance->mAlwaysInline)
  20761. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  20762. // if (prevFunc)
  20763. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  20764. }
  20765. methodInstance->mIRFunction = func;
  20766. //if (!ignoreWrites)
  20767. //BF_ASSERT(!func.IsFake());
  20768. }
  20769. }
  20770. if (outIsIntrinsic != NULL)
  20771. *outIsIntrinsic = isIntrinsic;
  20772. if (!isIntrinsic)
  20773. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  20774. }
  20775. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  20776. {
  20777. if (methodInstance->mHotMethod != NULL)
  20778. return;
  20779. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  20780. {
  20781. auto srcTypeInst = methodInstance->GetOwner();
  20782. if (srcTypeInst->mHotTypeData == NULL)
  20783. return;
  20784. StringT<128> mangledName = inMangledName;
  20785. if (mangledName.IsEmpty())
  20786. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  20787. // We always keep the current primary method at the same address
  20788. BfHotMethod* hotMethod;
  20789. BfHotMethod** hotMethodPtr;
  20790. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  20791. {
  20792. hotMethod = new BfHotMethod();
  20793. *hotMethodPtr = hotMethod;
  20794. hotMethod->mRefCount = 1;
  20795. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20796. #ifdef BF_DBG_HOTMETHOD_IDX
  20797. static int sMethodIdx = 0;
  20798. hotMethod->mMethodIdx = sMethodIdx++;
  20799. #endif
  20800. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20801. }
  20802. else
  20803. {
  20804. hotMethod = *hotMethodPtr;
  20805. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  20806. {
  20807. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  20808. auto prevHotMethod = *hotMethodPtr;
  20809. hotMethod = new BfHotMethod();
  20810. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20811. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  20812. hotDupMethod->mRefCount++;
  20813. prevHotMethod->mReferences.Add(hotDupMethod);
  20814. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  20815. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20816. }
  20817. else if (mCompiler->IsHotCompile())
  20818. {
  20819. // Link the previous version into the mPrevVersion
  20820. BfHotMethod* prevMethod = new BfHotMethod();
  20821. prevMethod->mRefCount = 1;
  20822. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  20823. hotMethod->mPrevVersion = prevMethod;
  20824. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  20825. hotMethod->mSrcTypeVersion = NULL;
  20826. prevMethod->mFlags = hotMethod->mFlags;
  20827. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  20828. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  20829. #ifdef BF_DBG_HOTMETHOD_NAME
  20830. prevMethod->mMangledName = hotMethod->mMangledName;
  20831. #endif
  20832. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  20833. }
  20834. else
  20835. {
  20836. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20837. hotMethod->Clear(true);
  20838. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20839. }
  20840. }
  20841. if (methodInstance->mIsClosure)
  20842. {
  20843. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  20844. }
  20845. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  20846. hotMethod->mSrcTypeVersion->mRefCount++;
  20847. hotMethod->mRefCount++;
  20848. #ifdef BF_DBG_HOTMETHOD_NAME
  20849. hotMethod->mMangledName = mangledName;
  20850. #endif
  20851. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!IsHotCompile()))
  20852. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  20853. methodInstance->mHotMethod = hotMethod;
  20854. }
  20855. }
  20856. static void StackOverflow()
  20857. {
  20858. int i = 0;
  20859. if (i == 0)
  20860. StackOverflow();
  20861. }
  20862. void BfModule::StartMethodDeclaration(BfMethodInstance* methodInstance, BfMethodState* prevMethodState)
  20863. {
  20864. methodInstance->mHasStartedDeclaration = true;
  20865. auto methodDef = methodInstance->mMethodDef;
  20866. auto typeInstance = methodInstance->GetOwner();
  20867. bool hasNonGenericParams = false;
  20868. bool hasGenericParams = false;
  20869. int dependentGenericStartIdx = 0;
  20870. if (methodDef->mIsLocalMethod)
  20871. {
  20872. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  20873. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  20874. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  20875. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  20876. // over the local method each time
  20877. auto rootMethodInstance = prevMethodState->GetRootMethodState()->mMethodInstance;
  20878. dependentGenericStartIdx = 0;
  20879. if (rootMethodInstance != NULL)
  20880. {
  20881. if (rootMethodInstance->mMethodInfoEx != NULL)
  20882. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  20883. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  20884. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  20885. }
  20886. }
  20887. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodInstance->GetNumGenericArguments(); genericArgIdx++)
  20888. {
  20889. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  20890. if (genericArgType->IsGenericParam())
  20891. {
  20892. hasGenericParams = true;
  20893. auto genericParam = (BfGenericParamType*)genericArgType;
  20894. methodInstance->mIsUnspecialized = true;
  20895. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  20896. methodInstance->mIsUnspecializedVariation = true;
  20897. }
  20898. else
  20899. {
  20900. hasNonGenericParams = true;
  20901. if (genericArgType->IsUnspecializedType())
  20902. {
  20903. methodInstance->mIsUnspecialized = true;
  20904. methodInstance->mIsUnspecializedVariation = true;
  20905. }
  20906. }
  20907. }
  20908. if ((hasGenericParams) && (hasNonGenericParams))
  20909. {
  20910. methodInstance->mIsUnspecializedVariation = true;
  20911. }
  20912. if (typeInstance->IsUnspecializedType())
  20913. {
  20914. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  20915. // actually want to do method processing on it
  20916. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  20917. methodInstance->mIsUnspecializedVariation = true;
  20918. methodInstance->mIsUnspecialized = true;
  20919. }
  20920. if (methodInstance->mIsUnspecializedVariation)
  20921. BF_ASSERT(methodInstance->mIsUnspecialized);
  20922. //TODO: Why did we do this?
  20923. if (methodDef->mMethodType == BfMethodType_Mixin)
  20924. {
  20925. if (methodInstance->IsSpecializedGenericMethod())
  20926. methodInstance->mIsUnspecializedVariation = true;
  20927. methodInstance->mIsUnspecialized = true;
  20928. }
  20929. }
  20930. // methodDeclaration is NULL for default constructors
  20931. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  20932. {
  20933. BF_ASSERT((mCompiler->mCeMachine == NULL) || (!mCompiler->mCeMachine->mDbgPaused));
  20934. BP_ZONE("BfModule::DoMethodDeclaration");
  20935. auto typeInstance = mCurTypeInstance;
  20936. auto typeDef = typeInstance->mTypeDef;
  20937. auto methodDef = mCurMethodInstance->mMethodDef;
  20938. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  20939. // to effectively make mIgnoreWrites method-scoped
  20940. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  20941. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  20942. SetAndRestoreValue<bool> prevAllowLockYield(mContext->mAllowLockYield, false);
  20943. BfTypeState typeState(mCurTypeInstance);
  20944. typeState.mPrevState = mContext->mCurTypeState;
  20945. typeState.mCurMethodDef = methodDef;
  20946. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20947. BfModule* resolveModule = mContext->mUnreifiedModule;
  20948. if (mCompiler->IsAutocomplete())
  20949. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  20950. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  20951. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  20952. BfMethodState methodState;
  20953. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  20954. methodState.mTempKind = BfMethodState::TempKind_Static;
  20955. defer({ mCurMethodInstance->mHasBeenDeclared = true; });
  20956. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  20957. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  20958. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  20959. // if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  20960. // {
  20961. // BF_ASSERT(mContext->mResolvingVarField);
  20962. // isTemporaryFunc = true;
  20963. // }
  20964. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  20965. FinishInit();
  20966. if (methodDef->mName.StartsWith('_'))
  20967. {
  20968. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  20969. if (methodDef->mName == "__FATALERRORNAME")
  20970. BFMODULE_FATAL(this, "__FATALERRORNAME");
  20971. if (methodDef->mName == "__STACKOVERFLOW")
  20972. StackOverflow();
  20973. if (methodDef->mName == "__INTERNALERROR")
  20974. InternalError("Bad method name", methodDef->GetRefNode());
  20975. }
  20976. if (typeInstance->IsClosure())
  20977. {
  20978. if (methodDef->mName == "Invoke")
  20979. return;
  20980. }
  20981. auto methodInstance = mCurMethodInstance;
  20982. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  20983. addToWorkList = false;
  20984. if (!methodInstance->mHasStartedDeclaration)
  20985. StartMethodDeclaration(methodInstance, prevMethodState.mPrevVal);
  20986. BfAutoComplete* bfAutocomplete = NULL;
  20987. if (mCompiler->mResolvePassData != NULL)
  20988. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  20989. if (methodInstance->mMethodInfoEx != NULL)
  20990. {
  20991. BfTypeInstance* unspecializedTypeInstance = NULL;
  20992. Array<BfTypeReference*> deferredResolveTypes;
  20993. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  20994. {
  20995. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  20996. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  20997. {
  20998. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  20999. }
  21000. else
  21001. {
  21002. auto externConstraintDef = genericParam->GetExternConstraintDef();
  21003. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  21004. auto autoComplete = mCompiler->GetAutoComplete();
  21005. if (autoComplete != NULL)
  21006. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  21007. if (genericParam->mExternType != NULL)
  21008. {
  21009. //
  21010. }
  21011. else
  21012. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  21013. }
  21014. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized, &deferredResolveTypes);
  21015. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  21016. {
  21017. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  21018. if (bfAutocomplete != NULL)
  21019. {
  21020. for (auto nameNode : genericParamDef->mNameNodes)
  21021. {
  21022. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  21023. }
  21024. }
  21025. }
  21026. }
  21027. for (auto typeRef : deferredResolveTypes)
  21028. auto constraintType = ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_None);
  21029. if (methodInstance->mMethodInfoEx != NULL)
  21030. {
  21031. ValidateGenericParams(BfGenericParamKind_Method,
  21032. Span<BfGenericParamInstance*>((BfGenericParamInstance**)methodInstance->mMethodInfoEx->mGenericParams.mVals,
  21033. methodInstance->mMethodInfoEx->mGenericParams.mSize));
  21034. }
  21035. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  21036. AddDependency(genericParam, mCurTypeInstance);
  21037. }
  21038. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  21039. {
  21040. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  21041. BfAstNode* nameNode = methodDeclaration->mNameNode;
  21042. if (nameNode == NULL)
  21043. {
  21044. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  21045. nameNode = ctorDeclaration->mThisToken;
  21046. }
  21047. if ((autoComplete->IsAutocompleteNode(nameNode)) && (autoComplete->mResolveType != BfResolveType_Autocomplete))
  21048. {
  21049. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  21050. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  21051. autoComplete->mDefType = typeDef;
  21052. autoComplete->mDefMethod = methodDef;
  21053. autoComplete->SetDefinitionLocation(nameNode);
  21054. if (methodDef->mIsOverride)
  21055. {
  21056. bool found = false;
  21057. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  21058. {
  21059. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  21060. if (ventry.mDeclaringMethod.mMethodNum == -1)
  21061. continue;
  21062. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  21063. if (virtMethod != NULL)
  21064. {
  21065. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  21066. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  21067. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  21068. {
  21069. // Is matching method
  21070. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  21071. {
  21072. auto baseType = typeInstance->mBaseType;
  21073. if (baseType != NULL)
  21074. {
  21075. found = true;
  21076. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  21077. baseType = baseType->mBaseType;
  21078. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  21079. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  21080. autoComplete->mDefType = baseType->mTypeDef;
  21081. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  21082. }
  21083. }
  21084. break;
  21085. }
  21086. }
  21087. }
  21088. if ((!found) && (autoComplete->mIsGetDefinition) && (methodDef->mDeclaringType->IsExtension()))
  21089. {
  21090. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  21091. {
  21092. auto defaultMethod = methodGroup.mDefault;
  21093. if (defaultMethod == NULL)
  21094. continue;
  21095. if (!defaultMethod->mMethodDef->mIsExtern)
  21096. continue;
  21097. if (!CompareMethodSignatures(defaultMethod, methodInstance))
  21098. continue;
  21099. autoComplete->SetDefinitionLocation(defaultMethod->mMethodDef->GetRefNode(), true);
  21100. autoComplete->mDefType = typeInstance->mTypeDef;
  21101. autoComplete->mDefMethod = defaultMethod->mMethodDef;
  21102. }
  21103. }
  21104. }
  21105. }
  21106. }
  21107. bool reportErrors = true;
  21108. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  21109. reportErrors = true;
  21110. // Only the defining contexts needs to report errors here
  21111. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  21112. if (methodDef->mMethodType == BfMethodType_Dtor)
  21113. {
  21114. if (methodDef->mIsStatic)
  21115. {
  21116. }
  21117. else
  21118. {
  21119. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  21120. {
  21121. BfAstNode* refNode = methodDeclaration;
  21122. if (refNode == NULL)
  21123. {
  21124. // Whatever caused this ctor to be generated should have caused another failure
  21125. // But that failure might not be generated until the ctor is generated
  21126. }
  21127. else
  21128. {
  21129. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  21130. if (dtorDecl != NULL)
  21131. refNode = dtorDecl->mThisToken;
  21132. Fail("Structs cannot have destructors", refNode);
  21133. }
  21134. }
  21135. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21136. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  21137. (mCurTypeInstance != mContext->mBfObjectType))
  21138. {
  21139. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  21140. }
  21141. }
  21142. }
  21143. BfType* resolvedReturnType = NULL;
  21144. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  21145. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  21146. (methodDef->mReturnTypeRef != NULL))
  21147. {
  21148. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  21149. if (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>())
  21150. {
  21151. // An invalid 'var' error would not have been caught in the original property type pass
  21152. mIgnoreErrors = false;
  21153. }
  21154. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_NoReify);
  21155. if ((((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0) || (methodInstance->mIsAutocompleteMethod))
  21156. && (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>()))
  21157. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  21158. else
  21159. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration, flags);
  21160. if (resolvedReturnType == NULL)
  21161. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  21162. if ((methodDef->mIsReadOnly) && (!resolvedReturnType->IsRef()))
  21163. {
  21164. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration))
  21165. if (methodDeclaration->mReadOnlySpecifier != NULL)
  21166. Fail("Readonly specifier is only valid on 'ref' return types", methodDeclaration->mReadOnlySpecifier);
  21167. }
  21168. }
  21169. else
  21170. {
  21171. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  21172. }
  21173. BF_ASSERT(resolvedReturnType != NULL);
  21174. mCurMethodInstance->mReturnType = resolvedReturnType;
  21175. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  21176. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  21177. //if (!methodInstance->IsSpecializedGenericMethod())
  21178. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21179. if (methodDef->mExplicitInterface != NULL)
  21180. {
  21181. auto autoComplete = mCompiler->GetAutoComplete();
  21182. if (autoComplete != NULL)
  21183. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  21184. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  21185. BfTypeInstance* explicitInterface = NULL;
  21186. if (explicitType != NULL)
  21187. explicitInterface = explicitType->ToTypeInstance();
  21188. if (explicitInterface != NULL)
  21189. {
  21190. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  21191. if (autoComplete != NULL)
  21192. {
  21193. BfTokenNode* dotToken = NULL;
  21194. BfAstNode* nameNode = NULL;
  21195. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  21196. {
  21197. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  21198. nameNode = methodDeclaration->mNameNode;
  21199. }
  21200. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  21201. }
  21202. }
  21203. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  21204. {
  21205. bool interfaceFound = false;
  21206. for (auto ifaceInst : typeInstance->mInterfaces)
  21207. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  21208. if ((!interfaceFound) && (!typeInstance->mTypeFailed))
  21209. {
  21210. if (methodDef->mMethodDeclaration != NULL)
  21211. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  21212. else
  21213. {
  21214. // For property decls, we should have already given the error during type population
  21215. if (mCompiler->mRevision == 1)
  21216. AssertErrorState();
  21217. }
  21218. }
  21219. }
  21220. }
  21221. bool isThisStruct = mCurTypeInstance->IsStruct();
  21222. BfType* thisType = NULL;
  21223. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  21224. {
  21225. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  21226. {
  21227. thisType = mCurTypeInstance;
  21228. if (thisType == NULL)
  21229. return;
  21230. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  21231. {
  21232. BfTypeUtils::SplatIterate([&](BfType* checkType)
  21233. {
  21234. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  21235. }, thisType);
  21236. }
  21237. }
  21238. else
  21239. {
  21240. thisType = mCurTypeInstance;
  21241. resolveModule->PopulateType(thisType, BfPopulateType_Declaration);
  21242. }
  21243. }
  21244. int implicitParamCount = 0;
  21245. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  21246. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  21247. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  21248. bool hadDelegateParams = false;
  21249. bool hadParams = false;
  21250. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  21251. {
  21252. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  21253. BfParameterDef* paramDef = NULL;
  21254. int paramDefIdx = -1;
  21255. if (paramIdx < implicitParamCount)
  21256. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  21257. else
  21258. {
  21259. paramDefIdx = paramIdx - implicitParamCount;
  21260. paramDef = methodDef->mParams[paramDefIdx];
  21261. }
  21262. if (hadParams)
  21263. break;
  21264. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  21265. continue;
  21266. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  21267. (paramDef->mParamKind != BfParamKind_AppendIdx))
  21268. {
  21269. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  21270. if (mCompiler->mResolvePassData->mAutoComplete->IsAutocompleteNode(paramDef->mTypeRef))
  21271. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("token", "in"), paramDef->mTypeRef->ToString());
  21272. }
  21273. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  21274. {
  21275. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  21276. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  21277. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  21278. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  21279. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  21280. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  21281. }
  21282. BfType* resolvedParamType = NULL;
  21283. if (closureCaptureEntry != NULL)
  21284. resolvedParamType = closureCaptureEntry->mType;
  21285. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfLetTypeReference>()))
  21286. {
  21287. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  21288. resolvedParamType = mContext->mBfObjectType;
  21289. }
  21290. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfVarTypeReference>()))
  21291. {
  21292. if (methodDef->mMethodType != BfMethodType_Mixin)
  21293. {
  21294. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  21295. resolvedParamType = mContext->mBfObjectType;
  21296. }
  21297. else
  21298. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21299. }
  21300. BfType* unresolvedParamType = resolvedParamType;
  21301. bool wasGenericParam = false;
  21302. if (resolvedParamType == NULL)
  21303. {
  21304. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue | BfResolveTypeRefFlag_NoReify);
  21305. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  21306. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  21307. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  21308. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  21309. resolvedParamType = resolvedParamType->GetUnderlyingType();
  21310. }
  21311. if (resolvedParamType == NULL)
  21312. {
  21313. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21314. unresolvedParamType = resolvedParamType;
  21315. if (mCurTypeInstance->IsBoxed())
  21316. {
  21317. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  21318. // If we failed a lookup here then we better have also failed it in the original type
  21319. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.ContainsKey(boxedType->mElementType->ToTypeInstance()));
  21320. }
  21321. }
  21322. BF_ASSERT(!resolvedParamType->IsDeleting());
  21323. if (!methodInstance->IsSpecializedGenericMethod())
  21324. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21325. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  21326. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  21327. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  21328. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  21329. {
  21330. if (paramDef->mParamKind == BfParamKind_Params)
  21331. {
  21332. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  21333. if (refNode != NULL)
  21334. refNode = paramDef->mParamDeclaration->mModToken;
  21335. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  21336. }
  21337. BfTypedValue defaultValue;
  21338. if (resolvedParamType->IsConstExprValue())
  21339. {
  21340. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  21341. BfExprEvaluator exprEvaluator(this);
  21342. exprEvaluator.mExpectingType = constExprType->mType;
  21343. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  21344. defaultValue = exprEvaluator.GetResult();
  21345. }
  21346. else
  21347. {
  21348. BfTypeState typeState;
  21349. typeState.mType = mCurTypeInstance;
  21350. typeState.mCurTypeDef = methodDef->mDeclaringType;
  21351. //typeState.mCurMethodDef = methodDef;
  21352. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  21353. BfConstResolver constResolver(this);
  21354. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  21355. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  21356. {
  21357. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  21358. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  21359. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  21360. {
  21361. defaultValue = castedDefaultValue; // Good!
  21362. }
  21363. else if (!CanCast(defaultValue, resolvedParamType))
  21364. {
  21365. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  21366. // a conversion operator.
  21367. // This should throw an error
  21368. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  21369. AssertErrorState();
  21370. if (!defaultValue.mValue.IsConst())
  21371. defaultValue = BfTypedValue();
  21372. }
  21373. }
  21374. }
  21375. if (!defaultValue)
  21376. {
  21377. defaultValue = GetDefaultTypedValue(resolvedParamType);
  21378. if (!defaultValue.mValue.IsConst())
  21379. defaultValue = BfTypedValue();
  21380. }
  21381. if (defaultValue)
  21382. {
  21383. if (defaultValue.mType->IsVar())
  21384. {
  21385. AssertErrorState();
  21386. }
  21387. else
  21388. {
  21389. BF_ASSERT(defaultValue.mValue.IsConst());
  21390. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  21391. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  21392. CurrentAddToConstHolder(defaultValue.mValue);
  21393. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  21394. }
  21395. }
  21396. }
  21397. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  21398. {
  21399. bool addParams = true;
  21400. bool isValid = false;
  21401. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  21402. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->IsInstanceOf(mCompiler->mSpanTypeDef)))
  21403. {
  21404. // Span<T>
  21405. isValid = true;
  21406. }
  21407. else if (resolvedParamType->IsArray())
  21408. {
  21409. // Array is the 'normal' params type
  21410. isValid = true;
  21411. }
  21412. else if (resolvedParamType->IsSizedArray())
  21413. {
  21414. isValid = true;
  21415. }
  21416. else if (resolvedParamType->IsVar())
  21417. {
  21418. isValid = true;
  21419. }
  21420. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()) || (resolvedParamType->IsMethodRef()))
  21421. {
  21422. hadDelegateParams = true;
  21423. // This means we copy the params from a delegate
  21424. BfMethodParam methodParam;
  21425. methodParam.mResolvedType = resolvedParamType;
  21426. methodParam.mParamDefIdx = paramDefIdx;
  21427. methodParam.mDelegateParamIdx = 0;
  21428. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21429. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  21430. {
  21431. methodParam.mDelegateParamIdx = delegateParamIdx;
  21432. mCurMethodInstance->mParams.Add(methodParam);
  21433. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  21434. if (!methodInstance->IsSpecializedGenericMethod())
  21435. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21436. }
  21437. isValid = true;
  21438. addParams = false;
  21439. }
  21440. else if (resolvedParamType->IsGenericParam())
  21441. {
  21442. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  21443. if (genericParamInstance->mTypeConstraint != NULL)
  21444. {
  21445. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  21446. if ((genericParamInstance->mTypeConstraint->IsArray()) || (genericParamInstance->mTypeConstraint->IsSizedArray()))
  21447. {
  21448. BfMethodParam methodParam;
  21449. methodParam.mResolvedType = resolvedParamType;
  21450. methodParam.mParamDefIdx = paramDefIdx;
  21451. mCurMethodInstance->mParams.Add(methodParam);
  21452. isValid = true;
  21453. }
  21454. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  21455. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  21456. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  21457. {
  21458. mCurMethodInstance->mHadGenericDelegateParams = true;
  21459. isValid = true;
  21460. addParams = false;
  21461. }
  21462. }
  21463. }
  21464. else
  21465. {
  21466. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  21467. if ((paramTypeInst != NULL) &&
  21468. ((paramTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef))))
  21469. {
  21470. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  21471. isValid = true;
  21472. addParams = false;
  21473. }
  21474. }
  21475. if (!isValid)
  21476. {
  21477. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  21478. // Failure case, make it an Object[]
  21479. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  21480. }
  21481. if ((addParams) && (resolvedParamType != NULL))
  21482. {
  21483. BfMethodParam methodParam;
  21484. methodParam.mResolvedType = resolvedParamType;
  21485. methodParam.mParamDefIdx = paramDefIdx;
  21486. mCurMethodInstance->mParams.push_back(methodParam);
  21487. }
  21488. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  21489. {
  21490. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  21491. }
  21492. }
  21493. else
  21494. {
  21495. BfMethodParam methodParam;
  21496. methodParam.mResolvedType = resolvedParamType;
  21497. methodParam.mParamDefIdx = paramDefIdx;
  21498. mCurMethodInstance->mParams.Add(methodParam);
  21499. }
  21500. }
  21501. if (hadDelegateParams)
  21502. {
  21503. HashSet<String> usedNames;
  21504. Dictionary<int, int> usedParamDefIdx;
  21505. for (auto methodParam : methodDef->mParams)
  21506. {
  21507. usedNames.Add(methodParam->mName);
  21508. }
  21509. for (auto& methodParam : mCurMethodInstance->mParams)
  21510. {
  21511. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  21512. {
  21513. int* refCount = NULL;
  21514. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  21515. (*refCount)++;
  21516. }
  21517. }
  21518. for (auto& methodParam : mCurMethodInstance->mParams)
  21519. {
  21520. if (methodParam.mDelegateParamIdx != -1)
  21521. {
  21522. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  21523. methodParam.mDelegateParamNameCombine = true;
  21524. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21525. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  21526. if (usedNames.Contains(paramName))
  21527. methodParam.mDelegateParamNameCombine = true;
  21528. }
  21529. }
  21530. }
  21531. int argIdx = 0;
  21532. resolveModule->PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  21533. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  21534. {
  21535. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  21536. auto thisType = methodInstance->GetOwner();
  21537. if (methodInstance->GetParamIsSplat(thisIdx))
  21538. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  21539. else if (!thisType->IsValuelessType())
  21540. {
  21541. BfTypeCode loweredTypeCode = BfTypeCode_None;
  21542. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  21543. if ((!mIsComptimeModule) && (!methodDef->mIsMutating))
  21544. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  21545. argIdx++;
  21546. if (loweredTypeCode2 != BfTypeCode_None)
  21547. argIdx++;
  21548. }
  21549. }
  21550. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  21551. argIdx++;
  21552. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  21553. {
  21554. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  21555. BfType* checkType = methodParam.mResolvedType;
  21556. int checkArgIdx = argIdx;
  21557. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  21558. {
  21559. checkArgIdx = 0;
  21560. checkType = methodInstance->GetThisType();
  21561. }
  21562. if (checkType->IsMethodRef())
  21563. {
  21564. methodParam.mIsSplat = true;
  21565. }
  21566. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting(paramIdx)))
  21567. {
  21568. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  21569. if (checkType->IsSplattable())
  21570. {
  21571. bool isSplat = false;
  21572. auto checkTypeInstance = checkType->ToTypeInstance();
  21573. if ((checkTypeInstance != NULL) && (checkTypeInstance->mIsCRepr))
  21574. isSplat = true;
  21575. int splatCount = checkType->GetSplatCount();
  21576. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  21577. isSplat = true;
  21578. if (isSplat)
  21579. {
  21580. methodParam.mIsSplat = true;
  21581. argIdx += splatCount;
  21582. continue;
  21583. }
  21584. }
  21585. else if (!checkType->IsValuelessType())
  21586. {
  21587. BfTypeCode loweredTypeCode = BfTypeCode_None;
  21588. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  21589. if (!mIsComptimeModule)
  21590. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  21591. argIdx++;
  21592. if (loweredTypeCode2 != BfTypeCode_None)
  21593. argIdx++;
  21594. continue;
  21595. }
  21596. }
  21597. argIdx++;
  21598. }
  21599. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  21600. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  21601. {
  21602. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  21603. }
  21604. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  21605. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  21606. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  21607. (!methodDef->mIsSkipCall))
  21608. {
  21609. if (methodDeclaration->mEndSemicolon == NULL)
  21610. {
  21611. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  21612. {
  21613. //
  21614. }
  21615. else
  21616. AssertParseErrorState();
  21617. }
  21618. else
  21619. {
  21620. bool isError = true;
  21621. if (typeInstance->IsTypedPrimitive())
  21622. {
  21623. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  21624. {
  21625. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  21626. {
  21627. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  21628. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  21629. {
  21630. isError = false;
  21631. }
  21632. }
  21633. }
  21634. }
  21635. if (isError)
  21636. {
  21637. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  21638. MethodToString(methodInstance).c_str()),
  21639. methodDef->GetRefNode());
  21640. }
  21641. }
  21642. }
  21643. if (methodDef->IsEmptyPartial())
  21644. hasExternSpecifier = true;
  21645. if (!methodInstance->IsAutocompleteMethod())
  21646. {
  21647. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  21648. int implicitParamCount = methodInstance->GetImplicitParamCount();
  21649. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  21650. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  21651. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  21652. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  21653. int paramIdx = 0;
  21654. int defaultParamIdx = 0;
  21655. while (true)
  21656. {
  21657. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  21658. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  21659. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  21660. {
  21661. paramIdx++;
  21662. continue;
  21663. }
  21664. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  21665. {
  21666. defaultParamIdx++;
  21667. continue;
  21668. }
  21669. if ((isDone) || (isDefaultDone))
  21670. {
  21671. // 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
  21672. // to cause us to throw an assertion in the declaration here
  21673. if ((!defaultMethodInstance->mHadGenericDelegateParams) && (!methodInstance->mHasFailed) && (!defaultMethodInstance->mHasFailed))
  21674. BF_ASSERT((isDone) && (isDefaultDone));
  21675. break;
  21676. }
  21677. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  21678. if (paramType->IsRef())
  21679. paramType = paramType->GetUnderlyingType();
  21680. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  21681. paramIdx++;
  21682. defaultParamIdx++;
  21683. }
  21684. }
  21685. StringT<4096> mangledName;
  21686. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  21687. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  21688. {
  21689. auto paramType = methodInstance->GetParamType(paramIdx);
  21690. if (paramType->IsComposite())
  21691. resolveModule->PopulateType(paramType, BfPopulateType_Data);
  21692. if (!methodInstance->IsParamSkipped(paramIdx))
  21693. {
  21694. if (paramType->IsStruct())
  21695. {
  21696. //
  21697. }
  21698. else
  21699. {
  21700. PopulateType(paramType, BfPopulateType_Declaration);
  21701. }
  21702. }
  21703. }
  21704. // Only process method in default unspecialized mode, not in variations
  21705. if (methodInstance->mIsUnspecializedVariation)
  21706. return;
  21707. resolveModule->PopulateType(resolvedReturnType, BfPopulateType_Data);
  21708. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  21709. if (resolvedReturnType->IsValuelessType())
  21710. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  21711. if (!mBfIRBuilder->mIgnoreWrites)
  21712. {
  21713. bool isIntrinsic = false;
  21714. if (!methodInstance->mIRFunction)
  21715. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  21716. if (isIntrinsic)
  21717. {
  21718. addToWorkList = false;
  21719. }
  21720. }
  21721. else
  21722. {
  21723. GetMethodCustomAttributes(methodInstance);
  21724. }
  21725. auto func = methodInstance->mIRFunction;
  21726. // if (methodInstance->mIsReified)
  21727. // CheckHotMethod(methodInstance, mangledName);
  21728. for (auto& param : methodInstance->mParams)
  21729. {
  21730. BF_ASSERT(!param.mResolvedType->IsDeleting());
  21731. }
  21732. 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);
  21733. SizedArray<BfIRMDNode, 8> diParams;
  21734. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  21735. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  21736. {
  21737. //CS0708
  21738. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  21739. }
  21740. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  21741. {
  21742. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  21743. methodDef->mIsVirtual = false;
  21744. }
  21745. BfAstNode* mutSpecifier = NULL;
  21746. if (methodDeclaration != NULL)
  21747. mutSpecifier = methodDeclaration->mMutSpecifier;
  21748. else if (methodDef->GetPropertyMethodDeclaration() != NULL)
  21749. {
  21750. mutSpecifier = methodDef->GetPropertyMethodDeclaration()->mMutSpecifier;
  21751. if (mutSpecifier == NULL)
  21752. {
  21753. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21754. if (propertyDeclaration != NULL)
  21755. {
  21756. if (auto propExprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  21757. mutSpecifier = propExprBody->mMutSpecifier;
  21758. }
  21759. }
  21760. }
  21761. if ((mutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  21762. {
  21763. if (methodDef->mIsStatic)
  21764. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", mutSpecifier);
  21765. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  21766. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", mutSpecifier);
  21767. else if (methodDef->mMethodType == BfMethodType_Ctor)
  21768. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", mutSpecifier);
  21769. else if (methodDef->mMethodType == BfMethodType_Dtor)
  21770. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", mutSpecifier);
  21771. }
  21772. if (isTemporaryFunc)
  21773. {
  21774. // This handles temporary methods for autocomplete types
  21775. //BF_ASSERT(mIsScratchModule);
  21776. //BF_ASSERT(mCompiler->IsAutocomplete());
  21777. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  21778. return; // Bail out early for autocomplete pass
  21779. }
  21780. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  21781. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  21782. // autocompleter. Why did we have this check anyway?
  21783. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  21784. {
  21785. AddMethodReference(methodInstance);
  21786. mFuncReferences[methodInstance] = func;
  21787. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  21788. }*/
  21789. if (mParentModule != NULL)
  21790. {
  21791. // For extension modules we need to keep track of our own methods so we can know which methods
  21792. // we have defined ourselves and which are from the parent module or other extensions
  21793. if (!func.IsFake())
  21794. {
  21795. if (func)
  21796. mFuncReferences[methodInstance] = func;
  21797. }
  21798. }
  21799. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  21800. {
  21801. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  21802. auto owningModule = methodInstance->GetOwner()->mModule;
  21803. if (!owningModule->mIsScratchModule)
  21804. owningModule->mOnDemandMethodCount++;
  21805. VerifyOnDemandMethods();
  21806. }
  21807. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  21808. if (wasAwaitingDecl)
  21809. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  21810. if (addToWorkList)
  21811. {
  21812. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  21813. {
  21814. AddMethodToWorkList(methodInstance);
  21815. }
  21816. else
  21817. {
  21818. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  21819. methodInstance->mIgnoreBody = true;
  21820. if (typeInstance->IsUnspecializedType())
  21821. {
  21822. // Don't hold on to actual Function for unspecialized types
  21823. methodInstance->mIRFunction = BfIRFunction();
  21824. }
  21825. }
  21826. }
  21827. else
  21828. {
  21829. //BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  21830. }
  21831. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  21832. (!methodDef->mIsLocalMethod) &&
  21833. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  21834. (!methodDef->mReturnTypeRef->IsTemporary()))
  21835. {
  21836. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  21837. {
  21838. //TODO:
  21839. //CS0053
  21840. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  21841. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  21842. methodDef->mReturnTypeRef, true);
  21843. }
  21844. else
  21845. {
  21846. //CS0050
  21847. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  21848. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  21849. methodDef->mReturnTypeRef, true);
  21850. }
  21851. }
  21852. if (typeInstance->IsInterface())
  21853. {
  21854. if (methodDef->mMethodType == BfMethodType_Ctor)
  21855. Fail("Interfaces cannot contain constructors", methodDeclaration);
  21856. if (methodDeclaration != NULL)
  21857. {
  21858. if (methodDef->mBody == NULL)
  21859. {
  21860. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  21861. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  21862. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  21863. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  21864. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  21865. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  21866. }
  21867. }
  21868. }
  21869. bool foundHiddenMethod = false;
  21870. BfTokenNode* virtualToken = NULL;
  21871. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21872. if (propertyDeclaration != NULL)
  21873. virtualToken = propertyDeclaration->mVirtualSpecifier;
  21874. else if (methodDeclaration != NULL)
  21875. virtualToken = methodDeclaration->mVirtualSpecifier;
  21876. // Don't compare specialized generic methods against normal methods
  21877. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  21878. (!methodDef->mIsLocalMethod) && (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  21879. {
  21880. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  21881. {
  21882. typeDef->PopulateMemberSets();
  21883. BfMethodDef* nextMethod = NULL;
  21884. BfMemberSetEntry* entry = NULL;
  21885. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21886. nextMethod = (BfMethodDef*)entry->mMemberDef;
  21887. while (nextMethod != NULL)
  21888. {
  21889. auto checkMethod = nextMethod;
  21890. nextMethod = nextMethod->mNextWithSameName;
  21891. if (checkMethod == methodDef)
  21892. continue;
  21893. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21894. if (checkMethodInstance == NULL)
  21895. {
  21896. if ((methodDef->mDeclaringType->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension()))
  21897. checkMethodInstance = GetRawMethodInstanceAtIdx(typeInstance, checkMethod->mIdx);
  21898. if (checkMethodInstance == NULL)
  21899. continue;
  21900. }
  21901. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  21902. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  21903. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  21904. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  21905. {
  21906. bool canChain = false;
  21907. if ((methodDef->mParams.empty()) &&
  21908. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  21909. {
  21910. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  21911. canChain = true;
  21912. else if (methodDef->mMethodType == BfMethodType_Normal)
  21913. {
  21914. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  21915. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  21916. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  21917. canChain = true;
  21918. }
  21919. }
  21920. if (canChain)
  21921. {
  21922. bool isBetter;
  21923. bool isWorse;
  21924. CompareDeclTypes(typeInstance, checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  21925. if (isBetter && !isWorse)
  21926. {
  21927. methodInstance->mChainType = BfMethodChainType_ChainHead;
  21928. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  21929. }
  21930. else
  21931. {
  21932. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  21933. methodInstance->mChainType = BfMethodChainType_ChainMember;
  21934. }
  21935. }
  21936. else
  21937. {
  21938. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  21939. continue;
  21940. bool silentlyAllow = false;
  21941. bool extensionWarn = false;
  21942. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  21943. {
  21944. if (typeInstance->IsInterface())
  21945. {
  21946. if (methodDef->mIsOverride)
  21947. silentlyAllow = true;
  21948. }
  21949. else
  21950. {
  21951. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  21952. {
  21953. silentlyAllow = true;
  21954. methodInstance->mIsInnerOverride = true;
  21955. CheckOverridenMethod(methodInstance, checkMethodInstance);
  21956. }
  21957. else if (!checkMethod->mDeclaringType->IsExtension())
  21958. {
  21959. foundHiddenMethod = true;
  21960. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  21961. silentlyAllow = true;
  21962. else if (methodDef->mIsNew)
  21963. {
  21964. silentlyAllow = true;
  21965. }
  21966. else if (checkMethod->GetMethodDeclaration() == NULL)
  21967. silentlyAllow = true;
  21968. else if (methodDef->mIsOverride)
  21969. silentlyAllow = true;
  21970. else
  21971. extensionWarn = true;
  21972. }
  21973. else
  21974. silentlyAllow = true;
  21975. }
  21976. }
  21977. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  21978. silentlyAllow = true;
  21979. if (checkMethod->mMethodDeclaration == NULL)
  21980. {
  21981. // This can allow emission of a default ctor if we've already auto-added a default ctor
  21982. silentlyAllow = true;
  21983. }
  21984. if (!silentlyAllow)
  21985. {
  21986. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  21987. {
  21988. auto refNode = methodDef->GetRefNode();
  21989. BfError* bfError;
  21990. if (extensionWarn)
  21991. {
  21992. if (methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject)
  21993. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  21994. StrFormat("This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional. Note that this method is not callable from project '%s'.",
  21995. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  21996. else
  21997. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  21998. "This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional.", refNode);
  21999. }
  22000. else
  22001. {
  22002. bfError = Fail(StrFormat("Method '%s' already declared with the same parameter types", MethodToString(checkMethodInstance).c_str()), refNode, true);
  22003. }
  22004. if ((bfError != NULL) && (checkMethod->GetRefNode() != refNode))
  22005. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  22006. }
  22007. }
  22008. }
  22009. }
  22010. }
  22011. }
  22012. // Virtual methods give their error while slotting
  22013. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  22014. (!methodDef->mIsLocalMethod) &&
  22015. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  22016. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  22017. {
  22018. auto baseType = typeInstance->mBaseType;
  22019. while (baseType != NULL)
  22020. {
  22021. auto baseTypeDef = baseType->mTypeDef;
  22022. baseTypeDef->PopulateMemberSets();
  22023. BfMethodDef* checkMethod = NULL;
  22024. BfMemberSetEntry* entry = NULL;
  22025. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22026. checkMethod = (BfMethodDef*)entry->mMemberDef;
  22027. while (checkMethod != NULL)
  22028. {
  22029. if (checkMethod->mMethodDeclaration == NULL)
  22030. {
  22031. checkMethod = checkMethod->mNextWithSameName;
  22032. continue;
  22033. }
  22034. if (baseType->mMethodInstanceGroups.size() == 0)
  22035. {
  22036. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  22037. break;
  22038. }
  22039. if (checkMethod == methodDef)
  22040. {
  22041. checkMethod = checkMethod->mNextWithSameName;
  22042. continue;
  22043. }
  22044. if (checkMethod->mName != methodDef->mName)
  22045. {
  22046. checkMethod = checkMethod->mNextWithSameName;
  22047. continue;
  22048. }
  22049. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  22050. if (checkMethodInstance != NULL)
  22051. {
  22052. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  22053. (checkMethod->mProtection != BfProtection_Private) &&
  22054. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  22055. {
  22056. if ((!methodDef->mIsNew) && (!checkMethod->mDeclaringType->IsExtension()))
  22057. {
  22058. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  22059. if (refNode != NULL)
  22060. {
  22061. 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?
  22062. if (bfError != NULL)
  22063. {
  22064. bfError->mIsPersistent = true;
  22065. mCompiler->mPassInstance->MoreInfo("See inherited method", checkMethod->GetRefNode());
  22066. }
  22067. }
  22068. }
  22069. foundHiddenMethod = true;
  22070. break;
  22071. }
  22072. }
  22073. checkMethod = checkMethod->mNextWithSameName;
  22074. }
  22075. if (foundHiddenMethod)
  22076. break;
  22077. baseType = baseType->mBaseType;
  22078. }
  22079. if ((methodDef->mIsNew) && (!foundHiddenMethod) && (!mCurTypeInstance->IsSpecializedType()))
  22080. {
  22081. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22082. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  22083. methodDeclaration->mNewSpecifier;
  22084. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  22085. }
  22086. }
  22087. }
  22088. if ((methodDef->mIsConcrete) && (!methodInstance->mIsForeignMethodDef) && (!mCurTypeInstance->IsInterface()))
  22089. {
  22090. Fail("Only interfaces methods can be declared as 'concrete'", methodDeclaration->mVirtualSpecifier);
  22091. }
  22092. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic) && (!methodInstance->mIsInnerOverride))
  22093. {
  22094. if ((virtualToken != NULL) && (virtualToken->mToken == BfToken_Override) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  22095. Fail("No suitable method found to override", virtualToken, true);
  22096. else
  22097. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  22098. }
  22099. else if (methodDef->mIsVirtual)
  22100. {
  22101. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  22102. Fail("Virtual or abstract members cannot be 'private'", virtualToken, true);
  22103. if ((methodDef->mProtection == BfProtection_Internal) && (virtualToken != NULL))
  22104. Fail("Virtual or abstract members cannot be 'internal'. Consider using the 'protected internal' access specifier.", virtualToken, true);
  22105. }
  22106. mCompiler->mStats.mMethodDeclarations++;
  22107. mCompiler->UpdateCompletion();
  22108. }
  22109. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  22110. {
  22111. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  22112. auto typeInstance = mCurTypeInstance;
  22113. auto methodDef = methodInstance->mMethodDef;
  22114. int virtualMethodMatchIdx = -1;
  22115. if (typeInstance->mHotTypeData != NULL)
  22116. {
  22117. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  22118. {
  22119. BF_ASSERT(mCompiler->IsHotCompile());
  22120. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  22121. // may slot this override anyway (?)
  22122. int vTableStart = 0;
  22123. auto implBaseType = typeInstance->GetImplBaseType();
  22124. if (implBaseType != NULL)
  22125. vTableStart = implBaseType->mVirtualMethodTableSize;
  22126. StringT<512> mangledName;
  22127. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  22128. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  22129. {
  22130. // O(1) checking when virtual methods haven't changed
  22131. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  22132. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  22133. if (mangledName == entry.mFuncName)
  22134. {
  22135. virtualMethodMatchIdx = vTableStart + checkIdx;
  22136. break;
  22137. }
  22138. }
  22139. if (virtualMethodMatchIdx != -1)
  22140. {
  22141. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22142. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  22143. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  22144. }
  22145. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  22146. }
  22147. }
  22148. if (virtualMethodMatchIdx == -1)
  22149. {
  22150. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  22151. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  22152. typeInstance->mVirtualMethodTable.push_back(entry);
  22153. }
  22154. }
  22155. void BfModule::CompareDeclTypes(BfTypeInstance* typeInst, BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  22156. {
  22157. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  22158. {
  22159. // When we provide an extension override in the same project a root type override
  22160. isBetter = true;
  22161. isWorse = false;
  22162. }
  22163. else
  22164. {
  22165. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22166. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22167. }
  22168. if ((isBetter == isWorse) && (typeInst != NULL) && (newDeclType->IsExtension()) && (prevDeclType->IsExtension()))
  22169. {
  22170. if ((typeInst->mGenericTypeInfo != NULL) && (typeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL))
  22171. {
  22172. isBetter = false;
  22173. isWorse = false;
  22174. auto newConstraints = typeInst->GetGenericParamsVector(newDeclType);
  22175. auto prevConstraints = typeInst->GetGenericParamsVector(prevDeclType);
  22176. for (int genericIdx = 0; genericIdx < (int)newConstraints->size(); genericIdx++)
  22177. {
  22178. auto newConstraint = (*newConstraints)[genericIdx];
  22179. auto prevConstraint = (*prevConstraints)[genericIdx];
  22180. bool newIsSubset = AreConstraintsSubset(newConstraint, prevConstraint);
  22181. bool prevIsSubset = AreConstraintsSubset(prevConstraint, newConstraint);
  22182. if ((prevIsSubset) && (!newIsSubset))
  22183. isBetter = true;
  22184. if ((!prevIsSubset) && (newIsSubset))
  22185. isWorse = true;
  22186. }
  22187. }
  22188. }
  22189. }
  22190. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  22191. {
  22192. BP_ZONE("BfModule::SlotVirtualMethod");
  22193. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  22194. return false;
  22195. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  22196. {
  22197. if (!mCompiler->mOptions.mAllowHotSwapping)
  22198. return;
  22199. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  22200. return;
  22201. if (methodInstance->mHotMethod == NULL)
  22202. CheckHotMethod(methodInstance, "");
  22203. if (methodInstance->mHotMethod == NULL)
  22204. return;
  22205. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  22206. if (declMethodInstance->mHotMethod == NULL)
  22207. CheckHotMethod(declMethodInstance, "");
  22208. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  22209. virtualDecl->mRefCount++;
  22210. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  22211. };
  22212. auto typeInstance = mCurTypeInstance;
  22213. auto typeDef = typeInstance->mTypeDef;
  22214. auto methodDef = methodInstance->mMethodDef;
  22215. auto methodDeclaration = methodDef->GetMethodDeclaration();
  22216. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22217. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  22218. if (methodInstance->mIsInnerOverride)
  22219. return false;
  22220. BfAstNode* declaringNode = methodDeclaration;
  22221. if (propertyMethodDeclaration != NULL)
  22222. declaringNode = propertyMethodDeclaration->mNameNode;
  22223. BfMethodInstance* methodOverriden = NULL;
  22224. bool usedMethod = false;
  22225. BfTokenNode* virtualToken = NULL;
  22226. if (propertyDeclaration != NULL)
  22227. virtualToken = propertyDeclaration->mVirtualSpecifier;
  22228. else if (methodDeclaration != NULL)
  22229. virtualToken = methodDeclaration->mVirtualSpecifier;
  22230. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  22231. {
  22232. //Fail: Static members cannot be marked as override, virtual, or abstract
  22233. }
  22234. else if (methodDef->mIsVirtual)
  22235. {
  22236. if (IsHotCompile())
  22237. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  22238. BfTypeInstance* checkBase = typeInstance;
  22239. // If we are in an extension, look in ourselves first
  22240. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  22241. checkBase = checkBase->mBaseType;
  22242. if (typeInstance->IsValueType())
  22243. {
  22244. if (typeInstance->mBaseType == NULL)
  22245. return false; // It's actually ValueType
  22246. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  22247. if (!methodDef->mIsOverride)
  22248. {
  22249. Fail("Structs cannot have virtual methods", virtualToken, true);
  22250. return false;
  22251. }
  22252. checkBase = mContext->mBfObjectType;
  22253. if (checkBase->mVirtualMethodTableSize == 0)
  22254. PopulateType(checkBase, BfPopulateType_Full);
  22255. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  22256. return false; // System circular ref, don't do struct checking on those
  22257. }
  22258. int virtualMethodMatchIdx = -1;
  22259. bool hadHidingError = false;
  22260. BfMethodInstance* bestOverrideMethodInstance = NULL;
  22261. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  22262. int bestOverrideMethodIdx = -1;
  22263. int ambiguousOverrideMethodIdx = -1;
  22264. if (checkBase != NULL)
  22265. {
  22266. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22267. auto lookupType = checkBase;
  22268. while (lookupType != NULL)
  22269. {
  22270. lookupType->mTypeDef->PopulateMemberSets();
  22271. BfMethodDef* nextMethodDef = NULL;
  22272. BfMemberSetEntry* entry;
  22273. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  22274. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  22275. while (nextMethodDef != NULL)
  22276. {
  22277. auto checkMethodDef = nextMethodDef;
  22278. nextMethodDef = nextMethodDef->mNextWithSameName;
  22279. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  22280. continue;
  22281. BfMethodInstance* baseMethodInstance = NULL;
  22282. int checkMethodIdx = -1;
  22283. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  22284. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  22285. {
  22286. if (lookupType->IsUnspecializedTypeVariation())
  22287. {
  22288. if (!lookupMethodInstance->mMethodDef->mIsOverride)
  22289. {
  22290. baseMethodInstance = lookupMethodInstance;
  22291. checkMethodIdx = -2;
  22292. }
  22293. }
  22294. if (baseMethodInstance == NULL)
  22295. continue;
  22296. }
  22297. if (baseMethodInstance == NULL)
  22298. {
  22299. checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  22300. if (checkMethodIdx >= baseVirtualMethodTable.mSize)
  22301. {
  22302. Fail("SlotVirtualMethod out of bounds", checkMethodDef->GetRefNode());
  22303. continue;
  22304. }
  22305. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22306. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22307. {
  22308. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22309. continue;
  22310. }
  22311. baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22312. if (baseMethodInstance == NULL)
  22313. {
  22314. AssertErrorState();
  22315. continue;
  22316. }
  22317. }
  22318. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22319. {
  22320. if (methodDef->mIsOverride)
  22321. {
  22322. BfMethodInstance* checkMethodInstance;
  22323. if (checkMethodIdx == -2)
  22324. checkMethodInstance = baseMethodInstance;
  22325. else if (typeInstance->IsValueType())
  22326. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22327. else
  22328. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22329. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22330. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22331. continue;
  22332. if (bestOverrideMethodInstance != NULL)
  22333. {
  22334. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22335. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22336. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22337. if (isBetter == isWorse)
  22338. {
  22339. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22340. }
  22341. else
  22342. {
  22343. if (isWorse)
  22344. continue;
  22345. ambiguousOverrideMethodInstance = NULL;
  22346. }
  22347. }
  22348. bestOverrideMethodInstance = checkMethodInstance;
  22349. bestOverrideMethodIdx = checkMethodIdx;
  22350. }
  22351. else
  22352. {
  22353. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22354. {
  22355. if (!hadHidingError)
  22356. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22357. hadHidingError = true;
  22358. }
  22359. }
  22360. }
  22361. }
  22362. lookupType = lookupType->mBaseType;
  22363. }
  22364. }
  22365. //TODO:
  22366. if ((checkBase != NULL)
  22367. && (false)
  22368. )
  22369. {
  22370. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22371. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  22372. {
  22373. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22374. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22375. {
  22376. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22377. continue;
  22378. }
  22379. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22380. if (baseMethodInstance == NULL)
  22381. {
  22382. AssertErrorState();
  22383. continue;
  22384. }
  22385. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22386. {
  22387. if (methodDef->mIsOverride)
  22388. {
  22389. BfMethodInstance* checkMethodInstance;
  22390. if (typeInstance->IsValueType())
  22391. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22392. else
  22393. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22394. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22395. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22396. continue;
  22397. if (bestOverrideMethodInstance != NULL)
  22398. {
  22399. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22400. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22401. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22402. if (isBetter == isWorse)
  22403. {
  22404. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22405. }
  22406. else
  22407. {
  22408. if (isWorse)
  22409. continue;
  22410. ambiguousOverrideMethodInstance = NULL;
  22411. }
  22412. }
  22413. bestOverrideMethodInstance = checkMethodInstance;
  22414. bestOverrideMethodIdx = checkMethodIdx;
  22415. }
  22416. else
  22417. {
  22418. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22419. {
  22420. if (!hadHidingError)
  22421. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22422. hadHidingError = true;
  22423. }
  22424. }
  22425. }
  22426. }
  22427. }
  22428. if (bestOverrideMethodInstance != NULL)
  22429. {
  22430. if (ambiguousOverrideMethodInstance != NULL)
  22431. {
  22432. bool allow = false;
  22433. // 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.
  22434. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  22435. bool canSeeEachOther = false;
  22436. //
  22437. {
  22438. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  22439. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  22440. canSeeEachOther = true;
  22441. }
  22442. //
  22443. {
  22444. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  22445. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  22446. canSeeEachOther = true;
  22447. }
  22448. if (!canSeeEachOther)
  22449. {
  22450. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  22451. }
  22452. else
  22453. {
  22454. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  22455. if (error != NULL)
  22456. {
  22457. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  22458. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  22459. }
  22460. }
  22461. }
  22462. }
  22463. if (bestOverrideMethodIdx == -2)
  22464. {
  22465. // Comes from an unspecialized variation
  22466. virtualMethodMatchIdx = bestOverrideMethodIdx;
  22467. }
  22468. else if ((bestOverrideMethodInstance != NULL) && (bestOverrideMethodIdx != -1))
  22469. {
  22470. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22471. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  22472. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  22473. {
  22474. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  22475. {
  22476. BfTypeReference* returnTypeRef;
  22477. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22478. {
  22479. returnTypeRef = propertyDeclaration->mTypeRef;
  22480. Fail("Property differs from overridden property by type", returnTypeRef, true);
  22481. }
  22482. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22483. {
  22484. returnTypeRef = methodDeclaration->mReturnType;
  22485. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  22486. }
  22487. else
  22488. {
  22489. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  22490. }
  22491. return usedMethod;
  22492. }
  22493. }
  22494. if (methodDef->mIsOverride)
  22495. {
  22496. // We can have multiple matches when a virtual method is used to implement interface methods
  22497. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  22498. // vtable entries for this method signature
  22499. virtualMethodMatchIdx = bestOverrideMethodIdx;
  22500. if (!typeInstance->IsValueType())
  22501. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22502. if (typeInstance->IsValueType())
  22503. {
  22504. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22505. }
  22506. else
  22507. {
  22508. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22509. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  22510. BfMethodInstance* setMethodInstance = methodInstance;
  22511. bool doOverride = false;
  22512. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22513. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  22514. {
  22515. methodOverriden = overridenRef;
  22516. doOverride = true;
  22517. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  22518. {
  22519. bool isBetter = false;
  22520. bool isWorse = false;
  22521. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  22522. if (isBetter == isWorse)
  22523. {
  22524. // We have to resolve later per-project
  22525. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  22526. {
  22527. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22528. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  22529. }
  22530. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  22531. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  22532. doOverride = false;
  22533. }
  22534. else
  22535. {
  22536. if ((isBetter) && (ambiguityContext != NULL))
  22537. {
  22538. ambiguityContext->Remove(virtualMethodMatchIdx);
  22539. }
  22540. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  22541. {
  22542. if (preferRootDefinition)
  22543. {
  22544. // Leave the master GCMarkMember
  22545. isBetter = false;
  22546. isWorse = true;
  22547. }
  22548. }
  22549. doOverride = isBetter;
  22550. }
  22551. }
  22552. }
  22553. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  22554. {
  22555. methodOverriden = overridenRef;
  22556. doOverride = true;
  22557. }
  22558. if (doOverride)
  22559. {
  22560. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22561. _AddVirtualDecl(declMethodInstance);
  22562. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22563. auto& implMethodRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22564. if ((!mCompiler->mIsResolveOnly) && (implMethodRef.mMethodNum >= 0) &&
  22565. (implMethodRef.mTypeInstance == typeInstance) && (methodInstance->GetOwner() == typeInstance))
  22566. {
  22567. auto prevImplMethodInstance = (BfMethodInstance*)implMethodRef;
  22568. if (prevImplMethodInstance->mMethodDef->mDeclaringType->mProject != methodInstance->mMethodDef->mDeclaringType->mProject)
  22569. {
  22570. // We may need to have to previous method reified when we must re-slot in another project during vdata creation
  22571. BfReifyMethodDependency dep;
  22572. dep.mDepMethod = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22573. dep.mMethodIdx = implMethodRef.mMethodNum;
  22574. typeInstance->mReifyMethodDependencies.Add(dep);
  22575. }
  22576. if (!methodInstance->mMangleWithIdx)
  22577. {
  22578. // Keep mangled names from conflicting
  22579. methodInstance->mMangleWithIdx = true;
  22580. if ((methodInstance->mIRFunction) && (methodInstance->mDeclModule->mIsModuleMutable))
  22581. {
  22582. StringT<4096> mangledName;
  22583. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  22584. methodInstance->mDeclModule->mBfIRBuilder->SetFunctionName(methodInstance->mIRFunction, mangledName);
  22585. }
  22586. }
  22587. }
  22588. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  22589. }
  22590. }
  22591. if (methodOverriden != NULL)
  22592. {
  22593. CheckOverridenMethod(methodInstance, methodOverriden);
  22594. }
  22595. }
  22596. }
  22597. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  22598. {
  22599. if (methodDef->mIsOverride)
  22600. {
  22601. BfTokenNode* overrideToken = NULL;
  22602. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  22603. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  22604. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22605. overrideToken = methodDeclaration->mVirtualSpecifier;
  22606. if (overrideToken != NULL)
  22607. {
  22608. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  22609. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  22610. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  22611. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  22612. else
  22613. Fail("No suitable method found to override", overrideToken, true);
  22614. }
  22615. return usedMethod;
  22616. }
  22617. UniqueSlotVirtualMethod(methodInstance);
  22618. }
  22619. else
  22620. usedMethod = true;
  22621. if (typeInstance->IsValueType())
  22622. return usedMethod;
  22623. }
  22624. bool foundInterface = false;
  22625. bool hadAnyMatch = false;
  22626. // See if this method matches interfaces
  22627. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  22628. {
  22629. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  22630. if (ifaceInst->IsIncomplete())
  22631. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  22632. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  22633. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  22634. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  22635. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  22636. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  22637. continue;
  22638. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  22639. continue;
  22640. bool hadMatch = false;
  22641. BfMethodInstance* hadNameMatch = NULL;
  22642. BfType* expectedReturnType = NULL;
  22643. bool showedError = false;
  22644. // We go through our VTable looking for NULL entries within the interface sections
  22645. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  22646. // because a normal method declared in this type could have matched earlier
  22647. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  22648. ifaceInst->mTypeDef->PopulateMemberSets();
  22649. BfMethodDef* checkMethodDef = NULL;
  22650. BfMemberSetEntry* entry;
  22651. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  22652. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  22653. while (checkMethodDef != NULL)
  22654. {
  22655. int iMethodIdx = checkMethodDef->mIdx;
  22656. int iTableIdx = iMethodIdx + startIdx;
  22657. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  22658. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  22659. bool storeIFaceMethod = false;
  22660. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  22661. {
  22662. checkMethodDef = checkMethodDef->mNextWithSameName;
  22663. continue;
  22664. }
  22665. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  22666. auto iMethodInst = iMethodGroup.mDefault;
  22667. if (iMethodInst == NULL)
  22668. {
  22669. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  22670. AssertErrorState();
  22671. checkMethodDef = checkMethodDef->mNextWithSameName;
  22672. continue;
  22673. }
  22674. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  22675. hadNameMatch = iMethodInst;
  22676. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  22677. if ((!doesMethodSignatureMatch) && (interfaceMethodEntry->mMethodRef.IsNull()))
  22678. {
  22679. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  22680. }
  22681. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  22682. {
  22683. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  22684. {
  22685. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  22686. {
  22687. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  22688. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  22689. if (error != NULL)
  22690. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  22691. showedError = true;
  22692. }
  22693. }
  22694. }
  22695. if (doesMethodSignatureMatch)
  22696. {
  22697. usedMethod = true;
  22698. hadMatch = true;
  22699. hadAnyMatch = true;
  22700. storeIFaceMethod = true;
  22701. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  22702. {
  22703. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  22704. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance) && (!mIsComptimeModule))
  22705. {
  22706. // When autocompletion regenerates a single method body but not the whole type then
  22707. // we will see ourselves in the vtable already
  22708. return usedMethod;
  22709. }
  22710. bool isBetter = false;
  22711. bool isWorse = false;
  22712. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  22713. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  22714. if (isBetter == isWorse)
  22715. {
  22716. isBetter = methodInstance->mReturnType == iMethodInst->mReturnType;
  22717. isWorse = prevMethod->mReturnType == iMethodInst->mReturnType;
  22718. }
  22719. if (isBetter == isWorse)
  22720. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  22721. if (isBetter == isWorse)
  22722. {
  22723. if (ambiguityContext != NULL)
  22724. {
  22725. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  22726. }
  22727. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  22728. storeIFaceMethod = true;
  22729. }
  22730. else
  22731. {
  22732. if ((isBetter) && (ambiguityContext != NULL))
  22733. ambiguityContext->Remove(~iTableIdx);
  22734. storeIFaceMethod = isBetter;
  22735. }
  22736. }
  22737. }
  22738. if (storeIFaceMethod)
  22739. {
  22740. if (methodInstance->GetNumGenericParams() != 0)
  22741. _AddVirtualDecl(iMethodInst);
  22742. *iMethodPtr = methodInstance;
  22743. }
  22744. checkMethodDef = checkMethodDef->mNextWithSameName;
  22745. }
  22746. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  22747. {
  22748. if (expectedReturnType != NULL)
  22749. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  22750. else if (hadNameMatch != NULL)
  22751. {
  22752. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  22753. if (error != NULL)
  22754. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  22755. }
  22756. else
  22757. {
  22758. auto propertyDecl = methodDef->GetPropertyDeclaration();
  22759. if (propertyDecl != NULL)
  22760. {
  22761. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  22762. String name;
  22763. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  22764. name = "this[]";
  22765. else if (propertyDecl->mNameNode != NULL)
  22766. propertyDecl->mNameNode->ToString(name);
  22767. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  22768. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  22769. }
  22770. else
  22771. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  22772. }
  22773. }
  22774. }
  22775. // Any overriden virtual methods that were used in interfaces also need to be replaced
  22776. if (methodOverriden != NULL)
  22777. {
  22778. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  22779. {
  22780. if (methodEntry.mMethodRef == methodOverriden)
  22781. methodEntry.mMethodRef = methodInstance;
  22782. }
  22783. }
  22784. return usedMethod;
  22785. }
  22786. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  22787. {
  22788. auto methodDef = methodInstance->mMethodDef;
  22789. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  22790. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  22791. {
  22792. const char* protectionNames[] = { "disabled", "hidden", "private", "internal", "protected", "protected internal", "public" };
  22793. BF_STATIC_ASSERT(BF_ARRAY_COUNT(protectionNames) == BfProtection_COUNT);
  22794. BfAstNode* protectionRefNode = NULL;
  22795. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  22796. {
  22797. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  22798. if (protectionRefNode == NULL)
  22799. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  22800. if (protectionRefNode == NULL)
  22801. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  22802. }
  22803. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22804. {
  22805. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  22806. if (protectionRefNode == NULL)
  22807. protectionRefNode = methodDeclaration->mNameNode;
  22808. }
  22809. if (protectionRefNode != NULL)
  22810. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  22811. }
  22812. }
  22813. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  22814. {
  22815. auto typeInstance = mCurTypeInstance;
  22816. auto methodDef = methodInstance->mMethodDef;
  22817. if (methodDef->mMethodType == BfMethodType_Ctor)
  22818. return true;
  22819. bool foundOverride = false;
  22820. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  22821. {
  22822. auto methodDeclaration = methodDef->GetMethodDeclaration();
  22823. BfAstNode* refNode = NULL;
  22824. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22825. refNode = propertyDeclaration->mProtectionSpecifier;
  22826. else if (methodDeclaration != NULL)
  22827. refNode = methodDeclaration->mProtectionSpecifier;
  22828. Fail("Private interface methods must provide a body", refNode);
  22829. }
  22830. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  22831. {
  22832. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  22833. }
  22834. BfAstNode* declaringNode = methodDef->GetRefNode();
  22835. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  22836. {
  22837. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  22838. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  22839. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  22840. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  22841. continue;
  22842. ifaceInst->mTypeDef->PopulateMemberSets();
  22843. BfMethodDef* nextMethod = NULL;
  22844. BfMemberSetEntry* entry = NULL;
  22845. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22846. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22847. while (nextMethod != NULL)
  22848. {
  22849. auto checkMethod = nextMethod;
  22850. nextMethod = nextMethod->mNextWithSameName;
  22851. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22852. if (ifaceMethod == NULL)
  22853. continue;
  22854. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22855. {
  22856. if (methodDef->mIsOverride)
  22857. {
  22858. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  22859. {
  22860. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  22861. if (error != NULL)
  22862. {
  22863. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  22864. }
  22865. }
  22866. foundOverride = true;
  22867. }
  22868. else if (!methodDef->mIsNew)
  22869. {
  22870. auto error = Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  22871. if (error != NULL)
  22872. {
  22873. mCompiler->mPassInstance->MoreInfo("See inherited method", ifaceMethod->mMethodDef->GetRefNode());
  22874. }
  22875. }
  22876. }
  22877. }
  22878. }
  22879. if ((methodDef->mIsOverride) && (!foundOverride))
  22880. {
  22881. // This allows us to declare a method in the base definition or in an extension and then provide
  22882. // an implementation in a more-specific extension
  22883. typeInstance->mTypeDef->PopulateMemberSets();
  22884. BfMethodDef* nextMethod = NULL;
  22885. BfMemberSetEntry* entry = NULL;
  22886. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22887. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22888. while (nextMethod != NULL)
  22889. {
  22890. auto checkMethod = nextMethod;
  22891. nextMethod = nextMethod->mNextWithSameName;
  22892. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22893. if (ifaceMethod == NULL)
  22894. continue;
  22895. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  22896. continue;
  22897. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22898. {
  22899. foundOverride = true;
  22900. }
  22901. }
  22902. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  22903. // {
  22904. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  22905. // if (ifaceMethod == NULL)
  22906. // continue;
  22907. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  22908. // continue;
  22909. //
  22910. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22911. // {
  22912. // foundOverride = true;
  22913. // }
  22914. // }
  22915. }
  22916. if (methodDef->mIsOverride)
  22917. {
  22918. if (!foundOverride)
  22919. {
  22920. BfTokenNode* overrideToken = NULL;
  22921. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22922. overrideToken = propertyDeclaration->mVirtualSpecifier;
  22923. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22924. overrideToken = methodDeclaration->mVirtualSpecifier;
  22925. if (overrideToken != NULL)
  22926. {
  22927. Fail("No suitable method found to override", overrideToken, true);
  22928. }
  22929. else
  22930. {
  22931. // Possible cause - DTOR with params
  22932. AssertErrorState();
  22933. }
  22934. }
  22935. return true;
  22936. }
  22937. // Generic methods can't be called virtually
  22938. if (methodInstance->GetNumGenericParams() != 0)
  22939. return true;
  22940. // Only public methods can be called virtually
  22941. if (methodDef->mProtection != BfProtection_Public)
  22942. return true;
  22943. UniqueSlotVirtualMethod(methodInstance);
  22944. return true;
  22945. }
  22946. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  22947. {
  22948. if (methodInstance->mMethodInfoEx == NULL)
  22949. return;
  22950. int wantMinDepth = -1;
  22951. if (mCurTypeInstance != NULL)
  22952. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  22953. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  22954. {
  22955. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  22956. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  22957. wantMinDepth = wantTypeMinDepth;
  22958. }
  22959. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  22960. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  22961. }
  22962. void BfModule::DbgFinish()
  22963. {
  22964. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  22965. return;
  22966. if (mAwaitingInitFinish)
  22967. FinishInit();
  22968. if (mHasForceLinkMarker)
  22969. return;
  22970. String markerName;
  22971. BfIRValue linkMarker;
  22972. if (mBfIRBuilder->DbgHasInfo())
  22973. {
  22974. bool needForceLinking = false;
  22975. if (WantsDebugHelpers())
  22976. {
  22977. for (auto& ownedType : mOwnedTypeInstances)
  22978. {
  22979. bool hasConfirmedReference = false;
  22980. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  22981. {
  22982. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  22983. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  22984. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)) &&
  22985. (methodInstGroup.mHasEmittedReference))
  22986. {
  22987. hasConfirmedReference = true;
  22988. }
  22989. }
  22990. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  22991. needForceLinking = true;
  22992. }
  22993. }
  22994. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  22995. {
  22996. BfMethodState methodState;
  22997. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  22998. methodState.mTempKind = BfMethodState::TempKind_Static;
  22999. mHasForceLinkMarker = true;
  23000. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  23001. SizedArray<BfIRType, 0> paramTypes;
  23002. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  23003. String linkName = "FORCELINKMOD_" + mModuleName;
  23004. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  23005. mBfIRBuilder->SetActiveFunction(func);
  23006. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  23007. mBfIRBuilder->SetInsertPoint(entryBlock);
  23008. auto firstType = mOwnedTypeInstances[0];
  23009. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  23010. SizedArray<BfIRMDNode, 1> diParamTypes;
  23011. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  23012. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  23013. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  23014. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  23015. methodState.mCurScope->mDIScope = diScope;
  23016. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  23017. SizedArray<BfIRValue, 8> args;
  23018. BfExprEvaluator exprEvaluator(this);
  23019. for (auto& ownedType : mOwnedTypeInstances)
  23020. {
  23021. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  23022. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  23023. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  23024. }
  23025. mBfIRBuilder->CreateRetVoid();
  23026. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  23027. }
  23028. }
  23029. }
  23030. bool BfModule::Finish()
  23031. {
  23032. BP_ZONE("BfModule::Finish");
  23033. BfLogSysM("BfModule finish: %p\n", this);
  23034. if (mHadBuildError)
  23035. {
  23036. // Don't AssertErrorState here, this current pass may not have failed but
  23037. // the module was still queued in mFinishedModuleWorkList
  23038. ClearModule();
  23039. return true;
  23040. }
  23041. if (mUsedSlotCount != -1)
  23042. {
  23043. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  23044. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  23045. }
  23046. if ((!mGeneratesCode) && (!mAddedToCount))
  23047. return true;
  23048. BF_ASSERT(mAddedToCount);
  23049. mAddedToCount = false;
  23050. mAwaitingFinish = false;
  23051. mCompiler->mStats.mModulesFinished++;
  23052. if (HasCompiledOutput())
  23053. {
  23054. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  23055. DbgFinish();
  23056. if (mAwaitingInitFinish)
  23057. FinishInit();
  23058. for (auto ownedTypeInst : mOwnedTypeInstances)
  23059. {
  23060. // Generate dbg info and add global variables if we haven't already
  23061. mBfIRBuilder->PopulateType(ownedTypeInst);
  23062. }
  23063. if (mBfIRBuilder->DbgHasInfo())
  23064. {
  23065. mBfIRBuilder->DbgFinalize();
  23066. }
  23067. String objOutputPath;
  23068. String irOutputPath;
  23069. mIsModuleMutable = false;
  23070. //mOutFileNames.Clear();
  23071. BF_ASSERT(((int)mOutFileNames.size() >= mExtensionCount) || (mParentModule != NULL));
  23072. bool writeModule = mBfIRBuilder->HasExports();
  23073. String outputPath;
  23074. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  23075. auto& compilerOpts = mCompiler->mOptions;
  23076. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  23077. auto moduleOptions = GetModuleOptions();
  23078. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  23079. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  23080. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  23081. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  23082. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  23083. codeGenOptions.mVirtualMethodOfs = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  23084. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  23085. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  23086. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  23087. bool allowWriteToLib = true;
  23088. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  23089. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  23090. {
  23091. codeGenOptions.mWriteToLib = true;
  23092. mWroteToLib = true;
  23093. }
  23094. else
  23095. {
  23096. mWroteToLib = false;
  23097. }
  23098. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  23099. {
  23100. outputPath = mModuleName;
  23101. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  23102. BfModuleFileName moduleFileName;
  23103. if (mParentModule != NULL)
  23104. {
  23105. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  23106. {
  23107. if (checkPair.mValue == this)
  23108. moduleFileName.mProjects = checkPair.mKey;
  23109. }
  23110. }
  23111. moduleFileName.mProjects.Add(mProject);
  23112. if (fileIdx > 0)
  23113. outputPath += StrFormat("@%d", fileIdx + 1);
  23114. if (mCompiler->mOptions.mWriteIR)
  23115. irOutputPath = outputPath + ".ll";
  23116. if (mCompiler->mOptions.mGenerateObj)
  23117. {
  23118. objOutputPath = outputPath + BF_OBJ_EXT;
  23119. moduleFileName.mFileName = objOutputPath;
  23120. }
  23121. else if (mCompiler->mOptions.mWriteIR)
  23122. {
  23123. moduleFileName.mFileName = irOutputPath;
  23124. }
  23125. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  23126. {
  23127. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  23128. }
  23129. moduleFileName.mModuleWritten = writeModule;
  23130. moduleFileName.mWroteToLib = mWroteToLib;
  23131. if (!mOutFileNames.Contains(moduleFileName))
  23132. mOutFileNames.Add(moduleFileName);
  23133. }
  23134. if (mCompiler->IsHotCompile())
  23135. {
  23136. codeGenOptions.mIsHotCompile = true;
  23137. if (mParentModule != NULL)
  23138. mParentModule->mHadHotObjectWrites = true;
  23139. mHadHotObjectWrites = true;
  23140. }
  23141. //TODO: Testing VDATA
  23142. /*if (mModuleName == "vdata")
  23143. {
  23144. codeGenOptions.mOptLevel = 4;
  23145. }*/
  23146. codeGenOptions.GenerateHash();
  23147. BP_ZONE("BfModule::Finish.WriteObjectFile");
  23148. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  23149. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  23150. mLastModuleWrittenRevision = mCompiler->mRevision;
  23151. }
  23152. else
  23153. {
  23154. for (auto type : mOwnedTypeInstances)
  23155. {
  23156. BF_ASSERT((!type->IsIncomplete()) || (type->IsSpecializedByAutoCompleteMethod()));
  23157. }
  23158. }
  23159. for (auto& specModulePair : mSpecializedMethodModules)
  23160. {
  23161. auto specModule = specModulePair.mValue;
  23162. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  23163. {
  23164. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  23165. }
  23166. }
  23167. CleanupFileInstances();
  23168. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  23169. return true;
  23170. }
  23171. void BfModule::ReportMemory(MemReporter* memReporter)
  23172. {
  23173. memReporter->Add(sizeof(BfModule));
  23174. if (mBfIRBuilder != NULL)
  23175. {
  23176. memReporter->BeginSection("IRBuilder_ConstData");
  23177. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  23178. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  23179. memReporter->EndSection();
  23180. memReporter->BeginSection("IRBuilder_BFIR");
  23181. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  23182. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  23183. memReporter->EndSection();
  23184. memReporter->Add(sizeof(BfIRBuilder));
  23185. }
  23186. memReporter->BeginSection("FileInstanceMap");
  23187. memReporter->AddMap(mFileInstanceMap);
  23188. memReporter->AddMap(mNamedFileInstanceMap);
  23189. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  23190. memReporter->EndSection();
  23191. memReporter->AddVec(mOwnedTypeInstances, false);
  23192. memReporter->AddVec(mSpecializedMethodModules, false);
  23193. memReporter->AddVec(mOutFileNames, false);
  23194. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  23195. memReporter->AddMap(mInterfaceSlotRefs, false);
  23196. memReporter->AddMap(mStaticFieldRefs, false);
  23197. memReporter->AddMap(mClassVDataRefs, false);
  23198. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  23199. memReporter->AddMap(mTypeDataRefs, false);
  23200. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  23201. memReporter->AddMap(mDeferredMethodCallData, false);
  23202. memReporter->AddHashSet(mDeferredMethodIds, false);
  23203. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  23204. }
  23205. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  23206. // be transient through the next compile
  23207. void BfModule::ClearModuleData(bool clearTransientData)
  23208. {
  23209. BfLogSysM("ClearModuleData %p\n", this);
  23210. if (mAddedToCount)
  23211. {
  23212. mCompiler->mStats.mModulesFinished++;
  23213. mAddedToCount = false;
  23214. }
  23215. mDICompileUnit = BfIRMDNode();
  23216. if (clearTransientData)
  23217. mIncompleteMethodCount = 0;
  23218. mHasGenericMethods = false;
  23219. // We don't want to clear these because we want it to persist through module extensions-
  23220. // otherwise we may think an extension succeeds even though the base module failed
  23221. //mHadBuildError = false;
  23222. //mHadBuildWarning = false;
  23223. mClassVDataRefs.Clear();
  23224. mClassVDataExtRefs.Clear();
  23225. for (auto& kv : mTypeDataRefs)
  23226. kv.mValue = BfIRValue();
  23227. mStringCharPtrPool.Clear();
  23228. mStringObjectPool.Clear();
  23229. mStaticFieldRefs.Clear();
  23230. BF_ASSERT(!mIgnoreErrors);
  23231. for (auto prevIRBuilder : mPrevIRBuilders)
  23232. delete prevIRBuilder;
  23233. mPrevIRBuilders.Clear();
  23234. for (auto& specPair : mSpecializedMethodModules)
  23235. {
  23236. auto specModule = specPair.mValue;
  23237. specModule->ClearModuleData();
  23238. }
  23239. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  23240. mBuiltInFuncs[i] = BfIRFunction();
  23241. if (mNextAltModule != NULL)
  23242. mNextAltModule->ClearModuleData();
  23243. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  23244. mIsModuleMutable = false;
  23245. delete mBfIRBuilder;
  23246. mBfIRBuilder = NULL;
  23247. mWantsIRIgnoreWrites = false;
  23248. }
  23249. void BfModule::DisownMethods()
  23250. {
  23251. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  23252. mBuiltInFuncs[i] = BfIRFunction();
  23253. BfModule* methodModule = this;
  23254. if (mParentModule != NULL)
  23255. methodModule = mParentModule;
  23256. for (auto typeInst : methodModule->mOwnedTypeInstances)
  23257. {
  23258. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  23259. {
  23260. if (methodGroup.mDefault != NULL)
  23261. {
  23262. if (methodGroup.mDefault->mIRFunction)
  23263. {
  23264. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  23265. if (methodGroup.mDefault->mDeclModule == this)
  23266. {
  23267. methodGroup.mDefault->mIRFunction = BfIRFunction();
  23268. }
  23269. }
  23270. }
  23271. if (methodGroup.mMethodSpecializationMap != NULL)
  23272. {
  23273. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  23274. {
  23275. auto methodInstance = mapPair.mValue;
  23276. if (methodInstance->mDeclModule == this)
  23277. {
  23278. methodInstance->mIRFunction = BfIRFunction();
  23279. }
  23280. }
  23281. }
  23282. }
  23283. }
  23284. }
  23285. void BfModule::ClearModule()
  23286. {
  23287. ClearModuleData();
  23288. DisownMethods();
  23289. for (auto& specPair : mSpecializedMethodModules)
  23290. {
  23291. auto specModule = specPair.mValue;
  23292. specModule->ClearModule();
  23293. }
  23294. if (mNextAltModule != NULL)
  23295. mNextAltModule->ClearModule();
  23296. }