BfModule.cpp 907 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710
  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 (memberProtection == BfProtection_Hidden)
  2498. return false;
  2499. if (memberProtection == BfProtection_Public)
  2500. return true;
  2501. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2502. {
  2503. BfTypeInstance* curCheckType = mCurTypeInstance;
  2504. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2505. {
  2506. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2507. curCheckType = mixinOwner;
  2508. }
  2509. bool allowPrivate = (curCheckType != NULL) && (memberOwner->IsInstanceOf(curCheckType->mTypeDef));
  2510. if (curCheckType != NULL)
  2511. {
  2512. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2513. if (memberOwner->mTypeDef->IsGlobalsContainer())
  2514. allowPrivate |= curCheckType->mTypeDef->mNamespace == memberOwner->mTypeDef->mNamespace;
  2515. }
  2516. if (allowPrivate)
  2517. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2518. else
  2519. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2520. }
  2521. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2522. return true;
  2523. if ((memberProtection == BfProtection_Protected) || (memberProtection == BfProtection_ProtectedInternal))
  2524. {
  2525. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2526. {
  2527. bool allowProtected = false;
  2528. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2529. auto curCheckType = mCurTypeInstance;
  2530. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2531. {
  2532. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2533. curCheckType = mixinOwner;
  2534. }
  2535. if ((flags & BfProtectionCheckFlag_InstanceLookup) != 0)
  2536. {
  2537. auto lookupCheckType = lookupStartType;
  2538. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2539. {
  2540. if (lookupCheckType == curCheckType)
  2541. {
  2542. allowProtected = true;
  2543. break;
  2544. }
  2545. if (lookupCheckType == memberOwner)
  2546. break;
  2547. lookupCheckType = lookupCheckType->mBaseType;
  2548. if (lookupCheckType == NULL)
  2549. break;
  2550. }
  2551. }
  2552. else
  2553. {
  2554. auto lookupCheckType = curCheckType;
  2555. while (lookupCheckType->mInheritDepth >= memberOwner->mInheritDepth)
  2556. {
  2557. if (lookupCheckType == memberOwner)
  2558. {
  2559. allowProtected = true;
  2560. break;
  2561. }
  2562. lookupCheckType = lookupCheckType->mBaseType;
  2563. if (lookupCheckType == NULL)
  2564. break;
  2565. }
  2566. }
  2567. if (!allowProtected)
  2568. {
  2569. // It's possible our outer type is derived from 'memberOwner'
  2570. while (curCheckType->mTypeDef->mNestDepth > 0)
  2571. {
  2572. curCheckType = GetOuterType(curCheckType);
  2573. if (curCheckType == NULL)
  2574. break;
  2575. auto lookupCheckType = lookupStartType;
  2576. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2577. {
  2578. if (lookupCheckType == curCheckType)
  2579. {
  2580. allowProtected = true;
  2581. break;
  2582. }
  2583. if (lookupCheckType == memberOwner)
  2584. break;
  2585. lookupCheckType = lookupCheckType->mBaseType;
  2586. if (lookupCheckType == NULL)
  2587. break;
  2588. }
  2589. }
  2590. }
  2591. if (allowProtected)
  2592. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2593. else
  2594. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2595. }
  2596. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2597. return true;
  2598. }
  2599. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2600. {
  2601. mAttributeState->mUsed = true;
  2602. return true;
  2603. }
  2604. if (((memberProtection == BfProtection_Internal) || (memberProtection == BfProtection_ProtectedInternal)) && (memberOwner != NULL))
  2605. {
  2606. if (CheckInternalProtection(memberOwner->mTypeDef))
  2607. return true;
  2608. }
  2609. return false;
  2610. }
  2611. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2612. {
  2613. if (mCompiler->mResolvePassData != NULL)
  2614. {
  2615. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2616. sourceClassifier->SetElementType(astNode, elementType);
  2617. }
  2618. }
  2619. bool BfModule::PreFail()
  2620. {
  2621. if (!mIgnoreErrors)
  2622. return true;
  2623. SetFail();
  2624. return false;
  2625. }
  2626. void BfModule::SetFail()
  2627. {
  2628. if (mIgnoreErrors)
  2629. {
  2630. if (mAttributeState != NULL)
  2631. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2632. }
  2633. }
  2634. void BfModule::VerifyOnDemandMethods()
  2635. {
  2636. #ifdef _DEBUG
  2637. // if (mParentModule != NULL)
  2638. // {
  2639. // BF_ASSERT(mOnDemandMethodCount == 0);
  2640. // mParentModule->VerifyOnDemandMethods();
  2641. // return;
  2642. // }
  2643. //
  2644. // int onDemandCount = 0;
  2645. // for (auto type : mOwnedTypeInstances)
  2646. // {
  2647. // auto typeInst = type->ToTypeInstance();
  2648. // for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  2649. // {
  2650. // if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  2651. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  2652. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  2653. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  2654. // onDemandCount++;
  2655. // }
  2656. // }
  2657. //
  2658. // BF_ASSERT(mOnDemandMethodCount == onDemandCount);
  2659. #endif
  2660. }
  2661. bool BfModule::IsSkippingExtraResolveChecks()
  2662. {
  2663. if (mIsComptimeModule)
  2664. return false;
  2665. return mCompiler->IsSkippingExtraResolveChecks();
  2666. }
  2667. bool BfModule::AddErrorContext(StringImpl& errorString, BfAstNode* refNode, BfWhileSpecializingFlags& isWhileSpecializing, bool isWarning)
  2668. {
  2669. bool isWhileSpecializingMethod = false;
  2670. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2671. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2672. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2673. errorString += StrFormat("\n while generating append size calculating method");
  2674. else if (refNode == NULL)
  2675. {
  2676. if (mCurTypeInstance != NULL)
  2677. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2678. else if (mProject != NULL)
  2679. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2680. }
  2681. if (mCurTypeInstance != NULL)
  2682. {
  2683. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2684. {
  2685. // Propogate the fail all the way to the main method (assuming we're in a local method or lambda)
  2686. if (isWarning)
  2687. methodInstance->mHasWarning = true;
  2688. else
  2689. methodInstance->mHasFailed = true;
  2690. if (!methodInstance->mHasStartedDeclaration)
  2691. StartMethodDeclaration(methodInstance, NULL);
  2692. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2693. if (isSpecializedMethod)
  2694. {
  2695. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2696. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2697. if (unspecializedMethod == methodInstance)
  2698. {
  2699. // This is a local method inside a generic method
  2700. BF_ASSERT(methodInstance->mMethodDef->mIsLocalMethod);
  2701. }
  2702. else
  2703. {
  2704. if (isWarning)
  2705. {
  2706. if (unspecializedMethod->mHasWarning)
  2707. return false; // At least SOME error has already been reported
  2708. }
  2709. else
  2710. {
  2711. if (unspecializedMethod->mHasFailed)
  2712. return false; // At least SOME error has already been reported
  2713. }
  2714. }
  2715. }
  2716. if (isSpecializedMethod)
  2717. {
  2718. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2719. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2720. isWhileSpecializingMethod = true;
  2721. }
  2722. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2723. {
  2724. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2725. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2726. isWhileSpecializingMethod = true;
  2727. }
  2728. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2729. {
  2730. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2731. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2732. }
  2733. return true;
  2734. };
  2735. bool hadMethodInstance = false;
  2736. if (mCurMethodState != NULL)
  2737. {
  2738. auto checkMethodState = mCurMethodState;
  2739. while (checkMethodState != NULL)
  2740. {
  2741. auto methodInstance = checkMethodState->mMethodInstance;
  2742. if (methodInstance == NULL)
  2743. {
  2744. checkMethodState = checkMethodState->mPrevMethodState;
  2745. continue;
  2746. }
  2747. hadMethodInstance = true;
  2748. if (!_CheckMethodInstance(methodInstance))
  2749. return false;
  2750. checkMethodState = checkMethodState->mPrevMethodState;
  2751. }
  2752. }
  2753. if ((!hadMethodInstance) && (mCurMethodInstance != NULL))
  2754. {
  2755. if (!_CheckMethodInstance(mCurMethodInstance))
  2756. return false;
  2757. }
  2758. }
  2759. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2760. {
  2761. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2762. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2763. }
  2764. return true;
  2765. }
  2766. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent, bool deferError)
  2767. {
  2768. BP_ZONE("BfModule::Fail");
  2769. if (mIgnoreErrors)
  2770. {
  2771. mHadIgnoredError = true;
  2772. if (mAttributeState != NULL)
  2773. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2774. return NULL;
  2775. }
  2776. if (!mReportErrors)
  2777. {
  2778. mCompiler->mPassInstance->SilentFail();
  2779. return NULL;
  2780. }
  2781. if (refNode != NULL)
  2782. refNode = BfNodeToNonTemporary(refNode);
  2783. //BF_ASSERT(refNode != NULL);
  2784. if (mIsComptimeModule)
  2785. {
  2786. if (auto ceDbgState = GetCeDbgState())
  2787. {
  2788. // Follow normal fail path
  2789. }
  2790. else
  2791. {
  2792. mHadBuildError = true;
  2793. if ((mCompiler->mCeMachine->mCurContext != NULL) && (mCompiler->mCeMachine->mCurContext->mCurCallSource != NULL) &&
  2794. (mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode != NULL))
  2795. {
  2796. BfError* bfError = mCompiler->mPassInstance->Fail("Comptime method generation had errors",
  2797. mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode);
  2798. if (bfError != NULL)
  2799. mCompiler->mPassInstance->MoreInfo(error, refNode);
  2800. return bfError;
  2801. }
  2802. return NULL;
  2803. }
  2804. }
  2805. if ((mCurMethodState != NULL) && (mCurMethodState->mConstResolveState != NULL) && (mCurMethodState->mConstResolveState->mInCalcAppend))
  2806. {
  2807. mCurMethodState->mConstResolveState->mFailed = true;
  2808. return NULL;
  2809. }
  2810. if (mCurMethodInstance != NULL)
  2811. mCurMethodInstance->mHasFailed = true;
  2812. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2813. return NULL;
  2814. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2815. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2816. if (!mHadBuildError)
  2817. mHadBuildError = true;
  2818. if (mParentModule != NULL)
  2819. mParentModule->mHadBuildError = true;
  2820. if (mCurTypeInstance != NULL)
  2821. AddFailType(mCurTypeInstance);
  2822. BfLogSysM("BfModule::Fail module %p type %p %s @ %s\n", this, mCurTypeInstance, error.c_str(), (refNode != NULL) ? refNode->LocationToString().c_str() : "???");
  2823. String errorString = error;
  2824. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2825. if (!AddErrorContext(errorString, refNode, isWhileSpecializing, false))
  2826. return NULL;
  2827. BfError* bfError = NULL;
  2828. if (isWhileSpecializing)
  2829. deferError = true;
  2830. if (!mHadBuildError)
  2831. mHadBuildError = true;
  2832. // Check mixins
  2833. {
  2834. auto checkMethodState = mCurMethodState;
  2835. while (checkMethodState != NULL)
  2836. {
  2837. auto rootMixinState = checkMethodState->GetRootMixinState();
  2838. if (rootMixinState != NULL)
  2839. {
  2840. String mixinErr = StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str());
  2841. if (deferError)
  2842. bfError = mCompiler->mPassInstance->DeferFail(mixinErr, rootMixinState->mSource);
  2843. else
  2844. bfError = mCompiler->mPassInstance->Fail(mixinErr, rootMixinState->mSource);
  2845. if (bfError == NULL)
  2846. return NULL;
  2847. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2848. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2849. auto mixinState = checkMethodState->mMixinState;
  2850. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2851. {
  2852. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2853. mixinState = mixinState->mPrevMixinState;
  2854. }
  2855. return bfError;
  2856. }
  2857. checkMethodState = checkMethodState->mPrevMethodState;
  2858. }
  2859. }
  2860. if (deferError)
  2861. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2862. else if (refNode == NULL)
  2863. bfError = mCompiler->mPassInstance->Fail(errorString);
  2864. else
  2865. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2866. if (bfError != NULL)
  2867. {
  2868. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2869. bfError->mProject = mProject;
  2870. bfError->mIsPersistent = isPersistent;
  2871. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2872. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2873. else if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2874. mCompiler->mPassInstance->MoreInfo("Error in emitted code", mCurMethodState->mEmitRefNode);
  2875. }
  2876. return bfError;
  2877. }
  2878. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2879. {
  2880. if (mHadBuildError)
  2881. return NULL;
  2882. return Fail(error, refNode);
  2883. }
  2884. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2885. {
  2886. if (mIgnoreErrors)
  2887. return NULL;
  2888. if (refNode != NULL)
  2889. refNode = BfNodeToNonTemporary(refNode);
  2890. mHadBuildError = true;
  2891. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2892. if (bfError != NULL)
  2893. bfError->mProject = mProject;
  2894. return bfError;
  2895. }
  2896. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent, bool showInSpecialized)
  2897. {
  2898. if (mIgnoreErrors || mIgnoreWarnings)
  2899. return NULL;
  2900. if (!mReportErrors)
  2901. {
  2902. mCompiler->mPassInstance->SilentFail();
  2903. return NULL;
  2904. }
  2905. BfAstNode* unwarnNode = refNode;
  2906. //
  2907. {
  2908. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2909. while (parentNodeEntry != NULL)
  2910. {
  2911. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2912. break;
  2913. unwarnNode = parentNodeEntry->mNode;
  2914. parentNodeEntry = parentNodeEntry->mPrev;
  2915. }
  2916. }
  2917. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2918. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2919. {
  2920. return NULL;
  2921. }
  2922. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2923. if (mCurMethodInstance != NULL)
  2924. {
  2925. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2926. {
  2927. if (!showInSpecialized)
  2928. return NULL;
  2929. }
  2930. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2931. return NULL; // No ctorCalcAppend warnings
  2932. }
  2933. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2934. {
  2935. if (!showInSpecialized)
  2936. return NULL;
  2937. }
  2938. if (refNode != NULL)
  2939. refNode = BfNodeToNonTemporary(refNode);
  2940. String warningString = warning;
  2941. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2942. if (!AddErrorContext(warningString, refNode, isWhileSpecializing, true))
  2943. return NULL;
  2944. bool deferWarning = isWhileSpecializing != BfWhileSpecializingFlag_None;
  2945. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2946. {
  2947. // We used to bubble up warnings into the mixin injection site, BUT
  2948. // we are now assuming any relevant warnings will be given at the declaration site
  2949. return NULL;
  2950. }
  2951. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2952. {
  2953. BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Emitted code had errors", mCurMethodState->mEmitRefNode);
  2954. if (bfError != NULL)
  2955. mCompiler->mPassInstance->MoreInfo(warningString, refNode);
  2956. return bfError;
  2957. }
  2958. BfError* bfError;
  2959. if (refNode != NULL)
  2960. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warningString, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2961. else
  2962. bfError = mCompiler->mPassInstance->Warn(warningNum, warningString);
  2963. if (bfError != NULL)
  2964. {
  2965. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2966. bfError->mProject = mProject;
  2967. AddFailType(mCurTypeInstance);
  2968. mHadBuildWarning = true;
  2969. bfError->mIsPersistent = isPersistent;
  2970. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2971. {
  2972. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2973. if (parser != NULL)
  2974. {
  2975. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2976. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2977. if (warningNum != 0)
  2978. {
  2979. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  2980. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  2981. }
  2982. }
  2983. }
  2984. }
  2985. return bfError;
  2986. }
  2987. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfFieldInstance* fieldInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  2988. {
  2989. if (customAttributes == NULL)
  2990. return;
  2991. auto _AddDeclarationMoreInfo = [&]()
  2992. {
  2993. if (methodInstance != NULL)
  2994. {
  2995. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  2996. mCompiler->mPassInstance->MoreInfo(
  2997. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  2998. methodInstance->mMethodDef->GetRefNode());
  2999. }
  3000. else
  3001. {
  3002. mCompiler->mPassInstance->MoreInfo(
  3003. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  3004. typeInstance->mTypeDef->GetRefNode());
  3005. }
  3006. };
  3007. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  3008. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  3009. if ((customAttribute != NULL) && (targetSrc != NULL))
  3010. {
  3011. String err;
  3012. if (fieldInstance != NULL)
  3013. err = StrFormat("'%s' is obsolete", FieldToString(fieldInstance).c_str());
  3014. else if (methodInstance != NULL)
  3015. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  3016. else
  3017. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3018. bool isError = false;
  3019. if (customAttribute->mCtorArgs.size() >= 1)
  3020. {
  3021. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  3022. if (constant->mTypeCode == BfTypeCode_Boolean)
  3023. {
  3024. isError = constant->mBool;
  3025. }
  3026. else if (constant->mTypeCode == BfTypeCode_StringId)
  3027. {
  3028. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3029. if (str != NULL)
  3030. {
  3031. err += ":\n '";
  3032. err += *str;
  3033. err += "'";
  3034. }
  3035. if (customAttribute->mCtorArgs.size() >= 2)
  3036. {
  3037. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  3038. isError = constant->mBool;
  3039. }
  3040. }
  3041. }
  3042. BfError* error = NULL;
  3043. if (isError)
  3044. error = Fail(err, targetSrc);
  3045. else
  3046. error = Warn(0, err, targetSrc, false, true);
  3047. if (error != NULL)
  3048. _AddDeclarationMoreInfo();
  3049. }
  3050. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  3051. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3052. {
  3053. String err;
  3054. if (fieldInstance != NULL)
  3055. err += StrFormat("Method error: '", FieldToString(fieldInstance).c_str());
  3056. else if (methodInstance != NULL)
  3057. err += StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  3058. else
  3059. err += StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3060. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3061. if (str != NULL)
  3062. err += *str;
  3063. err += "'";
  3064. if (Fail(err, targetSrc) != NULL)
  3065. _AddDeclarationMoreInfo();
  3066. }
  3067. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  3068. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  3069. {
  3070. String err;
  3071. if (fieldInstance != NULL)
  3072. err += StrFormat("Field warning: '", FieldToString(fieldInstance).c_str());
  3073. else if (methodInstance != NULL)
  3074. err += StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  3075. else
  3076. err += StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3077. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3078. if (str != NULL)
  3079. err += *str;
  3080. err += "'";
  3081. if (Warn(0, err, targetSrc, false, true) != NULL)
  3082. _AddDeclarationMoreInfo();
  3083. }
  3084. }
  3085. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  3086. {
  3087. if (mBfIRBuilder->mOpFailed)
  3088. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  3089. }
  3090. void BfModule::FatalError(const StringImpl& error, const char* file, int line, int column)
  3091. {
  3092. static bool sHadFatalError = false;
  3093. static bool sHadReentrancy = false;
  3094. if (sHadFatalError)
  3095. {
  3096. return;
  3097. sHadReentrancy = true;
  3098. }
  3099. sHadFatalError = true;
  3100. String fullError = error;
  3101. if (file != NULL)
  3102. {
  3103. fullError += StrFormat(" at %s:%d", file, line);
  3104. if (column != -1)
  3105. fullError += StrFormat(":%d", column);
  3106. }
  3107. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3108. if (mCurTypeInstance != NULL)
  3109. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3110. if (mCurMethodInstance != NULL)
  3111. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3112. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3113. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3114. if (sHadReentrancy)
  3115. fullError += "\nError had reentrancy";
  3116. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  3117. }
  3118. void BfModule::FatalError(const StringImpl& error, BfAstNode* refNode)
  3119. {
  3120. if (refNode != NULL)
  3121. {
  3122. auto parser = refNode->GetParserData();
  3123. if (parser != NULL)
  3124. {
  3125. int line = -1;
  3126. int lineChar = -1;
  3127. parser->GetLineCharAtIdx(refNode->mSrcStart, line, lineChar);
  3128. if (line != -1)
  3129. FatalError(error, parser->mFileName.c_str(), line, lineChar);
  3130. }
  3131. }
  3132. FatalError(error);
  3133. }
  3134. void BfModule::InternalError(const StringImpl& error, BfAstNode* refNode, const char* file, int line)
  3135. {
  3136. String fullError = error;
  3137. if (file != NULL)
  3138. fullError += StrFormat(" at %s:%d", file, line);
  3139. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3140. if (mCurTypeInstance != NULL)
  3141. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3142. if (mCurMethodInstance != NULL)
  3143. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3144. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3145. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3146. Fail(String("INTERNAL ERROR: ") + fullError, refNode);
  3147. }
  3148. void BfModule::NotImpl(BfAstNode* astNode)
  3149. {
  3150. Fail("INTERNAL ERROR: Not implemented", astNode);
  3151. }
  3152. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  3153. {
  3154. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  3155. if (!allowPrivate)
  3156. allowPrivate |= memberType->IsInterface();
  3157. bool allowProtected = allowPrivate;
  3158. //TODO: We had this commented out, but this makes accessing protected properties fail
  3159. if (mCurTypeInstance != NULL)
  3160. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  3161. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  3162. {
  3163. return false;
  3164. }
  3165. return true;
  3166. }
  3167. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  3168. {
  3169. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  3170. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  3171. auto memberTypeInstance = memberType->ToTypeInstance();
  3172. if (memberTypeInstance == NULL)
  3173. {
  3174. auto underlyingType = memberType->GetUnderlyingType();
  3175. if (underlyingType != NULL)
  3176. return CheckDefineMemberProtection(protection, underlyingType);
  3177. return true;
  3178. }
  3179. if (memberTypeInstance->mTypeDef->mProtection < protection)
  3180. return false;
  3181. if (memberTypeInstance->IsGenericTypeInstance())
  3182. {
  3183. // When we're a generic struct, our data layout can depend on our generic parameters as well
  3184. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  3185. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3186. {
  3187. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  3188. return false;
  3189. }
  3190. }
  3191. return true;
  3192. }
  3193. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags, BfDepContext* depContext)
  3194. {
  3195. if (usedType == userType)
  3196. return;
  3197. if (((flags & BfDependencyMap::DependencyFlag_ConstValue) != 0) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_FieldType))
  3198. {
  3199. // This can be an `int32[UsedType.cVal]` type reference
  3200. flags = (BfDependencyMap::DependencyFlags)(flags | BfDependencyMap::DependencyFlag_ValueTypeSizeDep);
  3201. }
  3202. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  3203. {
  3204. if (userType->IsMethodRef())
  3205. {
  3206. // We cannot short-circuit dependencies because of method group ref counting
  3207. }
  3208. else
  3209. return;
  3210. }
  3211. if (usedType->IsSpecializedByAutoCompleteMethod())
  3212. {
  3213. if ((flags & (BfDependencyMap::DependencyFlag_TypeGenericArg | BfDependencyMap::DependencyFlag_MethodGenericArg |
  3214. BfDependencyMap::DependencyFlag_OuterType | BfDependencyMap::DependencyFlag_DerivedFrom)) == 0)
  3215. return;
  3216. }
  3217. // if (usedType->IsBoxed())
  3218. // {
  3219. // NOP;
  3220. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  3221. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  3222. // {
  3223. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  3224. // }
  3225. // }
  3226. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  3227. // BfType* origUsedType = usedType;
  3228. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  3229. // if (isDataAccess)
  3230. // {
  3231. // while (true)
  3232. // {
  3233. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  3234. // usedType = usedType->GetUnderlyingType();
  3235. // else if (usedType->IsArray())
  3236. // {
  3237. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  3238. // }
  3239. // else
  3240. // break;
  3241. // }
  3242. // }
  3243. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  3244. {
  3245. bool addType = true;
  3246. auto checkType = usedType;
  3247. PopulateType(checkType, BfPopulateType_Data);
  3248. if (checkType->IsValuelessType())
  3249. addType = false;
  3250. else if (checkType->IsPrimitiveType())
  3251. addType = false;
  3252. else
  3253. {
  3254. auto checkTypeInst = checkType->ToTypeInstance();
  3255. if (checkTypeInst == NULL)
  3256. {
  3257. addType = false;
  3258. }
  3259. else
  3260. {
  3261. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  3262. addType = false;
  3263. }
  3264. }
  3265. if (addType)
  3266. {
  3267. auto checkTypeInst = checkType->ToTypeInstance();
  3268. if (checkTypeInst->mHotTypeData != NULL)
  3269. {
  3270. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  3271. BF_ASSERT(hotTypeVersion != NULL);
  3272. if (hotTypeVersion != NULL)
  3273. {
  3274. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  3275. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  3276. (checkType->IsComposite()))
  3277. isAllocation = true;
  3278. if (isAllocation)
  3279. {
  3280. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  3281. }
  3282. else
  3283. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  3284. }
  3285. }
  3286. }
  3287. }
  3288. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  3289. {
  3290. auto usingModule = userType->GetModule();
  3291. BfModule* usedModule;
  3292. if (usedType->IsFunction())
  3293. {
  3294. if (mCompiler->mFunctionTypeDef != NULL)
  3295. {
  3296. auto functionType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  3297. usedModule = functionType->GetModule();
  3298. }
  3299. }
  3300. else
  3301. usedModule = usedType->GetModule();
  3302. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  3303. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  3304. {
  3305. if ((flags & ~(BfDependencyMap::DependencyFlag_OuterType)) == 0)
  3306. {
  3307. // Not a 'use' dependency
  3308. }
  3309. else
  3310. {
  3311. usingModule->mModuleRefs.Add(usedModule);
  3312. }
  3313. }
  3314. }
  3315. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  3316. {
  3317. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  3318. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  3319. if (genericArg == usedType)
  3320. return;
  3321. }
  3322. auto depFlag = flags;
  3323. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  3324. {
  3325. if (usedType->IsDependendType())
  3326. {
  3327. // Cause a rebuild but not an outright deletion of the type
  3328. // We can only do this if the 'usedType' can actually hold the dependency which can actually trigger a deletion chain
  3329. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef;
  3330. }
  3331. }
  3332. if (usedType->IsTypeAlias())
  3333. {
  3334. auto underlyingType = usedType->GetUnderlyingType();
  3335. if (underlyingType != NULL)
  3336. {
  3337. BfDepContext newDepContext;
  3338. if (depContext == NULL)
  3339. depContext = &newDepContext;
  3340. if (++depContext->mAliasDepth > 8)
  3341. {
  3342. if (!depContext->mDeepSeenAliases.Add(underlyingType))
  3343. return; // Circular!
  3344. }
  3345. AddDependency(underlyingType, userType, depFlag);
  3346. }
  3347. }
  3348. else if (!usedType->IsGenericTypeInstance())
  3349. {
  3350. auto underlyingType = usedType->GetUnderlyingType();
  3351. if (underlyingType != NULL)
  3352. AddDependency(underlyingType, userType, depFlag);
  3353. }
  3354. BfDependedType* checkDType = usedType->ToDependedType();
  3355. if (checkDType == NULL)
  3356. return;
  3357. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  3358. mContext->MarkAsReferenced(checkDType);
  3359. #ifdef _DEBUG
  3360. // If a MethodRef depends ON US, that means it's a local method that we own
  3361. if (userType->IsMethodRef())
  3362. {
  3363. auto methodRefType = (BfMethodRefType*)userType;
  3364. BF_ASSERT(methodRefType->mOwner == checkDType);
  3365. }
  3366. #endif
  3367. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  3368. return;
  3369. if ((checkDType->IsGenericTypeInstance()) && (!userType->IsMethodRef()))
  3370. {
  3371. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  3372. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3373. {
  3374. AddDependency(genericArg, userType, depFlag);
  3375. }
  3376. }
  3377. if (checkDType->IsTuple())
  3378. {
  3379. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  3380. {
  3381. if (field.mDataIdx != -1)
  3382. AddDependency(field.mResolvedType, userType, depFlag);
  3383. }
  3384. }
  3385. }
  3386. void BfModule::AddDependency(BfGenericParamInstance* genericParam, BfTypeInstance* usingType)
  3387. {
  3388. if ((genericParam->mExternType != NULL) && (!genericParam->mExternType->IsGenericParam()))
  3389. AddDependency(genericParam->mExternType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3390. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  3391. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3392. for (auto& operatorConstraint : genericParam->mOperatorConstraints)
  3393. {
  3394. if (operatorConstraint.mLeftType != NULL)
  3395. AddDependency(operatorConstraint.mLeftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3396. if (operatorConstraint.mRightType != NULL)
  3397. AddDependency(operatorConstraint.mRightType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3398. }
  3399. if (genericParam->mTypeConstraint != NULL)
  3400. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3401. }
  3402. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  3403. {
  3404. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  3405. {
  3406. if (methodInstance->mHotMethod == NULL)
  3407. CheckHotMethod(methodInstance, "");
  3408. BF_ASSERT(methodInstance->mHotMethod != NULL);
  3409. if (devirtualized)
  3410. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  3411. else
  3412. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  3413. }
  3414. }
  3415. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  3416. {
  3417. auto checkTypeInst = typeInst;
  3418. while (checkTypeInst != NULL)
  3419. {
  3420. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  3421. return true;
  3422. checkTypeInst = checkTypeInst->mBaseType;
  3423. }
  3424. return false;
  3425. }
  3426. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  3427. {
  3428. if (mContext->mCurTypeState == NULL)
  3429. return;
  3430. BP_ZONE("PopulateGlobalContainersList");
  3431. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  3432. if ((userTypeDef == NULL) && (mCurMethodInstance != NULL))
  3433. userTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  3434. if (userTypeDef == NULL)
  3435. userTypeDef = mCurTypeInstance->mTypeDef;
  3436. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  3437. {
  3438. mContext->mCurTypeState->mGlobalContainers.Clear();
  3439. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  3440. {
  3441. BfAtomComposite findStr;
  3442. if (namespaceIdx != -1)
  3443. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  3444. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  3445. while (typeDefItr)
  3446. {
  3447. auto typeDef = *typeDefItr;
  3448. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  3449. {
  3450. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  3451. {
  3452. BfGlobalContainerEntry globalEntry;
  3453. globalEntry.mTypeDef = typeDef;
  3454. globalEntry.mTypeInst = NULL;
  3455. typeDef->PopulateMemberSets();
  3456. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  3457. }
  3458. }
  3459. else if (!typeDef->mIsPartial)
  3460. {
  3461. //break;
  3462. }
  3463. typeDefItr.MoveToNextHashMatch();
  3464. }
  3465. }
  3466. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  3467. }
  3468. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  3469. // reifing types
  3470. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  3471. {
  3472. if (globalEntry.mTypeInst == NULL)
  3473. {
  3474. bool include = false;
  3475. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  3476. include = true;
  3477. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  3478. {
  3479. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  3480. include = true;
  3481. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  3482. include = true;
  3483. }
  3484. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  3485. {
  3486. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  3487. include = true;
  3488. }
  3489. if (include)
  3490. {
  3491. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  3492. if (type != NULL)
  3493. globalEntry.mTypeInst = type->ToTypeInstance();
  3494. }
  3495. }
  3496. }
  3497. }
  3498. BfStaticSearch* BfModule::GetStaticSearch()
  3499. {
  3500. auto activeTypeDef = GetActiveTypeDef();
  3501. BfStaticSearch* staticSearch = NULL;
  3502. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3503. return staticSearch;
  3504. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3505. return staticSearch;
  3506. return NULL;
  3507. }
  3508. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  3509. {
  3510. auto activeTypeDef = GetActiveTypeDef();
  3511. BfInternalAccessSet* internalAccessSet = NULL;
  3512. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3513. return internalAccessSet;
  3514. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3515. return internalAccessSet;
  3516. return NULL;
  3517. }
  3518. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  3519. {
  3520. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  3521. return true;
  3522. if ((mCurMethodInstance != NULL) &&
  3523. ((mCurMethodInstance->mIsUnspecializedVariation) || (mCurMethodInstance->IsSpecializedGenericMethod())))
  3524. return true;
  3525. auto internalAccessSet = GetInternalAccessSet();
  3526. if (internalAccessSet == NULL)
  3527. return false;
  3528. for (auto& nameComposite : internalAccessSet->mNamespaces)
  3529. {
  3530. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  3531. return true;
  3532. }
  3533. for (auto internalType : internalAccessSet->mTypes)
  3534. {
  3535. auto checkTypeDef = usingTypeDef->GetDefinition();
  3536. while (checkTypeDef != NULL)
  3537. {
  3538. if (checkTypeDef == internalType->mTypeDef->GetDefinition())
  3539. return true;
  3540. checkTypeDef = checkTypeDef->mOuterType;
  3541. }
  3542. }
  3543. return false;
  3544. }
  3545. void PrintUsers(llvm::MDNode* md);
  3546. BfModuleOptions BfModule::GetModuleOptions()
  3547. {
  3548. if (mIsScratchModule)
  3549. return BfModuleOptions();
  3550. if (mModuleOptions != NULL)
  3551. return *mModuleOptions;
  3552. BfModuleOptions moduleOptions;
  3553. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3554. if (mProject != NULL)
  3555. {
  3556. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3557. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3558. }
  3559. auto headModule = this;
  3560. while (headModule->mParentModule != NULL)
  3561. headModule = headModule->mParentModule;
  3562. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata") || mIsSpecialModule);
  3563. if (headModule->mOwnedTypeInstances.size() > 0)
  3564. {
  3565. auto typeInst = headModule->mOwnedTypeInstances[0];
  3566. if (typeInst->mTypeOptionsIdx == -2)
  3567. PopulateType(typeInst);
  3568. if (typeInst->mTypeOptionsIdx != -1)
  3569. {
  3570. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3571. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3572. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3573. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3574. }
  3575. }
  3576. return moduleOptions;
  3577. }
  3578. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3579. {
  3580. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3581. return BfCheckedKind_Unchecked;
  3582. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3583. auto typeOptions = GetTypeOptions();
  3584. if (typeOptions != NULL)
  3585. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3586. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3587. }
  3588. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3589. {
  3590. BF_ASSERT(typeInstance != NULL);
  3591. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_InFailTypes) != 0)
  3592. return;
  3593. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_InFailTypes);
  3594. mContext->mFailTypes.TryAdd(typeInstance, BfFailKind_Normal);
  3595. }
  3596. void BfModule::DeferRebuildType(BfTypeInstance* typeInstance)
  3597. {
  3598. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_RebuildQueued) != 0)
  3599. return;
  3600. mCompiler->mHasQueuedTypeRebuilds = true;
  3601. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_RebuildQueued);
  3602. AddFailType(typeInstance);
  3603. }
  3604. void BfModule::CheckAddFailType()
  3605. {
  3606. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3607. // but we still need to add the owning type to the FailTypes list
  3608. //.. OLD:
  3609. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3610. /*if (mCurTypeInstance->mModule != this)
  3611. return;*/
  3612. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3613. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3614. // being recompiled. This forces types with warnings to be recompiled.
  3615. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3616. // constantly warning-aware
  3617. if ((mHadBuildError) ||
  3618. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3619. {
  3620. //mContext->mFailTypes.Add(mCurTypeInstance);
  3621. }
  3622. }
  3623. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3624. {
  3625. if (!mCompiler->IsHotCompile())
  3626. return;
  3627. typeInst->mDirty = true;
  3628. for (auto& dep : typeInst->mDependencyMap)
  3629. {
  3630. auto depType = dep.mKey;
  3631. auto depFlags = dep.mValue.mFlags;
  3632. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3633. {
  3634. MarkDerivedDirty(depType->ToTypeInstance());
  3635. }
  3636. }
  3637. }
  3638. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3639. {
  3640. auto fieldType = fieldInstance->GetResolvedType();
  3641. auto field = fieldInstance->GetFieldDef();
  3642. if (fieldType->IsVar())
  3643. return;
  3644. BfIRValue initValue;
  3645. if (field->mIsConst)
  3646. {
  3647. if (fieldType->IsPointer())
  3648. fieldType = fieldType->GetUnderlyingType();
  3649. }
  3650. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3651. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3652. storageKind = BfIRStorageKind_Export;
  3653. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3654. storageKind = BfIRStorageKind_Import;
  3655. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3656. initValue = GetDefaultValue(fieldType);
  3657. if (fieldInstance->mOwner->IsUnspecializedType())
  3658. {
  3659. // Placeholder
  3660. auto ptrVal = CreatePointerType(fieldType);
  3661. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3662. }
  3663. else
  3664. {
  3665. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3666. StringT<4096> staticVarName;
  3667. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3668. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3669. {
  3670. BfIRType irType;
  3671. if (fieldInstance->IsAppendedObject())
  3672. {
  3673. irType = mBfIRBuilder->MapTypeInst(fieldType->ToTypeInstance(), BfIRPopulateType_Eventually_Full);
  3674. initValue = mBfIRBuilder->CreateConstAggZero(irType);
  3675. }
  3676. else
  3677. irType = mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full);
  3678. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3679. irType,
  3680. false,
  3681. BfIRLinkageType_External,
  3682. initValue,
  3683. staticVarName,
  3684. isThreadLocal);
  3685. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3686. if (storageKind != BfIRStorageKind_Normal)
  3687. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3688. BF_ASSERT(globalVar);
  3689. mStaticFieldRefs[fieldInstance] = globalVar;
  3690. }
  3691. }
  3692. }
  3693. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3694. {
  3695. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3696. BfType* fieldType = NULL;
  3697. if (fieldInstance != NULL)
  3698. {
  3699. fieldType = fieldInstance->GetResolvedType();
  3700. if (fieldType == NULL)
  3701. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3702. }
  3703. else
  3704. {
  3705. BF_ASSERT(mCompiler->IsAutocomplete());
  3706. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3707. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3708. {
  3709. fieldType = typeInstance;
  3710. }
  3711. else
  3712. {
  3713. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3714. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3715. if (isLet || isVar)
  3716. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3717. else
  3718. fieldType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  3719. if (fieldType == NULL)
  3720. fieldType = mContext->mBfObjectType;
  3721. }
  3722. }
  3723. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3724. return;
  3725. if (mContext->mFieldResolveReentrys.size() > 1)
  3726. {
  3727. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3728. {
  3729. String failStr = "Circular data reference detected between the following fields:";
  3730. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3731. {
  3732. if (i > 1)
  3733. failStr += ",";
  3734. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3735. }
  3736. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3737. if (err)
  3738. err->mIsPersistent = true;
  3739. return;
  3740. }
  3741. }
  3742. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3743. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3744. if (fieldInstance == NULL)
  3745. popTypeResolveReentry.Pop();
  3746. auto typeDef = typeInstance->mTypeDef;
  3747. BfIRValue constValue;
  3748. if (fieldDef->mIsExtern)
  3749. {
  3750. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3751. {
  3752. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3753. Fail("Extern consts must be pointer types", fieldDef->mTypeRef);
  3754. }
  3755. if (fieldDef->GetInitializer() != NULL)
  3756. {
  3757. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3758. Fail("Extern consts cannot have initializers", fieldDef->GetNameNode());
  3759. }
  3760. }
  3761. else if (fieldDef->GetInitializer() == NULL)
  3762. {
  3763. if (fieldDef->IsEnumCaseEntry())
  3764. {
  3765. if (typeInstance->IsTypedPrimitive())
  3766. {
  3767. BfFieldInstance* prevFieldInstance = NULL;
  3768. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3769. {
  3770. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3771. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3772. {
  3773. prevFieldInstance = checkFieldInst;
  3774. break;
  3775. }
  3776. }
  3777. if (prevFieldInstance == NULL)
  3778. constValue = GetConstValue(0, typeInstance);
  3779. else
  3780. {
  3781. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3782. if (prevFieldInstance->mConstIdx == -1)
  3783. {
  3784. if (!mCompiler->IsAutocomplete())
  3785. AssertErrorState();
  3786. constValue = GetConstValue(0, typeInstance);
  3787. }
  3788. else
  3789. {
  3790. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3791. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3792. }
  3793. }
  3794. }
  3795. }
  3796. else
  3797. {
  3798. Fail("Const requires initializer", fieldDef->GetNameNode());
  3799. }
  3800. }
  3801. else if (mBfIRBuilder != NULL)
  3802. {
  3803. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3804. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3805. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3806. BfMethodState methodState;
  3807. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3808. methodState.mTempKind = BfMethodState::TempKind_Static;
  3809. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3810. if ((fieldType->IsVar()) || (fieldType->IsUndefSizedArray()))
  3811. {
  3812. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3813. if (!initValue)
  3814. {
  3815. AssertErrorState();
  3816. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3817. }
  3818. if (fieldInstance != NULL)
  3819. {
  3820. if (fieldType->IsUndefSizedArray())
  3821. {
  3822. if ((initValue.mType->IsSizedArray()) && (initValue.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3823. {
  3824. fieldInstance->mResolvedType = initValue.mType;
  3825. }
  3826. }
  3827. else
  3828. fieldInstance->mResolvedType = initValue.mType;
  3829. }
  3830. constValue = initValue.mValue;
  3831. }
  3832. else
  3833. {
  3834. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3835. constValue = uncastedInitValue.mValue;
  3836. }
  3837. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3838. {
  3839. // Illegal
  3840. constValue = BfIRValue();
  3841. }
  3842. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3843. }
  3844. if (fieldInstance != NULL)
  3845. {
  3846. fieldType = fieldInstance->GetResolvedType();
  3847. if ((fieldType == NULL) || (fieldType->IsVar()))
  3848. {
  3849. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3850. AssertErrorState();
  3851. // Default const type is 'int'
  3852. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3853. if (fieldInstance != NULL)
  3854. {
  3855. fieldInstance->mResolvedType = initValue.mType;
  3856. }
  3857. constValue = initValue.mValue;
  3858. }
  3859. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3860. {
  3861. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3862. CurrentAddToConstHolder(constValue);
  3863. fieldInstance->mConstIdx = constValue.mId;
  3864. }
  3865. }
  3866. }
  3867. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3868. {
  3869. bool isDeclType = (field->mFieldDeclaration != NULL) && BfNodeDynCastExact<BfExprModTypeRef>(field->mTypeRef) != NULL;
  3870. auto fieldType = fieldInstance->GetResolvedType();
  3871. if ((field->mIsConst) && (!isDeclType))
  3872. {
  3873. ResolveConstField(typeInstance, fieldInstance, field);
  3874. return fieldInstance->GetResolvedType();
  3875. }
  3876. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3877. if (!fieldInstance->mIsInferredType)
  3878. return fieldType;
  3879. if ((!fieldType->IsVar()) && (!fieldType->IsUndefSizedArray()))
  3880. return fieldType;
  3881. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3882. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3883. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mType != typeInstance);
  3884. auto typeDef = typeInstance->mTypeDef;
  3885. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3886. {
  3887. AssertErrorState();
  3888. return fieldType;
  3889. }
  3890. bool hadInferenceCycle = false;
  3891. if (mContext->mFieldResolveReentrys.size() > 1)
  3892. {
  3893. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3894. {
  3895. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3896. {
  3897. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3898. auto fieldDef = fieldInst->GetFieldDef();
  3899. auto fieldOwner = fieldInst->mOwner;
  3900. auto fieldModule = fieldOwner->mModule;
  3901. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3902. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3903. }
  3904. return fieldType;
  3905. }
  3906. }
  3907. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3908. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3909. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3910. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3911. if ((field->GetInitializer() == NULL) && (!isDeclType))
  3912. {
  3913. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3914. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3915. return fieldType;
  3916. }
  3917. BfType* resolvedType = NULL;
  3918. if (!hadInferenceCycle)
  3919. {
  3920. BfTypeState typeState;
  3921. typeState.mPrevState = mContext->mCurTypeState;
  3922. typeState.mType = typeInstance;
  3923. typeState.mCurFieldDef = field;
  3924. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3925. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3926. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3927. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3928. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3929. BfMethodState methodState;
  3930. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3931. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3932. if (!staticOnly)
  3933. {
  3934. //BfLocalVariable localVar;
  3935. //methodState.mLocals.push_back(localVar);
  3936. }
  3937. if (isDeclType)
  3938. {
  3939. auto fieldDef = fieldInstance->GetFieldDef();
  3940. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3941. }
  3942. else
  3943. {
  3944. BfTypedValue valueFromExpr;
  3945. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3946. FixIntUnknown(valueFromExpr);
  3947. if (fieldType->IsUndefSizedArray())
  3948. {
  3949. if ((valueFromExpr.mType != NULL) && (valueFromExpr.mType->IsSizedArray()) && (valueFromExpr.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3950. resolvedType = valueFromExpr.mType;
  3951. }
  3952. else
  3953. resolvedType = valueFromExpr.mType;
  3954. }
  3955. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3956. }
  3957. if (resolvedType == NULL)
  3958. return fieldType;
  3959. fieldInstance->SetResolvedType(resolvedType);
  3960. if (field->mIsStatic)
  3961. {
  3962. }
  3963. else if (fieldInstance->mDataIdx >= 0)
  3964. {
  3965. }
  3966. else
  3967. {
  3968. BF_ASSERT(typeInstance->IsIncomplete());
  3969. }
  3970. return resolvedType;
  3971. }
  3972. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3973. {
  3974. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3975. auto fieldType = fieldInstance->GetResolvedType();
  3976. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3977. {
  3978. int fieldIdx = 0;
  3979. int fieldCount = 0;
  3980. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  3981. fieldIdx--;
  3982. int count = fieldCount;
  3983. if (fieldIdx == -1)
  3984. count = 1;
  3985. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3986. auto thisVariable = GetThisVariable();
  3987. if (thisVariable != NULL)
  3988. {
  3989. for (int i = 0; i < count; i++)
  3990. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  3991. }
  3992. }
  3993. }
  3994. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3995. {
  3996. if (fieldInstance->mCustomAttributes == NULL)
  3997. return false;
  3998. auto fieldDef = fieldInstance->GetFieldDef();
  3999. if (!fieldDef->mIsStatic)
  4000. return false;
  4001. bool isThreadLocal = false;
  4002. if (fieldInstance->mCustomAttributes != NULL)
  4003. {
  4004. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4005. {
  4006. if (customAttr.mType->ToTypeInstance()->IsInstanceOf(mCompiler->mThreadStaticAttributeTypeDef))
  4007. return true;
  4008. }
  4009. }
  4010. return false;
  4011. }
  4012. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  4013. {
  4014. if (fieldDef == NULL)
  4015. fieldDef = fieldInstance->GetFieldDef();
  4016. if (fieldType == NULL)
  4017. fieldType = fieldInstance->GetResolvedType();
  4018. if (initializer == NULL)
  4019. {
  4020. if (fieldDef == NULL)
  4021. return BfTypedValue();
  4022. initializer = fieldDef->GetInitializer();
  4023. }
  4024. BfTypedValue staticVarRef;
  4025. BfTypedValue result;
  4026. if (initializer == NULL)
  4027. {
  4028. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  4029. }
  4030. else
  4031. {
  4032. if (mCompiler->mIsResolveOnly)
  4033. {
  4034. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  4035. {
  4036. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  4037. sourceClassifier->VisitChildNoRef(initializer);
  4038. }
  4039. }
  4040. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  4041. {
  4042. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  4043. BfConstResolver constResolver(this);
  4044. constResolver.Resolve(initializer);
  4045. return GetDefaultTypedValue(fieldType);
  4046. }
  4047. else if (mCurTypeInstance->IsUnspecializedTypeVariation())
  4048. {
  4049. return GetDefaultTypedValue(fieldType);
  4050. }
  4051. else if (fieldDef->mIsConst)
  4052. {
  4053. int ceExecuteId = -1;
  4054. if (mCompiler->mCeMachine != NULL)
  4055. ceExecuteId = mCompiler->mCeMachine->mExecuteId;
  4056. BfTypeState typeState;
  4057. typeState.mType = mCurTypeInstance;
  4058. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  4059. typeState.mCurFieldDef = fieldDef;
  4060. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  4061. BfConstResolver constResolver(this);
  4062. if (fieldType->IsVar())
  4063. return constResolver.Resolve(initializer);
  4064. else
  4065. {
  4066. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  4067. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  4068. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  4069. {
  4070. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  4071. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  4072. resolveFlags = BfConstResolveFlag_NoCast;
  4073. }
  4074. UpdateSrcPos(initializer);
  4075. auto result = constResolver.Resolve(initializer, fieldType, resolveFlags);
  4076. if ((mCompiler->mCeMachine != NULL) && (fieldInstance != NULL))
  4077. {
  4078. if (mCompiler->mCeMachine->mExecuteId != ceExecuteId)
  4079. fieldInstance->mHadConstEval = true;
  4080. }
  4081. if (auto autoComplete = mCompiler->GetAutoComplete())
  4082. autoComplete->CheckResult(initializer, result);
  4083. return result;
  4084. }
  4085. }
  4086. BfExprEvaluator exprEvaluator(this);
  4087. if (doStore)
  4088. {
  4089. staticVarRef = ReferenceStaticField(fieldInstance);
  4090. exprEvaluator.mReceivingValue = &staticVarRef;
  4091. }
  4092. if (fieldType->IsVar())
  4093. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4094. else
  4095. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4096. if (doStore)
  4097. {
  4098. if (exprEvaluator.mReceivingValue == NULL)
  4099. doStore = false; // Already stored
  4100. }
  4101. }
  4102. if (fieldInstance != NULL)
  4103. MarkFieldInitialized(fieldInstance);
  4104. if ((doStore) && (result))
  4105. {
  4106. if (fieldInstance->mResolvedType->IsUndefSizedArray())
  4107. {
  4108. if ((!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mFastFinish))
  4109. AssertErrorState();
  4110. }
  4111. else
  4112. {
  4113. result = LoadValue(result);
  4114. if (!result.mType->IsValuelessType())
  4115. mBfIRBuilder->CreateAlignedStore(result.mValue, staticVarRef.mValue, result.mType->mAlign);
  4116. }
  4117. }
  4118. return result;
  4119. }
  4120. void BfModule::AppendedObjectInit(BfFieldInstance* fieldInst)
  4121. {
  4122. BfExprEvaluator exprEvaluator(this);
  4123. bool failed = false;
  4124. auto fieldDef = fieldInst->GetFieldDef();
  4125. auto initializer = fieldDef->GetInitializer();
  4126. BfResolvedArgs resolvedArgs;
  4127. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(initializer))
  4128. {
  4129. bool isDot = false;
  4130. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  4131. isDot = (memberRefExpr->mTarget == NULL) && (memberRefExpr->mMemberName == NULL);
  4132. if (!isDot)
  4133. {
  4134. auto resolvedType = ResolveTypeRef(invocationExpr->mTarget, {});
  4135. if ((resolvedType == NULL) || (resolvedType != fieldInst->mResolvedType))
  4136. failed = true;
  4137. }
  4138. SetAndRestoreValue<BfType*> prevExpectingType(exprEvaluator.mExpectingType, fieldInst->mResolvedType);
  4139. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  4140. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  4141. }
  4142. else if (initializer != NULL)
  4143. {
  4144. GetFieldInitializerValue(fieldInst);
  4145. failed = true;
  4146. }
  4147. if (failed)
  4148. Fail("Append fields can only be initialized with a call to their constructor", initializer);
  4149. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  4150. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4151. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4152. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  4153. auto fieldTypeInst = fieldInst->mResolvedType->ToTypeInstance();
  4154. BfIRValue fieldAddr;
  4155. if (fieldDef->mIsStatic)
  4156. {
  4157. fieldAddr = ReferenceStaticField(fieldInst).mValue;
  4158. }
  4159. else
  4160. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  4161. auto thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  4162. auto indexVal = BfTypedValue(CreateAlloca(intType), CreateRefType(intType));
  4163. auto intThisVal = mBfIRBuilder->CreatePtrToInt(thisValue.mValue, (intType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  4164. auto curValPtr = mBfIRBuilder->CreateAdd(intThisVal, GetConstValue(fieldTypeInst->mInstSize, intType));
  4165. mBfIRBuilder->CreateStore(curValPtr, indexVal.mValue);
  4166. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 0);
  4167. auto vDataRef = CreateClassVDataGlobal(fieldInst->mResolvedType->ToTypeInstance());
  4168. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  4169. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  4170. mBfIRBuilder->CreateStore(srcVal, destAddr);
  4171. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  4172. {
  4173. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4174. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4175. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(thisValue.mValue, ptrType);
  4176. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_AppendAlloc), thisFlagsPtr);
  4177. }
  4178. exprEvaluator.MatchConstructor(fieldDef->GetNameNode(), NULL, thisValue, fieldInst->mResolvedType->ToTypeInstance(), resolvedArgs, false, BfMethodGenericArguments(), true, &indexVal);
  4179. }
  4180. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  4181. {
  4182. }
  4183. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  4184. {
  4185. PopulateType(classType);
  4186. if (isInterfacePass)
  4187. {
  4188. for (auto ifaceInst : classType->mInterfaces)
  4189. {
  4190. if (exChecks->Contains(ifaceInst.mInterfaceType))
  4191. continue;
  4192. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  4193. continue;
  4194. if (ifaceInst.mDeclaringType->IsExtension())
  4195. {
  4196. bool needsExCheck = false;
  4197. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  4198. {
  4199. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  4200. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  4201. {
  4202. exChecks->push_back(ifaceInst.mInterfaceType);
  4203. continue;
  4204. }
  4205. else
  4206. {
  4207. // We can only do an 'exCheck' if we're actually going to slot this interface
  4208. }
  4209. }
  4210. }
  4211. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  4212. }
  4213. }
  4214. else
  4215. {
  4216. outVals->push_back(classType->mTypeId);
  4217. }
  4218. if (classType->mBaseType != NULL)
  4219. {
  4220. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  4221. }
  4222. }
  4223. void BfModule::CreateDynamicCastMethod()
  4224. {
  4225. auto objType = mContext->mBfObjectType;
  4226. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  4227. {
  4228. // The main reason to punt on this method for ResolveOnly is because types can be created
  4229. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  4230. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  4231. // remove this punt when we recycle typeId's
  4232. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  4233. mCurMethodState->mHadReturn = true;
  4234. return;
  4235. }
  4236. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  4237. auto func = mCurMethodState->mIRFunction;
  4238. auto thisValue = mBfIRBuilder->GetArgument(0);
  4239. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  4240. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4241. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  4242. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  4243. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  4244. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  4245. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  4246. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4247. SizedArray<int, 8> typeMatches;
  4248. SizedArray<BfTypeInstance*, 8> exChecks;
  4249. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  4250. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  4251. {
  4252. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  4253. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  4254. BfTypeVector genericArgs;
  4255. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  4256. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  4257. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef->GetDefinition(), genericArgs, BfPopulateType_Declaration);
  4258. typeMatches.push_back(unboundType->mTypeId);
  4259. }
  4260. if (mCurTypeInstance->IsBoxed())
  4261. {
  4262. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  4263. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  4264. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  4265. if (innerType->IsTypedPrimitive())
  4266. {
  4267. auto underlyingType = innerType->GetUnderlyingType();
  4268. typeMatches.push_back(underlyingType->mTypeId);
  4269. }
  4270. auto innerTypeInst = innerType->ToTypeInstance();
  4271. if ((innerTypeInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef)) ||
  4272. (innerTypeInst->IsInstanceOf(mCompiler->mPointerTTypeDef)) ||
  4273. (innerTypeInst->IsInstanceOf(mCompiler->mMethodRefTypeDef)))
  4274. {
  4275. PopulateType(innerTypeInst);
  4276. //TODO: What case was this supposed to handle?
  4277. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  4278. }
  4279. }
  4280. auto curBlock = mBfIRBuilder->GetInsertBlock();
  4281. BfIRValue vDataPtr;
  4282. if (!exChecks.empty())
  4283. {
  4284. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4285. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  4286. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  4287. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4288. }
  4289. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  4290. for (auto typeMatch : typeMatches)
  4291. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  4292. Array<BfIRValue> incomingFalses;
  4293. for (auto ifaceTypeInst : exChecks)
  4294. {
  4295. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  4296. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  4297. mBfIRBuilder->SetInsertPoint(nextBB);
  4298. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  4299. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4300. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4301. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4302. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  4303. incomingFalses.push_back(nextBB);
  4304. }
  4305. mBfIRBuilder->AddBlock(trueBB);
  4306. mBfIRBuilder->SetInsertPoint(trueBB);
  4307. mBfIRBuilder->CreateBr(exitBB);
  4308. mBfIRBuilder->AddBlock(exitBB);
  4309. mBfIRBuilder->SetInsertPoint(exitBB);
  4310. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  4311. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  4312. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  4313. for (auto incomingFalseBlock : incomingFalses)
  4314. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  4315. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  4316. mBfIRBuilder->CreateRet(phi);
  4317. mCurMethodState->mHadReturn = true;
  4318. }
  4319. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  4320. {
  4321. BfExprEvaluator exprEvaluator(this);
  4322. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  4323. auto typeInst = rightValue.mType->ToTypeInstance();
  4324. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  4325. BfTypedValue result = exprEvaluator.GetResult();
  4326. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  4327. {
  4328. // Fail?
  4329. }
  4330. if ((result) && (!result.mType->IsVar()))
  4331. {
  4332. auto nextBB = mBfIRBuilder->CreateBlock("next");
  4333. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  4334. mBfIRBuilder->AddBlock(nextBB);
  4335. mBfIRBuilder->SetInsertPoint(nextBB);
  4336. }
  4337. }
  4338. void BfModule::CreateFakeCallerMethod(const String& funcName)
  4339. {
  4340. if (mCurMethodInstance->mHasFailed)
  4341. return;
  4342. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  4343. return;
  4344. BF_ASSERT(mCurMethodInstance->mIRFunction);
  4345. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  4346. SizedArray<BfIRType, 4> paramTypes;
  4347. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  4348. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  4349. mBfIRBuilder->SetActiveFunction(func);
  4350. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  4351. mBfIRBuilder->SetInsertPoint(entryBlock);
  4352. BfMethodState methodState;
  4353. methodState.mIRHeadBlock = entryBlock;
  4354. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4355. SizedArray<BfIRValue, 8> args;
  4356. BfExprEvaluator exprEvaluator(this);
  4357. if (mCurMethodInstance->GetStructRetIdx() == 0)
  4358. {
  4359. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4360. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4361. }
  4362. if (mCurMethodInstance->HasThis())
  4363. {
  4364. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  4365. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  4366. }
  4367. if (mCurMethodInstance->GetStructRetIdx() == 1)
  4368. {
  4369. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4370. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4371. }
  4372. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  4373. {
  4374. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  4375. if (paramType->IsValuelessType())
  4376. continue;
  4377. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  4378. }
  4379. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  4380. mBfIRBuilder->CreateRetVoid();
  4381. }
  4382. void BfModule::CreateDelegateEqualsMethod()
  4383. {
  4384. if (mBfIRBuilder->mIgnoreWrites)
  4385. return;
  4386. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4387. if (refNode == NULL)
  4388. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4389. UpdateSrcPos(refNode);
  4390. SetIllegalSrcPos();
  4391. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4392. auto resultVal = CreateAlloca(boolType);
  4393. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4394. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4395. auto delegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  4396. mBfIRBuilder->PopulateType(delegateType);
  4397. BfExprEvaluator exprEvaluator(this);
  4398. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4399. BfTypedValue lhsDelegate = BfTypedValue(mBfIRBuilder->CreateBitCast(leftTypedVal.mValue, mBfIRBuilder->MapType(delegateType)), delegateType);
  4400. BfTypedValue rhsDelegate = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4401. rhsDelegate = LoadValue(rhsDelegate);
  4402. BfTypedValue rightTypedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(rhsDelegate.mValue, mBfIRBuilder->MapType(mCurTypeInstance)), mCurTypeInstance);
  4403. auto& targetFieldInstance = delegateType->mFieldInstances[0];
  4404. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(lhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4405. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4406. leftValue = LoadValue(leftValue);
  4407. rightValue = LoadValue(rightValue);
  4408. EmitEquals(leftValue, rightValue, exitBB, false);
  4409. bool hadComparison = false;
  4410. for (auto& fieldRef : mCurTypeInstance->mFieldInstances)
  4411. {
  4412. BfFieldInstance* fieldInstance = &fieldRef;
  4413. if (fieldInstance->mDataOffset == -1)
  4414. continue;
  4415. auto fieldType = fieldInstance->mResolvedType;
  4416. if (fieldType->IsValuelessType())
  4417. continue;
  4418. if (fieldType->IsVar())
  4419. continue;
  4420. if (fieldType->IsMethodRef())
  4421. continue;
  4422. if (fieldType->IsRef())
  4423. fieldType = CreatePointerType(fieldType->GetUnderlyingType());
  4424. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(leftTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4425. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rightTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4426. if (!fieldInstance->mResolvedType->IsComposite())
  4427. {
  4428. leftValue = LoadValue(leftValue);
  4429. rightValue = LoadValue(rightValue);
  4430. }
  4431. EmitEquals(leftValue, rightValue, exitBB, false);
  4432. }
  4433. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4434. mBfIRBuilder->CreateBr(exitBB);
  4435. mBfIRBuilder->AddBlock(exitBB);
  4436. mBfIRBuilder->SetInsertPoint(exitBB);
  4437. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4438. ClearLifetimeEnds();
  4439. mBfIRBuilder->CreateRet(loadedResult);
  4440. mCurMethodState->mHadReturn = true;
  4441. }
  4442. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  4443. {
  4444. if (mCurMethodInstance->mIsUnspecialized)
  4445. return;
  4446. if (mBfIRBuilder->mIgnoreWrites)
  4447. return;
  4448. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  4449. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  4450. bool isValid = true;
  4451. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4452. if (compareType->IsValuelessType())
  4453. {
  4454. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4455. return;
  4456. }
  4457. if (compareType->IsTypedPrimitive())
  4458. {
  4459. BfExprEvaluator exprEvaluator(this);
  4460. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  4461. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  4462. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  4463. mBfIRBuilder->CreateRet(cmpResult);
  4464. return;
  4465. }
  4466. auto compareDType = compareType->ToDependedType();
  4467. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  4468. if (compareTypeInst != NULL)
  4469. {
  4470. if (compareType->IsPrimitiveType())
  4471. compareTypeInst = GetWrappedStructType(compareType);
  4472. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  4473. {
  4474. isValid = false;
  4475. }
  4476. mBfIRBuilder->PopulateType(compareTypeInst);
  4477. }
  4478. if (!isValid)
  4479. {
  4480. ClearLifetimeEnds();
  4481. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4482. return;
  4483. }
  4484. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  4485. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4486. if (refNode == NULL)
  4487. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4488. UpdateSrcPos(refNode);
  4489. SetIllegalSrcPos();
  4490. auto resultVal = CreateAlloca(boolType);
  4491. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4492. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4493. if (compareType->IsValuelessType())
  4494. {
  4495. // Always equal, nothing to do
  4496. }
  4497. else if (compareType->IsSizedArray())
  4498. {
  4499. auto sizedArrayType = (BfSizedArrayType*)compareType;
  4500. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  4501. {
  4502. BfTypedValue result;
  4503. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index, true);
  4504. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4505. if (!result.mType->IsValueType())
  4506. result = LoadValue(result);
  4507. return result;
  4508. };
  4509. if (sizedArrayType->mElementCount > 6)
  4510. {
  4511. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4512. auto itr = CreateAlloca(intPtrType);
  4513. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  4514. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  4515. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  4516. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  4517. mBfIRBuilder->CreateBr(loopBB);
  4518. mBfIRBuilder->SetInsertPoint(loopBB);
  4519. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  4520. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  4521. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  4522. mBfIRBuilder->SetInsertPoint(bodyBB);
  4523. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  4524. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  4525. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4526. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  4527. mBfIRBuilder->CreateStore(incValue, itr);
  4528. mBfIRBuilder->CreateBr(loopBB);
  4529. mBfIRBuilder->SetInsertPoint(doneBB);
  4530. }
  4531. else
  4532. {
  4533. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  4534. {
  4535. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4536. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4537. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4538. }
  4539. }
  4540. }
  4541. else if (compareType->IsMethodRef())
  4542. {
  4543. auto methodRefType = (BfMethodRefType*)compareType;
  4544. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  4545. BfExprEvaluator exprEvaluator(this);
  4546. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4547. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4548. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  4549. // values for the same method reference -- they will always refer back to the same local variables.
  4550. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  4551. if (dataIdx != -1)
  4552. {
  4553. bool failed = false;
  4554. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  4555. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  4556. BF_ASSERT(!failed);
  4557. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4558. }
  4559. }
  4560. else if (compareTypeInst->IsEnum())
  4561. {
  4562. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4563. BfExprEvaluator exprEvaluator(this);
  4564. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4565. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4566. auto dscrType = compareTypeInst->GetDiscriminatorType();
  4567. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  4568. leftValue = LoadValue(leftValue);
  4569. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  4570. rightValue = LoadValue(rightValue);
  4571. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  4572. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  4573. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4574. int enumCount = 0;
  4575. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4576. {
  4577. BfFieldInstance* fieldInstance = &fieldRef;
  4578. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4579. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4580. {
  4581. enumCount = -fieldInstance->mDataIdx;
  4582. }
  4583. }
  4584. if (enumCount > 0)
  4585. {
  4586. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  4587. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  4588. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4589. {
  4590. BfFieldInstance* fieldInstance = &fieldRef;
  4591. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4592. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4593. {
  4594. int enumIdx = -fieldInstance->mDataIdx - 1;
  4595. if (fieldInstance->mResolvedType->mSize == 0)
  4596. {
  4597. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  4598. }
  4599. else
  4600. {
  4601. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  4602. mBfIRBuilder->SetInsertPoint(caseBlock);
  4603. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  4604. BfTypedValue leftTuple;
  4605. BfTypedValue rightTuple;
  4606. if (leftPayload.IsAddr())
  4607. {
  4608. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4609. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4610. }
  4611. else
  4612. {
  4613. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4614. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4615. }
  4616. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  4617. mBfIRBuilder->CreateBr(matchedBlock);
  4618. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  4619. }
  4620. }
  4621. }
  4622. mBfIRBuilder->AddBlock(matchedBlock);
  4623. mBfIRBuilder->SetInsertPoint(matchedBlock);
  4624. }
  4625. }
  4626. else if (compareTypeInst->IsUnion())
  4627. {
  4628. auto innerType = compareTypeInst->GetUnionInnerType();
  4629. if (!innerType->IsValuelessType())
  4630. {
  4631. BfExprEvaluator exprEvaluator(this);
  4632. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4633. leftTypedVal = AggregateSplat(leftTypedVal);
  4634. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  4635. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4636. rightTypedVal = AggregateSplat(rightTypedVal);
  4637. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  4638. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  4639. }
  4640. }
  4641. else
  4642. {
  4643. BfExprEvaluator exprEvaluator(this);
  4644. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4645. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4646. bool hadComparison = false;
  4647. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4648. {
  4649. BfFieldInstance* fieldInstance = &fieldRef;
  4650. if (fieldInstance->mDataOffset == -1)
  4651. continue;
  4652. if (fieldInstance->mResolvedType->IsValuelessType())
  4653. continue;
  4654. if (fieldInstance->mResolvedType->IsVar())
  4655. continue;
  4656. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4657. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4658. if (!fieldInstance->mResolvedType->IsComposite())
  4659. {
  4660. leftValue = LoadValue(leftValue);
  4661. rightValue = LoadValue(rightValue);
  4662. }
  4663. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4664. }
  4665. auto baseTypeInst = compareTypeInst->mBaseType;
  4666. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  4667. {
  4668. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  4669. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  4670. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4671. }
  4672. }
  4673. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4674. mBfIRBuilder->CreateBr(exitBB);
  4675. mBfIRBuilder->AddBlock(exitBB);
  4676. mBfIRBuilder->SetInsertPoint(exitBB);
  4677. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4678. ClearLifetimeEnds();
  4679. mBfIRBuilder->CreateRet(loadedResult);
  4680. mCurMethodState->mHadReturn = true;
  4681. }
  4682. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  4683. {
  4684. if (mBfIRBuilder->mIgnoreWrites)
  4685. return mBfIRBuilder->GetFakeVal();
  4686. PopulateType(typeInstance, mIsComptimeModule ? BfPopulateType_Data : BfPopulateType_DataAndMethods);
  4687. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4688. if (mIsComptimeModule)
  4689. {
  4690. auto idVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, typeInstance->mTypeId);
  4691. return mBfIRBuilder->CreateIntToPtr(idVal, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4692. }
  4693. BfIRValue* globalVariablePtr = NULL;
  4694. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  4695. int numElements = 1;
  4696. if (mSystem->mPtrSize == 4)
  4697. numElements++;
  4698. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  4699. {
  4700. numElements += mCompiler->mMaxInterfaceSlots;
  4701. auto maxIFaceVirtIdx = 0;
  4702. if (!typeInstance->IsInterface())
  4703. {
  4704. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4705. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4706. numElements += typeInstance->GetOrigVTableSize();
  4707. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  4708. if (typeInstance->mHotTypeData != NULL)
  4709. {
  4710. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4711. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4712. }
  4713. numElements += ifaceMethodLen;
  4714. }
  4715. if (outNumElements != NULL)
  4716. *outNumElements = numElements;
  4717. }
  4718. StringT<128> classVDataName;
  4719. String memberName = "sBfClassVData";
  4720. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  4721. {
  4722. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  4723. memberName += "_";
  4724. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  4725. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  4726. }
  4727. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  4728. if (outMangledName != NULL)
  4729. *outMangledName = classVDataName;
  4730. BfIRValue globalVariable;
  4731. if (globalVariablePtr != NULL)
  4732. {
  4733. globalVariable = *globalVariablePtr;
  4734. }
  4735. else
  4736. {
  4737. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4738. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4739. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4740. arrayType,
  4741. true,
  4742. BfIRLinkageType_External,
  4743. BfIRValue(),
  4744. classVDataName);
  4745. mClassVDataRefs[typeInstance] = globalVariable;
  4746. }
  4747. return globalVariable;
  4748. }
  4749. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4750. {
  4751. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4752. if (mIsComptimeModule)
  4753. return mBfIRBuilder->Comptime_GetBfType(typeInstance->mTypeId, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4754. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4755. }
  4756. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4757. {
  4758. if (mBfIRBuilder->mIgnoreWrites)
  4759. return mBfIRBuilder->GetFakeVal();
  4760. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4761. BF_ASSERT(numElements >= 0);
  4762. if (numElements <= 0)
  4763. return BfIRValue();
  4764. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4765. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4766. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4767. BF_ASSERT(declTypeInst == implTypeInst);
  4768. else
  4769. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4770. if (declTypeInst != implTypeInst)
  4771. {
  4772. BfTypeInstance* highestImpl = declTypeInst;
  4773. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4774. {
  4775. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4776. break; // Start of an ext entry for another type
  4777. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4778. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4779. highestImpl = checkImplTypeInst;
  4780. }
  4781. if (highestImpl != implTypeInst)
  4782. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4783. }
  4784. BfVDataExtEntry mapEntry;
  4785. mapEntry.mDeclTypeInst = declTypeInst;
  4786. mapEntry.mImplTypeInst = implTypeInst;
  4787. BfIRValue* irValuePtr = NULL;
  4788. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4789. return *irValuePtr;
  4790. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4791. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4792. StringT<512> classVDataName;
  4793. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4794. if (declTypeInst != implTypeInst)
  4795. {
  4796. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4797. }
  4798. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4799. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4800. SizedArray<BfIRValue, 32> vData;
  4801. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4802. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4803. {
  4804. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4805. break; // Start of an ext entry for another type
  4806. BfIRValue vValue;
  4807. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4808. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4809. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4810. {
  4811. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4812. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4813. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4814. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4815. {
  4816. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4817. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4818. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4819. vValue = funcPtr;
  4820. }
  4821. }
  4822. if (!vValue)
  4823. vValue = voidPtrNull;
  4824. vData.Add(vValue);
  4825. }
  4826. BF_ASSERT((int)vData.size() == numElements);
  4827. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4828. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4829. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4830. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4831. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4832. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, vData);
  4833. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4834. mClassVDataExtRefs[mapEntry] = globalVariable;
  4835. return globalVariable;
  4836. }
  4837. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  4838. {
  4839. if (mBfIRBuilder->mIgnoreWrites)
  4840. {
  4841. return mBfIRBuilder->CreateTypeOf(type);
  4842. }
  4843. if (mIsComptimeModule)
  4844. {
  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::CreateTypeData(BfType* type, BfCreateTypeDataContext& ctx, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  5173. {
  5174. if ((IsHotCompile()) && (!type->mDirty))
  5175. return BfIRValue();
  5176. BfIRValue* irValuePtr = NULL;
  5177. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  5178. {
  5179. return *irValuePtr;
  5180. }
  5181. BfTypeInstance* typeInstance = type->ToTypeInstance();
  5182. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  5183. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  5184. if (typeInstanceType == NULL)
  5185. {
  5186. AssertErrorState();
  5187. return BfIRValue();
  5188. }
  5189. BfIRValue typeTypeData;
  5190. int typeFlags = 0;
  5191. if (needsTypeData)
  5192. {
  5193. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  5194. BfTypeInstance* typeDataSource = NULL;
  5195. if (typeInstance != NULL)
  5196. {
  5197. if (typeInstance->IsUnspecializedType())
  5198. {
  5199. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  5200. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  5201. }
  5202. else if (typeInstance->IsArray())
  5203. {
  5204. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  5205. typeFlags |= BfTypeFlags_Array;
  5206. }
  5207. else if (typeInstance->IsGenericTypeInstance())
  5208. {
  5209. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  5210. typeFlags |= BfTypeFlags_SpecializedGeneric;
  5211. }
  5212. else
  5213. typeDataSource = typeInstanceTypeInstance;
  5214. }
  5215. else if (type->IsPointer())
  5216. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5217. else if (type->IsRef())
  5218. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5219. else if (type->IsSizedArray())
  5220. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5221. else if (type->IsConstExprValue())
  5222. typeDataSource = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5223. else if (type->IsGenericParam())
  5224. {
  5225. typeFlags |= BfTypeFlags_GenericParam;
  5226. typeDataSource = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5227. }
  5228. else
  5229. typeDataSource = mContext->mBfTypeType;
  5230. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type) && (!mIsComptimeModule))
  5231. {
  5232. CreateTypeData(typeDataSource, ctx, false, true, needsTypeNames, true);
  5233. }
  5234. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  5235. ctx.mReflectTypeSet.Add(typeDataSource);
  5236. }
  5237. else
  5238. {
  5239. //typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  5240. typeTypeData = mBfIRBuilder->CreateConstNull();
  5241. }
  5242. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5243. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5244. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5245. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5246. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5247. BfType* typeIdType = intType;
  5248. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  5249. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  5250. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  5251. auto voidPtrNull = GetDefaultValue(voidPtrType);
  5252. SizedArray<BfIRValue, 4> typeValueParams;
  5253. GetConstClassValueParam(typeTypeData, typeValueParams);
  5254. FixConstValueParams(mContext->mBfObjectType, typeValueParams);
  5255. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5256. StringT<512> typeDataName;
  5257. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  5258. {
  5259. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  5260. if (typeInstance->mTypeDef->IsGlobalsContainer())
  5261. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  5262. }
  5263. else
  5264. {
  5265. typeDataName += "sBfTypeData.";
  5266. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  5267. }
  5268. int typeCode = BfTypeCode_None;
  5269. if (typeInstance != NULL)
  5270. {
  5271. BF_ASSERT((type->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || mIsComptimeModule);
  5272. typeCode = typeInstance->mTypeDef->mTypeCode;
  5273. if (typeInstance->IsBoxed())
  5274. typeCode = BfTypeCode_Object;
  5275. }
  5276. else if (type->IsPrimitiveType())
  5277. {
  5278. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  5279. typeCode = primType->mTypeDef->mTypeCode;
  5280. }
  5281. else if (type->IsPointer())
  5282. {
  5283. typeCode = BfTypeCode_Pointer;
  5284. typeFlags |= BfTypeFlags_Pointer;
  5285. }
  5286. else if (type->IsRef())
  5287. {
  5288. typeCode = BfTypeCode_Pointer;
  5289. typeFlags |= BfTypeFlags_Pointer;
  5290. }
  5291. if (type->IsObject())
  5292. {
  5293. typeFlags |= BfTypeFlags_Object;
  5294. if (typeInstance->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted)
  5295. {
  5296. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  5297. if ((methodInstance != NULL) && (methodInstance->GetOwner() != mContext->mBfObjectType))
  5298. typeFlags |= BfTypeFlags_HasDestructor;
  5299. }
  5300. }
  5301. if (type->IsStruct())
  5302. typeFlags |= BfTypeFlags_Struct;
  5303. if (type->IsInterface())
  5304. typeFlags |= BfTypeFlags_Interface;
  5305. if (type->IsBoxed())
  5306. {
  5307. typeFlags |= BfTypeFlags_Boxed;
  5308. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  5309. typeFlags |= BfTypeFlags_Pointer;
  5310. }
  5311. if (type->IsPrimitiveType())
  5312. typeFlags |= BfTypeFlags_Primitive;
  5313. if (type->IsTypedPrimitive())
  5314. typeFlags |= BfTypeFlags_TypedPrimitive;
  5315. if (type->IsTuple())
  5316. typeFlags |= BfTypeFlags_Tuple;
  5317. if (type->IsNullable())
  5318. typeFlags |= BfTypeFlags_Nullable;
  5319. if (type->IsSizedArray())
  5320. typeFlags |= BfTypeFlags_SizedArray;
  5321. if (type->IsConstExprValue())
  5322. typeFlags |= BfTypeFlags_ConstExpr;
  5323. if (type->IsSplattable())
  5324. typeFlags |= BfTypeFlags_Splattable;
  5325. if (type->IsUnion())
  5326. typeFlags |= BfTypeFlags_Union;
  5327. if (type->IsDelegate())
  5328. typeFlags |= BfTypeFlags_Delegate;
  5329. if (type->IsFunction())
  5330. typeFlags |= BfTypeFlags_Function;
  5331. if ((type->mDefineState != BfTypeDefineState_CETypeInit) && (type->WantsGCMarking()))
  5332. typeFlags |= BfTypeFlags_WantsMarking;
  5333. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsStatic))
  5334. typeFlags |= BfTypeFlags_Static;
  5335. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  5336. typeFlags |= BfTypeFlags_Abstract;
  5337. int virtSlotIdx = -1;
  5338. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5339. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5340. int memberDataOffset = 0;
  5341. if (type->IsInterface())
  5342. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  5343. else if (typeInstance != NULL)
  5344. {
  5345. for (auto& fieldInstance : typeInstance->mFieldInstances)
  5346. {
  5347. if (fieldInstance.mDataOffset != -1)
  5348. {
  5349. memberDataOffset = fieldInstance.mDataOffset;
  5350. break;
  5351. }
  5352. }
  5353. }
  5354. int boxedTypeId = 0;
  5355. if ((type->IsValueType()) || (type->IsWrappableType()))
  5356. {
  5357. auto boxedType = CreateBoxedType(type, false);
  5358. if ((boxedType != NULL) && (boxedType->mIsReified))
  5359. boxedTypeId = boxedType->mTypeId;
  5360. }
  5361. int stackCount = 0;
  5362. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  5363. {
  5364. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5365. if (typeOptions->mAllocStackTraceDepth != -1)
  5366. stackCount = BF_MIN(0xFF, BF_MAX(0x01, typeOptions->mAllocStackTraceDepth));
  5367. }
  5368. SizedArray<BfIRValue, 9> typeDataParams =
  5369. {
  5370. objectData,
  5371. GetConstValue(type->mSize, intType), // mSize
  5372. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5373. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  5374. GetConstValue(typeFlags, intType), // mTypeFlags
  5375. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  5376. GetConstValue(typeCode, byteType), // mTypeCode
  5377. GetConstValue(type->mAlign, byteType), // mAlign
  5378. GetConstValue(stackCount, byteType), // mAllocStackCountOverride
  5379. };
  5380. FixConstValueParams(mContext->mBfTypeType, typeDataParams);
  5381. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  5382. if (typeInstance == NULL)
  5383. {
  5384. BfIRValue typeDataVar;
  5385. if (needsTypeData)
  5386. {
  5387. if (type->IsPointer())
  5388. {
  5389. auto pointerType = (BfPointerType*)type;
  5390. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  5391. {
  5392. typeData,
  5393. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  5394. };
  5395. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5396. FixConstValueParams(reflectPointerType, pointerTypeDataParms);
  5397. auto pointerTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  5398. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  5399. BfIRLinkageType_External, pointerTypeData, typeDataName);
  5400. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5401. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5402. }
  5403. else if (type->IsRef())
  5404. {
  5405. auto refType = (BfRefType*)type;
  5406. SizedArray<BfIRValue, 3> refTypeDataParms =
  5407. {
  5408. typeData,
  5409. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  5410. GetConstValue((int8)refType->mRefKind, byteType),
  5411. };
  5412. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5413. FixConstValueParams(reflectRefType, refTypeDataParms);
  5414. auto refTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  5415. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  5416. BfIRLinkageType_External, refTypeData, typeDataName);
  5417. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5418. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5419. }
  5420. else if (type->IsSizedArray())
  5421. {
  5422. auto sizedArrayType = (BfSizedArrayType*)type;
  5423. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  5424. {
  5425. typeData,
  5426. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  5427. GetConstValue(sizedArrayType->mElementCount, intType)
  5428. };
  5429. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5430. FixConstValueParams(reflectSizedArrayType, sizedArrayTypeDataParms);
  5431. auto sizedArrayTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  5432. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  5433. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  5434. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5435. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5436. }
  5437. else if (type->IsConstExprValue())
  5438. {
  5439. auto constExprType = (BfConstExprValueType*)type;
  5440. SizedArray<BfIRValue, 3> constExprTypeDataParms =
  5441. {
  5442. typeData,
  5443. GetConstValue(constExprType->mType->mTypeId, typeIdType),
  5444. GetConstValue(constExprType->mValue.mInt64, longType)
  5445. };
  5446. auto reflectConstExprType = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5447. FixConstValueParams(reflectConstExprType, constExprTypeDataParms);
  5448. auto ConstExprTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectConstExprType, BfIRPopulateType_Full), constExprTypeDataParms);
  5449. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectConstExprType), true,
  5450. BfIRLinkageType_External, ConstExprTypeData, typeDataName);
  5451. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5452. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5453. }
  5454. else if (type->IsGenericParam())
  5455. {
  5456. auto genericParamType = (BfGenericParamType*)type;
  5457. SizedArray<BfIRValue, 3> genericParamTypeDataParms =
  5458. {
  5459. typeData
  5460. };
  5461. auto reflectGenericParamType = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5462. FixConstValueParams(reflectGenericParamType, genericParamTypeDataParms);
  5463. auto genericParamTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectGenericParamType, BfIRPopulateType_Full), genericParamTypeDataParms);
  5464. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectGenericParamType), true,
  5465. BfIRLinkageType_External, genericParamTypeData, typeDataName);
  5466. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5467. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5468. }
  5469. else
  5470. {
  5471. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  5472. BfIRLinkageType_External, typeData, typeDataName);
  5473. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5474. }
  5475. }
  5476. else
  5477. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5478. mTypeDataRefs[type] = typeDataVar;
  5479. return typeDataVar;
  5480. }
  5481. // Reserve position
  5482. mTypeDataRefs[typeInstance] = BfIRValue();
  5483. if ((typeInstance->IsReified()) && (!mIsComptimeModule))
  5484. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5485. BfTypeDef* typeDef = typeInstance->mTypeDef;
  5486. StringT<512> mangledName;
  5487. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  5488. if (!mIsComptimeModule)
  5489. {
  5490. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5491. {
  5492. auto methodDef = typeDef->mMethods[methodIdx];
  5493. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  5494. if (methodInstance == NULL)
  5495. continue;
  5496. if (typeInstance->IsUnspecializedType())
  5497. continue;
  5498. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5499. {
  5500. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  5501. {
  5502. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  5503. // We need to create an empty thunk for this chained method
  5504. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  5505. mBfIRBuilder->SetActiveFunction(func);
  5506. auto block = mBfIRBuilder->CreateBlock("entry", true);
  5507. mBfIRBuilder->SetInsertPoint(block);
  5508. mBfIRBuilder->CreateRetVoid();
  5509. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  5510. }
  5511. }
  5512. }
  5513. }
  5514. SizedArray<BfIRValue, 32> vData;
  5515. BfIRValue classVDataVar;
  5516. String classVDataName;
  5517. if (typeInstance->mSlotNum >= 0)
  5518. {
  5519. CreateSlotOfs(typeInstance);
  5520. }
  5521. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  5522. {
  5523. int dynCastDataElems = 0;
  5524. int numElements = 1;
  5525. int vDataOfs = mCompiler->GetVDataPrefixDataCount(); // The number of intptrs before the iface slot map
  5526. numElements += mCompiler->mMaxInterfaceSlots;
  5527. if (!typeInstance->IsInterface())
  5528. {
  5529. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  5530. numElements += mCompiler->GetDynCastVDataCount();
  5531. numElements += typeInstance->mVirtualMethodTableSize;
  5532. }
  5533. int expectNumElements = 0;
  5534. if (!typeDef->mIsStatic)
  5535. {
  5536. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  5537. }
  5538. for (int i = 0; i < mCompiler->GetVDataPrefixDataCount(); i++)
  5539. vData.push_back(BfIRValue()); // Type
  5540. SizedArray<BfIRValue, 1> extVTableData;
  5541. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  5542. if (!typeInstance->IsInterface())
  5543. {
  5544. Array<int32> dynCastData;
  5545. if (typeInstance->IsBoxed())
  5546. {
  5547. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  5548. dynCastData.Add(underlyingType->mInheritanceId);
  5549. }
  5550. else
  5551. dynCastData.Add(typeInstance->mInheritanceId);
  5552. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  5553. dynCastData.Add(0);
  5554. dynCastData.Add(0);
  5555. auto checkTypeInst = typeInstance;
  5556. while (checkTypeInst != NULL)
  5557. {
  5558. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5559. {
  5560. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  5561. {
  5562. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  5563. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  5564. }
  5565. }
  5566. checkTypeInst = checkTypeInst->GetImplBaseType();
  5567. }
  5568. if (mSystem->mPtrSize == 8)
  5569. {
  5570. int intPtrCount = (dynCastDataElems + 1) / 2;
  5571. vDataOfs += intPtrCount;
  5572. uint64* intPtrData = (uint64*)&dynCastData[0];
  5573. for (int i = 0; i < intPtrCount; i++)
  5574. {
  5575. uint64 val = intPtrData[i];
  5576. if (val == 0)
  5577. {
  5578. vData.push_back(voidPtrNull);
  5579. }
  5580. else
  5581. {
  5582. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5583. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5584. }
  5585. }
  5586. }
  5587. else
  5588. {
  5589. int intPtrCount = dynCastDataElems;
  5590. vDataOfs += intPtrCount;
  5591. uint32* intPtrData = (uint32*)&dynCastData[0];
  5592. for (int i = 0; i < intPtrCount; i++)
  5593. {
  5594. uint32 val = intPtrData[i];
  5595. if (val == 0)
  5596. {
  5597. vData.push_back(voidPtrNull);
  5598. }
  5599. else
  5600. {
  5601. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  5602. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5603. }
  5604. }
  5605. }
  5606. }
  5607. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  5608. vData.push_back(voidPtrNull);
  5609. struct _InterfaceMatchEntry
  5610. {
  5611. BfTypeInterfaceEntry* mEntry;
  5612. BfTypeInstance* mEntrySource;
  5613. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  5614. };
  5615. int highestIFaceVirtIdx = 0;
  5616. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  5617. auto checkTypeInst = typeInstance;
  5618. bool forceInterfaceSet = false;
  5619. while (checkTypeInst != NULL)
  5620. {
  5621. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5622. {
  5623. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  5624. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject)))
  5625. continue;
  5626. _InterfaceMatchEntry* matchEntry = NULL;
  5627. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  5628. {
  5629. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  5630. if (compareCheckTypeInst->IsBoxed())
  5631. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  5632. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  5633. if (compareEntrySource->IsBoxed())
  5634. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  5635. auto prevEntry = matchEntry->mEntry;
  5636. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  5637. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  5638. if ((!isBetter) && (!isWorse))
  5639. {
  5640. // Unboxed comparison to Object fix
  5641. if (compareCheckTypeInst == mContext->mBfObjectType)
  5642. isWorse = true;
  5643. else if (compareEntrySource == mContext->mBfObjectType)
  5644. isBetter = true;
  5645. }
  5646. if (forceInterfaceSet)
  5647. {
  5648. isBetter = true;
  5649. isWorse = false;
  5650. }
  5651. if (isBetter == isWorse)
  5652. CompareDeclTypes(checkTypeInst, interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  5653. if (isBetter == isWorse)
  5654. {
  5655. if (matchEntry->mAmbiguousEntries.empty())
  5656. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  5657. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  5658. continue;
  5659. }
  5660. else if (isBetter)
  5661. {
  5662. matchEntry->mEntry = &interfaceEntry;
  5663. matchEntry->mEntrySource = checkTypeInst;
  5664. matchEntry->mAmbiguousEntries.Clear();
  5665. }
  5666. else
  5667. continue;
  5668. }
  5669. else
  5670. {
  5671. _InterfaceMatchEntry matchEntry;
  5672. matchEntry.mEntry = &interfaceEntry;
  5673. matchEntry.mEntrySource = checkTypeInst;
  5674. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  5675. }
  5676. }
  5677. checkTypeInst = checkTypeInst->GetImplBaseType();
  5678. }
  5679. for (auto interfacePair : interfaceMap)
  5680. {
  5681. auto& interfaceMatchEntry = interfacePair.mValue;
  5682. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  5683. {
  5684. 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());
  5685. if (error != NULL)
  5686. {
  5687. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  5688. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  5689. }
  5690. }
  5691. }
  5692. if ((!mIsComptimeModule) && (!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  5693. {
  5694. int startTabIdx = (int)vData.size();
  5695. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  5696. BfTypeInstance* checkTypeInst = typeInstance;
  5697. while (checkTypeInst != NULL)
  5698. {
  5699. origVirtTypeStack.push_back(checkTypeInst);
  5700. checkTypeInst = checkTypeInst->GetImplBaseType();
  5701. }
  5702. Array<BfVirtualMethodEntry> origVTable;
  5703. int origVirtIdx = 0;
  5704. if (typeInstance->mTypeDef->mIsCombinedPartial)
  5705. {
  5706. HashSet<String> reslotNames;
  5707. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5708. {
  5709. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5710. if (entry.mDeclaringMethod.mMethodNum == -1)
  5711. continue;
  5712. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5713. if ((methodInstance == NULL) ||
  5714. ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))))
  5715. {
  5716. if (origVTable.empty())
  5717. origVTable = typeInstance->mVirtualMethodTable;
  5718. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  5719. if (declMethodInstance != NULL)
  5720. {
  5721. if ((mIsComptimeModule) || (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject)))
  5722. {
  5723. // Prepare to reslot...
  5724. entry.mImplementingMethod = entry.mDeclaringMethod;
  5725. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  5726. }
  5727. else
  5728. {
  5729. // Decl isn't accessible, null out entry
  5730. entry.mImplementingMethod = BfMethodRef();
  5731. }
  5732. }
  5733. }
  5734. }
  5735. if (!reslotNames.IsEmpty())
  5736. {
  5737. BfAmbiguityContext ambiguityContext;
  5738. ambiguityContext.mTypeInstance = typeInstance;
  5739. ambiguityContext.mModule = this;
  5740. ambiguityContext.mIsProjectSpecific = true;
  5741. ambiguityContext.mIsReslotting = true;
  5742. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5743. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  5744. {
  5745. auto methodInstance = methodGroup.mDefault;
  5746. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  5747. continue;
  5748. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  5749. continue;
  5750. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  5751. continue;
  5752. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  5753. continue;
  5754. SlotVirtualMethod(methodInstance, &ambiguityContext);
  5755. }
  5756. ambiguityContext.Finish();
  5757. }
  5758. }
  5759. bool isInExts = false;
  5760. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5761. {
  5762. BfIRValue vValue = voidPtrNull;
  5763. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5764. BfModuleMethodInstance moduleMethodInst;
  5765. if (entry.mDeclaringMethod.mMethodNum == -1)
  5766. {
  5767. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  5768. isInExts = true;
  5769. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  5770. if (vExt)
  5771. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  5772. }
  5773. else
  5774. {
  5775. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  5776. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  5777. {
  5778. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  5779. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  5780. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5781. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5782. {
  5783. BF_ASSERT((mIsComptimeModule) || typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  5784. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5785. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5786. vValue = funcPtr;
  5787. }
  5788. }
  5789. }
  5790. while (origVirtTypeStack.size() != 0)
  5791. {
  5792. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  5793. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  5794. {
  5795. // Moved past current base vtable size
  5796. origVirtTypeStack.pop_back();
  5797. continue;
  5798. }
  5799. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  5800. {
  5801. // We are within the original vtable size
  5802. int idx = startTabIdx + origVirtIdx;
  5803. origVirtIdx++;
  5804. vData.push_back(vValue);
  5805. }
  5806. else
  5807. {
  5808. // This is a new entry, it only gets added to the ext
  5809. BF_ASSERT(isInExts);
  5810. }
  5811. break;
  5812. }
  5813. }
  5814. if (!origVTable.empty())
  5815. typeInstance->mVirtualMethodTable = origVTable;
  5816. }
  5817. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  5818. if (typeInstance->mHotTypeData != NULL)
  5819. {
  5820. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  5821. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  5822. }
  5823. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  5824. int iFaceMethodStartIdx = (int)vData.size();
  5825. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  5826. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  5827. vData[i] = voidPtrNull;
  5828. if (expectNumElements != 0)
  5829. BF_ASSERT(expectNumElements == vData.size());
  5830. //BF_ASSERT(vData.size() == expectNumElements);
  5831. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  5832. // ifaceMethodExtData.Add(voidPtrNull);
  5833. int ifaceEntryIdx = iFaceMethodStartIdx;
  5834. for (auto& interfacePair : interfaceMap)
  5835. {
  5836. auto interfaceEntry = interfacePair.mValue.mEntry;
  5837. if (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  5838. {
  5839. BF_ASSERT(mIsComptimeModule);
  5840. break;
  5841. }
  5842. bool makeEmpty = false;
  5843. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject)))
  5844. makeEmpty = true;
  5845. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5846. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  5847. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5848. {
  5849. BfIRValue pushValue;
  5850. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5851. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5852. continue;
  5853. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5854. continue;
  5855. if (makeEmpty)
  5856. {
  5857. pushValue = voidPtrNull;
  5858. }
  5859. else
  5860. {
  5861. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5862. auto methodInstance = (BfMethodInstance*)methodRef;
  5863. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5864. {
  5865. BF_ASSERT(methodInstance->mIsReified);
  5866. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5867. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5868. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5869. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5870. pushValue = funcPtr;
  5871. }
  5872. else
  5873. {
  5874. pushValue = voidPtrNull;
  5875. }
  5876. }
  5877. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5878. if (idx < ifaceMethodExtStart)
  5879. {
  5880. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  5881. vData[iFaceMethodStartIdx + idx] = pushValue;
  5882. }
  5883. else
  5884. {
  5885. BF_ASSERT(useExt);
  5886. int extIdx = idx - ifaceMethodExtStart;
  5887. while (extIdx >= ifaceMethodExtData.size())
  5888. ifaceMethodExtData.Add(voidPtrNull);
  5889. ifaceMethodExtData[extIdx] = pushValue;
  5890. }
  5891. }
  5892. }
  5893. if (typeInstance->IsBoxed())
  5894. {
  5895. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  5896. if (boxedType->IsBoxedStructPtr())
  5897. {
  5898. // Force override of GetHashCode so we use the pointer address as the hash code
  5899. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  5900. // Force override of GetHashCode so we use the pointer address as the hash code
  5901. for (auto& checkIFace : checkTypeInst->mInterfaces)
  5902. {
  5903. if (checkIFace.mStartVirtualIdx < 0)
  5904. continue;
  5905. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5906. {
  5907. BfIRValue pushValue;
  5908. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5909. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5910. continue;
  5911. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5912. continue;
  5913. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5914. auto methodInstance = (BfMethodInstance*)methodRef;
  5915. BF_ASSERT(methodInstance->mIsReified);
  5916. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5917. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5918. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5919. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5920. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5921. vData[iFaceMethodStartIdx + idx] = funcPtr;
  5922. }
  5923. }
  5924. }
  5925. }
  5926. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic) && (!mIsComptimeModule))
  5927. {
  5928. BfIRValue ifaceMethodExtVar;
  5929. if ((!ifaceMethodExtData.IsEmpty()) && (!mIsComptimeModule))
  5930. {
  5931. StringT<512> classVDataName;
  5932. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  5933. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  5934. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  5935. BfIRLinkageType_External, BfIRValue(), classVDataName);
  5936. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  5937. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, ifaceMethodExtData);
  5938. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  5939. }
  5940. for (auto& ifaceInstPair : interfaceMap)
  5941. {
  5942. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  5943. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  5944. if (slotNum >= 0)
  5945. {
  5946. BfIRValue vtablePtr;
  5947. int idx = interfaceEntry->mStartVirtualIdx;
  5948. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5949. if ((endVirtualIdx > ifaceMethodExtStart) && (ifaceMethodExtVar))
  5950. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  5951. else
  5952. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  5953. int slotVirtIdx = slotNum + vDataOfs;
  5954. if (vData[slotVirtIdx] == voidPtrNull)
  5955. {
  5956. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  5957. }
  5958. else
  5959. {
  5960. if (mCompiler->IsHotCompile())
  5961. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  5962. else
  5963. Fail("Interface slot collision error", typeDef->GetRefNode());
  5964. }
  5965. }
  5966. }
  5967. }
  5968. }
  5969. BfIRValue typeNameConst;
  5970. BfIRValue namespaceConst;
  5971. if (needsTypeNames)
  5972. {
  5973. typeNameConst = GetStringObjectValue(typeDef->mName->mString, !mIsComptimeModule);
  5974. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), !mIsComptimeModule);
  5975. }
  5976. else
  5977. {
  5978. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  5979. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5980. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5981. }
  5982. int baseTypeId = 0;
  5983. if (typeInstance->mBaseType != NULL)
  5984. {
  5985. baseTypeId = typeInstance->mBaseType->mTypeId;
  5986. }
  5987. BfTypeOptions* typeOptions = NULL;
  5988. if (typeInstance->mTypeOptionsIdx >= 0)
  5989. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5990. SizedArray<BfIRValue, 16> customAttrs;
  5991. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  5992. BfIRValue castedClassVData;
  5993. if (classVDataVar)
  5994. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  5995. else
  5996. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  5997. bool freflectIncludeTypeData = false;
  5998. bool reflectIncludeAllFields = false;
  5999. bool reflectIncludeAllMethods = false;
  6000. if (TypeIsSubTypeOf(typeInstance, attributeType))
  6001. {
  6002. reflectIncludeAllFields = true;
  6003. reflectIncludeAllMethods = true;
  6004. }
  6005. if (typeInstance->IsTuple())
  6006. {
  6007. // Required to generate tuple name at runtime
  6008. reflectIncludeAllFields = true;
  6009. }
  6010. BfReflectKind reflectKind = BfReflectKind_Type;
  6011. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  6012. {
  6013. BfReflectKind reflectKind = BfReflectKind_None;
  6014. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  6015. if (customAttrs != NULL)
  6016. {
  6017. for (auto& attr : customAttrs->mAttributes)
  6018. {
  6019. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  6020. }
  6021. delete customAttrs;
  6022. }
  6023. return reflectKind;
  6024. };
  6025. reflectKind = GetReflectKind(reflectKind, typeInstance);
  6026. // Fields
  6027. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  6028. BfIRValue emptyValueType = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  6029. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  6030. {
  6031. if (customAttributes == NULL)
  6032. return -1;
  6033. Array<BfCustomAttribute*> reflectAttributes;
  6034. for (auto& attr : customAttributes->mAttributes)
  6035. {
  6036. bool wantAttribute = false;
  6037. if (attr.mType->mCustomAttributes != NULL)
  6038. {
  6039. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  6040. if (usageAttribute != NULL)
  6041. {
  6042. // Check for Flags arg
  6043. if (usageAttribute->mCtorArgs.size() < 2)
  6044. continue;
  6045. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  6046. if (constant == NULL)
  6047. continue;
  6048. if (constant->mTypeCode == BfTypeCode_Boolean)
  6049. continue;
  6050. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  6051. wantAttribute = true;
  6052. }
  6053. }
  6054. if ((wantAttribute) && (attr.mType->mIsReified))
  6055. {
  6056. reflectAttributes.Add(&attr);
  6057. }
  6058. }
  6059. if (reflectAttributes.size() == 0)
  6060. return -1;
  6061. #define PUSH_INT8(val) data.push_back((uint8)val)
  6062. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  6063. #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); }
  6064. SizedArray<uint8, 16> data;
  6065. int customAttrIdx = (int)customAttrs.size();
  6066. data.push_back((uint8)reflectAttributes.size());
  6067. for (auto attr : reflectAttributes)
  6068. {
  6069. // Size prefix
  6070. int sizeIdx = (int)data.size();
  6071. PUSH_INT16(0); // mSize
  6072. PUSH_INT32(attr->mType->mTypeId); // mType
  6073. int ctorIdx = -1;
  6074. int ctorCount = 0;
  6075. attr->mType->mTypeDef->PopulateMemberSets();
  6076. BfMemberSetEntry* entry;
  6077. if (attr->mType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  6078. {
  6079. BfMethodDef* nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6080. while (nextMethodDef != NULL)
  6081. {
  6082. if (nextMethodDef == attr->mCtor)
  6083. ctorIdx = ctorCount;
  6084. nextMethodDef = nextMethodDef->mNextWithSameName;
  6085. ctorCount++;
  6086. }
  6087. }
  6088. BF_ASSERT(ctorIdx != -1);
  6089. if (ctorIdx != -1)
  6090. ctorIdx = (ctorCount - 1) - ctorIdx;
  6091. PUSH_INT16(ctorIdx);
  6092. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  6093. int argIdx = 0;
  6094. for (auto arg : attr->mCtorArgs)
  6095. {
  6096. auto argType = ctorMethodInstance->GetParamType(argIdx);
  6097. EncodeAttributeData(typeInstance, argType, arg, data, ctx.mUsedStringIdMap);
  6098. argIdx++;
  6099. }
  6100. int size = (int)data.size() - sizeIdx;
  6101. *((uint16*)&data[sizeIdx]) = size;
  6102. }
  6103. #undef PUSH_INT8
  6104. #undef PUSH_INT16
  6105. #undef PUSH_INT32
  6106. SizedArray<BfIRValue, 16> dataValues;
  6107. for (uint8 val : data)
  6108. dataValues.push_back(GetConstValue8(val));
  6109. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  6110. auto customAttrConst = mBfIRBuilder->CreateConstAgg_Value(dataArrayType, dataValues);
  6111. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  6112. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  6113. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  6114. customAttrs.push_back(customAttrArrayPtr);
  6115. return customAttrIdx;
  6116. };
  6117. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  6118. SizedArray<int, 16> reflectFieldIndices;
  6119. for (int pass = 0; pass < 2; pass++)
  6120. {
  6121. bool skippedField = false;
  6122. reflectFieldIndices.clear();
  6123. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  6124. {
  6125. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6126. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  6127. if (fieldDef == NULL)
  6128. continue;
  6129. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6130. bool includeField = reflectIncludeAllFields;
  6131. if (fieldInstance->mCustomAttributes != NULL)
  6132. {
  6133. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  6134. {
  6135. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6136. {
  6137. includeField = true;
  6138. }
  6139. else
  6140. {
  6141. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6142. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  6143. }
  6144. }
  6145. }
  6146. if ((fieldReflectKind & BfReflectKind_User) != 0)
  6147. includeField = true;
  6148. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  6149. includeField = true;
  6150. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  6151. includeField = true;
  6152. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  6153. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  6154. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  6155. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  6156. includeField |= forceReflectFields;
  6157. if (!includeField)
  6158. {
  6159. skippedField = true;
  6160. continue;
  6161. }
  6162. reflectFieldIndices.Add(fieldIdx);
  6163. }
  6164. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  6165. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  6166. // possible because we write out a SplatData structure containing just TypeIds in that case
  6167. if (pass == 0)
  6168. {
  6169. if (!typeInstance->IsSplattable())
  6170. break;
  6171. if (!skippedField)
  6172. break;
  6173. if (reflectFieldIndices.size() == 0)
  6174. break;
  6175. }
  6176. }
  6177. SizedArray<BfIRValue, 16> fieldTypes;
  6178. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  6179. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  6180. {
  6181. BfType* payloadType = typeInstance->GetUnionInnerType();
  6182. if (!payloadType->IsValuelessType())
  6183. {
  6184. BfIRValue payloadNameConst = GetStringObjectValue("$payload", !mIsComptimeModule);
  6185. SizedArray<BfIRValue, 8> payloadFieldVals;
  6186. if (is32Bit)
  6187. {
  6188. payloadFieldVals =
  6189. {
  6190. emptyValueType,
  6191. payloadNameConst, // mName
  6192. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6193. GetConstValue(0, intPtrType), // mData
  6194. GetConstValue(0, intPtrType), // mDataHi
  6195. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6196. GetConstValue(-1, intType), // mCustomAttributesIdx
  6197. };
  6198. }
  6199. else
  6200. {
  6201. payloadFieldVals =
  6202. {
  6203. emptyValueType,
  6204. payloadNameConst, // mName
  6205. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6206. GetConstValue(0, intPtrType), // mData
  6207. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6208. GetConstValue(-1, intType), // mCustomAttributesIdx
  6209. };
  6210. }
  6211. FixConstValueParams(reflectFieldDataType->ToTypeInstance(), payloadFieldVals);
  6212. auto payloadFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  6213. fieldTypes.push_back(payloadFieldData);
  6214. }
  6215. BfType* dscrType = typeInstance->GetDiscriminatorType();
  6216. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", !mIsComptimeModule);
  6217. SizedArray<BfIRValue, 8> dscrFieldVals;
  6218. if (is32Bit)
  6219. {
  6220. dscrFieldVals =
  6221. {
  6222. emptyValueType,
  6223. dscrNameConst, // mName
  6224. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6225. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6226. GetConstValue(0, intPtrType), // mDataHi
  6227. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6228. GetConstValue(-1, intType), // mCustomAttributesIdx
  6229. };
  6230. }
  6231. else
  6232. {
  6233. dscrFieldVals =
  6234. {
  6235. emptyValueType,
  6236. dscrNameConst, // mName
  6237. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6238. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6239. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6240. GetConstValue(-1, intType), // mCustomAttributesIdx
  6241. };
  6242. }
  6243. auto dscrFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  6244. fieldTypes.push_back(dscrFieldData);
  6245. }
  6246. for (auto fieldIdx : reflectFieldIndices)
  6247. {
  6248. if (!needsTypeData)
  6249. break;
  6250. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6251. fieldTypes.push_back(CreateFieldData(fieldInstance, _HandleCustomAttrs(fieldInstance->mCustomAttributes)));
  6252. }
  6253. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  6254. BfIRValue fieldDataPtr;
  6255. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  6256. if (fieldTypes.size() == 0)
  6257. {
  6258. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  6259. {
  6260. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  6261. SizedArray<BfIRValue, 3> splatTypes;
  6262. SizedArray<BfIRValue, 3> splatOffsets;
  6263. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  6264. {
  6265. auto checkTypeInstance = checkType->ToTypeInstance();
  6266. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  6267. PopulateType(checkTypeInstance);
  6268. if (checkType->IsStruct())
  6269. {
  6270. int dataEnd = offset;
  6271. if (checkTypeInstance->mBaseType != NULL)
  6272. _CheckSplat(checkTypeInstance->mBaseType, offset);
  6273. if (checkTypeInstance->mIsUnion)
  6274. {
  6275. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  6276. _CheckSplat(unionInnerType, offset);
  6277. }
  6278. else
  6279. {
  6280. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  6281. {
  6282. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  6283. if (fieldInstance->mDataIdx >= 0)
  6284. {
  6285. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  6286. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  6287. }
  6288. }
  6289. }
  6290. if (checkTypeInstance->IsEnum())
  6291. {
  6292. // Add discriminator
  6293. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  6294. if (checkTypeInstance->mPacking > 0)
  6295. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  6296. _CheckSplat(dscrType, dataEnd);
  6297. }
  6298. }
  6299. else if (checkType->IsMethodRef())
  6300. {
  6301. // auto methodRefType = (BfMethodRefType*)checkType;
  6302. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6303. // {
  6304. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6305. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  6306. // else
  6307. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  6308. // }
  6309. }
  6310. else if (!checkType->IsValuelessType())
  6311. {
  6312. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  6313. splatOffsets.Add(GetConstValue(offset, intType));
  6314. }
  6315. };
  6316. _CheckSplat(type, 0);
  6317. while (splatTypes.size() < 3)
  6318. {
  6319. splatTypes.Add(GetConstValue(0, typeIdType));
  6320. splatOffsets.Add(GetConstValue(0, intType));
  6321. }
  6322. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  6323. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  6324. SizedArray<BfIRValue, 8> splatVals =
  6325. {
  6326. emptyValueType,
  6327. splatTypesConst,
  6328. splatOffsetsConst
  6329. };
  6330. auto fieldSplatData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  6331. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  6332. fieldSplatData, typeDataName + ".splats");
  6333. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6334. }
  6335. else
  6336. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  6337. }
  6338. else
  6339. {
  6340. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  6341. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstAgg_Value(fieldDataConstType, fieldTypes);
  6342. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  6343. fieldDataConst, "fields." + typeDataName);
  6344. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6345. }
  6346. /// Methods
  6347. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  6348. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  6349. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  6350. struct _SortedMethodInfo
  6351. {
  6352. BfMethodDef* mMethodDef;
  6353. BfMethodCustomAttributes* mMethodCustomAttributes;
  6354. };
  6355. Array<_SortedMethodInfo> sortedMethodList;
  6356. SizedArray<BfIRValue, 16> methodTypes;
  6357. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  6358. {
  6359. if (!needsTypeData)
  6360. break;
  6361. // Disable const method reflection info for now
  6362. if (mIsComptimeModule)
  6363. break;
  6364. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6365. if (!methodInstanceGroup->IsImplemented())
  6366. continue;
  6367. auto methodDef = typeDef->mMethods[methodIdx];
  6368. if (methodDef->mIsNoReflect)
  6369. continue;
  6370. if (methodDef->mHasComptime)
  6371. continue;
  6372. auto defaultMethod = methodInstanceGroup->mDefault;
  6373. if (defaultMethod == NULL)
  6374. continue;
  6375. if (defaultMethod->mIsUnspecialized)
  6376. continue;
  6377. if (!defaultMethod->mIsReified)
  6378. continue;
  6379. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  6380. continue;
  6381. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  6382. continue;
  6383. if (!defaultMethod->mMethodDef->CanReflect())
  6384. continue;
  6385. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6386. bool includeMethod = reflectIncludeAllMethods;
  6387. if (typeInstance->IsDelegateOrFunction())
  6388. includeMethod = true;
  6389. BfMethodCustomAttributes* methodCustomAttributes = NULL;
  6390. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  6391. {
  6392. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes;
  6393. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  6394. {
  6395. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6396. {
  6397. includeMethod = true;
  6398. }
  6399. else
  6400. {
  6401. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6402. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  6403. }
  6404. }
  6405. }
  6406. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject)))
  6407. continue;
  6408. //
  6409. {
  6410. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  6411. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  6412. {
  6413. BfTypeState typeState;
  6414. typeState.mPrevState = mContext->mCurTypeState;
  6415. typeState.mForceActiveTypeDef = methodDef->mDeclaringType;
  6416. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  6417. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  6418. {
  6419. if (paramDecl->mAttributes != NULL)
  6420. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  6421. }
  6422. }
  6423. }
  6424. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  6425. includeMethod = true;
  6426. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  6427. includeMethod = true;
  6428. if ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend))
  6429. {
  6430. if ((methodReflectKind & BfReflectKind_Constructors) != 0)
  6431. includeMethod = true;
  6432. if ((methodDef->IsDefaultCtor()) && ((methodReflectKind & BfReflectKind_DefaultConstructor) != 0))
  6433. includeMethod = true;
  6434. }
  6435. if ((!includeMethod) && (typeOptions != NULL))
  6436. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  6437. if (!includeMethod)
  6438. continue;
  6439. sortedMethodList.Add({ methodDef, methodCustomAttributes });
  6440. }
  6441. auto _GetMethodKind = [](BfMethodDef* methodDef)
  6442. {
  6443. if (methodDef->mMethodType == BfMethodType_Ctor)
  6444. return 0;
  6445. return 1;
  6446. };
  6447. std::sort(sortedMethodList.begin(), sortedMethodList.end(), [_GetMethodKind](const _SortedMethodInfo& lhs, const _SortedMethodInfo& rhs)
  6448. {
  6449. int lhsKind = _GetMethodKind(lhs.mMethodDef);
  6450. int rhsKind = _GetMethodKind(rhs.mMethodDef);
  6451. if (lhsKind != rhsKind)
  6452. return lhsKind < rhsKind;
  6453. if (lhs.mMethodDef->mName != rhs.mMethodDef->mName)
  6454. return lhs.mMethodDef->mName < rhs.mMethodDef->mName;
  6455. return lhs.mMethodDef->mIdx < rhs.mMethodDef->mIdx;
  6456. });
  6457. for (auto& methodInfo : sortedMethodList)
  6458. {
  6459. auto methodDef = methodInfo.mMethodDef;
  6460. int methodIdx = methodDef->mIdx;
  6461. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6462. auto defaultMethod = methodInstanceGroup->mDefault;
  6463. BfModuleMethodInstance moduleMethodInstance;
  6464. BfIRValue funcVal = voidPtrNull;
  6465. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  6466. (!typeInstance->IsUnspecializedType()) &&
  6467. (methodDef->mMethodType != BfMethodType_Ignore) &&
  6468. (methodDef->mMethodType != BfMethodType_Mixin) &&
  6469. (!methodDef->mIsAbstract) &&
  6470. (methodDef->mGenericParams.size() == 0))
  6471. {
  6472. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6473. if (moduleMethodInstance.mFunc)
  6474. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6475. }
  6476. BfIRValue methodNameConst = GetStringObjectValue(methodDef->GetReflectName(), !mIsComptimeModule);
  6477. BfMethodFlags methodFlags = defaultMethod->GetMethodFlags();
  6478. int customAttrIdx = -1;
  6479. int returnCustomAttrIdx = -1;
  6480. if (methodInfo.mMethodCustomAttributes != NULL)
  6481. {
  6482. customAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mCustomAttributes);
  6483. returnCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mReturnCustomAttributes);
  6484. }
  6485. enum ParamFlags
  6486. {
  6487. ParamFlag_None = 0,
  6488. ParamFlag_Splat = 1,
  6489. ParamFlag_Implicit = 2,
  6490. ParamFlag_AppendIdx = 4,
  6491. ParamFlag_Params = 8
  6492. };
  6493. SizedArray<BfIRValue, 8> paramVals;
  6494. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  6495. {
  6496. String paramName = defaultMethod->GetParamName(paramIdx);
  6497. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  6498. ParamFlags paramFlags = ParamFlag_None;
  6499. if (defaultMethod->GetParamIsSplat(paramIdx))
  6500. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  6501. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  6502. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Implicit | ParamFlag_AppendIdx);
  6503. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_Params)
  6504. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Params);
  6505. BfIRValue paramNameConst = GetStringObjectValue(paramName, !mIsComptimeModule);
  6506. int paramCustomAttrIdx = -1;
  6507. if ((methodInfo.mMethodCustomAttributes != NULL) && (paramIdx < (int)methodInfo.mMethodCustomAttributes->mParamCustomAttributes.mSize))
  6508. paramCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mParamCustomAttributes[paramIdx]);
  6509. SizedArray<BfIRValue, 8> paramDataVals =
  6510. {
  6511. emptyValueType,
  6512. paramNameConst,
  6513. GetConstValue(paramType->mTypeId, typeIdType),
  6514. GetConstValue((int32)paramFlags, shortType),
  6515. GetConstValue(-1, intType), // defaultIdx
  6516. GetConstValue(paramCustomAttrIdx, intType) // customAttrIdx
  6517. };
  6518. auto paramData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  6519. paramVals.Add(paramData);
  6520. }
  6521. BfIRValue paramsVal;
  6522. if (paramVals.size() > 0)
  6523. {
  6524. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  6525. BfIRValue paramDataConst = mBfIRBuilder->CreateConstAgg_Value(paramDataArrayType, paramVals);
  6526. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  6527. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  6528. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  6529. }
  6530. else
  6531. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  6532. int vDataVal = -1;
  6533. if (defaultMethod->mVirtualTableIdx != -1)
  6534. {
  6535. int vDataIdx = -1;
  6536. if (type->IsInterface())
  6537. {
  6538. vDataIdx = defaultMethod->mVirtualTableIdx;
  6539. }
  6540. else
  6541. {
  6542. vDataIdx = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  6543. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  6544. {
  6545. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  6546. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6547. if (extMethodIdx >= 0)
  6548. {
  6549. // Extension?
  6550. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6551. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  6552. }
  6553. else
  6554. {
  6555. // Map this new virtual index back to the original index
  6556. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  6557. }
  6558. }
  6559. else
  6560. {
  6561. vDataIdx += defaultMethod->mVirtualTableIdx;
  6562. }
  6563. }
  6564. if (vDataVal == -1)
  6565. vDataVal = vDataIdx * mSystem->mPtrSize;
  6566. }
  6567. SizedArray<BfIRValue, 8> methodDataVals =
  6568. {
  6569. emptyValueType,
  6570. methodNameConst, // mName
  6571. funcVal, // mFuncPtr
  6572. paramsVal,
  6573. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  6574. GetConstValue((int)paramVals.size(), shortType),
  6575. GetConstValue(methodFlags, shortType),
  6576. GetConstValue(methodIdx, intType),
  6577. GetConstValue(vDataVal, intType),
  6578. GetConstValue(customAttrIdx, intType),
  6579. GetConstValue(returnCustomAttrIdx, intType),
  6580. };
  6581. auto methodData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  6582. methodTypes.push_back(methodData);
  6583. }
  6584. BfIRValue methodDataPtr;
  6585. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  6586. if (methodTypes.size() == 0)
  6587. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  6588. else
  6589. {
  6590. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  6591. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methodTypes);
  6592. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6593. methodDataConst, "methods." + typeDataName);
  6594. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  6595. }
  6596. /////
  6597. int interfaceCount = 0;
  6598. BfIRValue interfaceDataPtr;
  6599. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  6600. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  6601. Array<bool> wantsIfaceMethod;
  6602. bool wantsIfaceMethods = false;
  6603. if ((typeInstance->mInterfaces.IsEmpty()) || (!needsTypeData))
  6604. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  6605. else
  6606. {
  6607. SizedArray<BfIRValue, 16> interfaces;
  6608. for (auto& interface : typeInstance->mInterfaces)
  6609. {
  6610. SizedArray<BfIRValue, 8> interfaceDataVals =
  6611. {
  6612. emptyValueType,
  6613. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  6614. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  6615. GetConstValue(interface.mStartVirtualIdx, intType),
  6616. };
  6617. auto interfaceData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  6618. interfaces.push_back(interfaceData);
  6619. if (!mIsComptimeModule)
  6620. {
  6621. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6622. {
  6623. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  6624. if (ifaceMethodGroup->mExplicitlyReflected)
  6625. {
  6626. wantsIfaceMethods = true;
  6627. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  6628. while (tableIdx >= wantsIfaceMethod.size())
  6629. wantsIfaceMethod.Add(false);
  6630. wantsIfaceMethod[tableIdx] = true;
  6631. }
  6632. }
  6633. }
  6634. }
  6635. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  6636. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstAgg_Value(interfaceDataArrayType, interfaces);
  6637. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  6638. interfaceDataConst, "interfaces." + typeDataName);
  6639. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  6640. interfaceCount = (int)interfaces.size();
  6641. }
  6642. BfIRValue interfaceMethodTable;
  6643. int ifaceMethodTableSize = 0;
  6644. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  6645. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  6646. {
  6647. SizedArray<BfIRValue, 16> methods;
  6648. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  6649. {
  6650. BfIRValue funcVal = voidPtrNull;
  6651. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  6652. {
  6653. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  6654. if (!methodEntry.mMethodRef.IsNull())
  6655. {
  6656. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  6657. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  6658. (!methodInstance->mMethodDef->mIsAbstract))
  6659. {
  6660. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  6661. if (moduleMethodInstance.mFunc)
  6662. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6663. }
  6664. }
  6665. }
  6666. methods.Add(funcVal);
  6667. }
  6668. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  6669. methods.pop_back();
  6670. if (!methods.IsEmpty())
  6671. {
  6672. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  6673. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methods);
  6674. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6675. methodDataConst, "imethods." + typeDataName);
  6676. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  6677. ifaceMethodTableSize = (int)methods.size();
  6678. }
  6679. }
  6680. if (!interfaceMethodTable)
  6681. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6682. /////
  6683. int underlyingType = 0;
  6684. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  6685. {
  6686. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  6687. }
  6688. int outerTypeId = 0;
  6689. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  6690. if (outerType != NULL)
  6691. {
  6692. outerTypeId = outerType->mTypeId;
  6693. }
  6694. //
  6695. BfIRValue customAttrDataPtr;
  6696. if (customAttrs.size() > 0)
  6697. {
  6698. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  6699. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstAgg_Value(customAttrsArrayType, customAttrs);
  6700. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  6701. customAttrsConst, "customAttrs." + typeDataName);
  6702. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  6703. }
  6704. else
  6705. {
  6706. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6707. }
  6708. SizedArray<BfIRValue, 32> typeDataVals =
  6709. {
  6710. typeData,
  6711. castedClassVData, // mTypeClassVData
  6712. typeNameConst, // mName
  6713. namespaceConst, // mNamespace
  6714. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  6715. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  6716. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  6717. GetConstValue(baseTypeId, typeIdType), // mBaseType
  6718. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  6719. GetConstValue(outerTypeId, typeIdType), // mOuterType
  6720. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  6721. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  6722. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  6723. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  6724. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  6725. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  6726. GetConstValue(0, shortType), // mPropertyDataCount
  6727. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  6728. interfaceDataPtr, // mInterfaceDataPtr
  6729. interfaceMethodTable, // mInterfaceMethodTable
  6730. methodDataPtr, // mMethodDataPtr
  6731. voidPtrNull, // mPropertyDataPtr
  6732. fieldDataPtr, // mFieldDataPtr
  6733. customAttrDataPtr, // mCustomAttrDataPtr
  6734. };
  6735. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  6736. FixConstValueParams(typeInstanceType->ToTypeInstance(), typeDataVals);
  6737. auto typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, typeDataVals);
  6738. if (!needsTypeData)
  6739. {
  6740. // No need for anything beyond typeInstanceData
  6741. }
  6742. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  6743. {
  6744. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6745. SizedArray<BfIRValue, 4> unspecializedData =
  6746. {
  6747. typeInstanceData,
  6748. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  6749. };
  6750. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  6751. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6752. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, unspecializedData);
  6753. }
  6754. else if (typeInstance->IsGenericTypeInstance())
  6755. {
  6756. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6757. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  6758. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef->GetDefinition());
  6759. SizedArray<BfIRValue, 4> resolvedTypes;
  6760. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  6761. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  6762. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  6763. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  6764. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  6765. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstAgg_Value(genericArrayType, resolvedTypes);
  6766. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  6767. resolvedTypesConst, "resolvedTypes." + typeDataName);
  6768. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  6769. SizedArray<BfIRValue, 3> specGenericData =
  6770. {
  6771. typeInstanceData,
  6772. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  6773. resovledTypesPtr, // mFieldDataPtr
  6774. };
  6775. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6776. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, specGenericData);
  6777. if (typeInstance->IsArray())
  6778. {
  6779. auto arrayType = (BfArrayType*)typeInstance;
  6780. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  6781. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  6782. SizedArray<BfIRValue, 4> arrayData =
  6783. {
  6784. typeInstanceData,
  6785. GetConstValue(elementType->mSize, intType), // mElementSize
  6786. GetConstValue(1, byteType), // mRank
  6787. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  6788. };
  6789. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  6790. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  6791. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, arrayData);
  6792. }
  6793. }
  6794. BfIRValue typeDataVar;
  6795. if (needsTypeData)
  6796. {
  6797. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  6798. BfIRLinkageType_External, typeInstanceData, typeDataName);
  6799. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  6800. if (mBfIRBuilder->DbgHasInfo())
  6801. {
  6802. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  6803. }
  6804. }
  6805. else
  6806. {
  6807. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  6808. }
  6809. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  6810. mTypeDataRefs[typeInstance] = typeDataVar;
  6811. if ((!mIsComptimeModule) && (classVDataVar))
  6812. {
  6813. BF_ASSERT(!classVDataName.IsEmpty());
  6814. //vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  6815. int unboxedTypeId = type->mTypeId;
  6816. if (type->IsBoxed())
  6817. unboxedTypeId = type->GetUnderlyingType()->mTypeId;
  6818. if (mSystem->mPtrSize == 4)
  6819. {
  6820. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(type->mTypeId, intPtrType), voidPtrIRType);
  6821. vData[1] = mBfIRBuilder->CreateIntToPtr(GetConstValue(unboxedTypeId, intPtrType), voidPtrIRType);
  6822. }
  6823. else
  6824. {
  6825. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(((int64)unboxedTypeId << 32) | type->mTypeId, intPtrType), voidPtrIRType);
  6826. }
  6827. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  6828. auto classVDataConstData = mBfIRBuilder->CreateConstAgg_Value(classVDataConstDataType, vData);
  6829. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  6830. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6831. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  6832. else
  6833. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  6834. if (mBfIRBuilder->DbgHasInfo())
  6835. {
  6836. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6837. BfType* voidPtrType = CreatePointerType(voidType);
  6838. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6839. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  6840. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  6841. }
  6842. }
  6843. return typeDataVar;
  6844. }
  6845. BfIRValue BfModule::FixClassVData(BfIRValue value)
  6846. {
  6847. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  6848. return value;
  6849. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  6850. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  6851. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  6852. }
  6853. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  6854. {
  6855. // Note: this is not just for perf, it fixes a field var-type resolution issue
  6856. if (mBfIRBuilder->mIgnoreWrites)
  6857. return;
  6858. if (mIsComptimeModule)
  6859. return;
  6860. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  6861. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  6862. // When we access classes with static constructors FROM a static constructor,
  6863. // we call that other class's static constructor first. Recursion cannot occur, since
  6864. // we simply ignore subsequent attempts to re-enter the constructor
  6865. if (!typeInstance->mHasStaticInitMethod)
  6866. return;
  6867. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  6868. return;
  6869. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  6870. return;
  6871. auto checkTypeDef = typeInstance->mTypeDef;
  6872. checkTypeDef->PopulateMemberSets();
  6873. BfMethodDef* nextMethodDef = NULL;
  6874. BfMemberSetEntry* entry;
  6875. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  6876. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6877. while (nextMethodDef != NULL)
  6878. {
  6879. auto checkMethod = nextMethodDef;
  6880. nextMethodDef = nextMethodDef->mNextWithSameName;
  6881. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  6882. if (methodModule)
  6883. {
  6884. auto methodInstance = methodModule.mMethodInstance;
  6885. if ((methodInstance != NULL) &&
  6886. (methodInstance->mMethodDef->mIsStatic) &&
  6887. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  6888. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  6889. {
  6890. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  6891. break;
  6892. }
  6893. }
  6894. }
  6895. }
  6896. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  6897. {
  6898. auto methodOwner = methodInstance->GetOwner();
  6899. auto methodDef = methodInstance->mMethodDef;
  6900. auto methodDeclaration = methodDef->GetMethodDeclaration();
  6901. if (!methodDef->mIsExtern)
  6902. return BfIRFunction();
  6903. if (methodInstance->GetCustomAttributes() == NULL)
  6904. return BfIRFunction();
  6905. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  6906. {
  6907. String typeName = TypeToString(customAttribute.mType);
  6908. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  6909. {
  6910. methodInstance->mIsIntrinsic = true;
  6911. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  6912. String error;
  6913. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  6914. {
  6915. int stringId = constant->mInt32;
  6916. auto entry = mContext->mStringObjectIdMap[stringId];
  6917. String intrinName = entry.mString;
  6918. // if (intrinName.StartsWith(":"))
  6919. // {
  6920. // SizedArray<BfIRType, 2> paramTypes;
  6921. // for (auto& param : methodInstance->mParams)
  6922. // paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6923. // return mBfIRBuilder->GetIntrinsic(intrinName.Substring(1), mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6924. // }
  6925. // else
  6926. {
  6927. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  6928. if (intrinId != -1)
  6929. {
  6930. if (intrinId == BfIRIntrinsic_Malloc)
  6931. {
  6932. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6933. }
  6934. else if (intrinId == BfIRIntrinsic_Free)
  6935. {
  6936. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  6937. }
  6938. SizedArray<BfIRType, 2> paramTypes;
  6939. for (auto& param : methodInstance->mParams)
  6940. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6941. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6942. }
  6943. else if (reportFailure)
  6944. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  6945. }
  6946. }
  6947. else if (reportFailure)
  6948. error = "Intrinsic name must be a constant string";
  6949. if (reportFailure)
  6950. {
  6951. Fail(error, customAttribute.mRef);
  6952. }
  6953. }
  6954. }
  6955. return BfIRFunction();
  6956. }
  6957. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  6958. {
  6959. if (mBfIRBuilder->mIgnoreWrites)
  6960. return mBfIRBuilder->GetFakeFunction();
  6961. if (!mBuiltInFuncs[(int)funcTypeId])
  6962. {
  6963. SizedArray<BfIRType, 4> paramTypes;
  6964. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  6965. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6966. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  6967. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6968. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  6969. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  6970. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  6971. BfIRFunctionType funcType;
  6972. BfIRFunction func;
  6973. switch (funcTypeId)
  6974. {
  6975. case BfBuiltInFuncType_PrintF:
  6976. paramTypes.Add(nullPtrType);
  6977. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  6978. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  6979. break;
  6980. case BfBuiltInFuncType_Malloc:
  6981. {
  6982. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6983. {
  6984. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  6985. }
  6986. else
  6987. {
  6988. String funcName = mCompiler->mOptions.mMallocLinkName;
  6989. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  6990. funcName = "malloc";
  6991. func = mBfIRBuilder->GetFunction(funcName);
  6992. if (!func)
  6993. {
  6994. paramTypes.clear();
  6995. paramTypes.push_back(intType);
  6996. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  6997. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6998. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  6999. }
  7000. }
  7001. }
  7002. break;
  7003. case BfBuiltInFuncType_Free:
  7004. {
  7005. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7006. {
  7007. func = GetInternalMethod("Dbg_RawFree").mFunc;
  7008. }
  7009. else
  7010. {
  7011. String funcName = mCompiler->mOptions.mFreeLinkName;
  7012. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  7013. funcName = "free";
  7014. func = mBfIRBuilder->GetFunction(funcName);
  7015. if (!func)
  7016. {
  7017. paramTypes.clear();
  7018. paramTypes.push_back(nullPtrType);
  7019. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  7020. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  7021. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  7022. }
  7023. }
  7024. }
  7025. break;
  7026. case BfBuiltInFuncType_LoadSharedLibraries:
  7027. paramTypes.clear();
  7028. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  7029. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  7030. break;
  7031. default: break;
  7032. }
  7033. mBuiltInFuncs[(int)funcTypeId] = func;
  7034. return func;
  7035. }
  7036. return mBuiltInFuncs[(int)funcTypeId];
  7037. }
  7038. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized, Array<BfTypeReference*>* deferredResolveTypes)
  7039. {
  7040. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  7041. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  7042. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  7043. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  7044. BfAutoComplete* bfAutocomplete = NULL;
  7045. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  7046. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  7047. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  7048. {
  7049. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  7050. {
  7051. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  7052. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  7053. {
  7054. String filter = nameNode->ToString();
  7055. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  7056. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  7057. if (nameIdx != 0)
  7058. {
  7059. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  7060. }
  7061. }
  7062. }
  7063. }
  7064. for (auto constraint : constraintDef->mConstraints)
  7065. {
  7066. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  7067. {
  7068. BfGenericOperatorConstraintInstance opConstraintInstance;
  7069. if (opConstraint->mLeftType != NULL)
  7070. {
  7071. if (bfAutocomplete != NULL)
  7072. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  7073. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces_All);
  7074. if (opConstraintInstance.mLeftType == NULL)
  7075. continue;
  7076. }
  7077. if (opConstraint->mRightType == NULL)
  7078. {
  7079. // We had a failure in parsing
  7080. continue;
  7081. }
  7082. if (opConstraint->mRightType != NULL)
  7083. {
  7084. if (bfAutocomplete != NULL)
  7085. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  7086. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces_All);
  7087. if (opConstraintInstance.mRightType == NULL)
  7088. continue;
  7089. }
  7090. if (opConstraint->mOpToken == NULL)
  7091. {
  7092. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  7093. continue;
  7094. }
  7095. if (opConstraint->mLeftType != NULL)
  7096. {
  7097. if (opConstraint->mRightType == NULL)
  7098. {
  7099. // Parse should have failed
  7100. continue;
  7101. }
  7102. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  7103. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  7104. {
  7105. Fail("Invalid binary operator", opConstraint->mOpToken);
  7106. continue;
  7107. }
  7108. }
  7109. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  7110. {
  7111. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  7112. }
  7113. else
  7114. {
  7115. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  7116. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  7117. {
  7118. Fail("Invalid unary operator", opConstraint->mOpToken);
  7119. continue;
  7120. }
  7121. }
  7122. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  7123. continue;
  7124. }
  7125. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  7126. if (bfAutocomplete != NULL)
  7127. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  7128. //TODO: Constraints may refer to other generic params (of either type or method)
  7129. // TO allow resolution, perhaps move this generic param initialization into GetMethodInstance (passing a genericPass bool)
  7130. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_AllowGenericMethodParamConstValue;
  7131. if (isUnspecialized)
  7132. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_DisallowComptime);
  7133. // We we have a deferredResolveTypes then we defer the generic validation, because we may have a case like
  7134. // `where T : Dictionay<TElem, int> and TElem : IHashable` and we don't want to throw the error on `T` before we build `TElem`
  7135. BfType* constraintType;
  7136. if (constraintTypeRef->IsA<BfVarTypeReference>())
  7137. constraintType = GetPrimitiveType(BfTypeCode_Var);
  7138. else
  7139. constraintType = ResolveTypeRef(constraintTypeRef, (deferredResolveTypes != NULL) ? BfPopulateType_Identity : BfPopulateType_Declaration, resolveFlags);
  7140. if (constraintType != NULL)
  7141. {
  7142. if (deferredResolveTypes != NULL)
  7143. {
  7144. PopulateType(constraintType, BfPopulateType_Declaration);
  7145. if (constraintType->IsUnspecializedTypeVariation())
  7146. deferredResolveTypes->Add(constraintTypeRef);
  7147. }
  7148. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7149. {
  7150. bool isValidTypeCode = false;
  7151. BfTypeCode typeCode = BfTypeCode_None;
  7152. if (constraintType->IsTypedPrimitive())
  7153. {
  7154. auto underlyingType = constraintType->GetUnderlyingType();
  7155. if (underlyingType->IsPrimitiveType())
  7156. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  7157. }
  7158. if (constraintType->IsPrimitiveType())
  7159. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  7160. if (constraintType->IsInstanceOf(mCompiler->mStringTypeDef))
  7161. isValidTypeCode = true;
  7162. if (constraintType->IsValueType())
  7163. isValidTypeCode = true;
  7164. if (constraintType->IsVar())
  7165. isValidTypeCode = true;
  7166. switch (typeCode)
  7167. {
  7168. case BfTypeCode_StringId:
  7169. case BfTypeCode_Boolean:
  7170. case BfTypeCode_Int8:
  7171. case BfTypeCode_UInt8:
  7172. case BfTypeCode_Int16:
  7173. case BfTypeCode_UInt16:
  7174. case BfTypeCode_Int32:
  7175. case BfTypeCode_UInt32:
  7176. case BfTypeCode_Int64:
  7177. case BfTypeCode_UInt64:
  7178. case BfTypeCode_IntPtr:
  7179. case BfTypeCode_UIntPtr:
  7180. case BfTypeCode_IntUnknown:
  7181. case BfTypeCode_UIntUnknown:
  7182. case BfTypeCode_Float:
  7183. case BfTypeCode_Double:
  7184. case BfTypeCode_Char8:
  7185. case BfTypeCode_Char16:
  7186. case BfTypeCode_Char32:
  7187. isValidTypeCode = true;
  7188. break;
  7189. default: break;
  7190. }
  7191. if (isValidTypeCode)
  7192. {
  7193. genericParamInstance->mTypeConstraint = constraintType;
  7194. }
  7195. else
  7196. {
  7197. Fail("Const constraint must be a valuetype or string", constraintTypeRef);
  7198. }
  7199. }
  7200. else
  7201. {
  7202. bool checkEquality = false;
  7203. if (constraintType->IsVar())
  7204. {
  7205. // From a `comptype` generic undef resolution. Ignore.
  7206. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_ComptypeExpr);
  7207. genericParamInstance->mComptypeConstraint.Add(constraintTypeRef);
  7208. continue;
  7209. }
  7210. else if (constraintType->IsPrimitiveType())
  7211. {
  7212. checkEquality = true;
  7213. }
  7214. if (constraintType->IsArray())
  7215. {
  7216. if (isUnspecialized)
  7217. {
  7218. 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);
  7219. continue;
  7220. }
  7221. checkEquality = true;
  7222. }
  7223. if (constraintType->IsGenericParam())
  7224. {
  7225. checkEquality = true;
  7226. }
  7227. else if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  7228. {
  7229. checkEquality = true;
  7230. }
  7231. if (checkEquality)
  7232. {
  7233. genericParamInstance->mTypeConstraint = constraintType;
  7234. }
  7235. else if (constraintType->IsInterface())
  7236. {
  7237. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  7238. }
  7239. else
  7240. {
  7241. auto constraintTypeInst = constraintType->ToTypeInstance();
  7242. if (genericParamInstance->mTypeConstraint != NULL)
  7243. {
  7244. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  7245. {
  7246. // Allow more specific type
  7247. genericParamInstance->mTypeConstraint = constraintTypeInst;
  7248. }
  7249. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  7250. {
  7251. // Silently ignore less-specific type
  7252. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  7253. {
  7254. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  7255. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Class);
  7256. }
  7257. }
  7258. else
  7259. {
  7260. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  7261. return;
  7262. }
  7263. }
  7264. else
  7265. genericParamInstance->mTypeConstraint = constraintType;
  7266. }
  7267. }
  7268. }
  7269. }
  7270. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  7271. (genericParamInstance->mTypeConstraint == NULL))
  7272. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  7273. }
  7274. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  7275. {
  7276. if (genericParamSource.mMethodInstance != NULL)
  7277. {
  7278. //auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  7279. //SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  7280. return MethodToString(genericParamSource.mMethodInstance);
  7281. }
  7282. else
  7283. {
  7284. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  7285. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  7286. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  7287. return TypeToString(typeInst);
  7288. }
  7289. }
  7290. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  7291. {
  7292. Array<String> methodParamNameOverrides;
  7293. auto _TypeToString = [&](BfType* type)
  7294. {
  7295. if (genericParamSource.mMethodInstance != NULL)
  7296. {
  7297. if (methodParamNameOverrides.IsEmpty())
  7298. {
  7299. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  7300. methodParamNameOverrides.Add(genericParam->mName);
  7301. }
  7302. return TypeToString(type, &methodParamNameOverrides);
  7303. }
  7304. return TypeToString(type);
  7305. };
  7306. bool ignoreErrors = (errorOut == NULL) ||
  7307. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  7308. BfType* origCheckArgType = checkArgType;
  7309. if (origCheckArgType->IsRef())
  7310. origCheckArgType = origCheckArgType->GetUnderlyingType();
  7311. bool argIsReferenceType = false;
  7312. int checkGenericParamFlags = 0;
  7313. if (checkArgType->IsGenericParam())
  7314. {
  7315. BfGenericParamInstance* checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  7316. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  7317. if (checkGenericParamInst->mTypeConstraint != NULL)
  7318. checkArgType = checkGenericParamInst->mTypeConstraint;
  7319. if (checkGenericParamInst->mGenericParamFlags & BfGenericParamFlag_Var)
  7320. checkArgType = GetPrimitiveType(BfTypeCode_Var);
  7321. // if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  7322. // {
  7323. // argMayBeReferenceType = false;
  7324. // }
  7325. // else
  7326. // {
  7327. // argMayBeReferenceType = true;
  7328. // }
  7329. }
  7330. if (checkArgType->IsObjectOrInterface())
  7331. argIsReferenceType = true;
  7332. BfTypeInstance* typeConstraintInst = NULL;
  7333. if (genericParamInst->mTypeConstraint != NULL)
  7334. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  7335. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  7336. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  7337. {
  7338. if ((!ignoreErrors) && (PreFail()))
  7339. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  7340. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7341. return false;
  7342. }
  7343. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  7344. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  7345. {
  7346. if ((!ignoreErrors) && (PreFail()))
  7347. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  7348. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7349. return false;
  7350. }
  7351. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  7352. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argIsReferenceType))
  7353. {
  7354. if ((!ignoreErrors) && (PreFail()))
  7355. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  7356. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7357. return false;
  7358. }
  7359. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum)
  7360. {
  7361. bool isEnum = checkArgType->IsEnum();
  7362. if ((origCheckArgType->IsGenericParam()) && (checkArgType->IsInstanceOf(mCompiler->mEnumTypeDef)))
  7363. isEnum = true;
  7364. if (((checkGenericParamFlags & (BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!isEnum))
  7365. {
  7366. if ((!ignoreErrors) && (PreFail()))
  7367. *errorOut = Fail(StrFormat("The type '%s' must be an enum type in order to use it as parameter '%s' for '%s'",
  7368. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7369. return false;
  7370. }
  7371. }
  7372. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) &&
  7373. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (checkArgType->IsInterface()))
  7374. {
  7375. if ((!ignoreErrors) && (PreFail()))
  7376. *errorOut = Fail(StrFormat("The type '%s' must be an concrete type in order to use it as parameter '%s' for '%s'",
  7377. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7378. return false;
  7379. }
  7380. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Interface) &&
  7381. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsInterface()))
  7382. {
  7383. if ((!ignoreErrors) && (PreFail()))
  7384. *errorOut = Fail(StrFormat("The type '%s' must be an interface type in order to use it as parameter '%s' for '%s'",
  7385. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7386. return false;
  7387. }
  7388. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7389. {
  7390. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  7391. {
  7392. if ((!ignoreErrors) && (PreFail()))
  7393. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  7394. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7395. return false;
  7396. }
  7397. }
  7398. else
  7399. {
  7400. if (checkArgType->IsConstExprValue())
  7401. {
  7402. if ((!ignoreErrors) && (PreFail()))
  7403. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  7404. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7405. return false;
  7406. }
  7407. }
  7408. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  7409. {
  7410. bool canDelete = false;
  7411. if (checkArgType->IsPointer())
  7412. canDelete = true;
  7413. else if (checkArgType->IsObjectOrInterface())
  7414. canDelete = true;
  7415. else if ((checkGenericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var)) != 0)
  7416. canDelete = true;
  7417. if (!canDelete)
  7418. {
  7419. if ((!ignoreErrors) && (PreFail()))
  7420. {
  7421. if (checkArgType->IsGenericParam())
  7422. *errorOut = Fail(StrFormat("Must add 'where %s : delete' constraint in order to use type as parameter '%s' for '%s'",
  7423. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7424. else
  7425. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  7426. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7427. }
  7428. return false;
  7429. }
  7430. }
  7431. if (checkArgType->IsPointer())
  7432. {
  7433. auto ptrType = (BfPointerType*)checkArgType;
  7434. checkArgType = ptrType->mElementType;
  7435. }
  7436. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  7437. {
  7438. bool canAlloc = false;
  7439. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  7440. {
  7441. if (checkTypeInst->IsObjectOrStruct())
  7442. {
  7443. checkTypeInst->mTypeDef->PopulateMemberSets();
  7444. BfMemberSetEntry* entry = NULL;
  7445. BfMethodDef* checkMethodDef = NULL;
  7446. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  7447. if (entry != NULL)
  7448. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  7449. bool hadProtected = false;
  7450. while (checkMethodDef != NULL)
  7451. {
  7452. if (!checkMethodDef->mParams.IsEmpty())
  7453. {
  7454. auto firstParam = checkMethodDef->mParams[0];
  7455. if (((firstParam->mParamKind == BfParamKind_Params) || (firstParam->mParamKind == BfParamKind_AppendIdx) || (firstParam->mParamKind == BfParamKind_VarArgs)) ||
  7456. ((firstParam->mParamDeclaration != NULL) && (firstParam->mParamDeclaration->mInitializer != NULL)))
  7457. {
  7458. // Allow all-default params
  7459. }
  7460. else
  7461. {
  7462. checkMethodDef = checkMethodDef->mNextWithSameName;
  7463. continue;
  7464. }
  7465. }
  7466. if (checkMethodDef->mProtection == BfProtection_Public)
  7467. {
  7468. canAlloc = true;
  7469. break;
  7470. }
  7471. if ((checkMethodDef->mProtection == BfProtection_Protected) || (checkMethodDef->mProtection == BfProtection_ProtectedInternal))
  7472. hadProtected = true;
  7473. checkMethodDef = checkMethodDef->mNextWithSameName;
  7474. }
  7475. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  7476. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  7477. }
  7478. }
  7479. else if (checkArgType->IsGenericParam())
  7480. {
  7481. canAlloc = (checkGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) != 0;
  7482. }
  7483. else if (checkArgType->IsPrimitiveType())
  7484. {
  7485. // Any primitive types and stuff can be allocated
  7486. canAlloc = true;
  7487. }
  7488. if (!canAlloc)
  7489. {
  7490. if ((!ignoreErrors) && (PreFail()))
  7491. {
  7492. if (checkArgType->IsGenericParam())
  7493. *errorOut = Fail(StrFormat("Must add 'where %s : new' constraint in order to use type as parameter '%s' for '%s'",
  7494. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7495. else
  7496. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  7497. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7498. }
  7499. return false;
  7500. }
  7501. }
  7502. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  7503. return true;
  7504. if (genericParamInst->mTypeConstraint != NULL)
  7505. {
  7506. bool constraintMatched = false;
  7507. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7508. {
  7509. if (checkArgType->IsConstExprValue())
  7510. {
  7511. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  7512. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  7513. {
  7514. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  7515. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  7516. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  7517. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  7518. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  7519. (primType->mTypeDef->mTypeCode != BfTypeCode_Let) &&
  7520. (primType->mTypeDef->mTypeCode != BfTypeCode_Var))
  7521. {
  7522. bool doError = true;
  7523. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  7524. {
  7525. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7526. {
  7527. if (mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue))
  7528. doError = false;
  7529. }
  7530. }
  7531. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_Float) && ((constExprValueType->mValue.mTypeCode == BfTypeCode_Double)))
  7532. {
  7533. doError = false;
  7534. }
  7535. if (doError)
  7536. {
  7537. if ((!ignoreErrors) && (PreFail()))
  7538. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7539. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7540. return false;
  7541. }
  7542. }
  7543. }
  7544. else if (genericParamInst->mTypeConstraint != constExprValueType->mType)
  7545. {
  7546. if ((!ignoreErrors) && (PreFail()))
  7547. *errorOut = Fail(StrFormat("Const generic argument '%s', declared as '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7548. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7549. return false;
  7550. }
  7551. }
  7552. }
  7553. else
  7554. {
  7555. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  7556. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  7557. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7558. if (convCheckConstraint == NULL)
  7559. return false;
  7560. if ((checkArgType->IsMethodRef()) || (checkArgType->IsFunction()))
  7561. {
  7562. if (convCheckConstraint->IsDelegate())
  7563. {
  7564. BfMethodInstance* checkMethodInstance;
  7565. if (checkArgType->IsMethodRef())
  7566. {
  7567. auto methodRefType = (BfMethodRefType*)checkArgType;
  7568. checkMethodInstance = methodRefType->mMethodRef;
  7569. }
  7570. else
  7571. {
  7572. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  7573. }
  7574. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  7575. if (checkMethodInstance->HasExplicitThis() != 0)
  7576. {
  7577. // Don't allow functions with explicit 'this'
  7578. }
  7579. else
  7580. {
  7581. BfExprEvaluator exprEvaluator(this);
  7582. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  7583. constraintMatched = true;
  7584. }
  7585. }
  7586. else if (convCheckConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef))
  7587. constraintMatched = true;
  7588. else if ((checkArgType->IsFunction()) && (convCheckConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))
  7589. constraintMatched = true;
  7590. }
  7591. else if ((checkArgType == convCheckConstraint) || (checkArgType->IsVar()) || (TypeIsSubTypeOf(checkArgType->ToTypeInstance(), convCheckConstraint->ToTypeInstance())))
  7592. {
  7593. constraintMatched = true;
  7594. }
  7595. else if (origCheckArgType->IsWrappableType())
  7596. {
  7597. if (origCheckArgType->IsSizedArray())
  7598. {
  7599. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  7600. if (convCheckConstraint->IsGenericTypeInstance())
  7601. {
  7602. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  7603. if (convCheckConstraintInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  7604. {
  7605. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  7606. {
  7607. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  7608. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  7609. constraintMatched = true;
  7610. }
  7611. }
  7612. }
  7613. }
  7614. if (!constraintMatched)
  7615. {
  7616. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7617. if ((wrappedStructType == convCheckConstraint) || (TypeIsSubTypeOf(wrappedStructType, convCheckConstraint->ToTypeInstance())))
  7618. constraintMatched = true;
  7619. }
  7620. }
  7621. if (!constraintMatched)
  7622. {
  7623. if ((!ignoreErrors) && (PreFail()))
  7624. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  7625. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  7626. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  7627. return false;
  7628. }
  7629. }
  7630. }
  7631. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  7632. {
  7633. BfType* convCheckConstraint = checkConstraint;
  7634. if (convCheckConstraint->IsUnspecializedType())
  7635. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7636. if (convCheckConstraint == NULL)
  7637. return false;
  7638. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  7639. bool implementsInterface = false;
  7640. if (origCheckArgType != checkArgType)
  7641. {
  7642. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  7643. }
  7644. if (!implementsInterface)
  7645. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  7646. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  7647. {
  7648. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7649. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7650. implementsInterface = true;
  7651. }
  7652. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  7653. {
  7654. auto underlyingType = origCheckArgType->GetUnderlyingType();
  7655. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  7656. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7657. implementsInterface = true;
  7658. }
  7659. if (!implementsInterface)
  7660. {
  7661. if ((!ignoreErrors) && (PreFail()))
  7662. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  7663. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  7664. return false;
  7665. }
  7666. }
  7667. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  7668. {
  7669. auto leftType = checkOpConstraint.mLeftType;
  7670. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  7671. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs, mCurTypeInstance);
  7672. if (leftType != NULL)
  7673. leftType = FixIntUnknown(leftType);
  7674. auto rightType = checkOpConstraint.mRightType;
  7675. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  7676. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs, mCurTypeInstance);
  7677. if (rightType != NULL)
  7678. rightType = FixIntUnknown(rightType);
  7679. BfConstraintState constraintSet;
  7680. constraintSet.mPrevState = mContext->mCurConstraintState;
  7681. constraintSet.mGenericParamInstance = genericParamInst;
  7682. constraintSet.mLeftType = leftType;
  7683. constraintSet.mRightType = rightType;
  7684. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  7685. if (!CheckConstraintState(NULL))
  7686. return false;
  7687. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  7688. {
  7689. BfExprEvaluator exprEvaluator(this);
  7690. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  7691. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7692. //
  7693. {
  7694. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7695. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7696. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  7697. }
  7698. if ((!exprEvaluator.mResult) ||
  7699. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  7700. {
  7701. if ((!ignoreErrors) && (PreFail()))
  7702. {
  7703. if (genericParamInst->mExternType != NULL)
  7704. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  7705. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  7706. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7707. ), checkArgTypeRef);
  7708. else
  7709. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  7710. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7711. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7712. ), checkArgTypeRef);
  7713. }
  7714. return false;
  7715. }
  7716. }
  7717. else
  7718. {
  7719. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7720. StringT<128> failedOpName;
  7721. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  7722. {
  7723. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7724. failedOpName = "implicit conversion from '";
  7725. }
  7726. else
  7727. {
  7728. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7729. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7730. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  7731. {
  7732. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7733. failedOpName = "explicit conversion from '";
  7734. }
  7735. else
  7736. {
  7737. BfExprEvaluator exprEvaluator(this);
  7738. exprEvaluator.mResult = rightValue;
  7739. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  7740. if ((!exprEvaluator.mResult) ||
  7741. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  7742. {
  7743. failedOpName += "unary operation '";
  7744. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  7745. }
  7746. }
  7747. }
  7748. if (!failedOpName.IsEmpty())
  7749. {
  7750. if ((!ignoreErrors) && (PreFail()))
  7751. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  7752. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7753. failedOpName.c_str(), TypeToString(rightType).c_str()
  7754. ), checkArgTypeRef);
  7755. return false;
  7756. }
  7757. }
  7758. }
  7759. return true;
  7760. }
  7761. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  7762. {
  7763. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  7764. {
  7765. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  7766. return genericParamType;
  7767. }
  7768. auto genericParamType = new BfGenericParamType();
  7769. genericParamType->mContext = mContext;
  7770. genericParamType->mGenericParamKind = paramKind;
  7771. genericParamType->mGenericParamIdx = paramIdx;
  7772. PopulateType(genericParamType);
  7773. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  7774. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  7775. BfResolvedTypeSet::LookupContext lookupCtx;
  7776. lookupCtx.mModule = this;
  7777. BfResolvedTypeSet::EntryRef typeEntry;
  7778. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  7779. BF_ASSERT(inserted);
  7780. typeEntry->mValue = genericParamType;
  7781. return genericParamType;
  7782. }
  7783. static int sValueFromExprIdx = 0;
  7784. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  7785. {
  7786. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  7787. if ((result) && (!ignoreNullable))
  7788. {
  7789. if (result.mType->IsVar())
  7790. return result;
  7791. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  7792. //TODO: Make this work, needed for 'void' and such
  7793. BfType* nullableType = NULL;
  7794. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  7795. {
  7796. BfTypeVector typeVec;
  7797. typeVec.push_back(result.mType);
  7798. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  7799. BF_ASSERT(nullableType != NULL);
  7800. }
  7801. // Go back to start and do any setup we need
  7802. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7803. BfTypedValue nullableTypedValue;
  7804. if (nullableType != NULL)
  7805. {
  7806. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  7807. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  7808. GetConstValue(nullableType->mSize), nullableType->mAlign);
  7809. }
  7810. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7811. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  7812. mBfIRBuilder->SetInsertPoint(notNullBB);
  7813. result = LoadValue(result);
  7814. if (nullableTypedValue)
  7815. {
  7816. auto elementType = nullableType->GetUnderlyingType();
  7817. if (elementType->IsVar())
  7818. {
  7819. // Do nothing
  7820. }
  7821. else if (elementType->IsValuelessType())
  7822. {
  7823. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  7824. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  7825. }
  7826. else
  7827. {
  7828. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  7829. mBfIRBuilder->CreateAlignedStore(result.mValue, ptrValue, result.mType->mAlign);
  7830. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  7831. mBfIRBuilder->CreateAlignedStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue, 1);
  7832. }
  7833. result = nullableTypedValue;
  7834. }
  7835. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7836. AddBasicBlock(pendingNullCond->mDoneBB);
  7837. if (nullableType == NULL)
  7838. {
  7839. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  7840. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  7841. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  7842. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  7843. {
  7844. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  7845. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  7846. }
  7847. result.mValue = phi;
  7848. }
  7849. }
  7850. else
  7851. {
  7852. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7853. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7854. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7855. AddBasicBlock(pendingNullCond->mDoneBB);
  7856. }
  7857. delete mCurMethodState->mPendingNullConditional;
  7858. mCurMethodState->mPendingNullConditional = NULL;
  7859. return result;
  7860. }
  7861. BF_NOINLINE void BfModule::EvaluateWithNewConditionalScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  7862. {
  7863. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  7864. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData);
  7865. if (mCurMethodState != NULL)
  7866. {
  7867. deferredLocalAssignData.mIsIfCondition = true;
  7868. deferredLocalAssignData.mIfMayBeSkipped = true;
  7869. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  7870. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  7871. mCurMethodState->mDeferredLocalAssignData = &deferredLocalAssignData;
  7872. }
  7873. BfScopeData newScope;
  7874. newScope.mOuterIsConditional = true;
  7875. newScope.mAllowTargeting = false;
  7876. if (mCurMethodState != NULL)
  7877. {
  7878. mCurMethodState->AddScope(&newScope);
  7879. NewScopeState(true, false);
  7880. }
  7881. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7882. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  7883. if (mCurMethodState != NULL)
  7884. RestoreScopeState();
  7885. }
  7886. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7887. {
  7888. //
  7889. {
  7890. BP_ZONE("CreateValueFromExpression:CheckStack");
  7891. StackHelper stackHelper;
  7892. if (!stackHelper.CanStackExpand(128 * 1024))
  7893. {
  7894. BfTypedValue result;
  7895. if (!stackHelper.Execute([&]()
  7896. {
  7897. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7898. }))
  7899. {
  7900. Fail("Expression too complex to compile", expr);
  7901. }
  7902. return result;
  7903. }
  7904. }
  7905. BP_ZONE("BfModule::CreateValueFromExpression");
  7906. if (outOrigType != NULL)
  7907. *outOrigType = NULL;
  7908. exprEvaluator.mExpectingType = wantTypeRef;
  7909. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7910. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  7911. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  7912. {
  7913. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope->mScopeKind != BfScopeKind_StatementTarget_Conditional))
  7914. {
  7915. EvaluateWithNewConditionalScope(exprEvaluator, expr, flags);
  7916. }
  7917. else
  7918. {
  7919. SetAndRestoreValue<bool> prevIsConditional(mCurMethodState->mCurScope->mIsConditional, true);
  7920. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7921. }
  7922. }
  7923. else
  7924. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7925. if (!exprEvaluator.mResult)
  7926. {
  7927. if ((flags & BfEvalExprFlags_InferReturnType) != 0)
  7928. return exprEvaluator.mResult;
  7929. if (!mCompiler->mPassInstance->HasFailed())
  7930. {
  7931. if (PreFail())
  7932. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  7933. }
  7934. return BfTypedValue();
  7935. }
  7936. auto typedVal = exprEvaluator.mResult;
  7937. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  7938. {
  7939. BF_ASSERT(typedVal.mType->IsGenericParam());
  7940. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  7941. bool handled = false;
  7942. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7943. {
  7944. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  7945. if (genericTypeConstraint != NULL)
  7946. {
  7947. auto underlyingConstraint = genericTypeConstraint;
  7948. if ((underlyingConstraint != NULL) && (underlyingConstraint->IsBoxed()))
  7949. underlyingConstraint = underlyingConstraint->GetUnderlyingType();
  7950. if (underlyingConstraint != NULL)
  7951. {
  7952. BfTypedValue result;
  7953. result.mKind = BfTypedValueKind_Value;
  7954. result.mType = genericTypeConstraint;
  7955. result.mValue = mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(underlyingConstraint));
  7956. typedVal = result;
  7957. handled = true;
  7958. }
  7959. }
  7960. }
  7961. if (!handled)
  7962. {
  7963. //Fail("Only const generic parameters can be used as values", expr);
  7964. AssertErrorState();
  7965. return BfTypedValue();
  7966. }
  7967. }
  7968. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  7969. FixIntUnknown(typedVal);
  7970. if (!mBfIRBuilder->mIgnoreWrites)
  7971. FixValueActualization(typedVal);
  7972. exprEvaluator.CheckResultForReading(typedVal);
  7973. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  7974. {
  7975. if ((flags & BfEvalExprFlags_NoCast) == 0)
  7976. {
  7977. // Only allow a 'ref' type if we have an explicit 'ref' operator
  7978. bool allowRef = false;
  7979. BfAstNode* checkExpr = expr;
  7980. while (checkExpr != NULL)
  7981. {
  7982. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  7983. checkExpr = parenExpr->mExpression;
  7984. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  7985. {
  7986. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  7987. allowRef = true;
  7988. break;
  7989. }
  7990. if (auto block = BfNodeDynCast<BfBlock>(checkExpr))
  7991. {
  7992. if (block->mChildArr.mSize == 0)
  7993. break;
  7994. checkExpr = block->mChildArr.back();
  7995. }
  7996. else
  7997. break;
  7998. }
  7999. if (!allowRef)
  8000. typedVal = RemoveRef(typedVal);
  8001. }
  8002. }
  8003. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  8004. {
  8005. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsDataIncomplete()) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  8006. {
  8007. if (typedVal.mValue.IsFake())
  8008. {
  8009. InternalError("Unexpected fakeval in CreateValueFromExpression");
  8010. typedVal = GetDefaultTypedValue(typedVal.mType);
  8011. }
  8012. }
  8013. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8014. }
  8015. if (wantTypeRef != NULL)
  8016. {
  8017. if (outOrigType != NULL)
  8018. *outOrigType = typedVal.mType;
  8019. if (((flags & BfEvalExprFlags_NoCast) == 0) && (!wantTypeRef->IsVar()))
  8020. {
  8021. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  8022. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  8023. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  8024. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  8025. if (!typedVal)
  8026. return typedVal;
  8027. }
  8028. if (exprEvaluator.mIsVolatileReference)
  8029. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8030. }
  8031. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  8032. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8033. if (auto autoComplete = mCompiler->GetAutoComplete())
  8034. autoComplete->CheckResult(expr, typedVal);
  8035. return typedVal;
  8036. }
  8037. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  8038. {
  8039. BfExprEvaluator exprEvaluator(this);
  8040. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  8041. }
  8042. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  8043. {
  8044. BfExprEvaluator exprEvaluator(this);
  8045. exprEvaluator.Evaluate(expr);
  8046. if (!exprEvaluator.mResult)
  8047. {
  8048. Fail("Invalid expression type", expr);
  8049. return BfTypedValue();
  8050. }
  8051. if (!exprEvaluator.mResult.IsAddr())
  8052. {
  8053. Fail("Cannot assign to value", expr);
  8054. return BfTypedValue();
  8055. }
  8056. return exprEvaluator.mResult;
  8057. }
  8058. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  8059. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  8060. {
  8061. auto typeInstance = typedValue.mType->ToTypeInstance();
  8062. if (zeroMemory)
  8063. {
  8064. int zeroAlign = typedValue.mType->mAlign;
  8065. if (typeInstance != NULL)
  8066. zeroAlign = typeInstance->mInstAlign;
  8067. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  8068. }
  8069. if (!typedValue.mType->IsObject())
  8070. {
  8071. return;
  8072. }
  8073. if ((scopeData == NULL) && (mCurMethodState != NULL))
  8074. return; // Handled in heap alloc funcs
  8075. auto typeDef = typeInstance->mTypeDef;
  8076. mBfIRBuilder->PopulateType(typedValue.mType);
  8077. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  8078. bool isAutocomplete = mCompiler->IsAutocomplete();
  8079. BfIRValue vDataRef;
  8080. if (!isAutocomplete)
  8081. {
  8082. vDataRef = GetClassVDataPtr(typeInstance);
  8083. }
  8084. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8085. auto ptrType = CreatePointerType(i8Type);
  8086. auto ptrPtrType = CreatePointerType(ptrType);
  8087. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  8088. PopulateType(ptrType, BfPopulateType_Declaration);
  8089. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  8090. if (!isAutocomplete)
  8091. {
  8092. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8093. {
  8094. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8095. SizedArray<BfIRValue, 4> llvmArgs;
  8096. llvmArgs.push_back(objectPtr);
  8097. llvmArgs.push_back(vDataRef);
  8098. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  8099. if (objectStackInitMethod)
  8100. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  8101. }
  8102. else
  8103. {
  8104. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  8105. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  8106. mBfIRBuilder->CreateStore(srcVal, destAddr);
  8107. }
  8108. }
  8109. }
  8110. bool BfModule::IsAllocatorAligned()
  8111. {
  8112. if (mCompiler->mOptions.mMallocLinkName == "StompAlloc")
  8113. return false;
  8114. return true;
  8115. }
  8116. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  8117. {
  8118. BfIRValue result;
  8119. BfType* ptrType;
  8120. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  8121. ptrType = type;
  8122. else
  8123. ptrType = CreatePointerType(type);
  8124. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  8125. {
  8126. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8127. SizedArray<BfExpression*, 2> argExprs;
  8128. BfTypedValueExpression typedValueExpr;
  8129. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  8130. typedValueExpr.mRefNode = refNode;
  8131. argExprs.push_back(&typedValueExpr);
  8132. BfTypedValueExpression appendSizeValueExpr;
  8133. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  8134. appendSizeValueExpr.mRefNode = refNode;
  8135. argExprs.push_back(&appendSizeValueExpr);
  8136. BfExprEvaluator exprEvaluator(this);
  8137. BfTypedValue allocResult;
  8138. if (allocTarget.mScopedInvocationTarget != NULL)
  8139. {
  8140. SizedArray<BfTypeReference*, 2> genericArgs;
  8141. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, BfMethodGenericArguments());
  8142. allocResult = LoadValue(exprEvaluator.mResult);
  8143. }
  8144. else if (allocTarget.mCustomAllocator)
  8145. {
  8146. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8147. if (customTypeInst == NULL)
  8148. {
  8149. if (allocTarget.mCustomAllocator.mType->IsStructPtr())
  8150. customTypeInst = allocTarget.mCustomAllocator.mType->GetUnderlyingType()->ToTypeInstance();
  8151. }
  8152. if (customTypeInst == NULL)
  8153. {
  8154. Fail(StrFormat("Type '%s' cannot be used as a custom allocator", TypeToString(allocTarget.mCustomAllocator.mType).c_str()), refNode);
  8155. }
  8156. else
  8157. {
  8158. BfTypedValueExpression typeValueExpr;
  8159. String allocMethodName = "Alloc";
  8160. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  8161. {
  8162. allocMethodName = "AllocTyped";
  8163. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  8164. auto typeRefVal = CreateTypeDataRef(type);
  8165. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  8166. typeValueExpr.mRefNode = refNode;
  8167. argExprs.Insert(0, &typeValueExpr);
  8168. }
  8169. if (HasMixin(customTypeInst, allocMethodName, 2))
  8170. {
  8171. BfSizedArray<BfExpression*> argExprArr;
  8172. argExprArr.mSize = (int)argExprs.size();
  8173. argExprArr.mVals = &argExprs[0];
  8174. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  8175. allocResult = exprEvaluator.GetResult();
  8176. }
  8177. else
  8178. {
  8179. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8180. BfResolvedArgs argValues(&sizedArgExprs);
  8181. exprEvaluator.ResolveArgValues(argValues);
  8182. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  8183. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, BfMethodGenericArguments());
  8184. }
  8185. }
  8186. }
  8187. if (allocResult)
  8188. {
  8189. if (allocResult.mType->IsVoidPtr())
  8190. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  8191. else
  8192. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  8193. return result;
  8194. }
  8195. }
  8196. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  8197. return result;
  8198. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8199. {
  8200. BfIRValue allocData = GetDbgRawAllocData(type);
  8201. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  8202. SizedArray<BfIRValue, 2> llvmArgs;
  8203. llvmArgs.push_back(sizeValue);
  8204. llvmArgs.push_back(allocData);
  8205. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  8206. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8207. }
  8208. BfModuleMethodInstance moduleMethodInstance;
  8209. moduleMethodInstance = GetInternalMethod("Malloc");
  8210. SizedArray<BfIRValue, 1> llvmArgs;
  8211. llvmArgs.push_back(sizeValue);
  8212. auto func = moduleMethodInstance.mFunc;
  8213. if ((!func) || (func.IsFake()))
  8214. {
  8215. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  8216. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  8217. }
  8218. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  8219. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  8220. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  8221. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8222. return result;
  8223. }
  8224. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  8225. {
  8226. if (type->IsStruct())
  8227. {
  8228. auto typeInstance = type->ToTypeInstance();
  8229. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  8230. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8231. }
  8232. else if (type->IsObjectOrInterface())
  8233. {
  8234. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8235. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  8236. BF_ASSERT(moduleMethodInst.mFunc);
  8237. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8238. }
  8239. else
  8240. {
  8241. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8242. BfExprEvaluator exprEvaluator(this);
  8243. SizedArray<BfResolvedArg, 1> resolvedArgs;
  8244. BfResolvedArg resolvedArg;
  8245. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  8246. resolvedArgs.Add(resolvedArg);
  8247. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, BfMethodGenericArguments());
  8248. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  8249. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  8250. BF_ASSERT(moduleMethodInst.mFunc);
  8251. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8252. }
  8253. return BfIRValue();
  8254. }
  8255. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  8256. {
  8257. BfIRValue allocDataValue;
  8258. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  8259. return allocDataValue;
  8260. BfIRValue markFuncPtr;
  8261. if (type->WantsGCMarking())
  8262. markFuncPtr = GetMarkFuncPtr(type);
  8263. else
  8264. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8265. BfIRValue typeDataRef = CreateTypeDataRef(type);
  8266. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  8267. BfTypeInstance* typeInstance = type->ToTypeInstance();
  8268. if (typeInstance == NULL)
  8269. {
  8270. typeInstance = GetWrappedStructType(type);
  8271. if (typeInstance != NULL)
  8272. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8273. }
  8274. if (typeInstance != NULL)
  8275. PopulateType(typeInstance);
  8276. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8277. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  8278. {
  8279. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8280. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8281. }
  8282. SizedArray<BfIRValue, 2> dataValues;
  8283. dataValues.Add(mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  8284. dataValues.Add(typeDataRef);
  8285. dataValues.Add(markFuncPtr);
  8286. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  8287. BfIRValue dataStruct = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  8288. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  8289. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  8290. return allocDataValue;
  8291. }
  8292. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  8293. {
  8294. BP_ZONE("AllocFromType");
  8295. BfScopeData* scopeData = allocTarget.mScopeData;
  8296. BF_ASSERT(!type->IsVar());
  8297. auto typeInstance = type->ToTypeInstance();
  8298. if ((typeInstance == NULL) && (type->IsGenericParam()))
  8299. typeInstance = mContext->mBfObjectType;
  8300. bool isHeapAlloc = scopeData == NULL;
  8301. bool isScopeAlloc = scopeData != NULL;
  8302. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  8303. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  8304. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  8305. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  8306. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  8307. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  8308. {
  8309. BfPointerType* ptrType = CreatePointerType(type);
  8310. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  8311. return val;
  8312. }
  8313. if (typeInstance != NULL)
  8314. mBfIRBuilder->PopulateType(typeInstance);
  8315. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  8316. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  8317. {
  8318. return mBfIRBuilder->GetFakeVal();
  8319. }
  8320. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8321. BfIRValue sizeValue;
  8322. BfIRType allocType = mBfIRBuilder->MapType(type);
  8323. int allocSize = type->mSize;
  8324. int allocAlign = type->mAlign;
  8325. if (typeInstance != NULL)
  8326. {
  8327. if ((!mBfIRBuilder->mIgnoreWrites) && (!mIsComptimeModule))
  8328. typeInstance->mHasBeenInstantiated = true;
  8329. allocSize = typeInstance->mInstSize;
  8330. allocAlign = typeInstance->mInstAlign;
  8331. //if (typeInstance->IsEnum())
  8332. //allocType = typeInstance->mIRType;
  8333. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  8334. }
  8335. if (alignOverride != -1)
  8336. allocAlign = alignOverride;
  8337. // The "dynSize" cases:
  8338. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  8339. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  8340. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  8341. // though we'd expect their stack space to be released
  8342. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  8343. {
  8344. MarkDynStack(scopeData);
  8345. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8346. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  8347. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  8348. BfType* voidPtrType = CreatePointerType(voidType);
  8349. if (!mCurMethodState->mDynStackRevIdx)
  8350. {
  8351. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  8352. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8353. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8354. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  8355. mBfIRBuilder->ClearDebugLocation(storeInst);
  8356. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8357. }
  8358. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  8359. auto bytePtrType = CreatePointerType(byteType);
  8360. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  8361. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  8362. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8363. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8364. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  8365. mBfIRBuilder->ClearDebugLocation(storeInst);
  8366. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  8367. mBfIRBuilder->ClearDebugLocation(storeInst);
  8368. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8369. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  8370. if (IsTargetingBeefBackend())
  8371. {
  8372. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  8373. // to ensure there isn't any register collision during looping is just to not allow it to
  8374. // bind to a register at all
  8375. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  8376. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  8377. }
  8378. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  8379. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  8380. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  8381. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  8382. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  8383. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  8384. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  8385. mBfIRBuilder->AddBlock(verCheckBB);
  8386. mBfIRBuilder->SetInsertPoint(verCheckBB);
  8387. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  8388. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  8389. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  8390. mBfIRBuilder->AddBlock(resizeBB);
  8391. mBfIRBuilder->SetInsertPoint(resizeBB);
  8392. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8393. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  8394. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  8395. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  8396. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  8397. mBfIRBuilder->CreateBr(endBB);
  8398. mBfIRBuilder->AddBlock(endBB);
  8399. mBfIRBuilder->SetInsertPoint(endBB);
  8400. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  8401. };
  8402. if (isScopeAlloc)
  8403. {
  8404. if (arraySize)
  8405. {
  8406. bool isConstantArraySize = arraySize.IsConst();
  8407. if (isRawArrayAlloc)
  8408. {
  8409. BfPointerType* ptrType = CreatePointerType(type);
  8410. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8411. {
  8412. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8413. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  8414. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  8415. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  8416. }
  8417. else
  8418. {
  8419. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8420. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  8421. if (!isDynAlloc)
  8422. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8423. else
  8424. {
  8425. MarkDynStack(scopeData);
  8426. SaveStackState(scopeData);
  8427. }
  8428. int typeSize = type->GetStride();
  8429. BfIRValue allocaInst;
  8430. BfIRValue result;
  8431. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  8432. {
  8433. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  8434. result = allocaInst;
  8435. }
  8436. else
  8437. {
  8438. if (typeInstance->IsStruct())
  8439. typeSize = typeInstance->GetInstStride();
  8440. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  8441. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  8442. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8443. auto ptrType = CreatePointerType(typeInstance);
  8444. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  8445. if (!isDynAlloc)
  8446. mBfIRBuilder->ClearDebugLocation(result);
  8447. }
  8448. if (!isDynAlloc)
  8449. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8450. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8451. if (!isDynAlloc)
  8452. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8453. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  8454. if (arraySize.IsConst())
  8455. {
  8456. auto constant = mBfIRBuilder->GetConstant(arraySize);
  8457. if (constant->mInt64 == 0)
  8458. noDtorCall = true;
  8459. }
  8460. if (!noDtorCall)
  8461. {
  8462. bool isConstSize = arraySize.IsConst();
  8463. BfIRBlock clearBlock;
  8464. BfIRBlock contBlock;
  8465. bool wantsDeinit = ((!IsOptimized()) && (!mIsComptimeModule) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly));
  8466. if (wantsDeinit)
  8467. {
  8468. BfIRBlock prevBlock;
  8469. if (!isConstSize)
  8470. {
  8471. clearBlock = mBfIRBuilder->CreateBlock("clear");
  8472. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  8473. prevBlock = mBfIRBuilder->GetInsertBlock();
  8474. mBfIRBuilder->AddBlock(clearBlock);
  8475. mBfIRBuilder->SetInsertPoint(clearBlock);
  8476. }
  8477. auto deferredCall = AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  8478. if (!isConstSize)
  8479. {
  8480. mBfIRBuilder->CreateBr(contBlock);
  8481. mBfIRBuilder->SetInsertPoint(prevBlock);
  8482. if (deferredCall != NULL)
  8483. {
  8484. // Zero out size args
  8485. for (int i = 1; i < deferredCall->mModuleMethodInstance.mMethodInstance->GetParamCount(); i++)
  8486. {
  8487. auto scopedArg = deferredCall->mScopeArgs[i];
  8488. if (scopedArg != deferredCall->mOrigScopeArgs[i])
  8489. mBfIRBuilder->CreateStore(GetDefaultValue(deferredCall->mModuleMethodInstance.mMethodInstance->GetParamType(i)), deferredCall->mScopeArgs[i]);
  8490. }
  8491. }
  8492. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  8493. mBfIRBuilder->AddBlock(contBlock);
  8494. mBfIRBuilder->SetInsertPoint(contBlock);
  8495. }
  8496. }
  8497. }
  8498. return result;
  8499. }
  8500. }
  8501. else
  8502. {
  8503. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8504. {
  8505. // Generate and check new size
  8506. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8507. auto firstElementField = &arrayType->mFieldInstances.back();
  8508. int arrayClassSize = firstElementField->mDataOffset;
  8509. sizeValue = GetConstValue(arrayClassSize);
  8510. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8511. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8512. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  8513. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  8514. if (!noDtorCall)
  8515. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8516. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8517. return typedVal.mValue;
  8518. }
  8519. else
  8520. {
  8521. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8522. auto firstElementField = &arrayType->mFieldInstances.back();
  8523. if (!type->IsValuelessType())
  8524. {
  8525. int arrayClassSize = firstElementField->mDataOffset;
  8526. sizeValue = GetConstValue(arrayClassSize);
  8527. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8528. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8529. }
  8530. else
  8531. sizeValue = GetConstValue(arrayType->mInstSize);
  8532. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8533. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8534. if (!isDynAlloc)
  8535. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8536. else
  8537. {
  8538. MarkDynStack(scopeData);
  8539. SaveStackState(scopeData);
  8540. }
  8541. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  8542. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8543. if (!isDynAlloc)
  8544. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8545. auto allocaBlock = mBfIRBuilder->GetInsertBlock();
  8546. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8547. BfTypedValue typedVal;
  8548. if (!isDynAlloc)
  8549. {
  8550. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8551. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8552. mBfIRBuilder->ClearDebugLocation(typedVal.mValue);
  8553. mBfIRBuilder->SetInsertPoint(prevBlock);
  8554. allocaBlock = mCurMethodState->mIRInitBlock;
  8555. }
  8556. else
  8557. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8558. if (!noDtorCall)
  8559. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true, allocaBlock);
  8560. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8561. return typedVal.mValue;
  8562. }
  8563. }
  8564. }
  8565. else if (appendSizeValue)
  8566. {
  8567. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  8568. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  8569. // use the "dynSize" version conservatively
  8570. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8571. {
  8572. // Generate and check new size
  8573. sizeValue = GetConstValue(typeInstance->mInstSize);
  8574. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8575. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  8576. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  8577. if (!noDtorCall)
  8578. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  8579. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8580. return typedVal.mValue;
  8581. }
  8582. else // stack alloc, unlooped, with append
  8583. {
  8584. sizeValue = GetConstValue(typeInstance->mInstSize);
  8585. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8586. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8587. bool wasDynAlloc = isDynAlloc;
  8588. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8589. if (!isDynAlloc)
  8590. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8591. else
  8592. {
  8593. MarkDynStack(scopeData);
  8594. SaveStackState(scopeData);
  8595. }
  8596. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  8597. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  8598. if (!isDynAlloc)
  8599. {
  8600. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8601. }
  8602. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8603. bool mayBeLarge = false;
  8604. if (sizeValue.IsConst())
  8605. {
  8606. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  8607. if (constantInt->mInt64 >= 4096)
  8608. mayBeLarge = true;
  8609. }
  8610. else
  8611. mayBeLarge = true;
  8612. if (((type->IsObject() && (!mayBeLarge))) ||
  8613. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8614. ((zeroMemory) && (!mayBeLarge)))
  8615. {
  8616. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8617. }
  8618. BfIRValue castedVal;
  8619. if (!isDynAlloc)
  8620. {
  8621. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8622. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8623. mBfIRBuilder->ClearDebugLocation(castedVal);
  8624. mBfIRBuilder->SetInsertPoint(prevBlock);
  8625. if (WantsLifetimes())
  8626. {
  8627. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8628. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8629. }
  8630. }
  8631. else
  8632. {
  8633. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8634. }
  8635. auto typedVal = BfTypedValue(castedVal, typeInstance);
  8636. if (!noDtorCall)
  8637. {
  8638. bool doCondAlloca = false;
  8639. if (!IsTargetingBeefBackend())
  8640. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  8641. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  8642. }
  8643. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8644. return typedVal.mValue;
  8645. }
  8646. }
  8647. else // "Normal" stack alloc
  8648. {
  8649. BF_ASSERT(!sizeValue);
  8650. //TODO: If sizeValue is a constant then do this in the head IR builder
  8651. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8652. if (!isLoopedAlloc)
  8653. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8654. else
  8655. {
  8656. MarkDynStack(scopeData);
  8657. SaveStackState(scopeData);
  8658. }
  8659. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  8660. if (!isLoopedAlloc)
  8661. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8662. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8663. bool mayBeLarge = allocSize >= 4096;
  8664. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  8665. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8666. ((zeroMemory) && (!mayBeLarge)))
  8667. {
  8668. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  8669. // and memset is always safe
  8670. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8671. }
  8672. auto typedVal = BfTypedValue(allocaInst, type);
  8673. if (!isLoopedAlloc)
  8674. {
  8675. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8676. mBfIRBuilder->SetInsertPoint(prevBlock);
  8677. if (WantsLifetimes())
  8678. {
  8679. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8680. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8681. }
  8682. }
  8683. if (!noDtorCall)
  8684. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8685. if (typeInstance != NULL)
  8686. {
  8687. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  8688. }
  8689. else
  8690. {
  8691. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  8692. }
  8693. return allocaInst;
  8694. }
  8695. }
  8696. else if (arraySize)
  8697. {
  8698. if (isRawArrayAlloc)
  8699. {
  8700. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8701. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  8702. }
  8703. else
  8704. {
  8705. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8706. typeInstance = arrayType;
  8707. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8708. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8709. appendSizeValue = elementDataSize;
  8710. if (!type->IsSizeAligned())
  8711. {
  8712. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  8713. }
  8714. }
  8715. }
  8716. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  8717. {
  8718. auto vDataRef = GetClassVDataPtr(typeInstance);
  8719. BfIRValue result;
  8720. bool isResultInitialized = false;
  8721. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8722. if (typeInstance->mTypeOptionsIdx != -1)
  8723. {
  8724. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8725. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8726. }
  8727. if (mIsComptimeModule)
  8728. stackCount = 0;
  8729. if (!sizeValue)
  8730. sizeValue = GetConstValue(typeInstance->mInstSize);
  8731. if (appendSizeValue)
  8732. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8733. BfIRValue origSizeValue = sizeValue;
  8734. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  8735. if (isAllocEx)
  8736. {
  8737. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  8738. if (prepareStackTraceMethod)
  8739. {
  8740. SizedArray<BfIRValue, 2> irArgs;
  8741. irArgs.Add(sizeValue);
  8742. irArgs.Add(GetConstValue(stackCount));
  8743. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  8744. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  8745. }
  8746. }
  8747. if (allocTarget.mCustomAllocator)
  8748. {
  8749. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8750. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  8751. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  8752. {
  8753. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8754. mBfIRBuilder->PopulateType(classVDataType);
  8755. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8756. mBfIRBuilder->PopulateType(typeInstType);
  8757. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  8758. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  8759. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  8760. BfTypedValueExpression typedValueExpr;
  8761. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  8762. typedValueExpr.mRefNode = allocTarget.mRefNode;
  8763. BfExprEvaluator exprEvaluator(this);
  8764. SizedArray<BfExpression*, 2> argExprs;
  8765. argExprs.push_back(&typedValueExpr);
  8766. BfTypedValueExpression sizeValueExpr;
  8767. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  8768. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  8769. argExprs.push_back(&sizeValueExpr);
  8770. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8771. BfResolvedArgs argValues(&sizedArgExprs);
  8772. exprEvaluator.ResolveArgValues(argValues);
  8773. exprEvaluator.mNoBind = true;
  8774. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, BfMethodGenericArguments());
  8775. if (allocResult)
  8776. {
  8777. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  8778. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  8779. else
  8780. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  8781. isResultInitialized = true;
  8782. }
  8783. }
  8784. }
  8785. bool wasAllocated = false;
  8786. if (!result)
  8787. {
  8788. if (hasCustomAllocator)
  8789. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  8790. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8791. {
  8792. SizedArray<BfIRValue, 4> llvmArgs;
  8793. llvmArgs.push_back(sizeValue);
  8794. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8795. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8796. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8797. wasAllocated = true;
  8798. }
  8799. }
  8800. if (result)
  8801. {
  8802. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8803. {
  8804. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  8805. SizedArray<BfIRValue, 4> llvmArgs;
  8806. llvmArgs.push_back(objectPtr);
  8807. llvmArgs.push_back(origSizeValue);
  8808. llvmArgs.push_back(vDataRef);
  8809. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  8810. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  8811. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  8812. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  8813. if (wasAllocated)
  8814. {
  8815. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  8816. auto bytePtrType = CreatePointerType(byteType);
  8817. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  8818. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  8819. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  8820. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  8821. }
  8822. }
  8823. else
  8824. {
  8825. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  8826. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8827. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  8828. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  8829. }
  8830. }
  8831. else
  8832. {
  8833. if ((mBfIRBuilder->mIgnoreWrites) ||
  8834. ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)))
  8835. {
  8836. if (mBfIRBuilder->mIgnoreWrites)
  8837. {
  8838. return GetDefaultValue(typeInstance);
  8839. }
  8840. else
  8841. {
  8842. // Fake with alloca
  8843. mBfIRBuilder->PopulateType(typeInstance);
  8844. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInstance));
  8845. }
  8846. }
  8847. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8848. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  8849. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8850. {
  8851. SizedArray<BfIRValue, 4> llvmArgs;
  8852. llvmArgs.push_back(vData);
  8853. llvmArgs.push_back(sizeValue);
  8854. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  8855. llvmArgs.push_back(GetConstValue(stackCount));
  8856. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  8857. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  8858. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8859. }
  8860. else
  8861. {
  8862. SizedArray<BfIRValue, 4> llvmArgs;
  8863. llvmArgs.push_back(sizeValue);
  8864. BfIRFunction irFunc;
  8865. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8866. {
  8867. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  8868. irFunc = moduleMethodInstance.mFunc;
  8869. }
  8870. if (!irFunc)
  8871. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8872. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8873. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  8874. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  8875. if (mIsComptimeModule)
  8876. {
  8877. vdataPtr = mBfIRBuilder->CreateBitCast(vdataPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance())));
  8878. }
  8879. mBfIRBuilder->CreateStore(vData, vdataPtr);
  8880. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8881. }
  8882. }
  8883. if ((zeroMemory) && (arraySize))
  8884. {
  8885. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8886. typeInstance = arrayType;
  8887. auto firstElementField = &arrayType->mFieldInstances.back();
  8888. int arrayClassSize = firstElementField->mDataOffset;
  8889. BfIRValue elementDataSize;
  8890. bool skipZero = false;
  8891. if (arraySize.IsConst())
  8892. {
  8893. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8894. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8895. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  8896. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  8897. if (constVal->mInt64 <= 0)
  8898. skipZero = true;
  8899. }
  8900. else
  8901. {
  8902. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  8903. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8904. }
  8905. if (!skipZero)
  8906. {
  8907. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8908. auto ptrType = CreatePointerType(i8Type);
  8909. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  8910. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  8911. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  8912. appendSizeValue = elementDataSize;
  8913. }
  8914. }
  8915. return result;
  8916. }
  8917. else
  8918. {
  8919. if (!sizeValue)
  8920. sizeValue = GetConstValue(allocSize);
  8921. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  8922. }
  8923. }
  8924. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  8925. {
  8926. if ((type == NULL) || (refNode == NULL))
  8927. return;
  8928. auto typeInstance = type->ToTypeInstance();
  8929. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  8930. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  8931. }
  8932. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  8933. {
  8934. if (align <= 1)
  8935. return;
  8936. if (sizeMultiple == 0)
  8937. sizeMultiple = align;
  8938. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  8939. {
  8940. if (!IsAllocatorAligned())
  8941. {
  8942. // Don't align
  8943. }
  8944. else if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  8945. {
  8946. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8947. BF_ASSERT(localVar->mName == "appendIdx");
  8948. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  8949. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8950. if (align > 1)
  8951. {
  8952. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8953. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8954. }
  8955. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  8956. }
  8957. else
  8958. {
  8959. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  8960. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  8961. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  8962. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8963. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8964. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  8965. }
  8966. }
  8967. if (mCurMethodState->mCurAppendAlign == 0)
  8968. mCurMethodState->mCurAppendAlign = sizeMultiple;
  8969. else
  8970. {
  8971. if (sizeMultiple % align == 0)
  8972. mCurMethodState->mCurAppendAlign = align;
  8973. else
  8974. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  8975. }
  8976. }
  8977. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  8978. {
  8979. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8980. BF_ASSERT(localVar->mName == "appendIdx");
  8981. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  8982. BfIRValue retValue;
  8983. BfTypeInstance* retTypeInstance = NULL;
  8984. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  8985. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  8986. if (arraySize)
  8987. {
  8988. if (isRawArrayAlloc)
  8989. {
  8990. EmitAppendAlign(type->mAlign);
  8991. BfPointerType* ptrType = CreatePointerType(type);
  8992. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8993. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8994. if (mSystem->mPtrSize != 4)
  8995. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8996. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8997. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8998. if (zeroMemory)
  8999. {
  9000. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  9001. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  9002. }
  9003. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  9004. }
  9005. else
  9006. {
  9007. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  9008. EmitAppendAlign(arrayType->mAlign, type->mSize);
  9009. auto firstElementField = &arrayType->mFieldInstances.back();
  9010. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  9011. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  9012. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  9013. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  9014. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9015. if (mSystem->mPtrSize != 4)
  9016. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  9017. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9018. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9019. if (zeroMemory)
  9020. {
  9021. // Only zero out the actual elements
  9022. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  9023. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  9024. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  9025. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  9026. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  9027. }
  9028. retTypeInstance = arrayType;
  9029. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  9030. }
  9031. }
  9032. else
  9033. {
  9034. auto typeInst = type->ToTypeInstance();
  9035. BfIRValue sizeValue;
  9036. BfIRType toType;
  9037. if (typeInst != NULL)
  9038. {
  9039. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  9040. sizeValue = GetConstValue(typeInst->mInstSize);
  9041. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  9042. }
  9043. else
  9044. {
  9045. EmitAppendAlign(type->mAlign, type->mSize);
  9046. sizeValue = GetConstValue(type->mSize);
  9047. auto toPtrType = CreatePointerType(type);
  9048. toType = mBfIRBuilder->MapType(toPtrType);
  9049. }
  9050. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9051. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9052. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9053. retTypeInstance = typeInst;
  9054. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  9055. }
  9056. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  9057. {
  9058. mBfIRBuilder->PopulateType(retTypeInstance);
  9059. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  9060. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  9061. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  9062. auto curThis = GetThis();
  9063. BfIRValue newFlags;
  9064. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9065. {
  9066. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  9067. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  9068. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  9069. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  9070. }
  9071. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  9072. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  9073. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  9074. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  9075. mBfIRBuilder->CreateStore(srcVal, destAddr);
  9076. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9077. {
  9078. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  9079. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  9080. }
  9081. }
  9082. if (appendSizeValue)
  9083. {
  9084. EmitAppendAlign(appendAllocAlign);
  9085. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9086. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  9087. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9088. }
  9089. return retValue;
  9090. }
  9091. bool BfModule::IsOptimized()
  9092. {
  9093. if (mProject == NULL)
  9094. return false;
  9095. if (mIsComptimeModule)
  9096. return false;
  9097. int optLevel = GetModuleOptions().mOptLevel;
  9098. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  9099. }
  9100. bool BfModule::IsTargetingBeefBackend()
  9101. {
  9102. if (mProject == NULL)
  9103. return true;
  9104. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9105. }
  9106. bool BfModule::WantsLifetimes()
  9107. {
  9108. if (mBfIRBuilder->mIgnoreWrites)
  9109. return false;
  9110. if ((mIsComptimeModule) && (mBfIRBuilder->HasDebugLocation()))
  9111. return true;
  9112. else if (mProject == NULL)
  9113. return false;
  9114. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9115. }
  9116. bool BfModule::HasCompiledOutput()
  9117. {
  9118. return (!mSystem->mIsResolveOnly) && (mGeneratesCode) && (!mIsComptimeModule);
  9119. }
  9120. bool BfModule::HasExecutedOutput()
  9121. {
  9122. return ((!mSystem->mIsResolveOnly) && (mGeneratesCode)) || (mIsComptimeModule);
  9123. }
  9124. // We will skip the object access check for any occurrences of this value
  9125. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  9126. {
  9127. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9128. return;
  9129. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9130. return;
  9131. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  9132. return;
  9133. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  9134. }
  9135. bool BfModule::WantsObjectAccessCheck(BfType* type)
  9136. {
  9137. if ((mBfIRBuilder->mIgnoreWrites) || (!type->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9138. return false;
  9139. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9140. return false;
  9141. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9142. auto typeOptions = GetTypeOptions();
  9143. if (typeOptions != NULL)
  9144. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9145. if (!emitObjectAccessCheck)
  9146. return false;
  9147. return true;
  9148. }
  9149. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  9150. {
  9151. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9152. return;
  9153. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9154. return;
  9155. if (typedVal.mValue.IsConst())
  9156. {
  9157. int stringIdx = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  9158. if (stringIdx != -1)
  9159. return;
  9160. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  9161. if (constant->mTypeCode == BfTypeCode_NullPtr)
  9162. return;
  9163. if (constant->mConstType == BfConstType_BitCastNull)
  9164. return;
  9165. }
  9166. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9167. auto typeOptions = GetTypeOptions();
  9168. if (typeOptions != NULL)
  9169. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9170. if (!emitObjectAccessCheck)
  9171. return;
  9172. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  9173. {
  9174. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  9175. return;
  9176. }
  9177. if (typedVal.IsAddr())
  9178. typedVal = LoadValue(typedVal);
  9179. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  9180. }
  9181. bool BfModule::WantsDebugHelpers()
  9182. {
  9183. if (mBfIRBuilder->mIgnoreWrites)
  9184. return false;
  9185. if (mIsComptimeModule)
  9186. {
  9187. // Always add
  9188. }
  9189. else if ((mProject == NULL) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  9190. return false;
  9191. return true;
  9192. }
  9193. void BfModule::EmitEnsureInstructionAt()
  9194. {
  9195. if (!WantsDebugHelpers())
  9196. return;
  9197. mBfIRBuilder->CreateEnsureInstructionAt();
  9198. }
  9199. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  9200. {
  9201. if (mBfIRBuilder->mIgnoreWrites)
  9202. return; // Nothing needed here
  9203. auto irb = mBfIRBuilder;
  9204. auto checkBB = irb->CreateBlock("as.check");
  9205. auto isNull = irb->CreateIsNull(targetValue.mValue);
  9206. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  9207. if (mIsComptimeModule)
  9208. {
  9209. AddBasicBlock(checkBB);
  9210. auto callResult = mBfIRBuilder->Comptime_DynamicCastCheck(targetValue.mValue, targetType->mTypeId, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9211. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult, GetDefaultValue(mContext->mBfObjectType));
  9212. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9213. return;
  9214. }
  9215. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  9216. auto intPtrType = CreatePointerType(intType);
  9217. auto intPtrPtrType = CreatePointerType(intPtrType);
  9218. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  9219. auto int32PtrType = CreatePointerType(int32Type);
  9220. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  9221. if (mCompiler->mOptions.mAllowHotSwapping)
  9222. {
  9223. BfExprEvaluator exprEvaluator(this);
  9224. AddBasicBlock(checkBB);
  9225. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9226. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  9227. SizedArray<BfIRValue, 4> irArgs;
  9228. irArgs.push_back(objectParam);
  9229. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  9230. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  9231. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  9232. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9233. }
  9234. else
  9235. {
  9236. AddBasicBlock(checkBB);
  9237. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  9238. vDataPtr = irb->CreateLoad(vDataPtr);
  9239. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9240. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  9241. if (targetType->IsInterface())
  9242. {
  9243. auto targetTypeInst = targetType->ToTypeInstance();
  9244. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9245. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  9246. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  9247. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9248. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  9249. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  9250. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  9251. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  9252. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  9253. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9254. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  9255. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  9256. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9257. }
  9258. else
  9259. {
  9260. if (!targetType->IsTypeInstance())
  9261. targetType = GetWrappedStructType(targetType);
  9262. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9263. int inheritanceIdOfs = mSystem->mPtrSize * mCompiler->GetVDataPrefixDataCount();
  9264. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9265. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9266. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  9267. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  9268. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  9269. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  9270. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  9271. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9272. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  9273. fieldInst = &typeTypeInstance->mFieldInstances[10];
  9274. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  9275. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9276. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  9277. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  9278. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  9279. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9280. }
  9281. }
  9282. }
  9283. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  9284. {
  9285. if (mBfIRBuilder->mIgnoreWrites)
  9286. return;
  9287. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  9288. auto typeOptions = GetTypeOptions();
  9289. if (typeOptions != NULL)
  9290. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  9291. if (emitDynamicCastCheck)
  9292. {
  9293. int wantTypeId = 0;
  9294. if (!type->IsGenericParam())
  9295. wantTypeId = type->mTypeId;
  9296. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  9297. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  9298. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  9299. AddBasicBlock(failBlock);
  9300. if (mIsComptimeModule)
  9301. {
  9302. mBfIRBuilder->Comptime_Error(CeErrorKind_ObjectDynCheckFailed);
  9303. }
  9304. else
  9305. {
  9306. SizedArray<BfIRValue, 8> llvmArgs;
  9307. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9308. llvmArgs.push_back(bitAddr);
  9309. llvmArgs.push_back(GetConstValue32(wantTypeId));
  9310. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  9311. BF_ASSERT(objDynCheck);
  9312. if (objDynCheck)
  9313. {
  9314. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  9315. }
  9316. }
  9317. mBfIRBuilder->CreateBr(endBlock);
  9318. AddBasicBlock(endBlock);
  9319. }
  9320. }
  9321. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, BfCastFlags castFlags)
  9322. {
  9323. bool callDtor = (castFlags & BfCastFlags_NoBoxDtor) == 0;
  9324. bool wantConst = ((castFlags & BfCastFlags_WantsConst) != 0) && (typedVal.mValue.IsConst());
  9325. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9326. {
  9327. if (toType == mContext->mBfObjectType)
  9328. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9329. if (toType->IsBoxed())
  9330. {
  9331. BfBoxedType* boxedType = (BfBoxedType*)toType;
  9332. if (boxedType->mElementType->IsGenericParam())
  9333. {
  9334. if (typedVal.mType == boxedType->mElementType)
  9335. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9336. else
  9337. return BfTypedValue();
  9338. }
  9339. }
  9340. }
  9341. BP_ZONE("BoxValue");
  9342. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  9343. if (typedVal.mType->IsNullable())
  9344. {
  9345. typedVal = MakeAddressable(typedVal);
  9346. auto innerType = typedVal.mType->GetUnderlyingType();
  9347. if (!innerType->IsValueType())
  9348. {
  9349. if (!mIgnoreErrors)
  9350. Fail("Only value types can be boxed", srcNode);
  9351. return BfTypedValue();
  9352. }
  9353. auto boxedType = CreateBoxedType(innerType);
  9354. auto resultType = toType;
  9355. if (resultType == NULL)
  9356. resultType = boxedType;
  9357. if (mBfIRBuilder->mIgnoreWrites)
  9358. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  9359. auto prevBB = mBfIRBuilder->GetInsertBlock();
  9360. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  9361. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  9362. mBfIRBuilder->PopulateType(typedVal.mType);
  9363. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  9364. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  9365. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  9366. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9367. mBfIRBuilder->AddBlock(boxBB);
  9368. mBfIRBuilder->SetInsertPoint(boxBB);
  9369. BfScopeData newScope;
  9370. newScope.mOuterIsConditional = true;
  9371. mCurMethodState->AddScope(&newScope);
  9372. NewScopeState();
  9373. BfIRValue nullableValueAddr;
  9374. BfIRValue loadedVal;
  9375. if (innerType->IsValuelessType())
  9376. {
  9377. loadedVal = mBfIRBuilder->GetFakeVal();
  9378. }
  9379. else
  9380. {
  9381. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  9382. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  9383. }
  9384. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor ? BfCastFlags_None : BfCastFlags_NoBoxDtor);
  9385. RestoreScopeState();
  9386. if (!boxedVal)
  9387. return BfTypedValue();
  9388. mBfIRBuilder->CreateBr(endBB);
  9389. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  9390. mBfIRBuilder->AddBlock(endBB);
  9391. mBfIRBuilder->SetInsertPoint(endBB);
  9392. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  9393. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  9394. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  9395. return BfTypedValue(phi, resultType);
  9396. }
  9397. bool alreadyCheckedCast = false;
  9398. BfTypeInstance* toTypeInstance = NULL;
  9399. if (toType != NULL)
  9400. toTypeInstance = toType->ToTypeInstance();
  9401. bool isStructPtr = typedVal.mType->IsStructPtr();
  9402. if (fromStructTypeInstance == NULL)
  9403. {
  9404. auto primType = (BfPrimitiveType*)typedVal.mType;
  9405. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  9406. {
  9407. // Can always do IHashable
  9408. alreadyCheckedCast = true;
  9409. }
  9410. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  9411. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9412. else
  9413. {
  9414. auto checkStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9415. if (checkStructTypeInstance == toType->GetUnderlyingType())
  9416. fromStructTypeInstance = checkStructTypeInstance;
  9417. }
  9418. if (isStructPtr)
  9419. {
  9420. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9421. alreadyCheckedCast = true;
  9422. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  9423. }
  9424. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  9425. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9426. }
  9427. if (fromStructTypeInstance == NULL)
  9428. return BfTypedValue();
  9429. // Need to box it
  9430. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  9431. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9432. {
  9433. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9434. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  9435. auto boxedType = CreateBoxedType(typedVal.mType);
  9436. mBfIRBuilder->PopulateType(boxedType);
  9437. if (wantConst)
  9438. return BfTypedValue(mBfIRBuilder->CreateConstBox(typedVal.mValue, mBfIRBuilder->MapType(boxedType)), boxedType);
  9439. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9440. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  9441. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  9442. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  9443. if (boxedType->IsUnspecializedType())
  9444. {
  9445. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  9446. }
  9447. else
  9448. {
  9449. PopulateType(fromStructTypeInstance);
  9450. if (!fromStructTypeInstance->IsValuelessType())
  9451. {
  9452. typedVal = LoadValue(typedVal);
  9453. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  9454. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  9455. {
  9456. auto ptrType = CreatePointerType(typedVal.mType);
  9457. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  9458. }
  9459. if (typedVal.IsSplat())
  9460. {
  9461. AggregateSplatIntoAddr(typedVal, valPtr);
  9462. }
  9463. else
  9464. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr, typedVal.mType->mAlign);
  9465. }
  9466. }
  9467. if (toType == NULL)
  9468. {
  9469. return BfTypedValue(allocaInst, boxedType);
  9470. }
  9471. else
  9472. {
  9473. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  9474. return BfTypedValue(castedValue, toType);
  9475. }
  9476. }
  9477. return BfTypedValue();
  9478. }
  9479. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  9480. {
  9481. BfTypeInstance* checkTypeInst = typeInst;
  9482. while (checkTypeInst != NULL)
  9483. {
  9484. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  9485. {
  9486. if (checkProp->mName == propDef->mName)
  9487. {
  9488. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  9489. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  9490. {
  9491. propDef = checkProp;
  9492. typeInst = checkTypeInst;
  9493. return true;
  9494. }
  9495. }
  9496. }
  9497. checkTypeInst = checkTypeInst->mBaseType;
  9498. }
  9499. return false;
  9500. }
  9501. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  9502. {
  9503. if (!typeInstance->mResolvingVarField)
  9504. {
  9505. if (!typeInstance->DefineStateAllowsStaticMethods())
  9506. PopulateType(typeInstance, BfPopulateType_AllowStaticMethods);
  9507. }
  9508. else
  9509. {
  9510. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  9511. {
  9512. AssertErrorState();
  9513. return NULL;
  9514. }
  9515. }
  9516. if (assertName != NULL)
  9517. {
  9518. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9519. }
  9520. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9521. {
  9522. if (mCompiler->EnsureCeUnpaused(typeInstance))
  9523. {
  9524. BF_FATAL("OOB in GetRawMethodInstanceAtIdx");
  9525. }
  9526. return NULL;
  9527. }
  9528. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  9529. if (methodGroup.mDefault == NULL)
  9530. {
  9531. if (!mCompiler->mIsResolveOnly)
  9532. {
  9533. // Get it from the owning module so we don't create a reference prematurely...
  9534. auto declModule = typeInstance->mModule;
  9535. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  9536. {
  9537. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9538. if (!declModule->mIsScratchModule)
  9539. declModule->mOnDemandMethodCount++;
  9540. }
  9541. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  9542. (typeInstance->mTypeFailed) || (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted));
  9543. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  9544. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9545. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified);
  9546. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9547. }
  9548. else
  9549. {
  9550. auto declModule = typeInstance->mModule;
  9551. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass);
  9552. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9553. }
  9554. }
  9555. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9556. //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
  9557. // be from a call to the NON-raw version
  9558. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  9559. // {
  9560. // methodInstance->mIsReified = mIsReified;
  9561. // if (methodInstance->mMethodProcessRequest == NULL)
  9562. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  9563. // }
  9564. return methodInstance;
  9565. }
  9566. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  9567. {
  9568. if (methodDef->mIsLocalMethod)
  9569. {
  9570. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  9571. }
  9572. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx, NULL);
  9573. }
  9574. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  9575. {
  9576. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9577. while (typeInstance != NULL)
  9578. {
  9579. typeInstance->mTypeDef->PopulateMemberSets();
  9580. BfMemberSetEntry* entry = NULL;
  9581. BfMethodDef* methodDef = NULL;
  9582. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9583. methodDef = (BfMethodDef*)entry->mMemberDef;
  9584. while (methodDef != NULL)
  9585. {
  9586. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  9587. (methodDef->mGenericParams.size() == 0) &&
  9588. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9589. return GetRawMethodInstance(typeInstance, methodDef);
  9590. methodDef = methodDef->mNextWithSameName;
  9591. }
  9592. if (!checkBase)
  9593. break;
  9594. typeInstance = typeInstance->mBaseType;
  9595. }
  9596. return NULL;
  9597. }
  9598. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  9599. {
  9600. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9601. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  9602. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  9603. if (!useUnspecializedType)
  9604. return methodInstance;
  9605. if (!owner->IsGenericTypeInstance())
  9606. return methodInstance;
  9607. if ((owner->IsDelegateFromTypeRef()) ||
  9608. (owner->IsFunctionFromTypeRef()) ||
  9609. (owner->IsTuple()))
  9610. {
  9611. return methodInstance;
  9612. }
  9613. auto genericType = (BfTypeInstance*)owner;
  9614. if ((genericType->IsUnspecializedType()) && (!genericType->IsUnspecializedTypeVariation()))
  9615. return methodInstance;
  9616. if (methodInstance->mMethodDef->mIsLocalMethod)
  9617. return methodInstance;
  9618. if (methodInstance->mMethodDef->mDeclaringType->IsEmitted())
  9619. return methodInstance;
  9620. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef->GetDefinition());
  9621. if (unspecializedType == NULL)
  9622. {
  9623. AssertErrorState();
  9624. return methodInstance;
  9625. }
  9626. if (unspecializedType == NULL)
  9627. return methodInstance;
  9628. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  9629. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  9630. }
  9631. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  9632. {
  9633. int genericCount = 0;
  9634. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  9635. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  9636. {
  9637. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  9638. if (param->IsGenericParam())
  9639. genericCount++;
  9640. }
  9641. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  9642. genericCount++;
  9643. return genericCount;
  9644. }
  9645. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  9646. {
  9647. BF_ASSERT(!mIsScratchModule);
  9648. BF_ASSERT(mIsReified);
  9649. BfModule* mainModule = this;
  9650. if (mParentModule != NULL)
  9651. mainModule = mParentModule;
  9652. BfModule* specModule = NULL;
  9653. BfModule** specModulePtr = NULL;
  9654. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  9655. {
  9656. return *specModulePtr;
  9657. }
  9658. else
  9659. {
  9660. String specModuleName = mModuleName;
  9661. for (auto bfProject : projectList)
  9662. {
  9663. specModuleName += StrFormat("@%s", bfProject->mSafeName.c_str());
  9664. }
  9665. specModule = new BfModule(mContext, specModuleName);
  9666. specModule->mProject = mainModule->mProject;
  9667. specModule->mParentModule = mainModule;
  9668. specModule->mIsSpecializedMethodModuleRoot = true;
  9669. specModule->Init();
  9670. Array<BfProject*> projList;
  9671. for (auto project : projectList)
  9672. projList.Add(project);
  9673. mainModule->mSpecializedMethodModules[projList] = specModule;
  9674. }
  9675. return specModule;
  9676. }
  9677. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  9678. {
  9679. if (IsSkippingExtraResolveChecks())
  9680. return BfIRValue();
  9681. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  9682. {
  9683. //BF_ASSERT(!methodInstance->mIRFunction);
  9684. return BfIRValue();
  9685. }
  9686. auto methodDef = methodInstance->mMethodDef;
  9687. StringT<4096> methodName;
  9688. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  9689. if (isInlined != methodInstance->mAlwaysInline)
  9690. {
  9691. if (isInlined)
  9692. methodName += "__INLINE";
  9693. else
  9694. methodName += "__NOINLINE";
  9695. }
  9696. if (tryExisting)
  9697. {
  9698. auto func = mBfIRBuilder->GetFunction(methodName);
  9699. if (func)
  9700. return func;
  9701. }
  9702. auto intrinsic = GetIntrinsic(methodInstance);
  9703. if (intrinsic)
  9704. return intrinsic;
  9705. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  9706. {
  9707. return CreateDllImportGlobalVar(methodInstance, false);
  9708. }
  9709. BfIRType returnType;
  9710. SizedArray<BfIRType, 8> paramTypes;
  9711. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  9712. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  9713. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  9714. auto callingConv = GetIRCallingConvention(methodInstance);
  9715. if (callingConv != BfIRCallingConv_CDecl)
  9716. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  9717. SetupIRMethod(methodInstance, func, isInlined);
  9718. // auto srcModule = methodInstance->GetOwner()->GetModule();
  9719. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  9720. // {
  9721. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  9722. // {
  9723. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  9724. // }
  9725. // }
  9726. return func;
  9727. }
  9728. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  9729. {
  9730. if (assertName != NULL)
  9731. {
  9732. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9733. }
  9734. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9735. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9736. return BfModuleMethodInstance();
  9737. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9738. BfMethodDef* methodDef = NULL;
  9739. BfTypeInstance* foreignType = NULL;
  9740. if (methodInstance != NULL)
  9741. {
  9742. methodDef = methodInstance->mMethodDef;
  9743. if (methodInstance->mMethodInfoEx != NULL)
  9744. foreignType = methodInstance->mMethodInfoEx->mForeignType;
  9745. }
  9746. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  9747. {
  9748. // Can't use it, not reified
  9749. methodInstance = NULL;
  9750. }
  9751. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  9752. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  9753. {
  9754. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  9755. return BfModuleMethodInstance(methodInstance, func);
  9756. }
  9757. if (foreignType != NULL)
  9758. return GetMethodInstance(typeInstance, methodDef, BfTypeVector(), (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef), foreignType);
  9759. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  9760. }
  9761. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9762. {
  9763. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9764. while (typeInstance != NULL)
  9765. {
  9766. typeInstance->mTypeDef->PopulateMemberSets();
  9767. BfMemberSetEntry* entry = NULL;
  9768. BfMethodDef* methodDef = NULL;
  9769. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9770. methodDef = (BfMethodDef*)entry->mMemberDef;
  9771. while (methodDef != NULL)
  9772. {
  9773. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9774. (methodDef->mGenericParams.size() == 0) &&
  9775. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9776. {
  9777. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9778. if (moduleMethodInstance)
  9779. return moduleMethodInstance;
  9780. }
  9781. methodDef = methodDef->mNextWithSameName;
  9782. }
  9783. if (!checkBase)
  9784. break;
  9785. typeInstance = typeInstance->mBaseType;
  9786. }
  9787. return BfModuleMethodInstance();
  9788. }
  9789. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  9790. {
  9791. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9792. while (typeInstance != NULL)
  9793. {
  9794. typeInstance->mTypeDef->PopulateMemberSets();
  9795. BfMemberSetEntry* entry = NULL;
  9796. BfMethodDef* methodDef = NULL;
  9797. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9798. methodDef = (BfMethodDef*)entry->mMemberDef;
  9799. while (methodDef != NULL)
  9800. {
  9801. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9802. (methodDef->mGenericParams.size() == 0) &&
  9803. (paramTypes.size() == methodDef->mParams.size()))
  9804. {
  9805. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9806. if (moduleMethodInstance.mMethodInstance != NULL)
  9807. {
  9808. bool matches = true;
  9809. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  9810. {
  9811. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  9812. matches = false;
  9813. }
  9814. if (matches)
  9815. return moduleMethodInstance;
  9816. }
  9817. }
  9818. methodDef = methodDef->mNextWithSameName;
  9819. }
  9820. if (!checkBase)
  9821. break;
  9822. typeInstance = typeInstance->mBaseType;
  9823. }
  9824. return BfModuleMethodInstance();
  9825. }
  9826. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  9827. {
  9828. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  9829. PopulateType(internalType);
  9830. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  9831. if (!moduleMethodInstance)
  9832. {
  9833. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  9834. }
  9835. return moduleMethodInstance;
  9836. }
  9837. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  9838. {
  9839. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  9840. typeInstance->mOperatorInfo.Add(NULL);
  9841. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  9842. {
  9843. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  9844. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  9845. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  9846. BfTypeState typeState;
  9847. typeState.mType = typeInstance;
  9848. typeState.mCurTypeDef = operatorDef->mDeclaringType;
  9849. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  9850. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  9851. if (operatorDef->mReturnTypeRef != NULL)
  9852. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  9853. if (operatorDef->mParams.size() >= 1)
  9854. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  9855. if (operatorDef->mParams.size() >= 2)
  9856. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  9857. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  9858. }
  9859. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  9860. }
  9861. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  9862. {
  9863. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  9864. if (operatorInfo == NULL)
  9865. return NULL;
  9866. if (operatorInfo->mReturnType == NULL)
  9867. return NULL;
  9868. auto castFlags = BfCastFlags_IsConstraintCheck;
  9869. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9870. castFlags = (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator);
  9871. if (lhs)
  9872. {
  9873. if (operatorInfo->mLHSType == NULL)
  9874. return NULL;
  9875. if (!CanCast(lhs, operatorInfo->mLHSType, castFlags))
  9876. return NULL;
  9877. }
  9878. if (rhs)
  9879. {
  9880. if (operatorInfo->mRHSType == NULL)
  9881. return NULL;
  9882. if (!CanCast(rhs, operatorInfo->mRHSType, castFlags))
  9883. return NULL;
  9884. }
  9885. return operatorInfo->mReturnType;
  9886. }
  9887. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9888. {
  9889. while (typeInstance != NULL)
  9890. {
  9891. typeInstance->mTypeDef->PopulateMemberSets();
  9892. BfMemberSetEntry* entry = NULL;
  9893. BfMethodDef* methodDef = NULL;
  9894. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9895. methodDef = (BfMethodDef*)entry->mMemberDef;
  9896. while (methodDef != NULL)
  9897. {
  9898. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9899. (methodDef->mGenericParams.size() == 0) &&
  9900. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9901. {
  9902. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  9903. if (!methodInstanceGroup.IsImplemented())
  9904. return false;
  9905. if (methodInstanceGroup.mDefault == NULL)
  9906. return false;
  9907. return methodInstanceGroup.mDefault->mIsReified;
  9908. }
  9909. methodDef = methodDef->mNextWithSameName;
  9910. }
  9911. if (!checkBase)
  9912. break;
  9913. typeInstance = typeInstance->mBaseType;
  9914. }
  9915. return false;
  9916. }
  9917. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9918. {
  9919. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9920. while (typeInstance != NULL)
  9921. {
  9922. typeInstance->mTypeDef->PopulateMemberSets();
  9923. BfMemberSetEntry* entry = NULL;
  9924. BfMethodDef* methodDef = NULL;
  9925. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9926. methodDef = (BfMethodDef*)entry->mMemberDef;
  9927. while (methodDef != NULL)
  9928. {
  9929. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  9930. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9931. return true;
  9932. methodDef = methodDef->mNextWithSameName;
  9933. }
  9934. if (!checkBase)
  9935. break;
  9936. typeInstance = typeInstance->mBaseType;
  9937. }
  9938. return BfModuleMethodInstance();
  9939. }
  9940. String BfModule::FieldToString(BfFieldInstance* fieldInstance)
  9941. {
  9942. auto result = TypeToString(fieldInstance->mOwner);
  9943. result += ".";
  9944. auto fieldDef = fieldInstance->GetFieldDef();
  9945. if (fieldDef != NULL)
  9946. result += fieldDef->mName;
  9947. else
  9948. result += "???";
  9949. return result;
  9950. }
  9951. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* typeGenericArgs, BfTypeVector* methodGenericArgs)
  9952. {
  9953. auto methodDef = methodInst->mMethodDef;
  9954. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  9955. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9956. bool hasGenericArgs = (typeGenericArgs != NULL) || (methodGenericArgs != NULL);
  9957. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  9958. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9959. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  9960. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  9961. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9962. if (allowResolveGenericParamNames)
  9963. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9964. StringT<128> methodName;
  9965. auto _AddTypeName = [&](BfType* type)
  9966. {
  9967. auto typeNameFlags = BfTypeNameFlags_None;
  9968. if (allowResolveGenericParamNames)
  9969. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9970. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9971. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  9972. methodName += TypeToString(type, typeNameFlags);
  9973. };
  9974. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  9975. {
  9976. _AddTypeName(methodInst->mReturnType);
  9977. methodName += " ";
  9978. }
  9979. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  9980. {
  9981. methodName += TypeToString(type, typeNameFlags);
  9982. if (methodName == "$")
  9983. methodName = "";
  9984. else if (!methodName.IsEmpty())
  9985. methodName += ".";
  9986. }
  9987. String accessorString;
  9988. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  9989. if (methodInst->mMethodDef->mIsLocalMethod)
  9990. {
  9991. int atPos = (int)methodDefName.IndexOf('$');
  9992. methodDefName.RemoveToEnd(atPos);
  9993. methodDefName.Replace("@", ".");
  9994. }
  9995. else
  9996. {
  9997. int atPos = (int)methodDefName.IndexOf('$');
  9998. if (atPos != -1)
  9999. {
  10000. accessorString = methodDefName.Substring(0, atPos);
  10001. if ((accessorString == "get") || (accessorString == "set"))
  10002. {
  10003. methodDefName = methodDefName.Substring(atPos + 1);
  10004. }
  10005. else
  10006. accessorString = "";
  10007. }
  10008. }
  10009. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  10010. {
  10011. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10012. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10013. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10014. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  10015. methodName += ".";
  10016. }
  10017. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  10018. {
  10019. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10020. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10021. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10022. methodName += "[";
  10023. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  10024. methodName += "].";
  10025. }
  10026. if (methodDef->mMethodType == BfMethodType_Operator)
  10027. {
  10028. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  10029. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  10030. {
  10031. // Don't add explicit/implicit part, since that's not available in GCC mangling
  10032. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  10033. {
  10034. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  10035. methodName += "explicit ";
  10036. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  10037. methodName += "explicit ";
  10038. }*/
  10039. methodName += "operator ";
  10040. if (methodInst->mReturnType != NULL)
  10041. methodName += TypeToString(methodInst->mReturnType);
  10042. }
  10043. else
  10044. {
  10045. methodName += "operator";
  10046. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  10047. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  10048. }
  10049. }
  10050. else if (methodDef->mMethodType == BfMethodType_Ctor)
  10051. {
  10052. if (methodDef->mIsStatic)
  10053. methodName += "__BfStaticCtor";
  10054. else
  10055. methodName += "this";
  10056. accessorString = "";
  10057. }
  10058. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  10059. {
  10060. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10061. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10062. {
  10063. methodName += "get indexer";
  10064. }
  10065. else
  10066. {
  10067. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10068. propertyDecl->mNameNode->ToString(methodName);
  10069. methodName += " get accessor";
  10070. return methodName;
  10071. }
  10072. }
  10073. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10074. {
  10075. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10076. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10077. {
  10078. methodName += "set indexer";
  10079. }
  10080. else
  10081. {
  10082. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10083. propertyDecl->mNameNode->ToString(methodName);
  10084. methodName += " set accessor";
  10085. return methodName;
  10086. }
  10087. }
  10088. else
  10089. methodName += methodDefName;
  10090. if (methodDef->mMethodType == BfMethodType_Mixin)
  10091. methodName += "!";
  10092. BfTypeVector newMethodGenericArgs;
  10093. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  10094. {
  10095. methodName += "<";
  10096. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  10097. {
  10098. if (i > 0)
  10099. methodName += ", ";
  10100. BfTypeNameFlags typeNameFlags = BfTypeNameFlag_ShortConst;
  10101. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  10102. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10103. if (allowResolveGenericParamNames)
  10104. typeNameFlags = (BfTypeNameFlags)(typeNameFlags | BfTypeNameFlag_ResolveGenericParamNames);
  10105. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  10106. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  10107. {
  10108. bool hasEmpty = false;
  10109. for (auto arg : *methodGenericArgs)
  10110. {
  10111. if (arg == NULL)
  10112. hasEmpty = true;
  10113. }
  10114. if (hasEmpty)
  10115. {
  10116. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  10117. {
  10118. auto arg = (*methodGenericArgs)[genericIdx];
  10119. if (arg != NULL)
  10120. newMethodGenericArgs.push_back(arg);
  10121. else
  10122. {
  10123. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  10124. if (genericParamInst->mTypeConstraint != NULL)
  10125. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  10126. else
  10127. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  10128. }
  10129. }
  10130. methodGenericArgs = &newMethodGenericArgs;
  10131. }
  10132. if (type->IsUnspecializedType())
  10133. type = ResolveGenericType(type, NULL, methodGenericArgs, mCurTypeInstance);
  10134. }
  10135. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  10136. {
  10137. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  10138. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  10139. methodName += TypeToString(type, typeNameFlags);
  10140. }
  10141. else
  10142. methodName += TypeToString(type, typeNameFlags);
  10143. }
  10144. methodName += ">";
  10145. }
  10146. if (accessorString.length() == 0)
  10147. {
  10148. int dispParamIdx = 0;
  10149. methodName += "(";
  10150. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  10151. {
  10152. int paramKind = methodInst->GetParamKind(paramIdx);
  10153. if ((paramKind == BfParamKind_ImplicitCapture) || (paramKind == BfParamKind_AppendIdx))
  10154. continue;
  10155. if (dispParamIdx > 0)
  10156. methodName += ", ";
  10157. if (paramKind == BfParamKind_Params)
  10158. methodName += "params ";
  10159. BfType* type = methodInst->GetParamType(paramIdx);
  10160. _AddTypeName(type);
  10161. methodName += " ";
  10162. methodName += methodInst->GetParamName(paramIdx);
  10163. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  10164. if ((paramInitializer != NULL) && ((methodNameFlags & BfMethodNameFlag_NoAst) == 0))
  10165. {
  10166. methodName += " = ";
  10167. methodName += paramInitializer->ToString();
  10168. }
  10169. dispParamIdx++;
  10170. }
  10171. methodName += ")";
  10172. }
  10173. if (accessorString.length() != 0)
  10174. {
  10175. methodName += " ";
  10176. methodName += accessorString;
  10177. }
  10178. if ((methodNameFlags & BfMethodNameFlag_IncludeMut) != 0)
  10179. {
  10180. if ((methodDef->mIsMutating) && (methodInst->GetOwner()->IsValueType()))
  10181. methodName += " mut";
  10182. }
  10183. return methodName;
  10184. }
  10185. void BfModule::pt(BfType* type)
  10186. {
  10187. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  10188. }
  10189. void BfModule::pm(BfMethodInstance* type)
  10190. {
  10191. OutputDebugStrF("%s\n", MethodToString(type).c_str());
  10192. }
  10193. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  10194. {
  10195. if ((flagsLeft & checkFlag) == 0)
  10196. return;
  10197. if (!str.empty())
  10198. {
  10199. if (flagsLeft == checkFlag)
  10200. {
  10201. if ((int)str.IndexOf(',') != -1)
  10202. str += ", and ";
  10203. else
  10204. str += " and ";
  10205. }
  10206. else
  10207. str += ", ";
  10208. }
  10209. str += addString;
  10210. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  10211. }
  10212. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  10213. {
  10214. String resultStr;
  10215. auto flagsLeft = attrTarget;
  10216. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  10217. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  10218. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  10219. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  10220. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  10221. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  10222. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  10223. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  10224. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  10225. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  10226. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  10227. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  10228. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  10229. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  10230. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  10231. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  10232. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  10233. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  10234. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  10235. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  10236. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  10237. if (resultStr.IsEmpty())
  10238. return "<nothing>";
  10239. return resultStr;
  10240. }
  10241. BfIRType BfModule::CurrentAddToConstHolder(BfIRType irType)
  10242. {
  10243. if (irType.mKind == BfIRTypeData::TypeKind_SizedArray)
  10244. {
  10245. auto sizedArrayType = (BfConstantSizedArrayType*)mBfIRBuilder->GetConstantById(irType.mId);
  10246. return mCurTypeInstance->GetOrCreateConstHolder()->GetSizedArrayType(CurrentAddToConstHolder(sizedArrayType->mType), (int)sizedArrayType->mLength);
  10247. }
  10248. return irType;
  10249. }
  10250. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  10251. {
  10252. auto constant = mBfIRBuilder->GetConstant(irVal);
  10253. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  10254. if (stringPoolIdx != -1)
  10255. {
  10256. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  10257. return;
  10258. }
  10259. if (constant->mConstType == BfConstType_Agg)
  10260. {
  10261. auto constArray = (BfConstantAgg*)constant;
  10262. SizedArray<BfIRValue, 8> newVals;
  10263. for (auto val : constArray->mValues)
  10264. {
  10265. auto newVal = val;
  10266. CurrentAddToConstHolder(newVal);
  10267. newVals.push_back(newVal);
  10268. }
  10269. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstAgg(CurrentAddToConstHolder(constArray->mType), newVals);
  10270. return;
  10271. }
  10272. auto origConst = irVal;
  10273. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10274. {
  10275. auto bitcast = (BfConstantBitCast*)constant;
  10276. BfIRValue newVal;
  10277. if (constant->mConstType == BfConstType_BitCast)
  10278. {
  10279. newVal = BfIRValue(BfIRValueFlags_Const, bitcast->mTarget);
  10280. CurrentAddToConstHolder(newVal);
  10281. }
  10282. else
  10283. newVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstNull();
  10284. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstBitCast(newVal, CurrentAddToConstHolder(bitcast->mToType));
  10285. return;
  10286. }
  10287. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  10288. }
  10289. void BfModule::ClearConstData()
  10290. {
  10291. mBfIRBuilder->ClearConstData();
  10292. mStringObjectPool.Clear();
  10293. mStringCharPtrPool.Clear();
  10294. mStringPoolRefs.Clear();
  10295. mUnreifiedStringPoolRefs.Clear();
  10296. mStaticFieldRefs.Clear();
  10297. }
  10298. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  10299. {
  10300. switch (constant->mTypeCode)
  10301. {
  10302. case BfTypeCode_StringId:
  10303. case BfTypeCode_Boolean:
  10304. case BfTypeCode_Int8:
  10305. case BfTypeCode_UInt8:
  10306. case BfTypeCode_Int16:
  10307. case BfTypeCode_UInt16:
  10308. case BfTypeCode_Int32:
  10309. case BfTypeCode_UInt32:
  10310. case BfTypeCode_Int64:
  10311. case BfTypeCode_UInt64:
  10312. case BfTypeCode_IntPtr:
  10313. case BfTypeCode_UIntPtr:
  10314. case BfTypeCode_IntUnknown:
  10315. case BfTypeCode_UIntUnknown:
  10316. case BfTypeCode_Char8:
  10317. case BfTypeCode_Char16:
  10318. case BfTypeCode_Char32:
  10319. case BfTypeCode_Float:
  10320. case BfTypeCode_Double:
  10321. {
  10322. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10323. BfTypedValue typedValue;
  10324. bool allowUnactualized = mBfIRBuilder->mIgnoreWrites;
  10325. if (constant->mTypeCode == BfTypeCode_StringId)
  10326. {
  10327. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10328. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10329. {
  10330. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType, allowUnactualized), wantType);
  10331. return typedValue;
  10332. }
  10333. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  10334. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType, allowUnactualized), stringType);
  10335. }
  10336. if (!typedValue)
  10337. {
  10338. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10339. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  10340. }
  10341. if (typedValue.mType == wantType)
  10342. return typedValue;
  10343. if (wantType->IsTypedPrimitive())
  10344. {
  10345. if (typedValue.mType == wantType->GetUnderlyingType())
  10346. {
  10347. typedValue.mType = wantType;
  10348. return typedValue;
  10349. }
  10350. }
  10351. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  10352. if (!castedTypedValue)
  10353. return BfTypedValue();
  10354. return castedTypedValue;
  10355. }
  10356. break;
  10357. default: break;
  10358. }
  10359. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  10360. BF_ASSERT(irValue);
  10361. if (!irValue)
  10362. return BfTypedValue();
  10363. if (constant->mConstType == BfConstType_GlobalVar)
  10364. {
  10365. mBfIRBuilder->PopulateType(wantType);
  10366. auto result = BfTypedValue(irValue, wantType, true);
  10367. if (!wantType->IsComposite())
  10368. result = LoadValue(result);
  10369. return result;
  10370. }
  10371. return BfTypedValue(irValue, wantType, false);
  10372. }
  10373. bool BfModule::HasUnactializedConstant(BfConstant* constant, BfIRConstHolder* constHolder)
  10374. {
  10375. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  10376. return true;
  10377. if (constant->mTypeCode == BfTypeCode_StringId)
  10378. return true;
  10379. if (constant->mConstType == BfConstType_Agg)
  10380. {
  10381. auto constArray = (BfConstantAgg*)constant;
  10382. for (auto val : constArray->mValues)
  10383. {
  10384. if (HasUnactializedConstant(constHolder->GetConstant(val), constHolder))
  10385. return true;
  10386. }
  10387. }
  10388. return false;
  10389. }
  10390. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType, bool allowUnactualized)
  10391. {
  10392. if (constant->mTypeCode == BfTypeCode_NullPtr)
  10393. {
  10394. if ((wantType == NULL) && (constant->mIRType.mKind == BfIRTypeData::TypeKind_TypeId))
  10395. wantType = mContext->mTypes[constant->mIRType.mId];
  10396. if (wantType == NULL)
  10397. return mBfIRBuilder->CreateConstNull();
  10398. return GetDefaultValue(wantType);
  10399. }
  10400. if (constant->mTypeCode == BfTypeCode_StringId)
  10401. {
  10402. if (!allowUnactualized)
  10403. {
  10404. if ((wantType == NULL) ||
  10405. (wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10406. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10407. {
  10408. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  10409. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  10410. if ((wantType != NULL) && (wantType->IsPointer()))
  10411. return GetStringCharPtr(stringObjConst, true);
  10412. return stringObjConst;
  10413. }
  10414. }
  10415. }
  10416. if (constant->mConstType == Beefy::BfConstType_TypeOf)
  10417. {
  10418. auto constTypeOf = (BfTypeOf_Const*)constant;
  10419. if (mCurTypeInstance != NULL)
  10420. AddDependency(constTypeOf->mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10421. return CreateTypeDataRef(constTypeOf->mType);
  10422. }
  10423. if (constant->mConstType == BfConstType_PtrToInt)
  10424. {
  10425. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  10426. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10427. return mBfIRBuilder->CreatePtrToInt(ConstantToCurrent(fromTarget, constHolder, NULL), fromPtrToInt->mToTypeCode);
  10428. }
  10429. if (constant->mConstType == BfConstType_IntToPtr)
  10430. {
  10431. auto fromPtrToInt = (BfConstantIntToPtr*)constant;
  10432. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10433. BfIRType toIRType = fromPtrToInt->mToType;
  10434. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10435. {
  10436. auto toType = mContext->mTypes[toIRType.mId];
  10437. toIRType = mBfIRBuilder->MapType(toType);
  10438. }
  10439. return mBfIRBuilder->CreateIntToPtr(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10440. }
  10441. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10442. {
  10443. auto bitcast = (BfConstantBitCast*)constant;
  10444. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  10445. BfIRType toIRType = bitcast->mToType;
  10446. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10447. {
  10448. auto toType = mContext->mTypes[toIRType.mId];
  10449. toIRType = mBfIRBuilder->MapType(toType);
  10450. }
  10451. return mBfIRBuilder->CreateBitCast(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10452. }
  10453. if (constant->mConstType == BfConstType_Agg)
  10454. {
  10455. auto constArray = (BfConstantAgg*)constant;
  10456. if ((wantType == NULL) && (constArray->mType.mKind == BfIRTypeData::TypeKind_TypeId))
  10457. wantType = mContext->mTypes[constArray->mType.mId];
  10458. if (wantType->IsArray())
  10459. wantType = CreateSizedArrayType(wantType->GetUnderlyingType(), (int)constArray->mValues.mSize);
  10460. bool handleAsArray = false;
  10461. SizedArray<BfIRValue, 8> newVals;
  10462. if (wantType->IsSizedArray())
  10463. {
  10464. handleAsArray = true;
  10465. }
  10466. else if (wantType->IsInstanceOf(mCompiler->mSpanTypeDef))
  10467. {
  10468. auto valueType = ResolveTypeDef(mCompiler->mValueTypeTypeDef);
  10469. handleAsArray = true;
  10470. if (!constArray->mValues.IsEmpty())
  10471. {
  10472. auto firstConstant = constHolder->GetConstant(constArray->mValues[0]);
  10473. if ((firstConstant->mConstType == BfConstType_AggZero) && (firstConstant->mIRType.mKind == BfIRType::TypeKind_TypeId) &&
  10474. (firstConstant->mIRType.mId == valueType->mTypeId))
  10475. handleAsArray = false;
  10476. if (firstConstant->mConstType == BfConstType_Agg)
  10477. {
  10478. auto firstConstArray = (BfConstantAgg*)firstConstant;
  10479. if ((firstConstArray->mType.mKind == BfIRType::TypeKind_TypeId) &&
  10480. (firstConstArray->mType.mId == valueType->mTypeId))
  10481. handleAsArray = false;
  10482. }
  10483. }
  10484. }
  10485. if (handleAsArray)
  10486. {
  10487. auto elementType = wantType->GetUnderlyingType();
  10488. for (auto val : constArray->mValues)
  10489. {
  10490. newVals.Add(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  10491. }
  10492. }
  10493. else
  10494. {
  10495. auto wantTypeInst = wantType->ToTypeInstance();
  10496. if (wantTypeInst == NULL)
  10497. {
  10498. InternalError("BfModule::ConstantToCurrent typeInst error");
  10499. return BfIRValue();
  10500. }
  10501. if (wantTypeInst->mBaseType != NULL)
  10502. {
  10503. auto baseVal = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[0]), constHolder, wantTypeInst->mBaseType);
  10504. newVals.Add(baseVal);
  10505. }
  10506. if (wantType->IsUnion())
  10507. {
  10508. auto innerType = wantType->ToTypeInstance()->GetUnionInnerType();
  10509. if (!innerType->IsValuelessType())
  10510. {
  10511. auto val = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[1]), constHolder, innerType);
  10512. newVals.Add(val);
  10513. }
  10514. }
  10515. if ((!wantType->IsUnion()) || (wantType->IsPayloadEnum()))
  10516. {
  10517. for (auto& fieldInstance : wantTypeInst->mFieldInstances)
  10518. {
  10519. if (fieldInstance.mDataIdx < 0)
  10520. continue;
  10521. if (fieldInstance.mDataIdx >= constArray->mValues.mSize)
  10522. {
  10523. InternalError("BfModule::ConstantToCurrent union error");
  10524. return BfIRValue();
  10525. }
  10526. auto val = constArray->mValues[fieldInstance.mDataIdx];
  10527. BfIRValue memberVal = ConstantToCurrent(constHolder->GetConstant(val), constHolder, fieldInstance.mResolvedType);
  10528. if (fieldInstance.mDataIdx == newVals.mSize)
  10529. newVals.Add(memberVal);
  10530. else
  10531. {
  10532. while (fieldInstance.mDataIdx >= newVals.mSize)
  10533. newVals.Add(BfIRValue());
  10534. newVals[fieldInstance.mDataIdx] = memberVal;
  10535. }
  10536. }
  10537. }
  10538. for (auto& val : newVals)
  10539. {
  10540. if (!val)
  10541. val = mBfIRBuilder->CreateConstArrayZero(0);
  10542. }
  10543. }
  10544. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(wantType, BfIRPopulateType_Identity), newVals);
  10545. }
  10546. return mBfIRBuilder->CreateConst(constant, constHolder);
  10547. }
  10548. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget, bool force)
  10549. {
  10550. if (attrTarget == BfAttributeTargets_SkipValidate)
  10551. return;
  10552. for (auto& customAttribute : customAttributes->mAttributes)
  10553. {
  10554. if (!customAttribute.mAwaitingValidation)
  10555. continue;
  10556. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  10557. {
  10558. if ((customAttribute.mIsMultiUse) && (!force))
  10559. continue;
  10560. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  10561. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  10562. }
  10563. customAttribute.mAwaitingValidation = false;
  10564. }
  10565. }
  10566. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10567. {
  10568. bool allowNonConstArgs = (flags & BfGetCustomAttributesFlags_AllowNonConstArgs) != 0;
  10569. bool keepConstsInModule = (flags & BfGetCustomAttributesFlags_KeepConstsInModule) != 0;
  10570. if (!mCompiler->mHasRequiredTypes)
  10571. return;
  10572. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  10573. {
  10574. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  10575. sourceClassifier->VisitChild(attributesDirective);
  10576. }
  10577. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  10578. if (mCompiler->IsAutocomplete())
  10579. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  10580. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  10581. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  10582. BfTypeDef* activeTypeDef = GetActiveTypeDef();
  10583. BfAutoComplete* autoComplete = NULL;
  10584. if (mCompiler->mResolvePassData != NULL)
  10585. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  10586. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  10587. {
  10588. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  10589. {
  10590. if (captureInfo == NULL)
  10591. {
  10592. Fail("Capture specifiers can only be used in lambda allocations", tokenNode);
  10593. continue;
  10594. }
  10595. BfCaptureInfo::Entry captureEntry;
  10596. captureEntry.mRefNode = tokenNode;
  10597. captureEntry.mCaptureType = BfCaptureType_Copy;
  10598. if (tokenNode->mToken == BfToken_Ampersand)
  10599. captureEntry.mCaptureType = BfCaptureType_Reference;
  10600. if (tokenNode->mToken == BfToken_Question)
  10601. captureEntry.mCaptureType = BfCaptureType_Auto;
  10602. if (!attributesDirective->mArguments.IsEmpty())
  10603. {
  10604. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]))
  10605. captureEntry.mNameNode = identifierNode;
  10606. else if (auto thisExpr = BfNodeDynCast<BfThisExpression>(attributesDirective->mArguments[0]))
  10607. {
  10608. captureEntry.mNameNode = thisExpr;
  10609. }
  10610. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  10611. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  10612. }
  10613. captureInfo->mCaptures.Add(captureEntry);
  10614. continue;
  10615. }
  10616. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  10617. BfCustomAttribute customAttribute;
  10618. customAttribute.mAwaitingValidation = true;
  10619. customAttribute.mDeclaringType = activeTypeDef;
  10620. customAttribute.mRef = attributesDirective;
  10621. customAttribute.mIsMultiUse = attributesDirective->mIsMultiUse;
  10622. if (attributesDirective->mAttrOpenToken != NULL)
  10623. targetOverride = (BfAttributeTargets)0;
  10624. if (attributesDirective->mAttributeTypeRef == NULL)
  10625. {
  10626. AssertErrorState();
  10627. continue;
  10628. }
  10629. BfType* attrType;
  10630. if (mContext->mCurTypeState != NULL)
  10631. {
  10632. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10633. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10634. }
  10635. else
  10636. {
  10637. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10638. }
  10639. BfTypeDef* attrTypeDef = NULL;
  10640. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  10641. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  10642. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10643. {
  10644. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  10645. if (attrTypeDef != NULL)
  10646. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  10647. }
  10648. bool isBypassedAttr = false;
  10649. if (attrTypeDef != NULL)
  10650. {
  10651. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  10652. // We solve it by having a 'bypass' for known attributes that Object depends on
  10653. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  10654. {
  10655. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  10656. {
  10657. for (auto methodDef : attrTypeDef->mMethods)
  10658. {
  10659. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  10660. {
  10661. customAttribute.mType = attrType->ToTypeInstance();
  10662. customAttribute.mCtor = methodDef;
  10663. isBypassedAttr = true;
  10664. break;
  10665. }
  10666. }
  10667. }
  10668. }
  10669. if (isBypassedAttr)
  10670. {
  10671. customAttribute.mAwaitingValidation = false;
  10672. customAttributes->mAttributes.push_back(customAttribute);
  10673. continue;
  10674. }
  10675. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInst(mContext->mUnreifiedModule->mCurTypeInstance, mCurTypeInstance);
  10676. SetAndRestoreValue<BfMethodInstance*> prevCurMethodInst(mContext->mUnreifiedModule->mCurMethodInstance, mCurMethodInstance);
  10677. if (mContext->mCurTypeState != NULL)
  10678. {
  10679. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10680. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10681. }
  10682. else
  10683. {
  10684. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10685. }
  10686. }
  10687. BfTypeInstance* attrTypeInst = NULL;
  10688. if (attrType == NULL)
  10689. continue;
  10690. attrTypeInst = attrType->ToTypeInstance();
  10691. if ((attrTypeInst != NULL) && (attrTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting))
  10692. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  10693. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  10694. {
  10695. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  10696. continue;
  10697. }
  10698. if ((mIsReified) && (attrTypeInst->mAttributeData != NULL) && ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_ReflectAttribute) != 0))
  10699. {
  10700. // Reify attribute
  10701. PopulateType(attrTypeInst);
  10702. }
  10703. if (mCurTypeInstance != NULL)
  10704. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10705. customAttribute.mType = attrTypeInst;
  10706. bool allocatedMethodState = NULL;
  10707. defer(
  10708. {
  10709. if (allocatedMethodState)
  10710. {
  10711. delete mCurMethodState;
  10712. mCurMethodState = NULL;
  10713. }
  10714. });
  10715. if (mCurMethodState == NULL)
  10716. {
  10717. allocatedMethodState = true;
  10718. mCurMethodState = new BfMethodState();
  10719. mCurMethodState->mTempKind = BfMethodState::TempKind_Static;
  10720. }
  10721. BfConstResolver constResolver(this);
  10722. if (allowNonConstArgs)
  10723. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  10724. bool inPropSet = false;
  10725. SizedArray<BfResolvedArg, 2> argValues;
  10726. for (BfExpression* arg : attributesDirective->mArguments)
  10727. {
  10728. if (arg == NULL)
  10729. {
  10730. continue;
  10731. }
  10732. if (autoComplete != NULL)
  10733. autoComplete->mShowAttributeProperties = attrTypeInst;
  10734. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  10735. {
  10736. inPropSet = true;
  10737. if (autoComplete != NULL)
  10738. autoComplete->CheckNode(assignExpr->mLeft, true);
  10739. String findName = assignExpr->mLeft->ToString();
  10740. BfPropertyDef* bestProp = NULL;
  10741. BfTypeInstance* bestPropTypeInst = NULL;
  10742. BfFieldDef* bestField = NULL;
  10743. BfTypeInstance* bestFieldTypeInst = NULL;
  10744. auto checkTypeInst = attrTypeInst;
  10745. while (checkTypeInst != NULL)
  10746. {
  10747. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  10748. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  10749. {
  10750. if (prop->mName == findName)
  10751. {
  10752. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  10753. {
  10754. bestProp = prop;
  10755. bestPropTypeInst = checkTypeInst;
  10756. }
  10757. }
  10758. }
  10759. for (auto field : checkTypeInst->mTypeDef->mFields)
  10760. {
  10761. if (field->mName == findName)
  10762. {
  10763. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  10764. {
  10765. bestField = field;
  10766. bestFieldTypeInst = checkTypeInst;
  10767. }
  10768. }
  10769. }
  10770. if ((bestProp != NULL) || (bestField != NULL))
  10771. break;
  10772. checkTypeInst = checkTypeInst->mBaseType;
  10773. }
  10774. bool handledExpr = false;
  10775. if (bestField != NULL)
  10776. {
  10777. handledExpr = true;
  10778. if (mCompiler->mResolvePassData != NULL)
  10779. {
  10780. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  10781. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10782. {
  10783. autoComplete->mDefField = bestField;
  10784. autoComplete->mDefType = attrTypeDef;
  10785. }
  10786. }
  10787. if (bestField->mProtection != BfProtection_Public)
  10788. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10789. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10790. BfCustomAttributeSetField setField;
  10791. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  10792. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  10793. if (assignExpr->mRight != NULL)
  10794. {
  10795. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType, BfConstResolveFlag_NoActualizeValues);
  10796. if (result)
  10797. {
  10798. if (!keepConstsInModule)
  10799. CurrentAddToConstHolder(result.mValue);
  10800. setField.mParam = result;
  10801. customAttribute.mSetField.push_back(setField);
  10802. }
  10803. }
  10804. }
  10805. else if (bestProp == NULL)
  10806. {
  10807. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  10808. }
  10809. else
  10810. {
  10811. BfMethodDef* setMethod = NULL;
  10812. for (auto methodDef : bestProp->mMethods)
  10813. {
  10814. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10815. {
  10816. setMethod = methodDef;
  10817. break;
  10818. }
  10819. }
  10820. if (setMethod == NULL)
  10821. {
  10822. Fail("Property has no setter", assignExpr->mLeft);
  10823. }
  10824. else
  10825. {
  10826. if (mCompiler->mResolvePassData != NULL)
  10827. {
  10828. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  10829. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10830. {
  10831. autoComplete->mDefProp = bestProp;
  10832. autoComplete->mDefType = attrTypeDef;
  10833. }
  10834. }
  10835. handledExpr = true;
  10836. if (bestProp->mProtection != BfProtection_Public)
  10837. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10838. BfResolvedArg resolvedArg;
  10839. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10840. BfCustomAttributeSetProperty setProperty;
  10841. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  10842. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  10843. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  10844. if (methodInstance.mMethodInstance != NULL)
  10845. {
  10846. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  10847. if (assignExpr->mRight != NULL)
  10848. {
  10849. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType, BfConstResolveFlag_NoActualizeValues);
  10850. if ((result) && (!result.mType->IsVar()))
  10851. {
  10852. if (!result.mValue.IsConst())
  10853. result = GetDefaultTypedValue(result.mType);
  10854. BF_ASSERT(result.mType == propType);
  10855. if (!keepConstsInModule)
  10856. CurrentAddToConstHolder(result.mValue);
  10857. setProperty.mParam = result;
  10858. customAttribute.mSetProperties.push_back(setProperty);
  10859. }
  10860. }
  10861. }
  10862. }
  10863. }
  10864. if ((!handledExpr) && (assignExpr->mRight != NULL))
  10865. constResolver.Resolve(assignExpr->mRight, NULL, BfConstResolveFlag_NoActualizeValues);
  10866. }
  10867. else
  10868. {
  10869. if (inPropSet)
  10870. {
  10871. Fail("Named attribute argument expected", arg); // CS1016
  10872. }
  10873. BfDeferEvalChecker deferEvalChecker;
  10874. arg->Accept(&deferEvalChecker);
  10875. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  10876. BfResolvedArg resolvedArg;
  10877. resolvedArg.mExpression = arg;
  10878. if (deferParamEval)
  10879. {
  10880. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  10881. }
  10882. else
  10883. resolvedArg.mTypedValue = constResolver.Resolve(arg, NULL, BfConstResolveFlag_NoActualizeValues);
  10884. if (!inPropSet)
  10885. {
  10886. argValues.push_back(resolvedArg);
  10887. }
  10888. }
  10889. if (autoComplete != NULL)
  10890. autoComplete->mShowAttributeProperties = NULL;
  10891. }
  10892. auto wasCapturingMethodInfo = false;
  10893. if (autoComplete != NULL)
  10894. {
  10895. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  10896. if (attributesDirective->mCtorOpenParen != NULL)
  10897. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  10898. }
  10899. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, BfMethodGenericArguments());
  10900. methodMatcher.mBfEvalExprFlags = constResolver.mBfEvalExprFlags;
  10901. attrTypeDef = attrTypeInst->mTypeDef;
  10902. bool success = true;
  10903. bool isFailurePass = false;
  10904. for (int pass = 0; pass < 2; pass++)
  10905. {
  10906. bool isFailurePass = pass == 1;
  10907. for (auto checkMethod : attrTypeDef->mMethods)
  10908. {
  10909. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  10910. continue; // Don't match private default ctor if there's a user-defined one
  10911. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  10912. continue;
  10913. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  10914. continue;
  10915. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  10916. }
  10917. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  10918. break;
  10919. }
  10920. if (autoComplete != NULL)
  10921. {
  10922. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  10923. {
  10924. autoComplete->mIsCapturingMethodMatchInfo = true;
  10925. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  10926. }
  10927. else
  10928. autoComplete->mIsCapturingMethodMatchInfo = false;
  10929. }
  10930. if (methodMatcher.mBestMethodDef == NULL)
  10931. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  10932. if (methodMatcher.mBestMethodDef == NULL)
  10933. {
  10934. AssertErrorState();
  10935. continue;
  10936. }
  10937. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  10938. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  10939. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  10940. {
  10941. Fail("Custom attribute circular reference", attributesDirective);
  10942. }
  10943. if (mCurTypeInstance != NULL)
  10944. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10945. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  10946. success = false;
  10947. for (auto& arg : argValues)
  10948. {
  10949. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  10950. {
  10951. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  10952. constResolver.Resolve(expr, NULL, BfConstResolveFlag_NoActualizeValues);
  10953. }
  10954. }
  10955. // Move all those to the constHolder
  10956. if (!keepConstsInModule)
  10957. {
  10958. for (auto& ctorArg : customAttribute.mCtorArgs)
  10959. {
  10960. if (ctorArg.IsConst())
  10961. CurrentAddToConstHolder(ctorArg);
  10962. }
  10963. }
  10964. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  10965. {
  10966. targetOverride = BfAttributeTargets_ReturnValue;
  10967. if (attrTarget != BfAttributeTargets_Method)
  10968. {
  10969. 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.",
  10970. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  10971. success = false;
  10972. }
  10973. }
  10974. if ((success) && (targetOverride != (BfAttributeTargets)0))
  10975. {
  10976. if ((mCurMethodInstance != NULL) && (targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  10977. {
  10978. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  10979. if (methodInfoEx->mMethodCustomAttributes == NULL)
  10980. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  10981. if (success)
  10982. {
  10983. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  10984. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  10985. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  10986. }
  10987. }
  10988. // Mark as failed since we don't actually want to add this to the custom attributes set
  10989. success = false;
  10990. }
  10991. if (success)
  10992. {
  10993. if ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_DisallowAllowMultiple) != 0)
  10994. {
  10995. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  10996. {
  10997. if (prevCustomAttribute.mType == attrTypeInst)
  10998. {
  10999. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToCleanAttributeString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  11000. }
  11001. }
  11002. }
  11003. }
  11004. if (success)
  11005. {
  11006. customAttributes->mAttributes.push_back(customAttribute);
  11007. }
  11008. }
  11009. ValidateCustomAttributes(customAttributes, attrTarget);
  11010. }
  11011. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  11012. {
  11013. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  11014. GetCustomAttributes(customAttributes, attributesDirective, attrType, flags, captureInfo);
  11015. return customAttributes;
  11016. }
  11017. BfCustomAttributes* BfModule::GetCustomAttributes(BfTypeDef* typeDef)
  11018. {
  11019. BF_ASSERT(mCompiler->IsAutocomplete());
  11020. BfAttributeTargets attrTarget;
  11021. if (typeDef->mIsDelegate)
  11022. attrTarget = BfAttributeTargets_Delegate;
  11023. else if (typeDef->mIsFunction)
  11024. attrTarget = BfAttributeTargets_Function;
  11025. else if (typeDef->mTypeCode == BfTypeCode_Enum)
  11026. attrTarget = BfAttributeTargets_Enum;
  11027. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  11028. attrTarget = BfAttributeTargets_Interface;
  11029. else if (typeDef->mTypeCode == BfTypeCode_Struct)
  11030. attrTarget = BfAttributeTargets_Struct;
  11031. else if (typeDef->mTypeCode == BfTypeCode_Extension)
  11032. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Struct | BfAttributeTargets_Class | BfAttributeTargets_Interface | BfAttributeTargets_Enum);
  11033. else
  11034. attrTarget = BfAttributeTargets_Class;
  11035. return GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  11036. }
  11037. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  11038. {
  11039. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  11040. Warn(0, "Unused attributes", attributeState->mSrc);
  11041. }
  11042. void BfModule::ProcessTypeInstCustomAttributes(int& packing, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  11043. {
  11044. if (mCurTypeInstance->mTypeDef->mIsAlwaysInclude)
  11045. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11046. if (mCurTypeInstance->mCustomAttributes != NULL)
  11047. {
  11048. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11049. {
  11050. String typeName = TypeToString(customAttribute.mType);
  11051. if (typeName == "System.PackedAttribute")
  11052. {
  11053. packing = 1;
  11054. if (customAttribute.mCtorArgs.size() >= 1)
  11055. {
  11056. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11057. int checkPacking = alignConstant->mInt32;
  11058. if (((checkPacking & (checkPacking - 1)) == 0) && (packing > 0) && (packing < 256))
  11059. packing = checkPacking;
  11060. else
  11061. Fail("Packing must be a power of 2", customAttribute.GetRefNode());
  11062. }
  11063. }
  11064. else if (typeName == "System.UnionAttribute")
  11065. {
  11066. isUnion = true;
  11067. }
  11068. else if (typeName == "System.CReprAttribute")
  11069. {
  11070. isCRepr = true;
  11071. isOrdered = true;
  11072. }
  11073. else if (typeName == "System.OrderedAttribute")
  11074. {
  11075. isOrdered = true;
  11076. }
  11077. else if (typeName == "System.AlwaysIncludeAttribute")
  11078. {
  11079. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11080. for (auto setProp : customAttribute.mSetProperties)
  11081. {
  11082. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  11083. if (propertyDef->mName == "AssumeInstantiated")
  11084. {
  11085. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11086. if ((constant != NULL) && (constant->mBool))
  11087. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_AssumeInstantiated);
  11088. }
  11089. else if (propertyDef->mName == "IncludeAllMethods")
  11090. {
  11091. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11092. if ((constant != NULL) && (constant->mBool))
  11093. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_IncludeAllMethods);
  11094. }
  11095. }
  11096. }
  11097. else if (typeName == "System.AlignAttribute")
  11098. {
  11099. if (customAttribute.mCtorArgs.size() >= 1)
  11100. {
  11101. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11102. int checkAlign = alignConstant->mInt32;
  11103. if ((checkAlign & (checkAlign - 1)) == 0)
  11104. alignOverride = checkAlign;
  11105. else
  11106. Fail("Alignment must be a power of 2", customAttribute.GetRefNode());
  11107. }
  11108. }
  11109. else if (typeName == "System.UnderlyingArrayAttribute")
  11110. {
  11111. if (customAttribute.mCtorArgs.size() >= 2)
  11112. {
  11113. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11114. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  11115. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  11116. {
  11117. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  11118. underlyingArraySize = sizeConstant->mInt32;
  11119. }
  11120. }
  11121. }
  11122. if (customAttribute.mType->mAttributeData == NULL)
  11123. PopulateType(customAttribute.mType);
  11124. BF_ASSERT(customAttribute.mType->mAttributeData != NULL);
  11125. if ((customAttribute.mType->mAttributeData != NULL) && ((customAttribute.mType->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0))
  11126. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | customAttribute.mType->mAttributeData->mAlwaysIncludeUser);
  11127. }
  11128. }
  11129. }
  11130. // Checking to see if we're an attribute or not
  11131. void BfModule::ProcessCustomAttributeData()
  11132. {
  11133. if (mCurTypeInstance->mAttributeData != NULL)
  11134. return;
  11135. bool isAttribute = false;
  11136. auto checkTypeInst = mCurTypeInstance->mBaseType;
  11137. while (checkTypeInst != NULL)
  11138. {
  11139. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  11140. isAttribute = true;
  11141. checkTypeInst = checkTypeInst->mBaseType;
  11142. }
  11143. if (!isAttribute)
  11144. return;
  11145. auto attributeData = new BfAttributeData();
  11146. bool hasCustomAttribute = false;
  11147. if (mCurTypeInstance->mCustomAttributes != NULL)
  11148. {
  11149. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11150. {
  11151. if (customAttribute.mType->IsInstanceOf(mCompiler->mAttributeUsageAttributeTypeDef))
  11152. {
  11153. if (customAttribute.mCtorArgs.size() > 0)
  11154. {
  11155. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11156. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11157. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11158. }
  11159. if (customAttribute.mCtorArgs.size() == 2)
  11160. {
  11161. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11162. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11163. {
  11164. attributeData->mFlags = (BfAttributeFlags)constant->mInt32;
  11165. }
  11166. }
  11167. for (auto& setProp : customAttribute.mSetProperties)
  11168. {
  11169. BfPropertyDef* propDef = setProp.mPropertyRef;
  11170. if (propDef->mName == "AllowMultiple")
  11171. {
  11172. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11173. if ((constant != NULL) && (constant->mBool))
  11174. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_DisallowAllowMultiple);
  11175. else
  11176. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_DisallowAllowMultiple);
  11177. }
  11178. else if (propDef->mName == "Inherited")
  11179. {
  11180. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11181. if ((constant != NULL) && (constant->mBool))
  11182. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_NotInherited);
  11183. else
  11184. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_NotInherited);
  11185. }
  11186. else if (propDef->mName == "ValidOn")
  11187. {
  11188. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11189. if (constant != NULL)
  11190. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11191. }
  11192. else if (propDef->mName == "AlwaysIncludeUser")
  11193. {
  11194. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11195. if (constant != NULL)
  11196. attributeData->mAlwaysIncludeUser = (BfAlwaysIncludeFlags)constant->mInt32;
  11197. }
  11198. }
  11199. hasCustomAttribute = true;
  11200. }
  11201. }
  11202. }
  11203. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  11204. {
  11205. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  11206. attributeData->mFlags = mCurTypeInstance->mBaseType->mAttributeData->mFlags;
  11207. attributeData->mAlwaysIncludeUser = mCurTypeInstance->mBaseType->mAttributeData->mAlwaysIncludeUser;
  11208. }
  11209. mCurTypeInstance->mAttributeData = attributeData;
  11210. }
  11211. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  11212. {
  11213. auto constant = constHolder->GetConstant(irValue);
  11214. if (constant == NULL)
  11215. return false;
  11216. if (constant->mTypeCode != BfTypeCode_StringId)
  11217. return false;
  11218. int stringId = constant->mInt32;
  11219. BfStringPoolEntry* entry = NULL;
  11220. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  11221. {
  11222. str += entry->mString;
  11223. }
  11224. else
  11225. {
  11226. BF_DBG_FATAL("Failed to find string by id");
  11227. }
  11228. return true;
  11229. }
  11230. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  11231. {
  11232. BfVariant variant;
  11233. variant.mTypeCode = BfTypeCode_None;
  11234. BfType* primType = NULL;
  11235. if (value.mType->IsPrimitiveType())
  11236. primType = (BfPrimitiveType*)value.mType;
  11237. else if (value.mType->IsTypedPrimitive())
  11238. primType = value.mType->GetUnderlyingType();
  11239. else if (value.mType->IsInstanceOf(mCompiler->mStringTypeDef))
  11240. primType = value.mType;
  11241. if (primType)
  11242. {
  11243. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  11244. if (constant != NULL)
  11245. {
  11246. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  11247. {
  11248. variant.mUInt64 = 0;
  11249. variant.mTypeCode = BfTypeCode_Let;
  11250. return variant;
  11251. }
  11252. if (constant->mConstType == BfConstType_GlobalVar)
  11253. {
  11254. int stringIdx = GetStringPoolIdx(value.mValue, mBfIRBuilder);
  11255. if (stringIdx != -1)
  11256. {
  11257. variant.mTypeCode = BfTypeCode_StringId;
  11258. variant.mInt64 = stringIdx;
  11259. return variant;
  11260. }
  11261. }
  11262. switch (constant->mTypeCode)
  11263. {
  11264. case BfTypeCode_Boolean:
  11265. case BfTypeCode_Int8:
  11266. case BfTypeCode_UInt8:
  11267. case BfTypeCode_Int16:
  11268. case BfTypeCode_UInt16:
  11269. case BfTypeCode_Int32:
  11270. case BfTypeCode_UInt32:
  11271. case BfTypeCode_Int64:
  11272. case BfTypeCode_UInt64:
  11273. case BfTypeCode_IntPtr:
  11274. case BfTypeCode_UIntPtr:
  11275. case BfTypeCode_IntUnknown:
  11276. case BfTypeCode_UIntUnknown:
  11277. case BfTypeCode_Double:
  11278. case BfTypeCode_Char8:
  11279. case BfTypeCode_Char16:
  11280. case BfTypeCode_Char32:
  11281. case BfTypeCode_StringId:
  11282. variant.mTypeCode = constant->mTypeCode;
  11283. if (((variant.mTypeCode == BfTypeCode_Int64) || (variant.mTypeCode == BfTypeCode_UInt64)) &&
  11284. (primType->mSize > 0) && (primType->mSize < 8) &&
  11285. (mBfIRBuilder->IsIntable(primType->GetTypeCode())))
  11286. {
  11287. // We may have an 'int unknown' that we need to downsize
  11288. variant.mTypeCode = primType->GetTypeCode();
  11289. }
  11290. variant.mInt64 = constant->mInt64;
  11291. break;
  11292. case BfTypeCode_Float:
  11293. variant.mTypeCode = constant->mTypeCode;
  11294. variant.mSingle = (float)constant->mDouble;
  11295. break;
  11296. default:
  11297. if (refNode != NULL)
  11298. Fail("Invalid const expression type", refNode);
  11299. break;
  11300. }
  11301. }
  11302. }
  11303. else
  11304. {
  11305. int allocSize = value.mType->mSize + 4;
  11306. BfVariant::StructData* structData = (BfVariant::StructData*)(new uint8[allocSize]);
  11307. memset(structData, 0, allocSize);
  11308. structData->mSize = value.mType->mSize;
  11309. mBfIRBuilder->WriteConstant(value.mValue, structData->mData, value.mType);
  11310. variant.mTypeCode = BfTypeCode_Struct;
  11311. variant.mPtr = structData;
  11312. }
  11313. return variant;
  11314. }
  11315. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue, bool makeInReadOnly)
  11316. {
  11317. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  11318. {
  11319. auto refType = (BfRefType*)typedValue.mType;
  11320. auto elementType = typedValue.mType->GetUnderlyingType();
  11321. if (typedValue.IsAddr())
  11322. {
  11323. if (elementType->IsValuelessType())
  11324. {
  11325. BF_ASSERT(!typedValue.mValue);
  11326. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11327. }
  11328. else
  11329. typedValue = BfTypedValue(mBfIRBuilder->CreateAlignedLoad(typedValue.mValue, elementType->mAlign), elementType, true);
  11330. }
  11331. else
  11332. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11333. if (typedValue.mType->IsValuelessType())
  11334. {
  11335. BF_ASSERT(typedValue.mValue.IsFake());
  11336. }
  11337. if ((refType->mRefKind == BfRefType::RefKind_In) && (makeInReadOnly))
  11338. {
  11339. if (typedValue.mKind == BfTypedValueKind_Addr)
  11340. typedValue.mKind = BfTypedValueKind_ReadOnlyAddr;
  11341. }
  11342. }
  11343. return typedValue;
  11344. }
  11345. BfTypedValue BfModule::SanitizeAddr(BfTypedValue typedValue)
  11346. {
  11347. if (!typedValue)
  11348. return typedValue;
  11349. if (typedValue.mType->IsRef())
  11350. {
  11351. typedValue = LoadValue(typedValue);
  11352. auto copiedVal = BfTypedValue(CreateAlloca(typedValue.mType), typedValue.mType, true);
  11353. mBfIRBuilder->CreateStore(typedValue.mValue, copiedVal.mValue);
  11354. return copiedVal;
  11355. }
  11356. return typedValue;
  11357. }
  11358. BfTypedValue BfModule::ToRef(BfTypedValue typedValue, BfRefType* refType)
  11359. {
  11360. if (refType == NULL)
  11361. refType = CreateRefType(typedValue.mType);
  11362. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (typedValue.mType->IsObjectOrInterface()))
  11363. {
  11364. return LoadValue(typedValue);
  11365. }
  11366. if (refType->mRefKind == BfRefType::RefKind_Mut)
  11367. refType = CreateRefType(typedValue.mType);
  11368. if (!typedValue.mType->IsValuelessType())
  11369. typedValue = MakeAddressable(typedValue, false, true);
  11370. return BfTypedValue(typedValue.mValue, refType);
  11371. }
  11372. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  11373. {
  11374. if (!typedValue.IsAddr())
  11375. return typedValue;
  11376. PopulateType(typedValue.mType);
  11377. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  11378. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  11379. if (typedValue.mValue.IsConst())
  11380. {
  11381. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  11382. if (constantValue != NULL)
  11383. {
  11384. if (constantValue->mConstType == BfConstType_GlobalVar)
  11385. {
  11386. auto globalVar = (BfGlobalVar*)constantValue;
  11387. if (globalVar->mName[0] == '#')
  11388. {
  11389. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  11390. if (result)
  11391. {
  11392. // We want to avoid 'unreachable code' issues from values that
  11393. // are technically constant but change depending on compilation context
  11394. if (mCurMethodState != NULL)
  11395. {
  11396. auto checkScope = mCurMethodState->mCurScope;
  11397. while (checkScope != NULL)
  11398. {
  11399. checkScope->mSupressNextUnreachable = true;
  11400. checkScope = checkScope->mPrevScope;
  11401. }
  11402. }
  11403. return result;
  11404. }
  11405. if (!mIsComptimeModule)
  11406. return GetDefaultTypedValue(typedValue.mType);
  11407. }
  11408. }
  11409. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  11410. {
  11411. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  11412. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  11413. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  11414. auto ceTypedValue = ceDebugger->GetAddr(constantValue);
  11415. if (ceTypedValue)
  11416. {
  11417. if ((typedValue.mType->IsObjectOrInterface()) || (typedValue.mType->IsPointer()) || (typedValue.mType->IsRef()))
  11418. {
  11419. void* data = ceContext->GetMemoryPtr((addr_ce)ceTypedValue.mAddr, sizeof(addr_ce));
  11420. if (data == NULL)
  11421. {
  11422. Fail("Invalid address", refNode);
  11423. return GetDefaultTypedValue(typedValue.mType);
  11424. }
  11425. uint64 dataAddr;
  11426. if (mSystem->mPtrSize == 4)
  11427. dataAddr = *(uint32*)data;
  11428. else
  11429. dataAddr = *(uint64*)data;
  11430. return BfTypedValue(mBfIRBuilder->CreateIntToPtr(
  11431. mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataAddr), mBfIRBuilder->MapType(typedValue.mType)), typedValue.mType);
  11432. }
  11433. auto constVal = ceContext->CreateConstant(this, ceContext->mMemory.mVals + ceTypedValue.mAddr, typedValue.mType);
  11434. if (!constVal)
  11435. {
  11436. Fail("Failed to create const", refNode);
  11437. return GetDefaultTypedValue(typedValue.mType);
  11438. }
  11439. return BfTypedValue(constVal, typedValue.mType);
  11440. }
  11441. }
  11442. }
  11443. }
  11444. BfIRValue loadedVal = typedValue.mValue;
  11445. if (loadedVal)
  11446. {
  11447. if (typedValue.mType->IsVar())
  11448. {
  11449. return BfTypedValue(loadedVal, typedValue.mType, false);
  11450. }
  11451. PopulateType(typedValue.mType, BfPopulateType_Data);
  11452. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile || typedValue.IsVolatile());
  11453. }
  11454. return BfTypedValue(loadedVal, typedValue.mType, false);
  11455. }
  11456. BfTypedValue BfModule::PrepareConst(BfTypedValue& typedValue)
  11457. {
  11458. if (!typedValue.mValue.IsConst())
  11459. return typedValue;
  11460. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  11461. if (constant->mTypeCode == BfTypeCode_StringId)
  11462. return GetTypedValueFromConstant(constant, mBfIRBuilder, typedValue.mType);
  11463. return typedValue;
  11464. }
  11465. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  11466. {
  11467. if (typedValue.IsSplat())
  11468. return AggregateSplat(typedValue);
  11469. if (typedValue.IsAddr())
  11470. return LoadValue(typedValue);
  11471. return typedValue;
  11472. }
  11473. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  11474. {
  11475. if (!typedValue.IsSplat())
  11476. return typedValue;
  11477. BF_ASSERT(!mIsComptimeModule);
  11478. if (typedValue.mType->IsValuelessType())
  11479. return typedValue;
  11480. int elementIdx = 0;
  11481. auto _ExtractValue = [&](BfType* checkType)
  11482. {
  11483. if (valueArrPtr != NULL)
  11484. return valueArrPtr[elementIdx++];
  11485. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  11486. };
  11487. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11488. {
  11489. if (checkType->IsStruct())
  11490. {
  11491. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11492. auto checkTypeInstance = checkType->ToTypeInstance();
  11493. if (checkTypeInstance->mBaseType != NULL)
  11494. {
  11495. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  11496. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  11497. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  11498. }
  11499. if (checkTypeInstance->mIsUnion)
  11500. {
  11501. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11502. if (!unionInnerType->IsValuelessType())
  11503. {
  11504. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  11505. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  11506. }
  11507. if (checkTypeInstance->IsEnum())
  11508. {
  11509. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11510. BfIRValue fieldValue = checkTypeLambda(dscrType);
  11511. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  11512. }
  11513. }
  11514. else
  11515. {
  11516. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11517. {
  11518. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11519. if (fieldInstance->mDataIdx >= 0)
  11520. {
  11521. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  11522. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  11523. }
  11524. }
  11525. }
  11526. return curValue;
  11527. }
  11528. else if (checkType->IsMethodRef())
  11529. {
  11530. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11531. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11532. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11533. {
  11534. BfIRValue fieldValue;
  11535. auto checkType = methodRefType->GetCaptureType(dataIdx);
  11536. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11537. {
  11538. fieldValue = checkTypeLambda(checkType);
  11539. }
  11540. else
  11541. {
  11542. fieldValue = _ExtractValue(checkType);
  11543. }
  11544. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  11545. }
  11546. return curValue;
  11547. }
  11548. else if (!checkType->IsValuelessType())
  11549. {
  11550. return _ExtractValue(checkType);
  11551. }
  11552. return BfIRValue();
  11553. };
  11554. BfIRValue value = checkTypeLambda(typedValue.mType);
  11555. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  11556. }
  11557. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  11558. {
  11559. if (!typedValue.IsSplat())
  11560. return;
  11561. if (typedValue.mType->IsValuelessType())
  11562. return;
  11563. BF_ASSERT(!mIsComptimeModule);
  11564. /*static int sCallIdx = 0;
  11565. if (!mCompiler->mIsResolveOnly)
  11566. sCallIdx++;
  11567. int callIdx = sCallIdx;*/
  11568. int elementIdx = 0;
  11569. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  11570. {
  11571. if (checkType->IsStruct())
  11572. {
  11573. auto checkTypeInstance = checkType->ToTypeInstance();
  11574. if (checkTypeInstance->mBaseType != NULL)
  11575. {
  11576. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  11577. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  11578. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  11579. }
  11580. if (checkTypeInstance->mIsUnion)
  11581. {
  11582. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11583. if (!unionInnerType->IsValuelessType())
  11584. {
  11585. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  11586. checkTypeLambda(unionInnerType, fieldAddrVal);
  11587. }
  11588. if (checkTypeInstance->IsEnum())
  11589. {
  11590. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11591. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  11592. checkTypeLambda(dscrType, fieldAddrVal);
  11593. }
  11594. }
  11595. else
  11596. {
  11597. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11598. {
  11599. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11600. if (fieldInstance->mDataIdx >= 0)
  11601. {
  11602. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  11603. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  11604. }
  11605. }
  11606. }
  11607. }
  11608. else if (checkType->IsMethodRef())
  11609. {
  11610. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11611. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11612. {
  11613. auto dataType = methodRefType->GetCaptureType(dataIdx);
  11614. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  11615. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11616. {
  11617. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  11618. }
  11619. else
  11620. {
  11621. // static int sItrCount = 0;
  11622. // sItrCount++;
  11623. // int curItr = sItrCount;
  11624. // if (curItr == 1)
  11625. // {
  11626. // NOP;
  11627. // }
  11628. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  11629. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  11630. }
  11631. }
  11632. }
  11633. else if (!checkType->IsValuelessType())
  11634. {
  11635. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  11636. mBfIRBuilder->CreateStore(val, curAddrVal);
  11637. }
  11638. };
  11639. checkTypeLambda(typedValue.mType, addrVal);
  11640. }
  11641. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal, bool forceMutable, bool forceAddressable)
  11642. {
  11643. bool wasReadOnly = typedVal.IsReadOnly();
  11644. if ((forceAddressable) ||
  11645. ((typedVal.mType->IsValueType()) &&
  11646. (!typedVal.mType->IsValuelessType())))
  11647. {
  11648. wasReadOnly = true; // Any non-addr is implicitly read-only
  11649. //static int gCallIdx = 0;
  11650. FixValueActualization(typedVal);
  11651. if (typedVal.IsAddr())
  11652. return typedVal;
  11653. BfType* type = typedVal.mType;
  11654. PopulateType(type);
  11655. BfIRValue tempVar;
  11656. if (typedVal.mValue.IsFake())
  11657. tempVar = mBfIRBuilder->GetFakeVal();
  11658. else
  11659. {
  11660. tempVar = CreateAlloca(type);
  11661. if (typedVal.IsSplat())
  11662. AggregateSplatIntoAddr(typedVal, tempVar);
  11663. else
  11664. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  11665. }
  11666. if (forceMutable)
  11667. wasReadOnly = false;
  11668. return BfTypedValue(tempVar, type,
  11669. typedVal.IsThis() ?
  11670. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  11671. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  11672. }
  11673. return LoadValue(typedVal);
  11674. }
  11675. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  11676. {
  11677. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  11678. typedValue.mKind = BfTypedValueKind_Addr;
  11679. return typedValue;
  11680. }
  11681. BfTypedValue BfModule::CopyValue(const BfTypedValue& typedValue)
  11682. {
  11683. return MakeAddressable(LoadValue(typedValue), true);
  11684. }
  11685. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  11686. {
  11687. BF_ASSERT(!mIsComptimeModule);
  11688. BfIRValue val;
  11689. if (typedValue.mValue.IsArg())
  11690. {
  11691. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  11692. if (isAddr != NULL)
  11693. {
  11694. if (wantType != NULL)
  11695. *isAddr = wantType->IsComposite();
  11696. else
  11697. *isAddr = false;
  11698. }
  11699. else if (wantType->IsComposite())
  11700. val = mBfIRBuilder->CreateLoad(val);
  11701. }
  11702. if (!val)
  11703. {
  11704. auto checkMethodState = mCurMethodState;
  11705. while (checkMethodState != NULL)
  11706. {
  11707. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  11708. {
  11709. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  11710. if (decompAddr == typedValue.mValue)
  11711. {
  11712. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  11713. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  11714. {
  11715. // This is really backing for a POINTER to a composite inside a methodRef
  11716. val = mBfIRBuilder->CreateLoad(val);
  11717. }
  11718. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  11719. {
  11720. *isAddr = true;
  11721. return val;
  11722. }
  11723. else
  11724. {
  11725. val = mBfIRBuilder->CreateAlignedLoad(val, wantType->mAlign);
  11726. break;
  11727. }
  11728. }
  11729. }
  11730. if (val)
  11731. break;
  11732. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  11733. {
  11734. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  11735. return mBfIRBuilder->GetFakeVal();
  11736. }
  11737. checkMethodState = checkMethodState->mPrevMethodState;
  11738. }
  11739. }
  11740. if (val)
  11741. {
  11742. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  11743. {
  11744. BF_ASSERT(wantType != NULL);
  11745. if (wantType != NULL)
  11746. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  11747. }
  11748. return val;
  11749. }
  11750. BFMODULE_FATAL(this, "Splat not found");
  11751. return BfIRValue();
  11752. }
  11753. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  11754. {
  11755. int useFieldIdx = fieldIdx;
  11756. BfType* fieldType = NULL;
  11757. if (fieldInstance != NULL)
  11758. {
  11759. fieldType = fieldInstance->mResolvedType;
  11760. if (typedValue.mType->IsUnion())
  11761. {
  11762. if (fieldIdx == 1)
  11763. {
  11764. if (typedValue.IsSplat())
  11765. {
  11766. bool isAddr = false;
  11767. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  11768. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  11769. }
  11770. }
  11771. }
  11772. }
  11773. else
  11774. {
  11775. if (typedValue.mType->IsPayloadEnum())
  11776. {
  11777. auto typeInst = typedValue.mType->ToTypeInstance();
  11778. if (fieldIdx == 1)
  11779. fieldType = typeInst->GetUnionInnerType();
  11780. else if (fieldIdx == 2)
  11781. {
  11782. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  11783. }
  11784. }
  11785. else if (typedValue.mType->IsUnion())
  11786. {
  11787. if (fieldIdx == 1)
  11788. {
  11789. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  11790. if (typedValue.IsSplat())
  11791. {
  11792. bool isAddr = false;
  11793. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  11794. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  11795. }
  11796. }
  11797. }
  11798. }
  11799. BF_ASSERT(typedValue.mType->IsStruct());
  11800. if (typedValue.IsSplat())
  11801. {
  11802. if (typedValue.mType->IsPayloadEnum())
  11803. {
  11804. if (fieldIdx == 1)
  11805. {
  11806. // Payload
  11807. auto typeInst = typedValue.mType->ToTypeInstance();
  11808. auto unionInnerType = typeInst->GetUnionInnerType();
  11809. bool isAddr = false;
  11810. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  11811. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  11812. }
  11813. if (fieldIdx == 2)
  11814. {
  11815. // Discriminator
  11816. auto typeInst = typedValue.mType->ToTypeInstance();
  11817. auto unionInnerType = typeInst->GetUnionInnerType();
  11818. auto dscrType = typeInst->GetDiscriminatorType();
  11819. int argIdx = typedValue.mValue.mId;
  11820. int componentIdx = 0;
  11821. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  11822. bool isAddr;
  11823. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  11824. return BfTypedValue(irVal, dscrType, isAddr);
  11825. }
  11826. }
  11827. int componentIdx = 0;
  11828. BfTypedValue retVal;
  11829. BfFieldInstance* wantFieldInstance = fieldInstance;
  11830. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11831. {
  11832. if (checkType->IsStruct())
  11833. {
  11834. auto checkTypeInstance = checkType->ToTypeInstance();
  11835. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  11836. {
  11837. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  11838. fieldType = checkTypeInstance->GetUnionInnerType();
  11839. checkTypeLambda(fieldType);
  11840. if (checkType->IsEnum())
  11841. {
  11842. // Past discriminator...
  11843. componentIdx++;
  11844. }
  11845. return;
  11846. }
  11847. if (checkTypeInstance->mBaseType != NULL)
  11848. checkTypeLambda(checkTypeInstance->mBaseType);
  11849. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11850. {
  11851. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11852. if (fieldInstance == wantFieldInstance)
  11853. {
  11854. if (fieldInstance->mResolvedType->IsValuelessType())
  11855. {
  11856. retVal = GetDefaultTypedValue(fieldInstance->mResolvedType);
  11857. break;
  11858. }
  11859. bool isAddr = false;
  11860. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  11861. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  11862. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  11863. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  11864. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  11865. {
  11866. retVal = LoadValue(retVal);
  11867. }
  11868. break;
  11869. }
  11870. if (fieldInstance->mDataIdx >= 0)
  11871. checkTypeLambda(fieldInstance->GetResolvedType());
  11872. }
  11873. }
  11874. else if (!checkType->IsValuelessType())
  11875. {
  11876. componentIdx++;
  11877. //argIdx++;
  11878. }
  11879. };
  11880. checkTypeLambda(typedValue.mType);
  11881. BF_ASSERT(retVal);
  11882. return retVal;
  11883. }
  11884. if (typedValue.IsAddr())
  11885. {
  11886. BF_ASSERT(fieldType != NULL);
  11887. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  11888. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  11889. }
  11890. else
  11891. {
  11892. BF_ASSERT(fieldType != NULL);
  11893. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  11894. }
  11895. }
  11896. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  11897. {
  11898. if (typedValue.IsAddr())
  11899. {
  11900. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  11901. return mBfIRBuilder->CreateAlignedLoad(addrVal, typedValue.mType->mAlign);
  11902. }
  11903. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  11904. }
  11905. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  11906. {
  11907. if (isElementIndex)
  11908. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11909. else
  11910. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11911. // if (elementType->IsSizeAligned())
  11912. // {
  11913. // if (isElementIndex)
  11914. // return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11915. // else
  11916. // return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11917. // }
  11918. //
  11919. // auto ptrType = CreatePointerType(elementType);
  11920. // auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  11921. // auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  11922. // auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  11923. // BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  11924. // BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  11925. // return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  11926. }
  11927. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  11928. {
  11929. if (elementType->IsSizeAligned())
  11930. {
  11931. if (isElementIndex)
  11932. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  11933. else
  11934. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11935. }
  11936. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  11937. }
  11938. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  11939. {
  11940. if (modifyType == NULL)
  11941. modifyType = "modify";
  11942. if (typedValue.mType->IsVar())
  11943. return true;
  11944. if (typedValue.IsReadOnly())
  11945. {
  11946. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  11947. return false;
  11948. }
  11949. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  11950. {
  11951. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  11952. return false;
  11953. }
  11954. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  11955. {
  11956. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  11957. return false;
  11958. }
  11959. return true;
  11960. }
  11961. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  11962. {
  11963. // If one is an interface and the other is an impl, B is the impl
  11964. auto implOwner = methodB->GetOwner();
  11965. if (methodA->mMethodDef->mIsLocalMethod)
  11966. {
  11967. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  11968. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  11969. if (sepPosA != sepPosB)
  11970. return false;
  11971. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  11972. return false;
  11973. }
  11974. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  11975. return false;
  11976. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  11977. return false;
  11978. if (methodA->mMethodDef->mHasComptime != methodB->mMethodDef->mHasComptime)
  11979. return false;
  11980. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  11981. return false;
  11982. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  11983. {
  11984. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  11985. return false;
  11986. }
  11987. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  11988. {
  11989. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  11990. return false;
  11991. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  11992. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  11993. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  11994. return false;
  11995. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  11996. return false;
  11997. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  11998. return false;
  11999. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  12000. {
  12001. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  12002. return false;
  12003. }
  12004. }
  12005. int implicitParamCountA = methodA->GetImplicitParamCount();
  12006. int implicitParamCountB = methodB->GetImplicitParamCount();
  12007. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  12008. return false;
  12009. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  12010. return false;
  12011. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  12012. {
  12013. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  12014. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  12015. return false;
  12016. }
  12017. // Compare generic params. Generic params are part of the method signature here
  12018. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  12019. return false;
  12020. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  12021. {
  12022. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  12023. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  12024. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  12025. return false;
  12026. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  12027. return false;
  12028. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  12029. return false;
  12030. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  12031. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  12032. return false;
  12033. }
  12034. return true;
  12035. }
  12036. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  12037. {
  12038. if (!CompareMethodSignatures(methodA, methodB))
  12039. return false;
  12040. if (methodA->mReturnType != methodB->mReturnType)
  12041. return false;
  12042. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  12043. return false;
  12044. return true;
  12045. }
  12046. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  12047. {
  12048. if ((iMethodInst->GetNumGenericParams() != 0) || (methodInstance->GetNumGenericParams() != 0))
  12049. return false;
  12050. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  12051. return false;
  12052. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  12053. return false;
  12054. if (iMethodInst->mMethodDef->mIsOperator)
  12055. {
  12056. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  12057. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  12058. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  12059. return false;
  12060. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  12061. return false;
  12062. }
  12063. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  12064. return false;
  12065. auto selfType = methodInstance->GetOwner();
  12066. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  12067. {
  12068. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  12069. return false;
  12070. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  12071. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  12072. iParamType = ResolveSelfType(iParamType, selfType);
  12073. methodParamType = ResolveSelfType(methodParamType, selfType);
  12074. if (!iParamType->IsGenericParam())
  12075. {
  12076. if (methodParamType != iParamType)
  12077. return false;
  12078. }
  12079. else
  12080. {
  12081. if (!methodParamType->IsGenericParam())
  12082. return false;
  12083. auto genericParamType = (BfGenericParamType*)methodParamType;
  12084. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  12085. return false;
  12086. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12087. bool hadInterface = false;
  12088. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  12089. if (interfaceConstraint == iParamType)
  12090. hadInterface = true;
  12091. if (!hadInterface)
  12092. return false;
  12093. }
  12094. }
  12095. return true;
  12096. }
  12097. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  12098. {
  12099. BfMethodInstance* methodInstance = methodRef;
  12100. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  12101. {
  12102. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  12103. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  12104. {
  12105. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  12106. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  12107. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12108. BfMethodRef methodRef = methodInstance;
  12109. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  12110. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  12111. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  12112. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  12113. (mIsReified))
  12114. {
  12115. specializedMethodRefInfo->mHasReifiedRef = true;
  12116. }
  12117. }
  12118. }
  12119. }
  12120. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  12121. {
  12122. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  12123. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12124. if (mBfIRBuilder == NULL)
  12125. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12126. if (methodInstance->GetOwner()->IsFunction())
  12127. {
  12128. // No actual ref needed- not an actual generated function
  12129. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12130. }
  12131. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  12132. if (!isGenFunction)
  12133. AddMethodReference(methodInstance, flags);
  12134. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  12135. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  12136. if (IsSkippingExtraResolveChecks())
  12137. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12138. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  12139. {
  12140. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12141. }
  12142. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12143. if ((methodInstance->mIsIntrinsic) || (methodInstance->mMethodDef->mIsExtern))
  12144. isInlined = false;
  12145. BfMethodRef methodRef = methodInstance;
  12146. if (isInlined)
  12147. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  12148. else
  12149. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  12150. if (!isGenFunction)
  12151. {
  12152. BfIRValue* irFuncPtr = NULL;
  12153. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  12154. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  12155. }
  12156. if (mAwaitingInitFinish)
  12157. FinishInit();
  12158. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  12159. if (!isGenFunction)
  12160. {
  12161. BF_ASSERT(func || methodInstance->mMethodInstanceGroup->mOwner->IsInterface());
  12162. mFuncReferences[methodRef] = func;
  12163. }
  12164. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  12165. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12166. {
  12167. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  12168. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  12169. // type instance
  12170. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  12171. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  12172. for (auto ownedTypeInst : mOwnedTypeInstances)
  12173. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  12174. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  12175. {
  12176. mIncompleteMethodCount++;
  12177. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12178. inlineMethodRequest->mType = methodInstance->GetOwner();
  12179. inlineMethodRequest->mFromModule = this;
  12180. inlineMethodRequest->mFunc = func;
  12181. inlineMethodRequest->mFromModuleRevision = mRevision;
  12182. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  12183. inlineMethodRequest->mMethodInstance = methodInstance;
  12184. BF_ASSERT(mIsModuleMutable);
  12185. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12186. }
  12187. }
  12188. return BfModuleMethodInstance(methodInstance, func);
  12189. }
  12190. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  12191. {
  12192. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  12193. if (mBfIRBuilder == NULL)
  12194. {
  12195. // To allow for custom attribute data
  12196. PrepareForIRWriting(typeInst);
  12197. }
  12198. BfModule* declareModule = this;
  12199. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  12200. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  12201. declareModule = declareModule->mParentModule;
  12202. // Check for attributes
  12203. if (typeInst == mContext->mBfObjectType)
  12204. {
  12205. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  12206. if (methodDecl != NULL)
  12207. {
  12208. auto attributesDirective = methodDecl->mAttributes;
  12209. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  12210. {
  12211. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  12212. sourceClassifier->VisitChild(attributesDirective);
  12213. }
  12214. }
  12215. }
  12216. else
  12217. {
  12218. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  12219. GetMethodCustomAttributes(methodInstance);
  12220. }
  12221. BF_ASSERT(mModuleOptions == NULL);
  12222. if (methodInstance->GetCustomAttributes() != NULL)
  12223. {
  12224. auto project = typeInst->mTypeDef->mProject;
  12225. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  12226. BfModuleOptions wantOptions = moduleOptions;
  12227. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  12228. if (typeOptions != NULL)
  12229. {
  12230. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  12231. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  12232. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  12233. }
  12234. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  12235. {
  12236. StringT<128> attrName;
  12237. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  12238. {
  12239. attrName.Clear();
  12240. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  12241. Array<int>* arrPtr;
  12242. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  12243. {
  12244. for (auto optionsIdx : *arrPtr)
  12245. {
  12246. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  12247. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  12248. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  12249. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  12250. }
  12251. }
  12252. }
  12253. }
  12254. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  12255. {
  12256. auto lastCheckModule = this;
  12257. auto checkModule = this->mNextAltModule;
  12258. while (checkModule != NULL)
  12259. {
  12260. if (*checkModule->mModuleOptions == wantOptions)
  12261. {
  12262. declareModule = checkModule;
  12263. break;
  12264. }
  12265. lastCheckModule = checkModule;
  12266. checkModule = checkModule->mNextAltModule;
  12267. }
  12268. // Not found?
  12269. if (declareModule == this)
  12270. {
  12271. String specModuleName = mModuleName + "@@";
  12272. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  12273. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  12274. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  12275. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  12276. declareModule = new BfModule(mContext, specModuleName);
  12277. declareModule->mProject = project;
  12278. declareModule->mModuleOptions = new BfModuleOptions();
  12279. *declareModule->mModuleOptions = wantOptions;
  12280. declareModule->mParentModule = lastCheckModule;
  12281. declareModule->Init();
  12282. lastCheckModule->mNextAltModule = declareModule;
  12283. }
  12284. }
  12285. }
  12286. declareModule->PrepareForIRWriting(typeInst);
  12287. return declareModule;
  12288. }
  12289. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType, BfModule* referencingModule)
  12290. {
  12291. if (methodDef->mMethodType == BfMethodType_Init)
  12292. return BfModuleMethodInstance();
  12293. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  12294. {
  12295. // Don't bother inlining for resolve-only
  12296. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12297. }
  12298. if (methodDef->mIsExtern)
  12299. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12300. bool processNow = false;
  12301. bool keepInCurrentModule = false;
  12302. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  12303. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  12304. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  12305. {
  12306. return BfModuleMethodInstance();
  12307. }
  12308. if (methodDef->mIsLocalMethod)
  12309. {
  12310. auto rootMethodState = mCurMethodState->GetRootMethodState();
  12311. BfLocalMethod* localMethod;
  12312. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  12313. {
  12314. // Handle the def in the correct method state
  12315. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  12316. }
  12317. BFMODULE_FATAL(this, "Cannot find local method");
  12318. return BfModuleMethodInstance();
  12319. }
  12320. #ifdef _DEBUG
  12321. for (auto arg : methodGenericArguments)
  12322. BF_ASSERT(!arg->IsVar());
  12323. #endif
  12324. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  12325. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  12326. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  12327. // a FinishInit
  12328. if ((typeInst->IsIncomplete()) &&
  12329. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  12330. {
  12331. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  12332. // for resolve-only because we don't differentiate between reified/unreified there
  12333. if ((methodDef->mIsStatic) /*&& (mIsComptimeModule)*/)
  12334. {
  12335. if (!typeInst->DefineStateAllowsStaticMethods())
  12336. PopulateType(typeInst, BfPopulateType_AllowStaticMethods);
  12337. }
  12338. else
  12339. PopulateType(typeInst, BfPopulateType_Full);
  12340. if (typeInst->mDefineState < BfTypeDefineState_Defined)
  12341. {
  12342. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12343. {
  12344. BfLogSysM("GetMethodInstance (DefineState < BfTypeDefineState_Defined)) bailing due to IsCePaused\n");
  12345. return BfModuleMethodInstance();
  12346. }
  12347. }
  12348. }
  12349. bool tryModuleMethodLookup = false;
  12350. BfModuleMethodInstance moduleMethodInst;
  12351. BfModule* instModule = typeInst->mModule;
  12352. if (keepInCurrentModule)
  12353. {
  12354. // Stay here
  12355. instModule = this;
  12356. }
  12357. if (this == mContext->mUnreifiedModule)
  12358. {
  12359. // Stay in this 'resolve only' module here
  12360. }
  12361. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  12362. {
  12363. BF_ASSERT(this == mContext->mUnreifiedModule);
  12364. }
  12365. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  12366. {
  12367. BF_ASSERT(instModule == mParentModule);
  12368. }
  12369. else if (instModule != this)
  12370. {
  12371. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12372. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  12373. if ((!mIsComptimeModule) && (!mIsReified) && (instModule->mIsReified))
  12374. {
  12375. BF_ASSERT(!mCompiler->mIsResolveOnly);
  12376. // A resolve-only module is specializing a method from a type in a reified module,
  12377. // we need to take care that this doesn't cause anything new to become reified
  12378. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  12379. if (!moduleMethodInstance)
  12380. return moduleMethodInstance;
  12381. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  12382. return moduleMethodInstance;
  12383. }
  12384. else
  12385. {
  12386. if ((!mIsComptimeModule) && (mIsReified) && (!instModule->mIsReified))
  12387. {
  12388. if (!typeInst->IsUnspecializedType())
  12389. {
  12390. if (!instModule->mReifyQueued)
  12391. {
  12392. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  12393. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  12394. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  12395. mContext->mReifyModuleWorkList.Add(instModule);
  12396. instModule->mReifyQueued = true;
  12397. }
  12398. 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);
  12399. // This ensures that the method will actually be created when it gets reified
  12400. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  12401. specializationRequest->mFromModule = typeInst->mModule;
  12402. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  12403. specializationRequest->Init(typeInst, foreignType, methodDef);
  12404. //specializationRequest->mMethodDef = methodDef;
  12405. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  12406. specializationRequest->mType = typeInst;
  12407. specializationRequest->mFlags = flags;
  12408. }
  12409. }
  12410. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12411. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoReference);
  12412. if (mIsComptimeModule)
  12413. {
  12414. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12415. if (!mCompiler->mIsResolveOnly)
  12416. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification | BfGetMethodInstanceFlag_Unreified | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12417. }
  12418. // Not extern
  12419. // Create the instance in the proper module and then create a reference in this one
  12420. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType, this);
  12421. if (!moduleMethodInst)
  12422. return moduleMethodInst;
  12423. tryModuleMethodLookup = true;
  12424. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  12425. {
  12426. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  12427. }
  12428. }
  12429. }
  12430. if (tryModuleMethodLookup)
  12431. {
  12432. SetMethodDependency(moduleMethodInst.mMethodInstance);
  12433. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  12434. }
  12435. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  12436. {
  12437. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  12438. if (moduleMethodInstance)
  12439. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  12440. return moduleMethodInst;
  12441. }
  12442. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  12443. bool hadConcreteInterfaceGenericArgument = false;
  12444. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  12445. isReified = false;
  12446. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  12447. {
  12448. isReified = false;
  12449. }
  12450. BfTypeVector sanitizedMethodGenericArguments;
  12451. SizedArray<BfProject*, 4> projectList;
  12452. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  12453. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  12454. isUnspecializedPass = false;
  12455. // 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
  12456. bool isExternalExtensionMethod = false;
  12457. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  12458. {
  12459. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) &&
  12460. (methodDef->mDeclaringType != NULL) &&
  12461. (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  12462. {
  12463. auto specProject = methodDef->mDeclaringType->mProject;
  12464. isExternalExtensionMethod = true;
  12465. if (typeInst->IsGenericTypeInstance())
  12466. {
  12467. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12468. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12469. genericTypeInst->GenerateProjectsReferenced();
  12470. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  12471. {
  12472. // This is a generic type where a generic param is already confined to the project in question
  12473. isExternalExtensionMethod = false;
  12474. }
  12475. }
  12476. if (isExternalExtensionMethod)
  12477. {
  12478. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  12479. projectList.push_back(methodDef->mDeclaringType->mProject);
  12480. }
  12481. }
  12482. }
  12483. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  12484. {
  12485. int typeProjectsCounts = 0;
  12486. if (typeInst->IsGenericTypeInstance())
  12487. {
  12488. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12489. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12490. genericTypeInst->GenerateProjectsReferenced();
  12491. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  12492. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  12493. }
  12494. else
  12495. {
  12496. typeProjectsCounts = 1;
  12497. projectList.Insert(0, typeInst->mTypeDef->mProject);
  12498. }
  12499. isUnspecializedPass = true;
  12500. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  12501. {
  12502. auto genericArgType = methodGenericArguments[genericArgIdx];
  12503. //BF_ASSERT(!genericArgType->IsRef());
  12504. if (genericArgType->IsConcreteInterfaceType())
  12505. {
  12506. hadConcreteInterfaceGenericArgument = true;
  12507. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  12508. genericArgType = concreteInterfaceType->mInterface;
  12509. }
  12510. if (genericArgType->IsGenericParam())
  12511. {
  12512. auto genericParam = (BfGenericParamType*) genericArgType;
  12513. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  12514. isUnspecializedPass = false;
  12515. }
  12516. else
  12517. {
  12518. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  12519. isUnspecializedPass = false;
  12520. }
  12521. sanitizedMethodGenericArguments.push_back(genericArgType);
  12522. }
  12523. if ((int)projectList.size() > typeProjectsCounts)
  12524. {
  12525. // Just leave the new items
  12526. projectList.RemoveRange(0, typeProjectsCounts);
  12527. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  12528. {
  12529. return lhs->mName < rhs->mName;
  12530. });
  12531. }
  12532. else
  12533. {
  12534. projectList.Clear();
  12535. }
  12536. }
  12537. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  12538. BfMethodInstanceGroup* methodInstGroup = NULL;
  12539. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12540. {
  12541. BF_ASSERT(!typeInst->IsInterface());
  12542. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  12543. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  12544. {
  12545. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  12546. // if (checkGroup.mDefault == NULL)
  12547. // {
  12548. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  12549. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  12550. // methodInstGroup = &checkGroup;
  12551. // break;
  12552. // }
  12553. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  12554. {
  12555. methodInstGroup = &checkGroup;
  12556. break;
  12557. }
  12558. }
  12559. if (methodInstGroup == NULL)
  12560. {
  12561. if (lookupMethodGenericArguments.size() != 0)
  12562. {
  12563. BF_ASSERT((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0);
  12564. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12565. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12566. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12567. }
  12568. else
  12569. {
  12570. // Allocate a new entry
  12571. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  12572. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  12573. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  12574. methodInstGroup->mOwner = typeInst;
  12575. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12576. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12577. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  12578. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12579. else
  12580. {
  12581. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  12582. if (!mIsScratchModule)
  12583. mOnDemandMethodCount++;
  12584. }
  12585. }
  12586. }
  12587. }
  12588. else
  12589. {
  12590. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  12591. }
  12592. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12593. {
  12594. if (typeInst->mDefineState > BfTypeDefineState_DefinedAndMethodsSlotted)
  12595. {
  12596. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  12597. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12598. }
  12599. }
  12600. BfIRFunction prevIRFunc;
  12601. bool doingRedeclare = false;
  12602. BfMethodInstance* methodInstance = NULL;
  12603. auto _SetReified = [&]()
  12604. {
  12605. if (!mCompiler->mIsResolveOnly)
  12606. BF_ASSERT(mCompiler->mCompileState <= BfCompiler::CompileState_Normal);
  12607. methodInstance->mIsReified = true;
  12608. };
  12609. if (lookupMethodGenericArguments.size() == 0)
  12610. {
  12611. methodInstance = methodInstGroup->mDefault;
  12612. if ((methodInstance != NULL) && ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0))
  12613. return methodInstance;
  12614. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  12615. {
  12616. MarkDerivedDirty(typeInst);
  12617. if (!HasCompiledOutput())
  12618. {
  12619. BfLogSysM("Marking non-compiled-output module method instance as reified: %p\n", methodInstance);
  12620. _SetReified();
  12621. CheckHotMethod(methodInstance, "");
  12622. }
  12623. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  12624. {
  12625. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  12626. // the specializations to handle that for us
  12627. return BfModuleMethodInstance(methodInstance);
  12628. }
  12629. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  12630. {
  12631. if (methodDef->mIsAbstract)
  12632. {
  12633. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12634. _SetReified();
  12635. }
  12636. else
  12637. {
  12638. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12639. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  12640. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  12641. doingRedeclare = true;
  12642. mOnDemandMethodCount++;
  12643. VerifyOnDemandMethods();
  12644. }
  12645. }
  12646. else
  12647. {
  12648. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  12649. // We haven't processed it yet
  12650. _SetReified();
  12651. CheckHotMethod(methodInstance, "");
  12652. if (methodInstance->mDeclModule == this)
  12653. {
  12654. if (methodInstance->mMethodProcessRequest != NULL)
  12655. {
  12656. // Disconnect method process request
  12657. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  12658. }
  12659. }
  12660. else
  12661. {
  12662. if (methodInstance->mMethodProcessRequest != NULL)
  12663. {
  12664. // Disconnect method process request
  12665. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  12666. methodInstance->mMethodProcessRequest = NULL;
  12667. }
  12668. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  12669. {
  12670. // Add new request in proper module
  12671. methodInstance->mDeclModule = this;
  12672. }
  12673. else
  12674. {
  12675. if (methodInstance->mDeclModule == NULL)
  12676. {
  12677. //
  12678. }
  12679. else if (methodInstance->mDeclModule != this)
  12680. {
  12681. // Is from specialized module?
  12682. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  12683. }
  12684. }
  12685. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12686. {
  12687. methodInstance->mIRFunction = BfIRFunction();
  12688. if (!mIsModuleMutable)
  12689. StartExtension();
  12690. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  12691. {
  12692. StringT<512> mangledName;
  12693. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  12694. bool isIntrinsic = false;
  12695. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  12696. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  12697. }
  12698. }
  12699. AddMethodToWorkList(methodInstance);
  12700. }
  12701. }
  12702. }
  12703. }
  12704. else
  12705. {
  12706. if (methodInstGroup->mDefault == NULL)
  12707. {
  12708. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12709. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12710. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12711. }
  12712. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  12713. if (methodInstGroup->mMethodSpecializationMap == NULL)
  12714. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  12715. BfMethodInstance** methodInstancePtr = NULL;
  12716. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  12717. {
  12718. methodInstance = *methodInstancePtr;
  12719. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  12720. return methodInstance;
  12721. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  12722. {
  12723. BfLogSysM("Setting mRequestedByAutocomplete=false for method instance %p\n", methodInstance);
  12724. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  12725. if (methodInstance->mMethodProcessRequest == NULL)
  12726. AddMethodToWorkList(methodInstance);
  12727. methodInstance->mRequestedByAutocomplete = false;
  12728. }
  12729. if ((isReified) && (!methodInstance->mIsReified))
  12730. {
  12731. MarkDerivedDirty(typeInst);
  12732. if (methodInstance->mHasBeenProcessed)
  12733. {
  12734. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  12735. delete methodInstance;
  12736. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12737. methodInstance = NULL;
  12738. }
  12739. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12740. {
  12741. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  12742. delete methodInstance;
  12743. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12744. methodInstance = NULL;
  12745. }
  12746. else
  12747. {
  12748. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  12749. // We haven't processed it yet
  12750. _SetReified();
  12751. CheckHotMethod(methodInstance, "");
  12752. if (methodInstance->mMethodProcessRequest == NULL)
  12753. AddMethodToWorkList(methodInstance);
  12754. }
  12755. }
  12756. }
  12757. }
  12758. if ((methodInstance != NULL) && (!doingRedeclare))
  12759. {
  12760. SetMethodDependency(methodInstance);
  12761. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  12762. {
  12763. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  12764. BF_ASSERT(!methodInstance->mIsReified);*/
  12765. if ((!mCompiler->mIsResolveOnly) && (isReified))
  12766. {
  12767. auto refModule = referencingModule;
  12768. if (refModule == NULL)
  12769. refModule = this;
  12770. 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);
  12771. }
  12772. if (methodInstance->mIsReified != isReified)
  12773. {
  12774. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  12775. }
  12776. if ((!isReified) &&
  12777. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  12778. {
  12779. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  12780. methodInstance->mIRFunction = BfIRFunction();
  12781. }
  12782. methodInstance->mIsReified = isReified;
  12783. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  12784. {
  12785. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  12786. }
  12787. if (!methodInstance->mMethodDef->mIsAbstract)
  12788. {
  12789. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  12790. {
  12791. // Wait until unreified
  12792. }
  12793. else
  12794. AddMethodToWorkList(methodInstance);
  12795. }
  12796. else
  12797. {
  12798. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  12799. auto owningModule = methodInstance->GetOwner()->mModule;
  12800. if (!owningModule->mIsScratchModule)
  12801. {
  12802. owningModule->mOnDemandMethodCount--;
  12803. owningModule->VerifyOnDemandMethods();
  12804. }
  12805. }
  12806. }
  12807. if (mExtensionCount > 0)
  12808. {
  12809. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  12810. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  12811. {
  12812. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  12813. if (mAwaitingInitFinish)
  12814. FinishInit();
  12815. // We need to refer to a function that was defined in a prior module
  12816. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12817. if (methodInstance->mIsIntrinsic)
  12818. isInlined = false;
  12819. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  12820. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  12821. methodInstance->mDeclModule = this;
  12822. // Add this inlined def to ourselves
  12823. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12824. {
  12825. mIncompleteMethodCount++;
  12826. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12827. inlineMethodRequest->mType = typeInst;
  12828. inlineMethodRequest->mFromModule = this;
  12829. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  12830. inlineMethodRequest->mFromModuleRevision = mRevision;
  12831. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  12832. inlineMethodRequest->mMethodInstance = methodInstance;
  12833. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12834. BF_ASSERT(mIsModuleMutable);
  12835. }
  12836. }
  12837. }
  12838. if (IsSkippingExtraResolveChecks())
  12839. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12840. else
  12841. {
  12842. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12843. return methodInstance;
  12844. if (methodInstance->mDeclModule != this)
  12845. return ReferenceExternalMethodInstance(methodInstance, flags);
  12846. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  12847. {
  12848. auto importKind = methodInstance->GetImportCallKind();
  12849. if (importKind != BfImportCallKind_None)
  12850. {
  12851. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  12852. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  12853. auto func = CreateDllImportGlobalVar(methodInstance, true);
  12854. BF_ASSERT(func);
  12855. mFuncReferences[methodInstance] = func;
  12856. }
  12857. }
  12858. return BfModuleMethodInstance(methodInstance);
  12859. }
  12860. }
  12861. if (!doingRedeclare)
  12862. {
  12863. BfModule* specModule = NULL;
  12864. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  12865. {
  12866. specModule = GetSpecializedMethodModule(projectList);
  12867. }
  12868. if ((specModule != NULL) && (specModule != this))
  12869. {
  12870. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  12871. if (mAwaitingInitFinish)
  12872. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  12873. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12874. return specMethodInstance.mMethodInstance;
  12875. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  12876. }
  12877. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  12878. {
  12879. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  12880. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  12881. }
  12882. }
  12883. if (methodInstance == NULL)
  12884. {
  12885. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12886. {
  12887. BfLogSysM("GetMethodInstance (methodInstance == NULL) bailing due to IsCePaused\n");
  12888. return BfModuleMethodInstance();
  12889. }
  12890. if (lookupMethodGenericArguments.size() == 0)
  12891. {
  12892. BF_ASSERT(methodInstGroup->mDefault == NULL);
  12893. methodInstance = new BfMethodInstance();
  12894. methodInstGroup->mDefault = methodInstance;
  12895. BF_ASSERT(typeInst->mDefineState > BfTypeDefineState_Declared);
  12896. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  12897. }
  12898. else
  12899. {
  12900. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  12901. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12902. depthExceeded = true;
  12903. if (depthExceeded)
  12904. {
  12905. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  12906. return BfModuleMethodInstance();
  12907. }
  12908. BfMethodInstance** methodInstancePtr = NULL;
  12909. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  12910. BF_ASSERT(added);
  12911. methodInstance = new BfMethodInstance();
  12912. *methodInstancePtr = methodInstance;
  12913. if (mCompiler->IsAutocomplete())
  12914. methodInstance->mRequestedByAutocomplete = true;
  12915. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  12916. }
  12917. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  12918. methodInstance->mIRFunction = prevIRFunc; // Take it over
  12919. }
  12920. methodInstance->mMethodDef = methodDef;
  12921. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  12922. methodInstance->mMethodInstanceGroup = methodInstGroup;
  12923. methodInstance->mIsReified = isReified;
  12924. SetupMethodIdHash(methodInstance);
  12925. if (hadConcreteInterfaceGenericArgument)
  12926. methodInstance->mIgnoreBody = true;
  12927. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12928. {
  12929. methodInstance->mIsForeignMethodDef = true;
  12930. BF_ASSERT(foreignType != NULL);
  12931. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  12932. }
  12933. if ((typeInst->IsInstanceOf(mCompiler->mValueTypeTypeDef)) && (methodDef->mName == BF_METHODNAME_EQUALS))
  12934. {
  12935. if (!lookupMethodGenericArguments.empty())
  12936. {
  12937. auto compareType = lookupMethodGenericArguments[0];
  12938. PopulateType(compareType, BfPopulateType_Data);
  12939. if (compareType->IsSplattable())
  12940. methodInstance->mAlwaysInline = true;
  12941. }
  12942. }
  12943. if (methodDef->mMethodType == BfMethodType_Init)
  12944. {
  12945. methodInstance->mMangleWithIdx = true;
  12946. }
  12947. BF_ASSERT(typeInst == methodInstance->GetOwner());
  12948. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12949. if (isUnspecializedPass)
  12950. {
  12951. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  12952. {
  12953. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  12954. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  12955. }
  12956. }
  12957. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  12958. {
  12959. if (!sanitizedMethodGenericArguments.IsEmpty())
  12960. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  12961. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  12962. {
  12963. Fail("Internal error");
  12964. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  12965. return NULL;
  12966. }
  12967. for (auto genericArg : sanitizedMethodGenericArguments)
  12968. {
  12969. if (genericArg->IsPrimitiveType())
  12970. genericArg = GetWrappedStructType(genericArg);
  12971. if (genericArg != NULL)
  12972. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  12973. }
  12974. }
  12975. // Generic constraints
  12976. if (!methodDef->mGenericParams.IsEmpty())
  12977. {
  12978. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  12979. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  12980. {
  12981. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  12982. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12983. }
  12984. }
  12985. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  12986. {
  12987. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  12988. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12989. }
  12990. bool addToWorkList = !processNow;
  12991. if (mCompiler->GetAutoComplete() != NULL)
  12992. {
  12993. if (typeInst->IsSpecializedByAutoCompleteMethod())
  12994. addToWorkList = false;
  12995. if (methodInstance->mRequestedByAutocomplete)
  12996. addToWorkList = false;
  12997. }
  12998. BfModule* declareModule;
  12999. //
  13000. {
  13001. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13002. declareModule = GetOrCreateMethodModule(methodInstance);
  13003. }
  13004. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  13005. declareModule = methodInstance->mDeclModule;
  13006. BF_ASSERT(declareModule != NULL);
  13007. methodInstance->mDeclModule = declareModule;
  13008. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  13009. {
  13010. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  13011. // of a reified module -
  13012. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  13013. // BUT if we don't reify it then we have to remove the body after processing.
  13014. // 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
  13015. // the proper reified module.
  13016. declareModule = mContext->mUnreifiedModule;
  13017. }
  13018. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  13019. {
  13020. if (!methodInstance->mIsReified)
  13021. {
  13022. declareModule = mContext->mUnreifiedModule;
  13023. }
  13024. else
  13025. {
  13026. declareModule->PrepareForIRWriting(methodInstance->GetOwner());
  13027. }
  13028. }
  13029. SetMethodDependency(methodInstance);
  13030. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  13031. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  13032. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  13033. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  13034. {
  13035. // For mixins we only process the unspecialized version
  13036. addToWorkList = false;
  13037. }
  13038. if (((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0) && (methodInstGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  13039. {
  13040. addToWorkList = false;
  13041. }
  13042. // if ((flags & BfGetMethodInstanceFlag_NoReference) != 0)
  13043. // addToWorkList = false;
  13044. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  13045. if (processNow)
  13046. {
  13047. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  13048. ProcessMethod(methodInstance);
  13049. }
  13050. if (IsSkippingExtraResolveChecks())
  13051. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  13052. if (methodInstance->mDeclModule != this)
  13053. return ReferenceExternalMethodInstance(methodInstance, flags);
  13054. return BfModuleMethodInstance(methodInstance);
  13055. }
  13056. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  13057. {
  13058. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  13059. if (methodInstance->mIsForeignMethodDef)
  13060. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  13061. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  13062. }
  13063. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  13064. {
  13065. if (!methodInstance->mMethodDef->mIsLocalMethod)
  13066. return NULL;
  13067. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  13068. if (outerLocal == NULL)
  13069. return NULL;
  13070. BfTypeVector genericArgs;
  13071. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  13072. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  13073. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  13074. }
  13075. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  13076. {
  13077. HashContext hashCtx;
  13078. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  13079. {
  13080. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  13081. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  13082. if (methodInstance->GetNumGenericArguments() != 0)
  13083. {
  13084. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  13085. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13086. hashCtx.Mixin(methodGenericArg->mTypeId);
  13087. }
  13088. };
  13089. _MixinMethodInstance(methodInstance);
  13090. if (methodInstance->mMethodDef->mIsLocalMethod)
  13091. {
  13092. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  13093. if (outmostMethodInstance != NULL)
  13094. {
  13095. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  13096. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  13097. }
  13098. }
  13099. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  13100. }
  13101. bool BfModule::CheckUseMethodInstance(BfMethodInstance* methodInstance, BfAstNode* refNode)
  13102. {
  13103. if (methodInstance->mHasBeenDeclared)
  13104. return true;
  13105. Fail(StrFormat("Circular reference in method instance '%s'", MethodToString(methodInstance).c_str()), refNode);
  13106. return false;
  13107. }
  13108. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  13109. {
  13110. BfIRValue globalValue;
  13111. BfIRValue* globalValuePtr = NULL;
  13112. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  13113. {
  13114. globalValue = *globalValuePtr;
  13115. }
  13116. if (!globalValue)
  13117. {
  13118. // This is necessary to reify the interface type
  13119. PopulateType(ifaceType);
  13120. StringT<512> slotVarName;
  13121. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  13122. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  13123. BfIRValue value;
  13124. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  13125. {
  13126. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  13127. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  13128. int virtSlotIdx = ifaceType->mSlotNum + 1;
  13129. value = GetConstValue32(virtSlotIdx);*/
  13130. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  13131. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  13132. }
  13133. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  13134. mInterfaceSlotRefs[ifaceType] = globalValue;
  13135. // Make sure we reify
  13136. PopulateType(ifaceType, BfPopulateType_Declaration);
  13137. AddDependency(ifaceType, mCurTypeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  13138. }
  13139. return mBfIRBuilder->CreateAlignedLoad(globalValue/*, "slotOfs"*/, 4);
  13140. }
  13141. void BfModule::HadSlotCountDependency()
  13142. {
  13143. if (mCompiler->mIsResolveOnly)
  13144. return;
  13145. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  13146. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  13147. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  13148. }
  13149. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  13150. {
  13151. if (str == "#IsComptime")
  13152. {
  13153. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsComptimeModule ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13154. }
  13155. if (str == "#IsBuilding")
  13156. {
  13157. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (!mCompiler->mIsResolveOnly) ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13158. }
  13159. if (str == "#IsReified")
  13160. {
  13161. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsReified ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13162. }
  13163. if (str == "#CompileRev")
  13164. {
  13165. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mRevision), GetPrimitiveType(BfTypeCode_Int32));
  13166. }
  13167. if (str == "#NextId")
  13168. {
  13169. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)++mCompiler->mUniqueId), GetPrimitiveType(BfTypeCode_Int32));
  13170. }
  13171. if (str == "#ModuleName")
  13172. {
  13173. return BfTypedValue(GetStringObjectValue(mModuleName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13174. }
  13175. if (str == "#ProjectName")
  13176. {
  13177. if (mProject != NULL)
  13178. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13179. }
  13180. if (str == "#AllocStackCount")
  13181. {
  13182. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mOptions.mAllocStackCount), GetPrimitiveType(BfTypeCode_Int32));
  13183. }
  13184. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  13185. {
  13186. if (str == "#CallerLineNum")
  13187. {
  13188. return BfTypedValue(GetConstValue(mCurMethodState->mMixinState->mInjectFilePosition.mCurLine + 1), GetPrimitiveType(BfTypeCode_Int32));
  13189. }
  13190. else if (str == "#CallerFilePath")
  13191. {
  13192. String filePath = "";
  13193. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13194. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13195. return BfTypedValue(GetStringObjectValue(filePath), ResolveTypeDef(mCompiler->mStringTypeDef));
  13196. }
  13197. else if (str == "#CallerFileName")
  13198. {
  13199. String filePath = "";
  13200. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13201. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13202. return BfTypedValue(GetStringObjectValue(GetFileName(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13203. }
  13204. else if (str == "#CallerFileDir")
  13205. {
  13206. String filePath = "";
  13207. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13208. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13209. return BfTypedValue(GetStringObjectValue(GetFileDir(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13210. }
  13211. else if (str == "#CallerTypeName")
  13212. {
  13213. String typeName = "";
  13214. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13215. typeName = TypeToString(mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner());
  13216. return BfTypedValue(GetStringObjectValue(typeName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13217. }
  13218. else if (str == "#CallerType")
  13219. {
  13220. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  13221. BfType* type = NULL;
  13222. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13223. type = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  13224. if (type != NULL)
  13225. {
  13226. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  13227. return BfTypedValue(CreateTypeDataRef(type), typeType);
  13228. }
  13229. }
  13230. else if (str == "#CallerMemberName")
  13231. {
  13232. String memberName = "";
  13233. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13234. memberName = MethodToString(mCurMethodState->mMixinState->mMixinMethodInstance);
  13235. return BfTypedValue(GetStringObjectValue(memberName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13236. }
  13237. else if (str == "#CallerProject")
  13238. {
  13239. BfProject* project = NULL;
  13240. project = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mProject;
  13241. if (project != NULL)
  13242. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13243. }
  13244. }
  13245. if (str == "#TimeLocal")
  13246. {
  13247. time_t rawtime;
  13248. time(&rawtime);
  13249. tm* timeinfo = localtime(&rawtime);
  13250. char result[32];
  13251. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  13252. 1900 + timeinfo->tm_year,
  13253. timeinfo->tm_mon + 1,
  13254. timeinfo->tm_mday,
  13255. timeinfo->tm_hour,
  13256. timeinfo->tm_min,
  13257. timeinfo->tm_sec);
  13258. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  13259. }
  13260. return BfTypedValue();
  13261. }
  13262. BfTypedValue BfModule::GetCompilerFieldValue(BfTypedValue typedValue)
  13263. {
  13264. if (!typedValue.IsAddr())
  13265. return BfTypedValue();
  13266. if (typedValue.mValue.IsConst())
  13267. {
  13268. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  13269. if (constantValue != NULL)
  13270. {
  13271. if (constantValue->mConstType == BfConstType_GlobalVar)
  13272. {
  13273. auto globalVar = (BfGlobalVar*)constantValue;
  13274. if (globalVar->mName[0] == '#')
  13275. {
  13276. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  13277. return result;
  13278. }
  13279. }
  13280. }
  13281. }
  13282. return BfTypedValue();
  13283. }
  13284. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  13285. {
  13286. BfIRValue globalValue;
  13287. auto fieldDef = fieldInstance->GetFieldDef();
  13288. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  13289. {
  13290. if (fieldInstance->mConstIdx != -1)
  13291. {
  13292. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  13293. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  13294. }
  13295. else
  13296. {
  13297. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  13298. }
  13299. }
  13300. if ((mIsScratchModule) && (mCompiler->mIsResolveOnly) && (!fieldInstance->mOwner->IsInstanceOf(mCompiler->mCompilerTypeDef)))
  13301. {
  13302. // Just fake it for the extern and unspecialized modules
  13303. // We can't do this for compilation because unreified methods with default params need to get actual global variable refs
  13304. return BfTypedValue(mBfIRBuilder->CreateConstNull(), fieldInstance->GetResolvedType(), true);
  13305. }
  13306. BfIRValue* globalValuePtr = NULL;
  13307. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  13308. {
  13309. globalValue = *globalValuePtr;
  13310. BF_ASSERT(globalValue);
  13311. auto globalVar = (BfGlobalVar*)mBfIRBuilder->GetConstant(globalValue);
  13312. if ((globalVar->mStreamId == -1) && (!mBfIRBuilder->mIgnoreWrites))
  13313. {
  13314. mBfIRBuilder->MapType(fieldInstance->mResolvedType);
  13315. mBfIRBuilder->CreateGlobalVariable(globalValue);
  13316. }
  13317. }
  13318. else
  13319. {
  13320. StringT<512> staticVarName;
  13321. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  13322. auto typeType = fieldInstance->GetResolvedType();
  13323. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  13324. {
  13325. typeType = typeType->GetUnderlyingType();
  13326. }
  13327. if (mIsComptimeModule)
  13328. {
  13329. mCompiler->mCeMachine->QueueStaticField(fieldInstance, staticVarName);
  13330. }
  13331. PopulateType(typeType);
  13332. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  13333. {
  13334. BfIRType irType = mBfIRBuilder->MapType(typeType);
  13335. if (fieldInstance->IsAppendedObject())
  13336. irType = mBfIRBuilder->MapTypeInst(typeType->ToTypeInstance());
  13337. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  13338. globalValue = mBfIRBuilder->CreateGlobalVariable(
  13339. irType,
  13340. false,
  13341. BfIRLinkageType_External,
  13342. BfIRValue(),
  13343. staticVarName,
  13344. IsThreadLocal(fieldInstance));
  13345. BF_ASSERT(globalValue);
  13346. mStaticFieldRefs[fieldInstance] = globalValue;
  13347. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  13348. }
  13349. }
  13350. auto type = fieldInstance->GetResolvedType();
  13351. if (type->IsValuelessType())
  13352. return BfTypedValue(globalValue, type);
  13353. if (fieldDef->mIsVolatile)
  13354. return BfTypedValue(globalValue, type, BfTypedValueKind_VolatileAddr);
  13355. return BfTypedValue(globalValue, type, !fieldDef->mIsConst && !fieldInstance->IsAppendedObject());
  13356. }
  13357. BfFieldInstance* BfModule::GetFieldInstance(BfTypeInstance* typeInst, int fieldIdx, const char* fieldName)
  13358. {
  13359. if (typeInst->IsDataIncomplete())
  13360. PopulateType(typeInst);
  13361. if (fieldIdx >= typeInst->mFieldInstances.mSize)
  13362. {
  13363. Fail(StrFormat("Invalid field data in type '%s'", TypeToString(typeInst).c_str()));
  13364. return 0;
  13365. }
  13366. return &typeInst->mFieldInstances[fieldIdx];
  13367. }
  13368. void BfModule::MarkUsingThis()
  13369. {
  13370. auto useMethodState = mCurMethodState;
  13371. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13372. {
  13373. useMethodState = useMethodState->mPrevMethodState;
  13374. }
  13375. if ((useMethodState != NULL) && (!useMethodState->mLocals.IsEmpty()))
  13376. {
  13377. auto localVar = useMethodState->mLocals[0];
  13378. if (localVar->mIsThis)
  13379. localVar->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13380. }
  13381. }
  13382. BfTypedValue BfModule::GetThis(bool markUsing)
  13383. {
  13384. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  13385. {
  13386. if (mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis)
  13387. return mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis;
  13388. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  13389. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  13390. if ((activeFrame != NULL) && (activeFrame->mFunction->mDbgInfo != NULL))
  13391. {
  13392. for (auto& dbgVar : activeFrame->mFunction->mDbgInfo->mVariables)
  13393. {
  13394. if (dbgVar.mName == "this")
  13395. return BfTypedValue(mBfIRBuilder->CreateConstAggCE(mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs), dbgVar.mType,
  13396. dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  13397. }
  13398. }
  13399. return BfTypedValue();
  13400. }
  13401. auto useMethodState = mCurMethodState;
  13402. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13403. {
  13404. useMethodState = useMethodState->mPrevMethodState;
  13405. }
  13406. if (useMethodState != NULL)
  13407. {
  13408. // Fake a 'this' for var field resolution
  13409. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  13410. {
  13411. auto thisType = mCurTypeInstance;
  13412. if (thisType->IsValueType())
  13413. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  13414. else
  13415. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  13416. }
  13417. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  13418. {
  13419. return BfTypedValue();
  13420. }
  13421. }
  13422. else
  13423. {
  13424. //TODO: Do we allow useMethodState to be NULL anymore?
  13425. return BfTypedValue();
  13426. }
  13427. // Check mixin state for 'this'
  13428. {
  13429. auto checkMethodState = mCurMethodState;
  13430. while (checkMethodState != NULL)
  13431. {
  13432. if (checkMethodState->mMixinState != NULL)
  13433. {
  13434. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  13435. if (thisValue.HasType())
  13436. {
  13437. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13438. if (!thisValue.mType->IsValueType())
  13439. thisValue = LoadValue(thisValue);
  13440. return thisValue;
  13441. }
  13442. }
  13443. checkMethodState = checkMethodState->mPrevMethodState;
  13444. }
  13445. }
  13446. auto curMethodInstance = mCurMethodInstance;
  13447. if (useMethodState->mMethodInstance != NULL)
  13448. curMethodInstance = useMethodState->mMethodInstance;
  13449. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  13450. {
  13451. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  13452. {
  13453. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  13454. if (constLocal.mIsThis)
  13455. {
  13456. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  13457. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  13458. }
  13459. }
  13460. return BfTypedValue();
  13461. }
  13462. if (useMethodState->mLocals.IsEmpty())
  13463. {
  13464. // 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
  13465. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  13466. return BfTypedValue();
  13467. }
  13468. auto thisLocal = useMethodState->mLocals[0];
  13469. BF_ASSERT(thisLocal->mIsThis);
  13470. bool preferValue = !IsTargetingBeefBackend();
  13471. if (!thisLocal->mAddr)
  13472. preferValue = true;
  13473. bool usedVal = false;
  13474. BfIRValue thisValue;
  13475. if ((preferValue) && (!thisLocal->mIsLowered))
  13476. {
  13477. thisValue = thisLocal->mValue;
  13478. usedVal = true;
  13479. }
  13480. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  13481. thisValue = thisLocal->mAddr;
  13482. else
  13483. thisValue = mBfIRBuilder->CreateAlignedLoad(thisLocal->mAddr, thisLocal->mResolvedType->mAlign);
  13484. if (markUsing)
  13485. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13486. if (useMethodState->mClosureState != NULL)
  13487. {
  13488. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  13489. if (closureTypeInst != NULL)
  13490. {
  13491. if (closureTypeInst->mFieldInstances.size() > 0)
  13492. {
  13493. auto& field = closureTypeInst->mFieldInstances[0];
  13494. auto fieldDef = field.GetFieldDef();
  13495. if (fieldDef->mName == "__this")
  13496. {
  13497. if (mCurMethodState->mClosureState->mCapturing)
  13498. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  13499. // This is a captured 'this'
  13500. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  13501. if (field.mResolvedType->IsRef())
  13502. {
  13503. auto refType = (BfRefType*)field.mResolvedType;
  13504. auto underlyingType = refType->GetUnderlyingType();
  13505. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  13506. }
  13507. if (field.mResolvedType->IsObject())
  13508. {
  13509. result = LoadValue(result);
  13510. result.mKind = BfTypedValueKind_ThisValue;
  13511. }
  13512. else
  13513. {
  13514. if (fieldDef->mIsReadOnly)
  13515. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  13516. else
  13517. result.mKind = BfTypedValueKind_ThisAddr;
  13518. }
  13519. return result;
  13520. }
  13521. }
  13522. return BfTypedValue();
  13523. }
  13524. if (useMethodState->mClosureState->mCapturing)
  13525. {
  13526. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  13527. if (thisType->IsValueType())
  13528. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  13529. else
  13530. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  13531. }
  13532. }
  13533. if (mCurMethodInstance == NULL)
  13534. return BfTypedValue();
  13535. auto localDef = useMethodState->mLocals[0];
  13536. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  13537. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  13538. {
  13539. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  13540. {
  13541. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  13542. }
  13543. if (localDef->mIsSplat)
  13544. {
  13545. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  13546. }
  13547. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  13548. }
  13549. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  13550. }
  13551. BfLocalVariable* BfModule::GetThisVariable()
  13552. {
  13553. if (mCurMethodState == NULL)
  13554. return NULL;
  13555. auto methodState = mCurMethodState->GetNonCaptureState();
  13556. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  13557. return methodState->mLocals[0];
  13558. return NULL;
  13559. }
  13560. bool BfModule::IsInGeneric()
  13561. {
  13562. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  13563. }
  13564. bool BfModule::InDefinitionSection()
  13565. {
  13566. if (mCurTypeInstance != NULL)
  13567. {
  13568. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  13569. return false;
  13570. }
  13571. return !IsInSpecializedSection();
  13572. }
  13573. bool BfModule::IsInSpecializedGeneric()
  13574. {
  13575. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  13576. return true;
  13577. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  13578. return false;
  13579. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  13580. }
  13581. bool BfModule::IsInSpecializedSection()
  13582. {
  13583. return IsInSpecializedGeneric() ||
  13584. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  13585. }
  13586. bool BfModule::IsInUnspecializedGeneric()
  13587. {
  13588. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  13589. return true;
  13590. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedType()))
  13591. return true;
  13592. return false;
  13593. }
  13594. //////////////////////////////////////////////////////////////////////////
  13595. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  13596. {
  13597. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  13598. if (type->IsValuelessType())
  13599. return mBfIRBuilder->GetFakeVal();
  13600. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  13601. if ((!doLifetimeEnd) && (WantsLifetimes()))
  13602. {
  13603. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  13604. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  13605. }
  13606. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  13607. auto typeOptions = GetTypeOptions();
  13608. if (typeOptions != NULL)
  13609. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  13610. // Local variable inits are implicitly handled in the Beef Backend
  13611. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  13612. {
  13613. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13614. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13615. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  13616. mBfIRBuilder->ClearDebugLocation(storeInst);
  13617. mBfIRBuilder->SetInsertPoint(prevBlock);
  13618. }
  13619. return allocaInst;
  13620. }
  13621. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  13622. {
  13623. while (localVar->mName.StartsWith('@'))
  13624. {
  13625. localVar->mNamePrefixCount++;
  13626. localVar->mName.Remove(0);
  13627. }
  13628. if (mCurMethodState->mLocals.mAllocSize == 0)
  13629. {
  13630. mCurMethodState->mLocals.Reserve(16);
  13631. mCurMethodState->mLocalVarSet.Reserve(16);
  13632. }
  13633. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  13634. mCurMethodState->mLocals.push_back(localVar);
  13635. BfLocalVarEntry* localVarEntryPtr;
  13636. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  13637. {
  13638. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  13639. localVarEntryPtr->mLocalVar = localVar;
  13640. }
  13641. }
  13642. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13643. {
  13644. if (localVarDef->mResolvedType->IsVar())
  13645. return;
  13646. if ((mBfIRBuilder->DbgHasInfo()) &&
  13647. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  13648. (mHasFullDebugInfo) &&
  13649. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  13650. {
  13651. auto varType = localVarDef->mResolvedType;
  13652. if (localVarDef->mResolvedType->IsValuelessType())
  13653. {
  13654. }
  13655. else
  13656. {
  13657. bool isByAddr = false;
  13658. auto diValue = localVarDef->mValue;
  13659. if (localVarDef->mConstValue)
  13660. diValue = localVarDef->mConstValue;
  13661. else if (localVarDef->mAddr)
  13662. {
  13663. diValue = localVarDef->mAddr;
  13664. isByAddr = true;
  13665. }
  13666. if (diValue.IsConst())
  13667. {
  13668. auto constant = mBfIRBuilder->GetConstant(diValue);
  13669. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  13670. {
  13671. // Ignore for now
  13672. return;
  13673. }
  13674. }
  13675. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  13676. bool didConstToMem = false;
  13677. bool isConstant = false;
  13678. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  13679. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13680. else if (localVarDef->mConstValue)
  13681. {
  13682. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  13683. isConstant =
  13684. (constant->mConstType < BfConstType_GlobalVar) ||
  13685. (constant->mConstType == BfConstType_AggZero) ||
  13686. (constant->mConstType == BfConstType_Agg);
  13687. if (isConstant)
  13688. {
  13689. if (localVarDef->mResolvedType->IsComposite())
  13690. {
  13691. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  13692. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  13693. // if (IsTargetingBeefBackend())
  13694. // {
  13695. // diValue = mBfIRBuilder->CreateAliasValue(constMem);
  13696. // didConstToMem = true;
  13697. //
  13698. // diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13699. // }
  13700. //else
  13701. {
  13702. isByAddr = true;
  13703. mBfIRBuilder->SaveDebugLocation();
  13704. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13705. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13706. mBfIRBuilder->ClearDebugLocation();
  13707. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  13708. auto addrVal = CreateAlloca(ptrType);
  13709. mBfIRBuilder->CreateStore(constMem, addrVal);
  13710. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13711. diValue = addrVal;
  13712. didConstToMem = true;
  13713. mBfIRBuilder->SetInsertPoint(prevBlock);
  13714. mBfIRBuilder->RestoreDebugLocation();
  13715. }
  13716. }
  13717. if (mCompiler->mOptions.IsCodeView())
  13718. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13719. }
  13720. }
  13721. if (!mBfIRBuilder->mIgnoreWrites)
  13722. {
  13723. if ((localVarDef->mIsStatic) && (localVarDef->mAddr) && (!localVarDef->mResolvedType->IsValuelessType()))
  13724. {
  13725. auto refType = CreateRefType(localVarDef->mResolvedType);
  13726. diType = mBfIRBuilder->DbgGetType(refType);
  13727. auto refAlloca = CreateAlloca(refType);
  13728. mBfIRBuilder->CreateStore(localVarDef->mAddr, refAlloca);
  13729. diValue = refAlloca;
  13730. }
  13731. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13732. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  13733. localVarDef->mDbgVarInst = diVariable;
  13734. if (mBfIRBuilder->HasDebugLocation())
  13735. {
  13736. if ((isConstant) && (!didConstToMem))
  13737. {
  13738. BfTypedValue result(localVarDef->mConstValue, localVarDef->mResolvedType);
  13739. FixValueActualization(result);
  13740. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(result.mValue, diVariable);
  13741. }
  13742. else
  13743. {
  13744. if ((IsTargetingBeefBackend()) && (doAliasValue) && (!mIsComptimeModule))
  13745. {
  13746. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  13747. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  13748. }
  13749. if (isByAddr)
  13750. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  13751. else if (diValue)
  13752. {
  13753. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  13754. }
  13755. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  13756. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  13757. }
  13758. }
  13759. }
  13760. }
  13761. }
  13762. }
  13763. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13764. {
  13765. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  13766. {
  13767. if ((!localVarDef->mValue.IsConst()) &&
  13768. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  13769. {
  13770. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  13771. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  13772. }
  13773. }
  13774. if (addDebugInfo)
  13775. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  13776. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  13777. DoAddLocalVariable(localVarDef);
  13778. auto rootMethodState = mCurMethodState->GetRootMethodState();
  13779. if (localVarDef->mLocalVarId == -1)
  13780. {
  13781. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  13782. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  13783. }
  13784. bool checkLocal = true;
  13785. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  13786. {
  13787. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(mCurMethodInstance->mMethodDef->mMethodDeclaration))
  13788. checkLocal = false;
  13789. }
  13790. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!mIsComptimeModule) && (checkLocal))
  13791. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  13792. if (((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL)) && (checkLocal))
  13793. {
  13794. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  13795. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL) && (rootMethodState->mMethodInstance != NULL) && (!mIsComptimeModule))
  13796. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  13797. }
  13798. return localVarDef;
  13799. }
  13800. void BfModule::CreateDIRetVal()
  13801. {
  13802. if (!WantsDebugInfo())
  13803. return;
  13804. /*if (!mCurMethodState->mRetVal)
  13805. {
  13806. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  13807. return;
  13808. }*/
  13809. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  13810. {
  13811. BfType* dbgType = mCurMethodInstance->mReturnType;
  13812. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  13813. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13814. {
  13815. BF_ASSERT(mCurMethodState->mRetValAddr);
  13816. dbgType = CreatePointerType(dbgType);
  13817. dbgValue = mCurMethodState->mRetValAddr;
  13818. }
  13819. else
  13820. {
  13821. BF_ASSERT(!mCurMethodState->mRetValAddr);
  13822. }
  13823. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13824. "@return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  13825. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  13826. }
  13827. }
  13828. BfTypedValue BfModule::CreateTuple(const Array<BfTypedValue>& values, const Array<String>& fieldNames)
  13829. {
  13830. BfTypeVector fieldTypes;
  13831. for (auto arg : values)
  13832. fieldTypes.Add(arg.mType);
  13833. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  13834. auto tupleTypedValue = BfTypedValue(CreateAlloca(tupleType), tupleType, true);
  13835. for (int fieldIdx = 0; fieldIdx < tupleType->mFieldInstances.size(); fieldIdx++)
  13836. {
  13837. auto& fieldInstance = tupleType->mFieldInstances[fieldIdx];
  13838. if (fieldInstance.mDataIdx <= 0)
  13839. continue;
  13840. auto typedVal = values[fieldIdx];
  13841. typedVal = LoadOrAggregateValue(typedVal);
  13842. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, mBfIRBuilder->CreateInBoundsGEP(tupleTypedValue.mValue, 0, fieldInstance.mDataIdx), typedVal.mType->mAlign);
  13843. }
  13844. return tupleTypedValue;
  13845. }
  13846. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  13847. {
  13848. if (variableDef->mName.IsEmpty())
  13849. return;
  13850. BfLocalVarEntry* localVarEntryPtr = NULL;
  13851. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  13852. {
  13853. auto checkLocal = localVarEntryPtr->mLocalVar;
  13854. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  13855. {
  13856. BfError* error;
  13857. if (checkLocal->mIsImplicitParam)
  13858. return; // Ignore 'redefinition'
  13859. if (checkLocal->IsParam())
  13860. {
  13861. if (variableDef->IsParam())
  13862. error = Fail(StrFormat("A parameter named '%s' has already been declared", variableDef->mName.c_str()), variableDef->mNameNode);
  13863. else
  13864. 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);
  13865. }
  13866. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  13867. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13868. else
  13869. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13870. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  13871. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  13872. return;
  13873. }
  13874. }
  13875. }
  13876. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  13877. {
  13878. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  13879. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  13880. {
  13881. if (tokenNode->GetToken() == BfToken_Colon)
  13882. {
  13883. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  13884. {
  13885. Fail("Cannot access method scope across deferred block boundary", scopeName);
  13886. return NULL;
  13887. }
  13888. return &mCurMethodState->mHeadScope;
  13889. }
  13890. else if (tokenNode->GetToken() == BfToken_Mixin)
  13891. {
  13892. if (fromMixinState == NULL)
  13893. {
  13894. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  13895. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  13896. return mCurMethodState->mCurScope;
  13897. }
  13898. fromMixinState->mUsedInvocationScope = true;
  13899. return fromMixinState->mTargetScope;
  13900. }
  13901. else if (tokenNode->GetToken() == BfToken_New)
  13902. return NULL;
  13903. }
  13904. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  13905. {
  13906. auto findLabel = scopeName->ToString();
  13907. bool crossedDeferredBlock = false;
  13908. auto checkScope = mCurMethodState->mCurScope;
  13909. while (checkScope != NULL)
  13910. {
  13911. if (checkScope->mIsDeferredBlock)
  13912. crossedDeferredBlock = true;
  13913. if (checkScope->mLabel == findLabel)
  13914. {
  13915. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  13916. {
  13917. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  13918. return NULL;
  13919. }
  13920. return checkScope;
  13921. }
  13922. checkScope = checkScope->mPrevScope;
  13923. }
  13924. if (!inMixinDecl)
  13925. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  13926. }
  13927. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  13928. {
  13929. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  13930. }
  13931. return mCurMethodState->mCurScope;
  13932. }
  13933. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  13934. {
  13935. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  13936. }
  13937. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  13938. {
  13939. auto scopeData = FindScope(scopeName, false);
  13940. if (scopeData == NULL)
  13941. return NULL;
  13942. int scopeDepth = scopeData->GetDepth();
  13943. // Find the first break data that is at or below the depth of our requested scope
  13944. auto breakData = mCurMethodState->mBreakData;
  13945. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  13946. {
  13947. if (breakData->mScope->mIsConditional)
  13948. return NULL;
  13949. breakData = breakData->mPrevBreakData;
  13950. }
  13951. return breakData;
  13952. }
  13953. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  13954. {
  13955. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  13956. if (!IsTargetingBeefBackend())
  13957. return;
  13958. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  13959. {
  13960. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13961. }
  13962. }
  13963. void BfModule::ClearLifetimeEnds()
  13964. {
  13965. auto scopeData = mCurMethodState->mCurScope;
  13966. while (scopeData != NULL)
  13967. {
  13968. scopeData->mDeferredLifetimeEnds.Clear();
  13969. scopeData = scopeData->mPrevScope;
  13970. }
  13971. }
  13972. bool BfModule::WantsDebugInfo()
  13973. {
  13974. if ((mCurMethodInstance != NULL) &&
  13975. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  13976. return false;
  13977. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  13978. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  13979. }
  13980. BfTypeOptions* BfModule::GetTypeOptions()
  13981. {
  13982. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  13983. return mCurMethodState->mMethodTypeOptions;
  13984. if (mCurMethodInstance == NULL)
  13985. return NULL;
  13986. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  13987. }
  13988. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  13989. {
  13990. BfReflectKind reflectKind = BfReflectKind_None;
  13991. if (attrType->mCustomAttributes != NULL)
  13992. {
  13993. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  13994. {
  13995. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  13996. {
  13997. for (auto& prop : customAttr.mSetProperties)
  13998. {
  13999. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  14000. if (propDef->mName == "ReflectUser")
  14001. {
  14002. if (prop.mParam.mValue.IsConst())
  14003. {
  14004. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  14005. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  14006. }
  14007. }
  14008. }
  14009. // Check for Flags arg
  14010. if (customAttr.mCtorArgs.size() < 2)
  14011. continue;
  14012. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  14013. if (constant == NULL)
  14014. continue;
  14015. if (constant->mTypeCode == BfTypeCode_Boolean)
  14016. continue;
  14017. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  14018. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  14019. }
  14020. }
  14021. }
  14022. return reflectKind;
  14023. }
  14024. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  14025. {
  14026. auto checkTypeInstance = typeInstance;
  14027. while (checkTypeInstance != NULL)
  14028. {
  14029. if (checkTypeInstance->mCustomAttributes != NULL)
  14030. {
  14031. auto checkReflectKind = BfReflectKind_None;
  14032. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  14033. {
  14034. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  14035. {
  14036. if (customAttr.mCtorArgs.size() > 0)
  14037. {
  14038. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  14039. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  14040. }
  14041. else
  14042. {
  14043. checkReflectKind = BfReflectKind_All;
  14044. }
  14045. }
  14046. else
  14047. {
  14048. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  14049. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  14050. }
  14051. }
  14052. if ((checkTypeInstance == typeInstance) ||
  14053. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  14054. {
  14055. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  14056. }
  14057. }
  14058. for (auto ifaceEntry : typeInstance->mInterfaces)
  14059. {
  14060. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  14061. {
  14062. auto iface = ifaceEntry.mInterfaceType;
  14063. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  14064. if (customAttr != NULL)
  14065. {
  14066. for (auto& prop : customAttr->mSetProperties)
  14067. {
  14068. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  14069. if (propDef->mName == "ReflectImplementer")
  14070. {
  14071. if (prop.mParam.mValue.IsConst())
  14072. {
  14073. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  14074. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  14075. }
  14076. }
  14077. }
  14078. }
  14079. }
  14080. }
  14081. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  14082. }
  14083. return reflectKind;
  14084. }
  14085. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  14086. {
  14087. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14088. while (checkScope != NULL)
  14089. {
  14090. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  14091. return true;
  14092. if (checkScope == scope)
  14093. break;
  14094. checkScope = checkScope->mPrevScope;
  14095. }
  14096. return false;
  14097. }
  14098. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  14099. {
  14100. // Is there anything we need to do here?
  14101. if (mBfIRBuilder->mIgnoreWrites)
  14102. {
  14103. // Just visit deferred blocks
  14104. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14105. while (checkScope != NULL)
  14106. {
  14107. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14108. while (deferredCallEntry != NULL)
  14109. {
  14110. if (deferredCallEntry->mDeferredBlock != NULL)
  14111. {
  14112. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14113. if (checkScope == &mCurMethodState->mHeadScope)
  14114. CreateRetValLocal();
  14115. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry->mEmitRefNode);
  14116. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  14117. }
  14118. deferredCallEntry = deferredCallEntry->mNext;
  14119. }
  14120. if (checkScope == scopeData)
  14121. break;
  14122. checkScope = checkScope->mPrevScope;
  14123. }
  14124. return;
  14125. }
  14126. // Why did we want to do SetIllegalSrcPos here?
  14127. // Don't we always want to step onto these instances?
  14128. // Find a case where we don't and perhaps only do it there.
  14129. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  14130. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  14131. //SetIllegalSrcPos();
  14132. bool setSrcPos = false;
  14133. bool wantsNop = true;
  14134. BfAstNode* deferCloseNode = NULL;
  14135. if (mCurMethodState->mInPostReturn)
  14136. {
  14137. // These won't get used, they are post-return
  14138. return;
  14139. }
  14140. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  14141. BfScopeData* scopeJumpBlock = NULL;
  14142. bool hadExtraDeferredLifetimeEnds = false;
  14143. auto _FlushLifetimeEnds = [&]()
  14144. {
  14145. for (auto lifetimeEnd : deferredLifetimeEnds)
  14146. {
  14147. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14148. mBfIRBuilder->ClearDebugLocation_Last();
  14149. }
  14150. deferredLifetimeEnds.clear();
  14151. };
  14152. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14153. while (checkScope != NULL)
  14154. {
  14155. if (checkScope->mCloseNode != NULL)
  14156. deferCloseNode = checkScope->mCloseNode;
  14157. if (doneBlock)
  14158. {
  14159. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  14160. for (auto& checkHandler : checkScope->mDeferredHandlers)
  14161. {
  14162. if (checkHandler.mDoneBlock == doneBlock)
  14163. {
  14164. scopeJumpBlock = checkScope;
  14165. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  14166. mBfIRBuilder->ClearDebugLocation_Last();
  14167. _FlushLifetimeEnds();
  14168. break;
  14169. }
  14170. }
  14171. if (scopeJumpBlock != NULL)
  14172. break;
  14173. }
  14174. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  14175. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  14176. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  14177. if (hasWork)
  14178. {
  14179. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  14180. if (deferCloseNode != NULL)
  14181. {
  14182. UpdateSrcPos(deferCloseNode);
  14183. }
  14184. if (checkScope == &mCurMethodState->mHeadScope)
  14185. CreateRetValLocal();
  14186. if (doneBlock)
  14187. {
  14188. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  14189. String blockName = "deferredCalls";
  14190. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  14191. BfDeferredHandler deferredHandler;
  14192. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  14193. {
  14194. mBfIRBuilder->SaveDebugLocation();
  14195. mBfIRBuilder->ClearDebugLocation();
  14196. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  14197. mBfIRBuilder->RestoreDebugLocation();
  14198. }
  14199. else
  14200. {
  14201. // Definitely chain
  14202. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  14203. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  14204. mBfIRBuilder->ClearDebugLocation_Last();
  14205. _FlushLifetimeEnds();
  14206. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  14207. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  14208. }
  14209. deferredHandler.mDoneBlock = doneBlock;
  14210. if (!mBfIRBuilder->mIgnoreWrites)
  14211. checkScope->mDeferredHandlers.push_back(deferredHandler);
  14212. if (checkScope == &mCurMethodState->mHeadScope)
  14213. {
  14214. if (!mCurMethodState->mDIRetVal)
  14215. {
  14216. // 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
  14217. // be scoped to the physical method
  14218. /*if (deferCloseNode != NULL)
  14219. {
  14220. UpdateSrcPos(deferCloseNode);
  14221. }*/
  14222. CreateDIRetVal();
  14223. }
  14224. }
  14225. if (checkScope != mCurMethodState->mTailScope)
  14226. {
  14227. if (deferredHandler.mHandlerBlock.IsFake())
  14228. {
  14229. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14230. }
  14231. if (!mBfIRBuilder->mIgnoreWrites)
  14232. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  14233. }
  14234. }
  14235. HashSet<BfDeferredCallEntry*> handledSet;
  14236. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14237. while (deferredCallEntry != NULL)
  14238. {
  14239. BfDeferredCallEmitState deferredCallEmitState;
  14240. deferredCallEmitState.mCloseNode = deferCloseNode;
  14241. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  14242. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  14243. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14244. if (deferCloseNode != NULL)
  14245. {
  14246. UpdateSrcPos(deferCloseNode);
  14247. }
  14248. if (wantsNop)
  14249. EmitEnsureInstructionAt();
  14250. wantsNop = false;
  14251. if (deferredCallEntry->mDeferredBlock != NULL)
  14252. {
  14253. BfDeferredCallEntry** entryPtr = NULL;
  14254. if (!handledSet.TryAdd(deferredCallEntry, &entryPtr))
  14255. {
  14256. // Already handled, can happen if we defer again within the block
  14257. deferredCallEntry = deferredCallEntry->mNext;
  14258. continue;
  14259. }
  14260. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  14261. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14262. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  14263. {
  14264. // The list changed, start over and ignore anything we've already handled
  14265. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14266. }
  14267. else
  14268. deferredCallEntry = deferredCallEntry->mNext;
  14269. }
  14270. else
  14271. {
  14272. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14273. deferredCallEntry = deferredCallEntry->mNext;
  14274. }
  14275. }
  14276. if (checkScope->mSavedStack)
  14277. {
  14278. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  14279. if (mCurMethodState->mDynStackRevIdx)
  14280. {
  14281. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  14282. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  14283. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  14284. }
  14285. }
  14286. }
  14287. if (!checkScope->mIsScopeHead)
  14288. {
  14289. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  14290. if (!IsTargetingBeefBackend())
  14291. {
  14292. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14293. {
  14294. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14295. }
  14296. }
  14297. else
  14298. {
  14299. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14300. {
  14301. deferredLifetimeEnds.Add(lifetimeEnd);
  14302. }
  14303. }
  14304. }
  14305. if (checkScope == scopeData)
  14306. break;
  14307. checkScope = checkScope->mPrevScope;
  14308. }
  14309. if ((doneBlock) && (scopeJumpBlock == NULL))
  14310. {
  14311. mBfIRBuilder->CreateBr(doneBlock);
  14312. mBfIRBuilder->ClearDebugLocation_Last();
  14313. }
  14314. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  14315. // may have been created when other scope lifetimes were available
  14316. _FlushLifetimeEnds();
  14317. // Emit lifetimeEnds after the branch for Beef
  14318. /*if (IsTargetingBeefBackend())
  14319. {
  14320. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  14321. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14322. while (checkScope != NULL)
  14323. {
  14324. if (checkScope == scopeJumpBlock)
  14325. break;
  14326. if (!checkScope->mIsScopeHead)
  14327. {
  14328. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14329. {
  14330. if (needsEnsureInst)
  14331. {
  14332. needsEnsureInst = false;
  14333. }
  14334. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14335. }
  14336. }
  14337. if (checkScope == scopeData)
  14338. break;
  14339. checkScope = checkScope->mPrevScope;
  14340. }
  14341. }*/
  14342. }
  14343. void BfModule::MarkScopeLeft(BfScopeData* scopeData, bool isNoReturn)
  14344. {
  14345. if ((mCurMethodState->mDeferredLocalAssignData != NULL) && (!isNoReturn))
  14346. {
  14347. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  14348. while (deferredLocalAssignData != NULL)
  14349. {
  14350. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  14351. break;
  14352. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  14353. deferredLocalAssignData->mIsUnconditional = false;
  14354. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  14355. }
  14356. }
  14357. // When we leave a scope, mark those as assigned for deferred assignment purposes
  14358. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  14359. {
  14360. auto localDef = mCurMethodState->mLocals[localIdx];
  14361. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  14362. {
  14363. bool hadAssignment = false;
  14364. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  14365. {
  14366. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  14367. if (entry.mLocalVar == localDef)
  14368. hadAssignment = true;
  14369. }
  14370. if (!hadAssignment)
  14371. {
  14372. if (!isNoReturn)
  14373. localDef->mHadExitBeforeAssign = true;
  14374. mCurMethodState->LocalDefined(localDef);
  14375. }
  14376. }
  14377. }
  14378. }
  14379. void BfModule::CreateReturn(BfIRValue val)
  14380. {
  14381. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14382. {
  14383. // Store to sret
  14384. BF_ASSERT(val);
  14385. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14386. mBfIRBuilder->CreateRetVoid();
  14387. return;
  14388. }
  14389. if (mCurMethodInstance->mReturnType->IsVar())
  14390. return;
  14391. if (mCurMethodInstance->mReturnType->IsValuelessType())
  14392. {
  14393. mBfIRBuilder->CreateRetVoid();
  14394. return;
  14395. }
  14396. if (mCurMethodInstance->mReturnType->IsStruct())
  14397. {
  14398. BfTypeCode loweredReturnType = BfTypeCode_None;
  14399. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  14400. if (!mIsComptimeModule)
  14401. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  14402. if (loweredReturnType != BfTypeCode_None)
  14403. {
  14404. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  14405. mBfIRBuilder->CreateStore(val, retVal);
  14406. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  14407. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  14408. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  14409. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  14410. mBfIRBuilder->CreateRet(loadedReturnValue);
  14411. return;
  14412. }
  14413. }
  14414. BF_ASSERT(val);
  14415. mBfIRBuilder->CreateRet(val);
  14416. }
  14417. void BfModule::EmitReturn(const BfTypedValue& val)
  14418. {
  14419. if (mCurMethodState->mIRExitBlock)
  14420. {
  14421. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  14422. {
  14423. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  14424. {
  14425. if ((mCurMethodState->mRetValAddr) || (mCurMethodState->mRetVal))
  14426. {
  14427. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  14428. if (!mCurMethodState->mRetVal)
  14429. retVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetValAddr, mCurMethodInstance->mReturnType->mAlign);
  14430. mBfIRBuilder->CreateAlignedStore(val.mValue, retVal, mCurMethodInstance->mReturnType->mAlign);
  14431. }
  14432. else if (mIsComptimeModule)
  14433. {
  14434. if (!val.mType->IsValuelessType())
  14435. mBfIRBuilder->CreateSetRet(val.mValue, val.mType->mTypeId);
  14436. else
  14437. mBfIRBuilder->CreateSetRet(BfIRValue(), val.mType->mTypeId);
  14438. }
  14439. else
  14440. {
  14441. // Just ignore
  14442. BF_ASSERT(mCurMethodInstance->mReturnType->IsVar());
  14443. }
  14444. }
  14445. }
  14446. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14447. }
  14448. else
  14449. {
  14450. EmitDeferredScopeCalls(false, NULL);
  14451. if (val)
  14452. {
  14453. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14454. }
  14455. }
  14456. mCurMethodState->SetHadReturn(true);
  14457. mCurMethodState->mLeftBlockUncond = true;
  14458. }
  14459. void BfModule::EmitDefaultReturn()
  14460. {
  14461. if (mCurMethodState->mInDeferredBlock)
  14462. return;
  14463. if (mCurMethodState->mIRExitBlock)
  14464. {
  14465. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14466. }
  14467. else
  14468. {
  14469. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mReturnType->IsVar()))
  14470. {
  14471. // Ignore
  14472. }
  14473. else if (mCurMethodInstance->mReturnType->IsVoid())
  14474. mBfIRBuilder->CreateRetVoid();
  14475. else if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == -1))
  14476. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  14477. }
  14478. mCurMethodState->SetHadReturn(true);
  14479. mCurMethodState->mLeftBlockUncond = true;
  14480. }
  14481. void BfModule::AssertErrorState()
  14482. {
  14483. if (mIgnoreErrors)
  14484. return;
  14485. if (mHadBuildError)
  14486. return;
  14487. if (mCurTypeInstance != NULL)
  14488. {
  14489. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  14490. return;
  14491. }
  14492. if (mCurMethodInstance != NULL)
  14493. {
  14494. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  14495. return;
  14496. if (mCurMethodInstance->mHasFailed)
  14497. return;
  14498. }
  14499. // We want the module to be marked as failed even if it's just an error in the parser
  14500. if (mCurMethodInstance != NULL)
  14501. mCurMethodInstance->mHasFailed = true;
  14502. mHadBuildError = true;
  14503. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  14504. if (mCurTypeInstance != NULL)
  14505. {
  14506. if (mCurTypeInstance->mTypeFailed)
  14507. return;
  14508. if ((mCurTypeInstance->mTypeDef->GetDefinition()->mSource != NULL) && (mCurTypeInstance->mTypeDef->GetDefinition()->mSource->mParsingFailed))
  14509. return;
  14510. }
  14511. if (mCurMethodInstance != NULL)
  14512. {
  14513. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) &&
  14514. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14515. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14516. return;
  14517. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) &&
  14518. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14519. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14520. return;
  14521. }
  14522. if (mCompiler->IsAutocomplete())
  14523. return;
  14524. if (mCompiler->mPassInstance->HasFailed())
  14525. return;
  14526. InternalError("Compiler in invalid state but AssertErrorState failed to prior error");
  14527. }
  14528. void BfModule::AssertParseErrorState()
  14529. {
  14530. if (mCompiler->mRevision == 1)
  14531. AssertErrorState();
  14532. }
  14533. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  14534. {
  14535. BF_ASSERT(delegateType->IsDelegateOrFunction());
  14536. auto typeInst = delegateType->ToTypeInstance();
  14537. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  14538. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  14539. if (invokeMethodInstance == NULL)
  14540. return GetPrimitiveType(BfTypeCode_Var);
  14541. return invokeMethodInstance->mReturnType;
  14542. }
  14543. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  14544. {
  14545. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  14546. }
  14547. void BfModule::CreateDelegateInvokeMethod()
  14548. {
  14549. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  14550. //mBfIRBuilder->ClearDebugLocation();
  14551. SetIllegalSrcPos();
  14552. auto typeInstance = mCurTypeInstance;
  14553. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  14554. SizedArray<BfIRType, 4> staticParamTypes;
  14555. SizedArray<BfIRValue, 4> staticFuncArgs;
  14556. SizedArray<BfIRValue, 4> memberFuncArgs;
  14557. auto multicastDelegateType = typeInstance->mBaseType;
  14558. if (multicastDelegateType->mFieldInstances.size() != 2)
  14559. {
  14560. AssertErrorState();
  14561. return;
  14562. }
  14563. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  14564. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  14565. auto fieldVal = mBfIRBuilder->CreateAlignedLoad(fieldPtr, mSystem->mPtrSize);
  14566. BfExprEvaluator exprEvaluator(this);
  14567. SizedArray<BfIRType, 8> origParamTypes;
  14568. BfIRType origReturnType;
  14569. BfIRType staticReturnType;
  14570. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  14571. if (mCurMethodInstance->mReturnType->IsValueType())
  14572. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  14573. if ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() != 0))
  14574. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14575. int thisIdx = 0;
  14576. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14577. {
  14578. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  14579. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14580. }
  14581. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14582. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14583. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == 0))
  14584. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14585. mCurMethodInstance->GetIRFunctionInfo(this, staticReturnType, staticParamTypes, true);
  14586. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14587. {
  14588. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  14589. exprEvaluator.PushArg(localVal, staticFuncArgs);
  14590. exprEvaluator.PushArg(localVal, memberFuncArgs);
  14591. }
  14592. auto staticFunc = mBfIRBuilder->CreateFunctionType(staticReturnType, staticParamTypes, false);
  14593. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  14594. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  14595. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  14596. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  14597. auto doneBB = mBfIRBuilder->CreateBlock("done");
  14598. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  14599. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  14600. BfIRValue nonStaticResult;
  14601. BfIRValue staticResult;
  14602. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  14603. auto trueEndBB = trueBB;
  14604. /// Non-static invocation
  14605. {
  14606. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  14607. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  14608. mBfIRBuilder->SetInsertPoint(trueBB);
  14609. BfIRValue numVal;
  14610. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule) && (mCompiler->mSystem->mPtrSize == 8))
  14611. {
  14612. numVal = mBfIRBuilder->CreatePtrToInt(fieldVal, BfTypeCode_UInt64);
  14613. auto andVal = mBfIRBuilder->CreateAnd(numVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)~0x8000000000000000ULL));
  14614. fieldVal = mBfIRBuilder->CreateIntToPtr(andVal, mBfIRBuilder->MapType(mContext->mBfObjectType));
  14615. }
  14616. if ((WantsObjectAccessCheck(mContext->mBfObjectType) && (mCompiler->mSystem->mPtrSize == 8)))
  14617. {
  14618. auto oacDoBB = mBfIRBuilder->CreateBlock("oac.do", true);
  14619. auto oacDoneBB = mBfIRBuilder->CreateBlock("oac.done");
  14620. auto checkGTE = mBfIRBuilder->CreateCmpGTE(numVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)0x8000000000000000ULL), false);
  14621. mBfIRBuilder->CreateCondBr(checkGTE, oacDoBB, oacDoneBB);
  14622. mBfIRBuilder->SetInsertPoint(oacDoBB);
  14623. mBfIRBuilder->CreateObjectAccessCheck(fieldVal, !IsOptimized());
  14624. mBfIRBuilder->CreateBr(oacDoneBB);
  14625. mBfIRBuilder->AddBlock(oacDoneBB);
  14626. mBfIRBuilder->SetInsertPoint(oacDoneBB);
  14627. trueEndBB = oacDoneBB;
  14628. }
  14629. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  14630. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14631. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  14632. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14633. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  14634. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14635. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  14636. if (callingConv != BfIRCallingConv_CDecl)
  14637. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  14638. mCurMethodState->SetHadReturn(false);
  14639. mCurMethodState->mLeftBlockUncond = false;
  14640. mCurMethodState->mLeftBlockCond = false;
  14641. mBfIRBuilder->CreateBr(doneBB);
  14642. }
  14643. // Static invocation
  14644. {
  14645. mBfIRBuilder->AddBlock(falseBB);
  14646. mBfIRBuilder->SetInsertPoint(falseBB);
  14647. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14648. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  14649. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14650. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  14651. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14652. {
  14653. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  14654. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  14655. }
  14656. // We had a sret for the non-static but no sret for the static (because we have a lowered return type there)
  14657. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1) && (mCurMethodInstance->GetStructRetIdx(true) == -1))
  14658. {
  14659. auto sretToType = mBfIRBuilder->GetPointerTo(staticReturnType);
  14660. auto sretCastedPtr = mBfIRBuilder->CreateBitCast(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), sretToType);
  14661. mBfIRBuilder->CreateStore(staticResult, sretCastedPtr);
  14662. }
  14663. if (callingConv == BfIRCallingConv_ThisCall)
  14664. callingConv = BfIRCallingConv_CDecl;
  14665. if (callingConv != BfIRCallingConv_CDecl)
  14666. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  14667. mCurMethodState->SetHadReturn(false);
  14668. mCurMethodState->mLeftBlockUncond = false;
  14669. mCurMethodState->mLeftBlockCond = false;
  14670. mBfIRBuilder->CreateBr(doneBB);
  14671. }
  14672. mBfIRBuilder->AddBlock(doneBB);
  14673. mBfIRBuilder->SetInsertPoint(doneBB);
  14674. if (mCurMethodInstance->mReturnType->IsVar())
  14675. {
  14676. // Do nothing
  14677. }
  14678. else if ((mCurMethodInstance->mReturnType->IsValuelessType()) ||
  14679. ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1)))
  14680. {
  14681. mBfIRBuilder->CreateRetVoid();
  14682. }
  14683. else
  14684. {
  14685. BfIRType loweredIRReturnType;
  14686. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14687. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14688. if ((!mIsComptimeModule) && (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2)))
  14689. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  14690. else
  14691. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  14692. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  14693. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueEndBB);
  14694. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  14695. mBfIRBuilder->CreateRet(phi);
  14696. }
  14697. }
  14698. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  14699. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  14700. {
  14701. auto typeDef = typeInstance->mTypeDef;
  14702. auto methodDeclaration = methodDef->mMethodDeclaration;
  14703. if (!mCompiler->mIsResolveOnly)
  14704. return true;
  14705. if (typeInstance->IsGenericTypeInstance())
  14706. {
  14707. // We only really want to process the unspecialized type for autocompletion
  14708. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  14709. return false;
  14710. }
  14711. BfAstNode* checkNode = methodDeclaration;
  14712. if (methodDeclaration == NULL)
  14713. checkNode = methodDef->mBody;
  14714. if ((!mCompiler->mResolvePassData->mParsers.IsEmpty()) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParsers[0])))
  14715. {
  14716. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  14717. return true;
  14718. }
  14719. return false;
  14720. }
  14721. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  14722. {
  14723. methodInst->mAppendAllocAlign = 1;
  14724. }
  14725. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args, bool force)
  14726. {
  14727. BP_ZONE("BfModule::TryConstCalcAppend");
  14728. BF_ASSERT(methodInst->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  14729. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (!force))
  14730. return BfTypedValue();
  14731. // We want to regenerate all ctor calls when the method internals change
  14732. {
  14733. auto checkTypeInst = methodInst->GetOwner();
  14734. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  14735. {
  14736. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  14737. checkTypeInst = GetBaseType(checkTypeInst);
  14738. }
  14739. }
  14740. if (!methodInst->mMayBeConst)
  14741. return BfTypedValue();
  14742. // Do we need to iterate in order to resolve mAppendAllocAlign?
  14743. bool isFirstRun = methodInst->mEndingAppendAllocAlign < 0;
  14744. bool wasAllConst = true;
  14745. int argIdx = 0;
  14746. int paramIdx = 0;
  14747. while (true)
  14748. {
  14749. if (argIdx >= (int)args.size())
  14750. break;
  14751. auto paramType = methodInst->GetParamType(paramIdx);
  14752. PopulateType(paramType);
  14753. int argCount = 0;
  14754. if (!paramType->IsValuelessType())
  14755. {
  14756. if ((!mIsComptimeModule) && (methodInst->GetParamIsSplat(paramIdx)))
  14757. argCount = paramType->GetSplatCount();
  14758. else
  14759. argCount = 1;
  14760. for (int argOfs = 0; argOfs < argCount; argOfs++)
  14761. {
  14762. auto arg = args[argIdx + argOfs];
  14763. if (!arg.IsConst())
  14764. {
  14765. wasAllConst = false;
  14766. if (!isFirstRun)
  14767. {
  14768. auto& param = methodInst->mParams[argIdx];
  14769. if (param.mReferencedInConstPass)
  14770. {
  14771. // If this param is required as part of the const calculation then
  14772. // we require that it be const...
  14773. return BfTypedValue();
  14774. }
  14775. }
  14776. }
  14777. }
  14778. }
  14779. paramIdx++;
  14780. argIdx += argCount;
  14781. }
  14782. auto methodDef = methodInst->mMethodDef;
  14783. auto methodDecl = methodDef->GetMethodDeclaration();
  14784. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14785. if (methodDeclBlock == NULL)
  14786. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  14787. BfTypedValue constValue;
  14788. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  14789. auto checkState = mCurMethodState->mConstResolveState;
  14790. while (checkState != NULL)
  14791. {
  14792. if (checkState->mMethodInstance == methodInst)
  14793. {
  14794. return BfTypedValue();
  14795. }
  14796. checkState = checkState->mPrevConstResolveState;
  14797. }
  14798. //auto accumValue = GetConstValue(0);
  14799. bool failed = false;
  14800. //
  14801. {
  14802. BfConstResolveState constResolveState;
  14803. constResolveState.mMethodInstance = methodInst;
  14804. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  14805. constResolveState.mInCalcAppend = true;
  14806. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14807. BfMethodState methodState;
  14808. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  14809. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  14810. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  14811. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  14812. methodState.mConstResolveState = &constResolveState;
  14813. int argIdx = 0;
  14814. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14815. {
  14816. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  14817. continue;
  14818. auto paramType = methodInst->GetParamType(paramIdx);
  14819. // Fix this after we allow structs to be consts
  14820. //BF_ASSERT(!paramType->IsSplattable());
  14821. BfLocalVariable* localVar = new BfLocalVariable();
  14822. localVar->mName = methodInst->GetParamName(paramIdx);
  14823. localVar->mResolvedType = paramType;
  14824. localVar->mConstValue = args[argIdx];
  14825. localVar->mParamIdx = paramIdx;
  14826. AddLocalVariableDef(localVar);
  14827. argIdx++;
  14828. }
  14829. AppendAllocVisitor appendAllocVisitor;
  14830. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  14831. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  14832. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  14833. if (baseCtorAppendValue)
  14834. {
  14835. if (baseCtorAppendValue.mValue.IsFake())
  14836. appendAllocVisitor.mFailed = true;
  14837. else
  14838. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  14839. }
  14840. appendAllocVisitor.mModule = this;
  14841. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14842. if (constResolveState.mFailed)
  14843. appendAllocVisitor.mFailed = true;
  14844. if (!appendAllocVisitor.mFailed)
  14845. constValue = appendAllocVisitor.mConstAccum;
  14846. if (isFirstRun)
  14847. {
  14848. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  14849. if (mCurMethodInstance->mAppendAllocAlign <= 0)
  14850. mCurMethodInstance->mAppendAllocAlign = 1;
  14851. }
  14852. if (isFirstRun)
  14853. {
  14854. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14855. {
  14856. auto localVar = mCurMethodState->mLocals[paramIdx];
  14857. if (localVar->mReadFromId != -1)
  14858. {
  14859. auto& param = methodInst->mParams[paramIdx];
  14860. param.mReferencedInConstPass = true;
  14861. }
  14862. }
  14863. }
  14864. }
  14865. mBfIRBuilder->SetInsertPoint(prevBlock);
  14866. if (!constValue)
  14867. {
  14868. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  14869. // all-const args
  14870. if (wasAllConst)
  14871. {
  14872. methodInst->mMayBeConst = false;
  14873. }
  14874. }
  14875. return constValue;
  14876. }
  14877. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  14878. {
  14879. // Any errors should only be shown in the actual CTOR call
  14880. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  14881. auto methodDef = mCurMethodInstance->mMethodDef;
  14882. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  14883. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  14884. BfCustomAttributes* customAttributes = NULL;
  14885. defer(delete customAttributes);
  14886. BfInvocationExpression* ctorInvocation = NULL;
  14887. if (ctorDeclaration != NULL)
  14888. {
  14889. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  14890. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  14891. {
  14892. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  14893. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  14894. }
  14895. }
  14896. BfTypeInstance* targetType = NULL;
  14897. if (ctorInvocation != NULL)
  14898. {
  14899. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  14900. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  14901. }
  14902. else
  14903. targetType = mCurTypeInstance->mBaseType;
  14904. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  14905. return NULL;
  14906. auto targetRefNode = methodDef->GetRefNode();
  14907. BfType* targetThisType = targetType;
  14908. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  14909. BfExprEvaluator exprEvaluator(this);
  14910. BfResolvedArgs argValues;
  14911. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  14912. {
  14913. argValues.Init(&ctorInvocation->mArguments);
  14914. }
  14915. //
  14916. {
  14917. }
  14918. BfFunctionBindResult bindResult;
  14919. bindResult.mSkipThis = true;
  14920. bindResult.mWantsArgs = true;
  14921. {
  14922. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14923. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14924. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14925. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), true);
  14926. }
  14927. if (bindResult.mMethodInstance == NULL)
  14928. {
  14929. AssertErrorState();
  14930. return BfTypedValue();
  14931. }
  14932. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  14933. {
  14934. return BfTypedValue();
  14935. }
  14936. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14937. bindResult.mIRArgs.RemoveAt(0);
  14938. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  14939. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs, true);
  14940. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  14941. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  14942. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  14943. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  14944. if (appendSizeTypedValue)
  14945. return appendSizeTypedValue;
  14946. if (constOnly)
  14947. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  14948. bool needsRecalc = false;
  14949. for (auto irArg : bindResult.mIRArgs)
  14950. {
  14951. if (irArg.IsFake())
  14952. needsRecalc = true;
  14953. }
  14954. auto calcAppendArgs = bindResult.mIRArgs;
  14955. if (needsRecalc)
  14956. {
  14957. // Do it again, but without mIgnoreWrites set
  14958. BfResolvedArgs argValues;
  14959. argValues.Init(&ctorInvocation->mArguments);
  14960. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14961. BfFunctionBindResult bindResult;
  14962. bindResult.mSkipThis = true;
  14963. bindResult.mWantsArgs = true;
  14964. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14965. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), true);
  14966. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14967. bindResult.mIRArgs.RemoveAt(0);
  14968. calcAppendArgs = bindResult.mIRArgs;
  14969. }
  14970. if (mBfIRBuilder->mIgnoreWrites)
  14971. {
  14972. appendSizeTypedValue = GetFakeTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  14973. }
  14974. else
  14975. {
  14976. BF_ASSERT(calcAppendMethodModule.mFunc);
  14977. appendSizeTypedValue = exprEvaluator.CreateCall(NULL, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  14978. }
  14979. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  14980. return appendSizeTypedValue;
  14981. }
  14982. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  14983. void BfModule::EmitCtorCalcAppend()
  14984. {
  14985. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  14986. return;
  14987. auto methodDef = mCurMethodInstance->mMethodDef;
  14988. auto methodDecl = methodDef->GetMethodDeclaration();
  14989. Array<BfAstNode*> deferredNodeList;
  14990. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14991. if (methodDeclBlock == NULL)
  14992. return;
  14993. AppendAllocVisitor appendAllocVisitor;
  14994. auto baseCalcAppend = CallBaseCtorCalc(false);
  14995. if (baseCalcAppend)
  14996. {
  14997. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  14998. }
  14999. appendAllocVisitor.mModule = this;
  15000. appendAllocVisitor.VisitChild(methodDecl->mBody);
  15001. }
  15002. void BfModule::CreateStaticCtor()
  15003. {
  15004. auto typeDef = mCurTypeInstance->mTypeDef;
  15005. auto methodDef = mCurMethodInstance->mMethodDef;
  15006. BfIRBlock exitBB;
  15007. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15008. {
  15009. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  15010. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  15011. mBfIRBuilder->MapType(boolType),
  15012. false,
  15013. BfIRLinkageType_Internal,
  15014. GetDefaultValue(boolType),
  15015. "didStaticInit");
  15016. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  15017. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15018. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  15019. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  15020. mBfIRBuilder->SetInsertPoint(initBB);
  15021. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  15022. }
  15023. // Do DLL imports
  15024. if (!mDllImportEntries.empty())
  15025. {
  15026. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  15027. PopulateType(internalType);
  15028. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  15029. if (!getSharedProcAddressInstance)
  15030. {
  15031. if (!mCompiler->mPassInstance->HasFailed())
  15032. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  15033. }
  15034. }
  15035. // Fill in initializer values
  15036. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15037. {
  15038. for (auto fieldDef : typeDef->mFields)
  15039. {
  15040. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic))
  15041. {
  15042. // For extensions, only handle these fields in the appropriate extension
  15043. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15044. continue;
  15045. auto initializer = fieldDef->GetInitializer();
  15046. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15047. if (!fieldInst->mFieldIncluded)
  15048. continue;
  15049. if (fieldInst->mResolvedType->IsVar())
  15050. {
  15051. continue;
  15052. }
  15053. if (fieldInst->IsAppendedObject())
  15054. {
  15055. AppendedObjectInit(fieldInst);
  15056. }
  15057. else if (initializer != NULL)
  15058. {
  15059. UpdateSrcPos(initializer);
  15060. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  15061. }
  15062. }
  15063. }
  15064. auto _CheckInitBlock = [&](BfAstNode* node)
  15065. {
  15066. };
  15067. EmitInitBlocks(_CheckInitBlock);
  15068. }
  15069. else
  15070. {
  15071. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15072. {
  15073. if (tempTypeDef->mFullName == typeDef->mFullName)
  15074. {
  15075. for (auto fieldDef : tempTypeDef->mFields)
  15076. {
  15077. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  15078. {
  15079. if (fieldDef->GetInitializer() != NULL)
  15080. {
  15081. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDef->GetInitializer()))
  15082. {
  15083. sourceClassifier->SetElementType(fieldDef->GetInitializer(), BfSourceElementType_Normal);
  15084. sourceClassifier->VisitChildNoRef(fieldDef->GetInitializer());
  15085. }
  15086. BfType* wantType = NULL;
  15087. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  15088. {
  15089. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  15090. }
  15091. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  15092. if (fieldDef->mIsAppend)
  15093. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  15094. CreateValueFromExpression(fieldDef->GetInitializer(), wantType, exprFlags);
  15095. }
  15096. }
  15097. }
  15098. }
  15099. }
  15100. }
  15101. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15102. CallChainedMethods(mCurMethodInstance, false);
  15103. }
  15104. void BfModule::EmitDtorBody()
  15105. {
  15106. if (!mCurMethodState->mIRExitBlock)
  15107. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15108. if (mCurTypeInstance->IsClosure())
  15109. {
  15110. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  15111. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  15112. auto thisVal = GetThis();
  15113. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  15114. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  15115. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  15116. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  15117. SizedArray<BfIRValue, 1> args;
  15118. args.push_back(thisVal.mValue);
  15119. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  15120. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15121. // Fall through to Object::~this call
  15122. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  15123. if (mIsComptimeModule)
  15124. mCompiler->mCeMachine->QueueMethod(dtorFunc.mMethodInstance, dtorFunc.mFunc);
  15125. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  15126. SizedArray<BfIRValue, 1> vals = { basePtr };
  15127. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  15128. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  15129. mBfIRBuilder->SetTailCall(result);
  15130. return;
  15131. }
  15132. auto typeDef = mCurTypeInstance->mTypeDef;
  15133. auto methodDef = mCurMethodInstance->mMethodDef;
  15134. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15135. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15136. CallChainedMethods(mCurMethodInstance, true);
  15137. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15138. {
  15139. VisitEmbeddedStatement(bodyBlock);
  15140. if (bodyBlock->mCloseBrace != NULL)
  15141. {
  15142. UpdateSrcPos(bodyBlock->mCloseBrace);
  15143. }
  15144. }
  15145. else
  15146. {
  15147. if (methodDeclaration != NULL)
  15148. UpdateSrcPos(methodDeclaration);
  15149. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15150. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  15151. else if (typeDef->mTypeDeclaration != NULL)
  15152. UpdateSrcPos(typeDef->mTypeDeclaration);
  15153. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  15154. {
  15155. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  15156. }
  15157. }
  15158. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15159. {
  15160. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  15161. {
  15162. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  15163. auto fieldDef = fieldInst->GetFieldDef();
  15164. BfFieldDeclaration* fieldDecl = NULL;
  15165. if (fieldDef != NULL)
  15166. fieldDecl = fieldDef->GetFieldDeclaration();
  15167. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDecl != NULL) && (fieldDecl->mFieldDtor != NULL))
  15168. {
  15169. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15170. {
  15171. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15172. continue;
  15173. }
  15174. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  15175. {
  15176. Fail("Structs cannot have field destructors", fieldDecl->mFieldDtor->mTildeToken, true);
  15177. }
  15178. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  15179. auto fieldDtor = fieldDecl->mFieldDtor;
  15180. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  15181. continue;
  15182. UpdateSrcPos(fieldDtor);
  15183. BfScopeData scopeData;
  15184. mCurMethodState->AddScope(&scopeData);
  15185. NewScopeState();
  15186. UpdateSrcPos(fieldDtor);
  15187. bool hasDbgInfo = (!fieldDef->mIsConst);
  15188. if (hasDbgInfo)
  15189. {
  15190. mBfIRBuilder->SaveDebugLocation();
  15191. mBfIRBuilder->ClearDebugLocation();
  15192. }
  15193. BfIRValue value;
  15194. if (fieldDef->mIsStatic)
  15195. {
  15196. value = ReferenceStaticField(fieldInst).mValue;
  15197. }
  15198. else
  15199. {
  15200. PopulateType(fieldInst->mResolvedType);
  15201. if (fieldInst->mResolvedType->IsValuelessType())
  15202. {
  15203. value = mBfIRBuilder->GetFakeVal();
  15204. }
  15205. else if (!mCurTypeInstance->IsValueType())
  15206. {
  15207. auto thisValue = GetThis();
  15208. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  15209. }
  15210. else
  15211. {
  15212. AssertErrorState();
  15213. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15214. }
  15215. }
  15216. BfIRValue staticVal;
  15217. if (hasDbgInfo)
  15218. {
  15219. BfIRValue dbgShowValue = value;
  15220. BfLocalVariable* localDef = new BfLocalVariable();
  15221. localDef->mName = "_";
  15222. localDef->mResolvedType = fieldInst->mResolvedType;
  15223. if (fieldInst->IsAppendedObject())
  15224. {
  15225. localDef->mValue = mBfIRBuilder->CreateBitCast(value, mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15226. }
  15227. else
  15228. {
  15229. localDef->mAddr = value;
  15230. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  15231. {
  15232. // Create another pointer indirection, a ref to the gep
  15233. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  15234. auto allocaInst = CreateAlloca(refFieldType);
  15235. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  15236. localDef->mResolvedType = refFieldType;
  15237. localDef->mAddr = allocaInst;
  15238. }
  15239. }
  15240. mBfIRBuilder->RestoreDebugLocation();
  15241. auto defLocalVar = AddLocalVariableDef(localDef, true);
  15242. if (!fieldInst->IsAppendedObject())
  15243. {
  15244. // Put back so we actually modify the correct value*/
  15245. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  15246. defLocalVar->mAddr = value;
  15247. }
  15248. }
  15249. while (fieldDtor != NULL)
  15250. {
  15251. if (mCompiler->mResolvePassData != NULL)
  15252. {
  15253. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15254. {
  15255. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15256. sourceClassifier->VisitChild(fieldDtor);
  15257. }
  15258. }
  15259. UpdateSrcPos(fieldDtor);
  15260. VisitEmbeddedStatement(fieldDtor->mBody);
  15261. fieldDtor = fieldDtor->mNextFieldDtor;
  15262. }
  15263. RestoreScopeState();
  15264. }
  15265. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldInst->IsAppendedObject()))
  15266. {
  15267. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15268. {
  15269. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15270. continue;
  15271. }
  15272. auto refNode = fieldDef->GetRefNode();
  15273. UpdateSrcPos(refNode);
  15274. auto objectType = mContext->mBfObjectType;
  15275. BfTypeInstance* checkTypeInst = mCurTypeInstance->ToTypeInstance();
  15276. BfTypedValue val;
  15277. if (fieldDef->mIsStatic)
  15278. val = ReferenceStaticField(fieldInst);
  15279. else
  15280. {
  15281. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  15282. val = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  15283. }
  15284. bool allowPrivate = checkTypeInst == mCurTypeInstance;
  15285. bool allowProtected = allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst);
  15286. while (checkTypeInst != NULL)
  15287. {
  15288. auto dtorMethodDef = checkTypeInst->mTypeDef->GetMethodByName("~this");
  15289. if (dtorMethodDef)
  15290. {
  15291. if (!CheckProtection(dtorMethodDef->mProtection, checkTypeInst->mTypeDef, allowProtected, allowPrivate))
  15292. {
  15293. auto error = Fail(StrFormat("'%s.~this()' is inaccessible due to its protection level", TypeToString(checkTypeInst).c_str()), refNode); // CS0122
  15294. }
  15295. }
  15296. checkTypeInst = checkTypeInst->mBaseType;
  15297. allowPrivate = false;
  15298. }
  15299. // call dtor
  15300. BfExprEvaluator expressionEvaluator(this);
  15301. PopulateType(val.mType);
  15302. PopulateType(objectType, BfPopulateType_DataAndMethods);
  15303. if (objectType->mVirtualMethodTable.size() == 0)
  15304. {
  15305. if (!mCompiler->IsAutocomplete())
  15306. AssertErrorState();
  15307. }
  15308. else if (!IsSkippingExtraResolveChecks())
  15309. {
  15310. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  15311. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  15312. SizedArray<BfIRValue, 4> llvmArgs;
  15313. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  15314. expressionEvaluator.CreateCall(refNode, methodInstance, mBfIRBuilder->GetFakeVal(), false, llvmArgs);
  15315. }
  15316. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  15317. {
  15318. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  15319. auto int8PtrVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(int8PtrType));
  15320. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  15321. }
  15322. }
  15323. }
  15324. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15325. {
  15326. auto checkBaseType = mCurTypeInstance->mBaseType;
  15327. while (checkBaseType != NULL)
  15328. {
  15329. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15330. {
  15331. if (bodyBlock->mCloseBrace != NULL)
  15332. UpdateSrcPos(bodyBlock->mCloseBrace);
  15333. }
  15334. else
  15335. {
  15336. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  15337. }
  15338. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  15339. if (dtorMethodDef != NULL)
  15340. {
  15341. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  15342. if (IsSkippingExtraResolveChecks())
  15343. {
  15344. // Nothing
  15345. }
  15346. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  15347. {
  15348. if ((!IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  15349. {
  15350. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  15351. SizedArray<BfIRValue, 1> vals = { basePtr };
  15352. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  15353. if (mIsComptimeModule)
  15354. mCompiler->mCeMachine->QueueMethod(dtorMethodInstance.mMethodInstance, dtorMethodInstance.mFunc);
  15355. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  15356. }
  15357. }
  15358. else
  15359. {
  15360. // Invalid base dtor declaration
  15361. AssertErrorState();
  15362. }
  15363. break;
  15364. }
  15365. checkBaseType = checkBaseType->mBaseType;
  15366. }
  15367. }
  15368. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15369. }
  15370. else
  15371. {
  15372. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15373. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15374. // resolve pass, NOT the autocomplete expression
  15375. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15376. {
  15377. if (tempTypeDef->mFullName == typeDef->mFullName)
  15378. {
  15379. for (auto fieldDef : tempTypeDef->mFields)
  15380. {
  15381. auto fieldDecl = fieldDef->GetFieldDeclaration();
  15382. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  15383. (fieldDecl->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  15384. {
  15385. BfType* fieldType = NULL;
  15386. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  15387. {
  15388. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  15389. auto curFieldDef = curFieldInstance->GetFieldDef();
  15390. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  15391. fieldType = curFieldInstance->GetResolvedType();
  15392. }
  15393. if (fieldType == NULL)
  15394. fieldType = GetPrimitiveType(BfTypeCode_Var);
  15395. auto fieldDtor = fieldDecl->mFieldDtor;
  15396. BfScopeData scopeData;
  15397. mCurMethodState->AddScope(&scopeData);
  15398. NewScopeState();
  15399. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  15400. if (fieldType != NULL)
  15401. {
  15402. BfLocalVariable* localDef = new BfLocalVariable();
  15403. localDef->mName = "_";
  15404. localDef->mResolvedType = fieldType;
  15405. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  15406. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15407. AddLocalVariableDef(localDef);
  15408. }
  15409. while (fieldDtor != NULL)
  15410. {
  15411. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15412. {
  15413. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15414. sourceClassifier->VisitChild(fieldDtor);
  15415. }
  15416. UpdateSrcPos(fieldDtor);
  15417. VisitEmbeddedStatement(fieldDtor->mBody);
  15418. fieldDtor = fieldDtor->mNextFieldDtor;
  15419. }
  15420. RestoreScopeState();
  15421. }
  15422. }
  15423. }
  15424. }
  15425. }
  15426. }
  15427. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  15428. {
  15429. BF_ASSERT(methodInstance->mIsReified);
  15430. auto typeInstance = methodInstance->GetOwner();
  15431. bool foundDllImportAttr = false;
  15432. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  15433. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  15434. {
  15435. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  15436. {
  15437. foundDllImportAttr = true;
  15438. }
  15439. }
  15440. if (!foundDllImportAttr)
  15441. {
  15442. AssertErrorState();
  15443. return BfIRValue();
  15444. }
  15445. StringT<512> name = "bf_hs_preserve@";
  15446. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  15447. name += "__imp";
  15448. BfIRType returnType;
  15449. SizedArray<BfIRType, 8> paramTypes;
  15450. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  15451. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  15452. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  15453. BfIRValue initVal;
  15454. if (define)
  15455. {
  15456. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  15457. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  15458. }
  15459. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  15460. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  15461. {
  15462. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15463. auto ptrType = CreatePointerType(voidType);
  15464. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  15465. }
  15466. return globalVar;
  15467. }
  15468. void BfModule::CreateDllImportMethod()
  15469. {
  15470. if (mBfIRBuilder->mIgnoreWrites)
  15471. return;
  15472. auto globalVar = mFuncReferences[mCurMethodInstance];
  15473. if (!globalVar)
  15474. return;
  15475. bool allowTailCall = true;
  15476. mBfIRBuilder->ClearDebugLocation();
  15477. bool isHotCompile = mCompiler->IsHotCompile();
  15478. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  15479. if (isHotCompile)
  15480. {
  15481. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  15482. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  15483. }
  15484. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  15485. BfIRType returnType;
  15486. SizedArray<BfIRType, 8> paramTypes;
  15487. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15488. SizedArray<BfIRValue, 8> args;
  15489. for (int i = 0; i < (int)paramTypes.size(); i++)
  15490. args.push_back(mBfIRBuilder->GetArgument(i));
  15491. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15492. if (isHotCompile)
  15493. {
  15494. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  15495. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  15496. if (callingConvention == BfIRCallingConv_StdCall)
  15497. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  15498. else if (callingConvention == BfIRCallingConv_FastCall)
  15499. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  15500. else
  15501. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15502. if (allowTailCall)
  15503. mBfIRBuilder->SetTailCall(result);
  15504. CreateReturn(result);
  15505. mCurMethodState->mHadReturn = true;
  15506. }
  15507. if (HasCompiledOutput())
  15508. {
  15509. BfDllImportEntry dllImportEntry;
  15510. dllImportEntry.mFuncVar = globalVar;
  15511. dllImportEntry.mMethodInstance = mCurMethodInstance;
  15512. mDllImportEntries.push_back(dllImportEntry);
  15513. }
  15514. }
  15515. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  15516. {
  15517. auto methodDef = methodInstance->mMethodDef;
  15518. BfTypeInstance* owner = NULL;
  15519. if (!methodDef->mIsStatic)
  15520. owner = methodInstance->GetThisType()->ToTypeInstance();
  15521. if (owner == NULL)
  15522. owner = methodInstance->GetOwner();
  15523. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  15524. return BfIRCallingConv_CDecl;
  15525. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  15526. return BfIRCallingConv_StdCall;
  15527. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  15528. return BfIRCallingConv_FastCall;
  15529. if (!methodDef->mIsStatic)
  15530. {
  15531. if (owner->mIsCRepr)
  15532. return BfIRCallingConv_ThisCall;
  15533. if ((!owner->IsValuelessType()) &&
  15534. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  15535. return BfIRCallingConv_ThisCall;
  15536. }
  15537. return BfIRCallingConv_CDecl;
  15538. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  15539. }
  15540. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  15541. {
  15542. BfMethodDef* methodDef = NULL;
  15543. if (methodInstance != NULL)
  15544. methodDef = methodInstance->mMethodDef;
  15545. if (!func)
  15546. return;
  15547. if (mCompiler->mOptions.mNoFramePointerElim)
  15548. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  15549. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  15550. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  15551. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  15552. if (methodInstance == NULL)
  15553. return;
  15554. if (methodInstance->mReturnType->IsVar())
  15555. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_VarRet);
  15556. if (methodDef->mImportKind == BfImportKind_Export)
  15557. {
  15558. if (methodDef->mDeclaringType->mProject->mTargetType != BfTargetType_BeefLib_StaticLib)
  15559. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  15560. }
  15561. if (methodDef->mIsNoReturn)
  15562. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  15563. auto callingConv = GetIRCallingConvention(methodInstance);
  15564. if (callingConv != BfIRCallingConv_CDecl)
  15565. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  15566. if (isInlined)
  15567. {
  15568. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15569. }
  15570. int argIdx = 0;
  15571. int paramIdx = 0;
  15572. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  15573. paramIdx = -1;
  15574. int argCount = methodInstance->GetIRFunctionParamCount(this);
  15575. while (argIdx < argCount)
  15576. {
  15577. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  15578. {
  15579. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  15580. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  15581. argIdx++;
  15582. continue;
  15583. }
  15584. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  15585. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  15586. paramIdx++;
  15587. BfType* resolvedTypeRef = NULL;
  15588. BfType* resolvedTypeRef2 = NULL;
  15589. String paramName;
  15590. bool isSplattable = false;
  15591. bool tryLowering = !mIsComptimeModule;
  15592. if (isThis)
  15593. {
  15594. paramName = "this";
  15595. if (methodInstance->mIsClosure)
  15596. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  15597. else
  15598. resolvedTypeRef = methodInstance->GetThisType();
  15599. isSplattable = (!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(-1));
  15600. tryLowering = (!mIsComptimeModule) && (methodInstance->AllowsSplatting(-1));
  15601. }
  15602. else
  15603. {
  15604. paramName = methodInstance->GetParamName(paramIdx);
  15605. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  15606. if (resolvedTypeRef->IsMethodRef())
  15607. isSplattable = true;
  15608. else if ((!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(paramIdx)))
  15609. {
  15610. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15611. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15612. {
  15613. // crepr splat is always splattable
  15614. isSplattable = true;
  15615. }
  15616. else
  15617. {
  15618. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15619. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15620. isSplattable = true;
  15621. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  15622. isSplattable = true;
  15623. }
  15624. }
  15625. }
  15626. if (tryLowering)
  15627. {
  15628. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15629. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15630. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  15631. {
  15632. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  15633. argIdx++;
  15634. if (loweredTypeCode2 != BfTypeCode_None)
  15635. {
  15636. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  15637. argIdx++;
  15638. }
  15639. paramIdx++;
  15640. continue;
  15641. }
  15642. }
  15643. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  15644. {
  15645. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  15646. int addDeref = -1;
  15647. if (resolvedTypeRef->IsRef())
  15648. {
  15649. auto refType = (BfRefType*)resolvedTypeRef;
  15650. auto elementType = refType->mElementType;
  15651. PopulateType(elementType, BfPopulateType_Data);
  15652. addDeref = elementType->mSize;
  15653. if ((addDeref <= 0) && (!elementType->IsValuelessType()) && (!elementType->IsOpaque()))
  15654. AssertErrorState();
  15655. }
  15656. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  15657. {
  15658. if (isThis)
  15659. {
  15660. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  15661. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  15662. addDeref = resolvedTypeRef->mSize;
  15663. }
  15664. else if (methodInstance->WantsStructsAttribByVal(resolvedTypeRef))
  15665. {
  15666. mBfIRBuilder->PopulateType(resolvedTypeRef, BfIRPopulateType_Full);
  15667. BF_ASSERT(resolvedTypeRef->mAlign > 0);
  15668. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  15669. }
  15670. }
  15671. else if (resolvedTypeRef->IsPrimitiveType())
  15672. {
  15673. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  15674. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  15675. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  15676. }
  15677. if (addDeref >= 0)
  15678. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  15679. argIdx++;
  15680. };
  15681. if (isSplattable)
  15682. {
  15683. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  15684. {
  15685. if (checkType->IsStruct())
  15686. {
  15687. auto checkTypeInstance = checkType->ToTypeInstance();
  15688. if (checkTypeInstance->mBaseType != NULL)
  15689. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  15690. if (checkTypeInstance->mIsUnion)
  15691. {
  15692. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  15693. checkTypeLambda(unionInnerType, curName + "_data");
  15694. }
  15695. else
  15696. {
  15697. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  15698. {
  15699. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  15700. auto fieldDef = fieldInstance->GetFieldDef();
  15701. if (fieldInstance->mDataIdx >= 0)
  15702. {
  15703. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  15704. }
  15705. }
  15706. }
  15707. if (checkTypeInstance->IsEnum())
  15708. {
  15709. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  15710. argIdx++;
  15711. }
  15712. }
  15713. else if (checkType->IsMethodRef())
  15714. {
  15715. auto methodRefType = (BfMethodRefType*)checkType;
  15716. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  15717. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  15718. {
  15719. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  15720. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  15721. {
  15722. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  15723. }
  15724. else
  15725. {
  15726. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  15727. }
  15728. }
  15729. }
  15730. else if (!checkType->IsValuelessType())
  15731. {
  15732. _SetupParam(curName, checkType);
  15733. }
  15734. };
  15735. checkTypeLambda(resolvedTypeRef, paramName);
  15736. paramIdx++;
  15737. continue;
  15738. }
  15739. _SetupParam(paramName, resolvedTypeRef);
  15740. if (resolvedTypeRef2 != NULL)
  15741. _SetupParam(paramName, resolvedTypeRef2);
  15742. paramIdx++;
  15743. }
  15744. }
  15745. void BfModule::EmitInitBlocks(const std::function<void(BfAstNode*)>& initBlockCallback)
  15746. {
  15747. auto methodDef = mCurMethodInstance->mMethodDef;
  15748. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  15749. BfMemberSetEntry* entry = NULL;
  15750. BfMethodDef* initMethodDef = NULL;
  15751. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  15752. if (entry != NULL)
  15753. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  15754. SizedArray<BfAstNode*, 8> initBodies;
  15755. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  15756. {
  15757. if (initMethodDef->mDeclaringType->GetDefinition() != methodDef->mDeclaringType->GetDefinition())
  15758. continue;
  15759. if (initMethodDef->mMethodType != BfMethodType_Init)
  15760. continue;
  15761. if (initMethodDef->mIsStatic != methodDef->mIsStatic)
  15762. continue;
  15763. initBodies.Insert(0, initMethodDef->mBody);
  15764. }
  15765. for (auto body : initBodies)
  15766. {
  15767. initBlockCallback(body);
  15768. VisitEmbeddedStatement(body);
  15769. }
  15770. }
  15771. void BfModule::EmitCtorBody(bool& skipBody)
  15772. {
  15773. auto methodInstance = mCurMethodInstance;
  15774. auto methodDef = methodInstance->mMethodDef;
  15775. auto methodDeclaration = methodDef->mMethodDeclaration;
  15776. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  15777. auto typeDef = mCurTypeInstance->mTypeDef;
  15778. BfCustomAttributes* customAttributes = NULL;
  15779. defer(delete customAttributes);
  15780. BfInvocationExpression* ctorInvocation = NULL;
  15781. BfAttributeState attributeState;
  15782. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  15783. if (ctorDeclaration != NULL)
  15784. {
  15785. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  15786. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  15787. {
  15788. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  15789. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  15790. }
  15791. }
  15792. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  15793. // Prologue
  15794. mBfIRBuilder->ClearDebugLocation();
  15795. bool hadThisInitializer = false;
  15796. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15797. {
  15798. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15799. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15800. if (targetToken->GetToken() == BfToken_This)
  15801. {
  15802. hadThisInitializer = true;
  15803. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  15804. mCurMethodState->LocalDefined(GetThisVariable());
  15805. }
  15806. }
  15807. // Zero out memory for default ctor
  15808. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()) && (!mCurTypeInstance->IsAnonymousInitializerType()) && (methodInstance->mChainType != BfMethodChainType_ChainMember) &&
  15809. (!mCurMethodState->mLocals.IsEmpty()))
  15810. {
  15811. if (mCurTypeInstance->IsTypedPrimitive())
  15812. {
  15813. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15814. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  15815. }
  15816. else if (mCurTypeInstance->mInstSize > 0)
  15817. {
  15818. BfIRValue fillValue = GetConstValue8(0);
  15819. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  15820. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15821. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  15822. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  15823. }
  15824. }
  15825. BfAstNode* baseCtorNode = NULL;
  15826. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  15827. baseCtorNode = ctorInvocation->mTarget;
  15828. else if (methodDef->mBody != NULL)
  15829. baseCtorNode = methodDef->mBody;
  15830. else if (ctorDeclaration != NULL)
  15831. baseCtorNode = ctorDeclaration;
  15832. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15833. baseCtorNode = methodDef->mDeclaringType->GetRefNode();
  15834. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15835. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  15836. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  15837. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  15838. else
  15839. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  15840. bool calledCtorNoBody = false;
  15841. if ((mCurTypeInstance->IsTypedPrimitive()) && (!mCurTypeInstance->IsValuelessType()))
  15842. {
  15843. // Zero out typed primitives in ctor
  15844. mBfIRBuilder->CreateAlignedStore(GetDefaultValue(mCurTypeInstance->GetUnderlyingType()), mBfIRBuilder->GetArgument(0), mCurTypeInstance->mAlign);
  15845. }
  15846. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  15847. {
  15848. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  15849. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  15850. {
  15851. BfMethodDef* defaultCtor = NULL;
  15852. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  15853. {
  15854. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  15855. {
  15856. defaultCtor = methodDef;
  15857. }
  15858. }
  15859. if (defaultCtor != NULL)
  15860. {
  15861. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  15862. SetIllegalSrcPos();
  15863. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  15864. BfExprEvaluator exprEvaluator(this);
  15865. SizedArray<BfIRValue, 1> irArgs;
  15866. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  15867. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  15868. if (mIsComptimeModule)
  15869. mCompiler->mCeMachine->QueueMethod(moduleMethodInstance);
  15870. calledCtorNoBody = true;
  15871. }
  15872. }
  15873. }
  15874. // Initialize fields (if applicable)
  15875. if (mCurTypeInstance->IsBoxed())
  15876. {
  15877. skipBody = true;
  15878. }
  15879. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  15880. {
  15881. // Field initializers occur in CtorNoBody methods for extensions
  15882. }
  15883. else if (!hadThisInitializer)
  15884. {
  15885. // If we had a 'this' initializer, that other ctor will have initialized our fields
  15886. //auto
  15887. if ((!mCompiler->mIsResolveOnly) ||
  15888. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  15889. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  15890. {
  15891. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  15892. // to properly set the assigned flags
  15893. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  15894. bool hadInlineInitBlock = false;
  15895. BfScopeData scopeData;
  15896. scopeData.mInInitBlock = true;
  15897. auto _CheckInitBlock = [&](BfAstNode* node)
  15898. {
  15899. if (!hadInlineInitBlock)
  15900. {
  15901. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  15902. {
  15903. UpdateSrcPos(baseCtorNode);
  15904. if (methodDef->mBody == NULL)
  15905. SetIllegalSrcPos();
  15906. // 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
  15907. EmitEnsureInstructionAt();
  15908. BfType* thisType = mCurTypeInstance;
  15909. if (thisType->IsValueType())
  15910. thisType = CreateRefType(thisType);
  15911. SizedArray<BfIRMDNode, 1> diParamTypes;
  15912. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  15913. mCurMethodState->AddScope(&scopeData);
  15914. NewScopeState();
  15915. int flags = 0;
  15916. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  15917. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  15918. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  15919. String linkageName;
  15920. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mCurBuilder != NULL))
  15921. linkageName = StrFormat("%d", mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(mCurMethodInstance, "$initFields"));
  15922. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", linkageName, mCurFilePosition.mFileInstance->mDIFile,
  15923. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  15924. UpdateSrcPos(node);
  15925. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  15926. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  15927. //
  15928. {
  15929. auto loadedThis = GetThis();
  15930. // LLVM can't handle two variables pointing to the same value
  15931. BfIRValue copiedThisPtr;
  15932. copiedThisPtr = CreateAlloca(thisType);
  15933. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  15934. mBfIRBuilder->ClearDebugLocation(storeInst);
  15935. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  15936. }
  15937. hadInlineInitBlock = true;
  15938. }
  15939. else
  15940. {
  15941. // Just do a simple one
  15942. mCurMethodState->AddScope(&scopeData);
  15943. NewScopeState();
  15944. hadInlineInitBlock = true;
  15945. }
  15946. }
  15947. UpdateSrcPos(node);
  15948. };
  15949. for (auto fieldDef : typeDef->mFields)
  15950. {
  15951. // For extensions, only handle these fields in the appropriate extension
  15952. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15953. continue;
  15954. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  15955. {
  15956. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15957. if (!fieldInst->mFieldIncluded)
  15958. continue;
  15959. if (fieldInst->mDataIdx < 0)
  15960. continue;
  15961. auto initializer = fieldDef->GetInitializer();
  15962. if (fieldInst->IsAppendedObject())
  15963. {
  15964. UpdateSrcPos(fieldDef->GetNameNode());
  15965. AppendedObjectInit(fieldInst);
  15966. continue;
  15967. }
  15968. if (initializer == NULL)
  15969. {
  15970. continue;
  15971. // if (fieldDef->mProtection != BfProtection_Hidden)
  15972. // continue;
  15973. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  15974. // continue;
  15975. }
  15976. if (fieldInst->mResolvedType == NULL)
  15977. {
  15978. BF_ASSERT(mHadBuildError);
  15979. continue;
  15980. }
  15981. if (initializer != NULL)
  15982. {
  15983. _CheckInitBlock(initializer);
  15984. }
  15985. BfIRValue fieldAddr;
  15986. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  15987. {
  15988. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  15989. }
  15990. else
  15991. {
  15992. // Failed
  15993. }
  15994. auto assignValue = GetFieldInitializerValue(fieldInst);
  15995. if (mCurTypeInstance->IsUnion())
  15996. {
  15997. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  15998. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  15999. }
  16000. if ((fieldAddr) && (assignValue))
  16001. mBfIRBuilder->CreateAlignedStore(assignValue.mValue, fieldAddr, fieldInst->mResolvedType->mAlign);
  16002. }
  16003. }
  16004. EmitInitBlocks(_CheckInitBlock);
  16005. if (hadInlineInitBlock)
  16006. {
  16007. RestoreScopeState();
  16008. // This gets set to false because of AddScope but we actually are still in the head block
  16009. mCurMethodState->mInHeadScope = true;
  16010. // Make sure we emit a return even if we had a NoReturn call or return inside ourselves
  16011. mCurMethodState->mHadReturn = false;
  16012. mCurMethodState->mLeftBlockUncond = false;
  16013. }
  16014. }
  16015. else // Autocomplete case
  16016. {
  16017. BfScopeData scopeData;
  16018. scopeData.mInInitBlock = true;
  16019. mCurMethodState->AddScope(&scopeData);
  16020. NewScopeState();
  16021. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  16022. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  16023. // resolve pass, NOT the autocomplete expression
  16024. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  16025. {
  16026. if (tempTypeDef->mFullName == typeDef->mFullName)
  16027. {
  16028. for (auto fieldDef : tempTypeDef->mFields)
  16029. {
  16030. auto initializer = fieldDef->GetInitializer();
  16031. if ((!fieldDef->mIsStatic) && (initializer != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  16032. {
  16033. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  16034. {
  16035. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  16036. sourceClassifier->VisitChild(initializer);
  16037. }
  16038. BfType* wantType = NULL;
  16039. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) &&
  16040. (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  16041. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowInferredSizedArray);
  16042. if ((wantType != NULL) &&
  16043. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  16044. wantType = NULL;
  16045. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  16046. if (fieldDef->mIsAppend)
  16047. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  16048. CreateValueFromExpression(initializer, wantType, exprFlags);
  16049. }
  16050. }
  16051. tempTypeDef->PopulateMemberSets();
  16052. BfMemberSetEntry* entry = NULL;
  16053. BfMethodDef* initMethodDef = NULL;
  16054. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  16055. if (entry != NULL)
  16056. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  16057. SizedArray<BfAstNode*, 8> initBodies;
  16058. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  16059. {
  16060. if (initMethodDef->mMethodType != BfMethodType_Init)
  16061. continue;
  16062. initBodies.Insert(0, initMethodDef->mBody);
  16063. }
  16064. for (auto body : initBodies)
  16065. VisitEmbeddedStatement(body);
  16066. }
  16067. }
  16068. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  16069. for (auto fieldDef : typeDef->mFields)
  16070. {
  16071. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->GetInitializer() != NULL))
  16072. {
  16073. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  16074. if (fieldDef->GetInitializer() != NULL)
  16075. MarkFieldInitialized(fieldInst);
  16076. }
  16077. }
  16078. RestoreScopeState();
  16079. }
  16080. }
  16081. if (!methodInstance->mIsAutocompleteMethod)
  16082. {
  16083. if (auto autoDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  16084. {
  16085. BfExprEvaluator exprEvaluator(this);
  16086. for (int paramIdx = 0; paramIdx < methodDef->mParams.mSize; paramIdx++)
  16087. {
  16088. auto paramDef = methodDef->mParams[paramIdx];
  16089. auto& fieldInstance = mCurTypeInstance->mFieldInstances[paramIdx];
  16090. BF_ASSERT(paramDef->mName == fieldInstance.GetFieldDef()->mName);
  16091. if (fieldInstance.mDataIdx < 0)
  16092. continue;
  16093. if (paramDef->mParamKind != BfParamKind_Normal)
  16094. continue;
  16095. auto localVar = mCurMethodState->mLocals[paramIdx + 1];
  16096. BF_ASSERT(localVar->mName == paramDef->mName);
  16097. auto localVal = exprEvaluator.LoadLocal(localVar);
  16098. localVal = LoadOrAggregateValue(localVal);
  16099. if (!localVal.mType->IsVar())
  16100. {
  16101. auto thisVal = GetThis();
  16102. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance.mDataIdx);
  16103. if (mCurTypeInstance->IsUnion())
  16104. fieldPtr = mBfIRBuilder->CreateBitCast(fieldPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInstance.mResolvedType)));
  16105. mBfIRBuilder->CreateAlignedStore(localVal.mValue, fieldPtr, localVar->mResolvedType->mAlign);
  16106. }
  16107. MarkFieldInitialized(&fieldInstance);
  16108. }
  16109. }
  16110. }
  16111. // Call base ctor (if applicable)
  16112. BfTypeInstance* targetType = NULL;
  16113. BfAstNode* targetRefNode = NULL;
  16114. if (ctorDeclaration != NULL)
  16115. targetRefNode = ctorDeclaration->mInitializer;
  16116. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  16117. targetRefNode = invocationExpr->mTarget;
  16118. if (targetRefNode == NULL)
  16119. targetRefNode = mCurTypeInstance->mTypeDef->GetRefNode();
  16120. if (baseCtorNode != NULL)
  16121. {
  16122. UpdateSrcPos(baseCtorNode);
  16123. if (methodDef->mBody == NULL)
  16124. SetIllegalSrcPos();
  16125. }
  16126. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16127. {
  16128. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  16129. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  16130. }
  16131. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()) && (methodDef->mMethodType != BfMethodType_CtorNoBody))
  16132. {
  16133. auto baseType = mCurTypeInstance->mBaseType;
  16134. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  16135. ((baseType->mTypeDef != mCompiler->mValueTypeTypeDef) || (!mContext->mCanSkipValueTypeCtor)) &&
  16136. ((baseType->mTypeDef != mCompiler->mBfObjectTypeDef) || (!mContext->mCanSkipObjectCtor)))
  16137. {
  16138. // Try to find a ctor without any params first
  16139. BfMethodDef* matchedMethod = NULL;
  16140. bool hadCtorWithAllDefaults = false;
  16141. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  16142. for (int pass = 0; pass < 2; pass++)
  16143. {
  16144. baseType->mTypeDef->PopulateMemberSets();
  16145. BfMemberSetEntry* entry = NULL;
  16146. BfMethodDef* checkMethodDef = NULL;
  16147. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  16148. if (entry != NULL)
  16149. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  16150. while (checkMethodDef != NULL)
  16151. {
  16152. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  16153. if (isHiddenGenerated)
  16154. {
  16155. // Allow calling of the default base ctor if it is implicitly defined
  16156. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  16157. allowMethod = true;
  16158. }
  16159. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  16160. {
  16161. if (checkMethodDef->mParams.size() == 0)
  16162. {
  16163. if (matchedMethod != NULL)
  16164. {
  16165. // Has multiple matched methods - can happen from extensions
  16166. matchedMethod = NULL;
  16167. break;
  16168. }
  16169. matchedMethod = checkMethodDef;
  16170. }
  16171. else if (isHiddenGenerated)
  16172. {
  16173. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  16174. hadCtorWithAllDefaults = true;
  16175. }
  16176. }
  16177. checkMethodDef = checkMethodDef->mNextWithSameName;
  16178. }
  16179. if (matchedMethod != NULL)
  16180. break;
  16181. }
  16182. if ((HasExecutedOutput()) && (matchedMethod != NULL))
  16183. {
  16184. SizedArray<BfIRValue, 1> args;
  16185. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  16186. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  16187. {
  16188. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  16189. args.push_back(basePtr);
  16190. }
  16191. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  16192. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  16193. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  16194. if (callingConv != BfIRCallingConv_CDecl)
  16195. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  16196. if (mIsComptimeModule)
  16197. mCompiler->mCeMachine->QueueMethod(ctorBodyMethodInstance);
  16198. }
  16199. if (matchedMethod == NULL)
  16200. {
  16201. targetType = mCurTypeInstance->mBaseType;
  16202. if (ctorDeclaration != NULL)
  16203. targetRefNode = ctorDeclaration->mThisToken;
  16204. else if ((typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mNameNode != NULL))
  16205. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  16206. }
  16207. }
  16208. }
  16209. if (methodDef->mHasAppend)
  16210. {
  16211. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  16212. }
  16213. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  16214. {
  16215. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  16216. {
  16217. if (targetType == mCurTypeInstance)
  16218. {
  16219. auto thisVariable = GetThisVariable();
  16220. if (thisVariable != NULL)
  16221. {
  16222. thisVariable->mUnassignedFieldFlags = 0;
  16223. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16224. }
  16225. }
  16226. targetType = NULL;
  16227. }
  16228. }
  16229. auto autoComplete = mCompiler->GetAutoComplete();
  16230. if ((targetType != NULL) && (!mCurTypeInstance->IsAnonymousInitializerType()))
  16231. {
  16232. BfAstNode* refNode = methodDeclaration;
  16233. if (refNode == NULL)
  16234. refNode = typeDef->mTypeDeclaration;
  16235. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  16236. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  16237. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16238. {
  16239. auto invocationExpr = ctorInvocation;
  16240. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  16241. }
  16242. BfType* targetThisType = targetType;
  16243. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  16244. BfExprEvaluator exprEvaluator(this);
  16245. BfResolvedArgs argValues;
  16246. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16247. {
  16248. argValues.Init(&ctorInvocation->mArguments);
  16249. if (gDebugStuff)
  16250. {
  16251. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  16252. }
  16253. }
  16254. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  16255. BfTypedValue appendIdxVal;
  16256. if (methodDef->mHasAppend)
  16257. {
  16258. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  16259. BF_ASSERT(localVar->mName == "appendIdx");
  16260. auto intRefType = localVar->mResolvedType;
  16261. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  16262. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  16263. }
  16264. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), methodDef->mHasAppend, &appendIdxVal);
  16265. if (autoComplete != NULL)
  16266. {
  16267. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  16268. {
  16269. if (autoComplete->mMethodMatchInfo != NULL)
  16270. autoComplete->mIsCapturingMethodMatchInfo = true;
  16271. else
  16272. autoComplete->mIsCapturingMethodMatchInfo = false;
  16273. }
  16274. else
  16275. autoComplete->mIsCapturingMethodMatchInfo = false;
  16276. }
  16277. }
  16278. auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration);
  16279. if ((autoComplete != NULL) && (autoComplete->CheckFixit(methodDeclaration)) && (methodDeclaration != NULL) && (autoCtorDecl != NULL))
  16280. {
  16281. auto typeDecl = methodDef->mDeclaringType->mTypeDeclaration;
  16282. BfParserData* parser = typeDecl->GetSourceData()->ToParserData();
  16283. if (parser != NULL)
  16284. {
  16285. String fixitStr = "Expand auto constructor\t";
  16286. int insertPos = typeDecl->mSrcStart;
  16287. bool needsBlock = false;
  16288. if (auto defBlock = BfNodeDynCast<BfBlock>(typeDecl->mDefineNode))
  16289. {
  16290. insertPos = defBlock->mOpenBrace->mSrcStart + 1;
  16291. }
  16292. else if (auto tokenNode = BfNodeDynCast<BfTokenNode>(typeDecl->mDefineNode))
  16293. {
  16294. insertPos = tokenNode->mSrcStart;
  16295. fixitStr += StrFormat("delete|%s-%d|\x01",
  16296. autoComplete->FixitGetLocation(parser, tokenNode->mSrcStart).c_str(), tokenNode->mSrcEnd - tokenNode->mSrcStart);
  16297. needsBlock = true;
  16298. }
  16299. int srcStart = methodDeclaration->mSrcStart;
  16300. if ((autoCtorDecl->mPrefix == NULL) && (typeDecl->mColonToken != NULL))
  16301. srcStart = typeDecl->mColonToken->mSrcStart;
  16302. while ((srcStart > 0) && (::isspace((uint8)parser->mSrc[srcStart - 1])))
  16303. srcStart--;
  16304. fixitStr += StrFormat("expand|%s|%d|",
  16305. parser->mFileName.c_str(), insertPos);
  16306. if (needsBlock)
  16307. fixitStr += "\t";
  16308. else
  16309. fixitStr += "\f";
  16310. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16311. {
  16312. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16313. paramStr.Replace('\n', '\r');
  16314. fixitStr += "public ";
  16315. fixitStr += paramStr;
  16316. fixitStr += ";\r";
  16317. }
  16318. fixitStr += "\rpublic this(";
  16319. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16320. {
  16321. if (paramIdx > 0)
  16322. fixitStr += ", ";
  16323. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16324. paramStr.Replace('\n', '\r');
  16325. fixitStr += paramStr;
  16326. }
  16327. fixitStr += ")\t";
  16328. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16329. {
  16330. if (paramIdx > 0)
  16331. fixitStr += "\r";
  16332. auto nameNode = autoCtorDecl->mParams[paramIdx]->mNameNode;
  16333. if (nameNode == NULL)
  16334. continue;
  16335. String nameStr = nameNode->ToString();
  16336. fixitStr += "this.";
  16337. fixitStr += nameStr;
  16338. fixitStr += " = ";
  16339. fixitStr += nameStr;
  16340. fixitStr += ";";
  16341. }
  16342. fixitStr += "\b";
  16343. if (needsBlock)
  16344. fixitStr += "\b";
  16345. fixitStr += StrFormat("\x01""delete|%s-%d|",
  16346. autoComplete->FixitGetLocation(parser, srcStart).c_str(), autoCtorDecl->mSrcEnd - srcStart);
  16347. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", fixitStr.c_str()));
  16348. }
  16349. }
  16350. }
  16351. void BfModule::EmitEnumToStringBody()
  16352. {
  16353. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16354. auto strVal = CreateAlloca(stringType);
  16355. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  16356. BfExprEvaluator exprEvaluator(this);
  16357. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16358. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  16359. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  16360. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  16361. BfType* discriminatorType = NULL;
  16362. BfTypedValue rawPayload;
  16363. BfIRValue enumVal;
  16364. if (mCurTypeInstance->IsPayloadEnum())
  16365. {
  16366. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  16367. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  16368. enumTypedValue = LoadValue(enumTypedValue);
  16369. enumVal = enumTypedValue.mValue;
  16370. rawPayload = ExtractValue(GetThis(), NULL, 1);
  16371. }
  16372. else
  16373. enumVal = mBfIRBuilder->GetArgument(0);
  16374. Array<BfType*> paramTypes;
  16375. paramTypes.Add(stringType);
  16376. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16377. BfIRValue switchVal;
  16378. if (!mCurTypeInstance->IsValuelessType())
  16379. switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  16380. HashSet<int64> handledCases;
  16381. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16382. {
  16383. if (fieldInstance.mIsEnumPayloadCase)
  16384. {
  16385. int tagId = -fieldInstance.mDataIdx - 1;
  16386. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16387. mBfIRBuilder->AddBlock(caseBlock);
  16388. mBfIRBuilder->SetInsertPoint(caseBlock);
  16389. BF_ASSERT(discriminatorType->IsPrimitiveType());
  16390. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  16391. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16392. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16393. auto stringDestVal = LoadValue(stringDestAddr);
  16394. SizedArray<BfIRValue, 2> args;
  16395. args.Add(stringDestVal.mValue);
  16396. args.Add(caseStr);
  16397. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16398. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  16399. BF_ASSERT(payloadType->IsTuple());
  16400. if (payloadType->mFieldInstances.size() != 0)
  16401. {
  16402. auto payload = rawPayload;
  16403. if (payload.mType != payloadType)
  16404. {
  16405. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  16406. }
  16407. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  16408. SizedArray<BfIRValue, 2> irArgs;
  16409. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  16410. stringDestVal = LoadValue(stringDestAddr);
  16411. irArgs.Add(stringDestVal.mValue);
  16412. exprEvaluator.CreateCall(NULL, toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  16413. }
  16414. mBfIRBuilder->CreateBr(endBlock);
  16415. continue;
  16416. }
  16417. if (fieldInstance.mConstIdx == -1)
  16418. continue;
  16419. // Only allow compact 'ValA, ValB' enum declaration fields through
  16420. auto fieldDef = fieldInstance.GetFieldDef();
  16421. auto fieldDecl = fieldDef->mFieldDeclaration;
  16422. if ((fieldDecl == NULL) || (fieldDef->mTypeRef != NULL))
  16423. continue;
  16424. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  16425. if (!handledCases.TryAdd(constant->mInt64, NULL))
  16426. {
  16427. // Duplicate
  16428. continue;
  16429. }
  16430. if (switchVal)
  16431. {
  16432. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16433. mBfIRBuilder->AddBlock(caseBlock);
  16434. mBfIRBuilder->SetInsertPoint(caseBlock);
  16435. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  16436. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16437. }
  16438. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16439. mBfIRBuilder->CreateStore(caseStr, strVal);
  16440. mBfIRBuilder->CreateBr(appendBlock);
  16441. }
  16442. mBfIRBuilder->AddBlock(appendBlock);
  16443. mBfIRBuilder->SetInsertPoint(appendBlock);
  16444. SizedArray<BfIRValue, 2> args;
  16445. auto stringDestVal = LoadValue(stringDestAddr);
  16446. args.Add(stringDestVal.mValue);
  16447. args.Add(mBfIRBuilder->CreateLoad(strVal));
  16448. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16449. if (switchVal)
  16450. {
  16451. mBfIRBuilder->CreateBr(endBlock);
  16452. mBfIRBuilder->AddBlock(noMatchBlock);
  16453. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  16454. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  16455. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  16456. args.clear();
  16457. args.Add(int64Val);
  16458. stringDestVal = LoadValue(stringDestAddr);
  16459. args.Add(stringDestVal.mValue);
  16460. exprEvaluator.CreateCall(NULL, toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  16461. mBfIRBuilder->CreateBr(endBlock);
  16462. mBfIRBuilder->AddBlock(endBlock);
  16463. mBfIRBuilder->SetInsertPoint(endBlock);
  16464. }
  16465. }
  16466. void BfModule::EmitTupleToStringBody()
  16467. {
  16468. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16469. BfExprEvaluator exprEvaluator(this);
  16470. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16471. Array<BfType*> paramTypes;
  16472. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  16473. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16474. paramTypes.Clear();
  16475. paramTypes.Add(stringType);
  16476. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16477. auto _AppendChar = [&](char c)
  16478. {
  16479. SizedArray<BfIRValue, 2> args;
  16480. auto stringDestVal = LoadValue(stringDestRef);
  16481. args.Add(stringDestVal.mValue);
  16482. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  16483. exprEvaluator.CreateCall(NULL, appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  16484. };
  16485. int fieldIdx = 0;
  16486. auto thisValue = GetThis();
  16487. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  16488. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  16489. BfIRValue commaStr;
  16490. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  16491. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  16492. _AppendChar('(');
  16493. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16494. {
  16495. if (fieldInstance.mDataIdx == -1)
  16496. continue;
  16497. if (fieldIdx > 0)
  16498. {
  16499. if (!commaStr)
  16500. commaStr = GetStringObjectValue(", ");
  16501. SizedArray<BfIRValue, 2> args;
  16502. auto stringDestVal = LoadValue(stringDestRef);
  16503. args.Add(stringDestVal.mValue);
  16504. args.Add(commaStr);
  16505. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16506. }
  16507. fieldIdx++;
  16508. if (fieldInstance.mResolvedType->IsValuelessType())
  16509. continue;
  16510. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  16511. if (fieldValue.mType->IsWrappableType())
  16512. {
  16513. auto wrappedType = GetWrappedStructType(fieldValue.mType);
  16514. if ((wrappedType->IsTypedPrimitive()) || (wrappedType->IsValuelessType()))
  16515. {
  16516. fieldValue.mType = wrappedType;
  16517. }
  16518. else
  16519. {
  16520. fieldValue = MakeAddressable(fieldValue);
  16521. fieldValue.mType = wrappedType;
  16522. fieldValue.mValue = mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapTypeInstPtr(fieldValue.mType->ToTypeInstance()));
  16523. if (!wrappedType->IsValuelessType())
  16524. fieldValue.mKind = BfTypedValueKind_Addr;
  16525. }
  16526. }
  16527. auto typeInstance = fieldValue.mType->ToTypeInstance();
  16528. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  16529. {
  16530. BfExprEvaluator exprEvaluator(this);
  16531. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16532. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16533. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  16534. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  16535. methodMatcher.TryDevirtualizeCall(fieldValue);
  16536. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16537. BfResolvedArg resolvedArg;
  16538. auto stringDestVal = LoadValue(stringDestRef);
  16539. resolvedArg.mTypedValue = stringDestVal;
  16540. resolvedArg.mResolvedType = stringDestVal.mType;
  16541. resolvedArgs.Add(resolvedArg);
  16542. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16543. continue;
  16544. }
  16545. if (fieldValue.mType->IsObjectOrInterface())
  16546. {
  16547. fieldValue = LoadValue(fieldValue);
  16548. BF_ASSERT(!fieldValue.IsAddr());
  16549. SizedArray<BfIRValue, 2> args;
  16550. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16551. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16552. stringDestVal = LoadValue(stringDestVal);
  16553. args.Add(stringDestVal.mValue);
  16554. exprEvaluator.CreateCall(NULL, toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  16555. continue;
  16556. }
  16557. BfExprEvaluator exprEvaluator(this);
  16558. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16559. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16560. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  16561. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  16562. methodMatcher.TryDevirtualizeCall(fieldValue);
  16563. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  16564. {
  16565. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  16566. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  16567. // Just append the type name
  16568. String typeName = TypeToString(fieldInstance.mResolvedType);
  16569. auto strVal = GetStringObjectValue(typeName);
  16570. SizedArray<BfIRValue, 2> args;
  16571. auto stringDestVal = LoadValue(stringDestRef);
  16572. args.Add(stringDestVal.mValue);
  16573. args.Add(strVal);
  16574. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16575. continue;
  16576. }
  16577. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16578. BfResolvedArg resolvedArg;
  16579. auto stringDestVal = LoadValue(stringDestRef);
  16580. resolvedArg.mTypedValue = stringDestVal;
  16581. resolvedArg.mResolvedType = stringDestVal.mType;
  16582. resolvedArgs.Add(resolvedArg);
  16583. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16584. }
  16585. _AppendChar(')');
  16586. }
  16587. void BfModule::EmitIteratorBlock(bool& skipBody)
  16588. {
  16589. auto methodInstance = mCurMethodInstance;
  16590. auto methodDef = methodInstance->mMethodDef;
  16591. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16592. auto typeDef = mCurTypeInstance->mTypeDef;
  16593. BfType* innerRetType = NULL;
  16594. BfTypeInstance* usingInterface = NULL;
  16595. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  16596. if (retTypeInst != NULL)
  16597. {
  16598. if ((retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef)) ||
  16599. (retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumeratorTypeDef)))
  16600. {
  16601. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  16602. }
  16603. }
  16604. if (innerRetType == NULL)
  16605. {
  16606. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  16607. return;
  16608. }
  16609. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  16610. if (blockBody == NULL)
  16611. return;
  16612. }
  16613. void BfModule::EmitGCMarkAppended(BfTypedValue markVal)
  16614. {
  16615. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  16616. if (gcType == NULL)
  16617. return;
  16618. BfModuleMethodInstance markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "MarkAppendedObject", 1);
  16619. if (!markFromGCThreadMethodInstance)
  16620. return;
  16621. SizedArray<BfIRValue, 1> args;
  16622. args.push_back(mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16623. BfExprEvaluator exprEvaluator(this);
  16624. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16625. }
  16626. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  16627. {
  16628. auto fieldType = markVal.mType;
  16629. auto fieldTypeInst = fieldType->ToTypeInstance();
  16630. if (fieldType == NULL)
  16631. return;
  16632. if (!markVal.mType->IsComposite())
  16633. markVal = LoadValue(markVal);
  16634. BfExprEvaluator exprEvaluator(this);
  16635. PopulateType(markVal.mType, BfPopulateType_Data);
  16636. if (markVal.mType->IsObjectOrInterface())
  16637. {
  16638. BfIRValue val = markVal.mValue;
  16639. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  16640. SizedArray<BfIRValue, 1> args;
  16641. args.push_back(val);
  16642. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16643. }
  16644. else if (fieldType->IsSizedArray())
  16645. {
  16646. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)fieldType;
  16647. if (sizedArrayType->mElementType->WantsGCMarking())
  16648. {
  16649. BfTypedValue arrayValue = markVal;
  16650. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  16651. auto itr = CreateAlloca(intPtrType);
  16652. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  16653. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  16654. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  16655. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  16656. mBfIRBuilder->CreateBr(loopBB);
  16657. mBfIRBuilder->SetInsertPoint(loopBB);
  16658. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  16659. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  16660. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  16661. mBfIRBuilder->SetInsertPoint(bodyBB);
  16662. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16663. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16664. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  16665. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16666. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16667. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  16668. mBfIRBuilder->CreateStore(incValue, itr);
  16669. mBfIRBuilder->CreateBr(loopBB);
  16670. mBfIRBuilder->SetInsertPoint(doneBB);
  16671. }
  16672. }
  16673. else if ((fieldType->IsComposite()) && (!fieldType->IsTypedPrimitive()) && (fieldTypeInst != NULL))
  16674. {
  16675. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  16676. if (markMemberMethodInstance)
  16677. {
  16678. SizedArray<BfIRValue, 1> args;
  16679. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  16680. if (markVal.mType != methodOwner)
  16681. markVal = Cast(NULL, markVal, methodOwner);
  16682. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  16683. exprEvaluator.CreateCall(NULL, markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  16684. }
  16685. }
  16686. }
  16687. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  16688. {
  16689. Array<BfMethodInstance*> methodInstances;
  16690. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  16691. {
  16692. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  16693. auto chainedMethodInst = methodInstGroup.mDefault;
  16694. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  16695. {
  16696. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  16697. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  16698. {
  16699. methodInstances.push_back(chainedMethodInst);
  16700. }
  16701. }
  16702. }
  16703. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  16704. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  16705. {
  16706. bool isBetter;
  16707. bool isWorse;
  16708. CompareDeclTypes(mCurTypeInstance, lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  16709. if (isBetter == isWorse)
  16710. {
  16711. return false;
  16712. }
  16713. return isWorse;
  16714. });
  16715. if (reverse)
  16716. std::reverse(methodInstances.begin(), methodInstances.end());
  16717. for (auto chainedMethodInst : methodInstances)
  16718. {
  16719. auto declModule = this;
  16720. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  16721. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  16722. BfExprEvaluator exprEvaluator(this);
  16723. SizedArray<BfIRValue, 1> args;
  16724. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  16725. exprEvaluator.CreateCall(NULL, moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  16726. }
  16727. }
  16728. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  16729. {
  16730. BF_ASSERT(mCurMethodInstance->mIsReified);
  16731. if (mCurTypeInstance->mHotTypeData == NULL)
  16732. {
  16733. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  16734. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  16735. }
  16736. auto hotMethod = mCurMethodInstance->mHotMethod;
  16737. for (auto depData : hotMethod->mReferences)
  16738. {
  16739. // Only virtual decls are allowed to already be there
  16740. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  16741. }
  16742. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  16743. int prevSize = (int)hotMethod->mReferences.size();
  16744. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  16745. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  16746. refCount++;
  16747. hotMethod->mReferences.Reserve(refCount);
  16748. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  16749. {
  16750. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  16751. hotThis->mRefCount++;
  16752. hotMethod->mReferences.Insert(0, hotThis);
  16753. prevSize++;
  16754. }
  16755. for (auto val : builder->mAllocatedData)
  16756. {
  16757. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  16758. hotMethod->mReferences.Add(hotAllocation);
  16759. }
  16760. for (auto val : builder->mUsedData)
  16761. hotMethod->mReferences.Add(val);
  16762. for (auto val : builder->mCalledMethods)
  16763. hotMethod->mReferences.Add(val);
  16764. for (auto val : builder->mDevirtualizedCalledMethods)
  16765. {
  16766. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  16767. hotMethod->mReferences.Add(devirtualizedMethod);
  16768. }
  16769. for (auto val : builder->mFunctionPtrs)
  16770. {
  16771. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  16772. hotMethod->mReferences.Add(funcRef);
  16773. }
  16774. for (auto val : builder->mInnerMethods)
  16775. {
  16776. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  16777. hotMethod->mReferences.Add(innerMethod);
  16778. }
  16779. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  16780. {
  16781. auto depData = hotMethod->mReferences[refIdx];
  16782. BF_ASSERT(depData != NULL);
  16783. depData->mRefCount++;
  16784. }
  16785. }
  16786. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  16787. {
  16788. auto methodDef = methodInstance->mMethodDef;
  16789. auto methodDeclaration = methodDef->mMethodDeclaration;
  16790. bool isThisStruct = false;
  16791. if (thisType != NULL)
  16792. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  16793. int argIdx = 0;
  16794. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16795. argIdx++;
  16796. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16797. if (!methodDef->mIsStatic)
  16798. {
  16799. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16800. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16801. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  16802. paramVar->mIsBumpAlloc = true;
  16803. paramVar->mResolvedType = thisType;
  16804. paramVar->mName.Reference("this");
  16805. if (!thisType->IsValuelessType())
  16806. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16807. else
  16808. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  16809. if ((!mIsComptimeModule) && (thisType->IsSplattable()) && (methodInstance->AllowsSplatting(-1)))
  16810. {
  16811. if (!thisType->IsTypedPrimitive())
  16812. paramVar->mIsSplat = true;
  16813. }
  16814. else if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  16815. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  16816. auto thisTypeInst = thisType->ToTypeInstance();
  16817. paramVar->mIsStruct = isThisStruct;
  16818. paramVar->mAddr = BfIRValue();
  16819. paramVar->mIsThis = true;
  16820. paramVar->mParamIdx = -1;
  16821. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  16822. {
  16823. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  16824. }
  16825. else
  16826. {
  16827. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16828. }
  16829. paramVar->mReadFromId = -1;
  16830. paramVar->Init();
  16831. if (methodDeclaration == NULL)
  16832. UseDefaultSrcPos();
  16833. AddLocalVariableDef(paramVar);
  16834. if (!thisType->IsValuelessType())
  16835. {
  16836. if (wantsDIData)
  16837. {
  16838. BfType* thisPtrType = thisType;
  16839. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  16840. if (!thisType->IsValueType())
  16841. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  16842. else if (!paramVar->mIsSplat)
  16843. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  16844. diParams->push_back(diType);
  16845. }
  16846. if (paramVar->mIsSplat)
  16847. {
  16848. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16849. }
  16850. else
  16851. {
  16852. argIdx++;
  16853. if (loweredTypeCode2 != BfTypeCode_None)
  16854. argIdx++;
  16855. }
  16856. }
  16857. }
  16858. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16859. argIdx++;
  16860. bool hadParams = false;
  16861. bool hasDefault = false;
  16862. int compositeVariableIdx = -1;
  16863. int paramIdx = 0;
  16864. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16865. {
  16866. // We already issues a type error for this param if we had one in declaration processing
  16867. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  16868. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  16869. paramVar->mIsBumpAlloc = true;
  16870. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16871. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16872. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  16873. auto resolvedType = methodInstance->GetParamType(paramIdx);
  16874. if (resolvedType == NULL)
  16875. {
  16876. AssertErrorState();
  16877. paramVar->mParamFailed = true;
  16878. }
  16879. prevIgnoreErrors.Restore();
  16880. PopulateType(resolvedType, BfPopulateType_Declaration);
  16881. paramVar->mResolvedType = resolvedType;
  16882. int namePrefixCount = 0;
  16883. methodInstance->GetParamName(paramIdx, paramVar->mName, namePrefixCount);
  16884. paramVar->mNamePrefixCount = (uint8)namePrefixCount;
  16885. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  16886. if (!isParamSkipped)
  16887. {
  16888. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16889. if (resolvedType->IsMethodRef())
  16890. {
  16891. paramVar->mIsSplat = true;
  16892. }
  16893. else if ((!mIsComptimeModule) && (resolvedType->IsComposite()) && (resolvedType->IsSplattable()))
  16894. {
  16895. if (methodInstance->AllowsSplatting(paramIdx))
  16896. {
  16897. auto resolveTypeInst = resolvedType->ToTypeInstance();
  16898. if ((resolveTypeInst != NULL) && (resolveTypeInst->mIsCRepr))
  16899. paramVar->mIsSplat = true;
  16900. else
  16901. {
  16902. int splatCount = resolvedType->GetSplatCount();
  16903. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16904. paramVar->mIsSplat = true;
  16905. }
  16906. }
  16907. }
  16908. }
  16909. else
  16910. {
  16911. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  16912. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  16913. }
  16914. paramVar->mIsLowered = (!mIsComptimeModule) && resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  16915. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  16916. paramVar->mParamIdx = paramIdx;
  16917. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  16918. paramVar->mReadFromId = 0;
  16919. if (resolvedType->IsRef())
  16920. {
  16921. auto refType = (BfRefType*)resolvedType;
  16922. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  16923. if (refType->mRefKind == BfRefType::RefKind_In)
  16924. {
  16925. paramVar->mIsReadOnly = true;
  16926. }
  16927. }
  16928. else
  16929. {
  16930. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16931. if (methodDef->mMethodType != BfMethodType_Mixin)
  16932. paramVar->mIsReadOnly = true;
  16933. }
  16934. if (paramVar->mResolvedType->IsGenericParam())
  16935. {
  16936. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  16937. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  16938. {
  16939. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  16940. paramVar->mResolvedType = typedVal.mType;
  16941. paramVar->mConstValue = typedVal.mValue;
  16942. }
  16943. }
  16944. if (paramVar->mResolvedType->IsConstExprValue())
  16945. {
  16946. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  16947. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  16948. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  16949. BF_ASSERT(unspecParamType->IsGenericParam());
  16950. if (unspecParamType->IsGenericParam())
  16951. {
  16952. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  16953. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  16954. {
  16955. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  16956. if (genericParamInst->mTypeConstraint != NULL)
  16957. {
  16958. BfExprEvaluator exprEvaluator(this);
  16959. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  16960. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  16961. auto checkType = genericParamInst->mTypeConstraint;
  16962. if (checkType->IsTypedPrimitive())
  16963. checkType = checkType->GetUnderlyingType();
  16964. auto typedVal = exprEvaluator.mResult;
  16965. if ((typedVal) && (typedVal.mType != checkType))
  16966. typedVal = Cast(NULL, typedVal, checkType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  16967. if ((typedVal.mType == checkType) && (typedVal.mValue.IsConst()))
  16968. {
  16969. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  16970. paramVar->mConstValue = typedVal.mValue;
  16971. BF_ASSERT(paramVar->mConstValue.IsConst());
  16972. paramVar->mIsConst = true;
  16973. }
  16974. else
  16975. {
  16976. AssertErrorState();
  16977. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  16978. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  16979. paramVar->mIsConst = true;
  16980. }
  16981. if (paramVar->mResolvedType->IsObject())
  16982. {
  16983. BfTypedValue typedVal(paramVar->mConstValue, paramVar->mResolvedType);
  16984. FixValueActualization(typedVal);
  16985. if (typedVal.mValue.IsConst())
  16986. paramVar->mConstValue = typedVal.mValue;
  16987. }
  16988. }
  16989. }
  16990. }
  16991. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  16992. if (paramVar->mResolvedType->IsConstExprValue())
  16993. {
  16994. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  16995. //AssertErrorState();
  16996. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  16997. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  16998. paramVar->mIsConst = true;
  16999. }
  17000. }
  17001. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  17002. {
  17003. if (compositeVariableIdx == -1)
  17004. {
  17005. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  17006. BfLocalVariable* localVar = new BfLocalVariable();
  17007. auto paramInst = &methodInstance->mParams[paramIdx];
  17008. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  17009. localVar->mName = paramDef->mName;
  17010. localVar->mNamePrefixCount = paramDef->mNamePrefixCount;
  17011. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  17012. localVar->mCompositeCount = 0;
  17013. DoAddLocalVariable(localVar);
  17014. }
  17015. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  17016. paramVar->mIsImplicitParam = true;
  17017. }
  17018. if (!mCurTypeInstance->IsDelegateOrFunction())
  17019. CheckVariableDef(paramVar);
  17020. paramVar->Init();
  17021. AddLocalVariableDef(paramVar);
  17022. if (!isParamSkipped)
  17023. {
  17024. if (wantsDIData)
  17025. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  17026. if (paramVar->mIsSplat)
  17027. {
  17028. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17029. }
  17030. else
  17031. {
  17032. argIdx++;
  17033. }
  17034. if (loweredTypeCode2 != BfTypeCode_None)
  17035. argIdx++;
  17036. }
  17037. }
  17038. // Try to find an ending delegate params composite
  17039. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  17040. {
  17041. auto paramDef = methodDef->mParams.back();
  17042. if (paramDef->mParamKind == BfParamKind_Params)
  17043. {
  17044. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  17045. if (paramsType == NULL)
  17046. {
  17047. // Had error or 'var'
  17048. }
  17049. else if (paramsType->IsGenericParam())
  17050. {
  17051. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  17052. if (genericParamInstance->mTypeConstraint != NULL)
  17053. {
  17054. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  17055. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  17056. ((typeInstConstraint != NULL) &&
  17057. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  17058. {
  17059. BfLocalVariable* localVar = new BfLocalVariable();
  17060. localVar->mName = paramDef->mName;
  17061. localVar->mResolvedType = paramsType;
  17062. localVar->mCompositeCount = 0;
  17063. DoAddLocalVariable(localVar);
  17064. }
  17065. }
  17066. }
  17067. else if (paramsType->IsDelegate())
  17068. {
  17069. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  17070. if (invokeMethodInstance != NULL)
  17071. {
  17072. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  17073. // and wasn't cleared by the preceding loop
  17074. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  17075. BfLocalVariable* localVar = new BfLocalVariable();
  17076. localVar->mName = paramDef->mName;
  17077. localVar->mResolvedType = paramsType;
  17078. localVar->mCompositeCount = 0;
  17079. DoAddLocalVariable(localVar);
  17080. }
  17081. }
  17082. }
  17083. }
  17084. }
  17085. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  17086. {
  17087. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  17088. // return;
  17089. auto startMethodState = mCurMethodState;
  17090. auto _ClearState = [&]()
  17091. {
  17092. mCurMethodState->mLocalMethods.Clear();
  17093. for (auto& local : mCurMethodState->mLocals)
  17094. {
  17095. if (local->mIsBumpAlloc)
  17096. local->~BfLocalVariable();
  17097. else
  17098. delete local;
  17099. }
  17100. mCurMethodState->mLocals.Clear();
  17101. mCurMethodState->mLocalVarSet.Clear();
  17102. };
  17103. while (true)
  17104. {
  17105. bool didWork = false;
  17106. // 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
  17107. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  17108. // however (compiler bug), so this is the safest way
  17109. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  17110. {
  17111. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  17112. {
  17113. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  17114. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  17115. if (!mHadBuildError)
  17116. {
  17117. // Process as a closure - that allows us to look back and see the const locals and stuff
  17118. BfClosureState closureState;
  17119. mCurMethodState->mClosureState = &closureState;
  17120. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17121. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  17122. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  17123. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  17124. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  17125. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17126. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  17127. _ClearState();
  17128. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  17129. {
  17130. auto localVar = new BfLocalVariable();
  17131. *localVar = constLocal;
  17132. DoAddLocalVariable(localVar);
  17133. }
  17134. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  17135. bool doProcess = !mCompiler->mCanceling;
  17136. if (doProcess)
  17137. {
  17138. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  17139. ProcessMethod(deferredLocalMethod->mMethodInstance);
  17140. }
  17141. }
  17142. delete deferredLocalMethod;
  17143. mContext->CheckLockYield();
  17144. didWork = true;
  17145. }
  17146. mCurMethodState->mDeferredLocalMethods.Clear();
  17147. }
  17148. for (auto& kv : mCurMethodState->mLocalMethodCache)
  17149. {
  17150. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  17151. }
  17152. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  17153. {
  17154. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  17155. {
  17156. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  17157. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  17158. BfClosureState closureState;
  17159. mCurMethodState->mClosureState = &closureState;
  17160. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17161. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  17162. if (lambdaInstance->mClosureTypeInstance != NULL)
  17163. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  17164. else
  17165. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  17166. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17167. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  17168. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  17169. _ClearState();
  17170. for (auto& constLocal : lambdaInstance->mConstLocals)
  17171. {
  17172. //if (constLocal.mIsThis)
  17173. {
  17174. // Valueless 'this'
  17175. closureState.mConstLocals.Add(constLocal);
  17176. }
  17177. /*else
  17178. {
  17179. auto localVar = new BfLocalVariable();
  17180. *localVar = constLocal;
  17181. DoAddLocalVariable(localVar);
  17182. }*/
  17183. }
  17184. BfMethodInstanceGroup methodInstanceGroup;
  17185. methodInstanceGroup.mOwner = mCurTypeInstance;
  17186. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  17187. bool doProcess = !mCompiler->mCanceling;
  17188. if (doProcess)
  17189. {
  17190. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  17191. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17192. ProcessMethod(lambdaInstance->mMethodInstance);
  17193. lambdaInstance->mMethodInstance->mMethodInstanceGroup = NULL;
  17194. if (lambdaInstance->mDtorMethodInstance != NULL)
  17195. {
  17196. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17197. auto startMethodState2 = mCurMethodState;
  17198. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  17199. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = NULL;
  17200. }
  17201. }
  17202. didWork = true;
  17203. }
  17204. mContext->CheckLockYield();
  17205. mCurMethodState->mDeferredLambdaInstances.Clear();
  17206. }
  17207. if (!didWork)
  17208. break;
  17209. }
  17210. }
  17211. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance, bool isAppendObject)
  17212. {
  17213. if (checkType->IsComposite())
  17214. PopulateType(checkType, BfPopulateType_Data);
  17215. if (!checkType->WantsGCMarking())
  17216. return;
  17217. auto typeInstance = checkType->ToTypeInstance();
  17218. bool callMarkMethod = false;
  17219. // Call the actual marking method
  17220. if (memberDepth == 0)
  17221. {
  17222. // Don't call marking method on self
  17223. }
  17224. else if (checkType->IsObjectOrInterface())
  17225. {
  17226. if (!objectOffsets.Add(curOffset))
  17227. {
  17228. return;
  17229. }
  17230. callMarkMethod = true;
  17231. }
  17232. else if (checkType->IsSizedArray())
  17233. {
  17234. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  17235. if (sizedArrayType->mElementType->WantsGCMarking())
  17236. {
  17237. BfTypedValue arrayValue = thisValue;
  17238. if (thisValue.mType != checkType)
  17239. {
  17240. BfIRValue srcValue = thisValue.mValue;
  17241. if (curOffset != 0)
  17242. {
  17243. if (!thisValue.mType->IsPointer())
  17244. {
  17245. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17246. auto int8PtrType = CreatePointerType(int8Type);
  17247. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  17248. }
  17249. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  17250. }
  17251. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  17252. }
  17253. if (sizedArrayType->mElementCount > 6)
  17254. {
  17255. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  17256. auto itr = CreateAlloca(intPtrType);
  17257. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  17258. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  17259. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  17260. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  17261. mBfIRBuilder->CreateBr(loopBB);
  17262. mBfIRBuilder->SetInsertPoint(loopBB);
  17263. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  17264. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  17265. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  17266. mBfIRBuilder->SetInsertPoint(bodyBB);
  17267. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17268. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17269. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  17270. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17271. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17272. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  17273. mBfIRBuilder->CreateStore(incValue, itr);
  17274. mBfIRBuilder->CreateBr(loopBB);
  17275. mBfIRBuilder->SetInsertPoint(doneBB);
  17276. }
  17277. else
  17278. {
  17279. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  17280. {
  17281. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17282. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17283. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  17284. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17285. HashSet<int> objectOffsets;
  17286. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17287. }
  17288. }
  17289. }
  17290. }
  17291. else if (typeInstance != NULL)
  17292. {
  17293. typeInstance->mTypeDef->PopulateMemberSets();
  17294. BfMemberSetEntry* entry = NULL;
  17295. BfMethodDef* methodDef = NULL;
  17296. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  17297. {
  17298. methodDef = (BfMethodDef*)entry->mMemberDef;
  17299. if (methodDef->HasBody())
  17300. {
  17301. callMarkMethod = true;
  17302. }
  17303. }
  17304. }
  17305. if (callMarkMethod)
  17306. {
  17307. BfTypedValue markValue;
  17308. auto memberType = checkType;
  17309. if (memberType->IsObjectOrInterface())
  17310. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  17311. auto memberPtrType = CreatePointerType(memberType);
  17312. if (curOffset == 0)
  17313. {
  17314. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17315. }
  17316. else
  17317. {
  17318. if (!thisValue.mType->IsPointer())
  17319. {
  17320. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17321. auto int8PtrType = CreatePointerType(int8Type);
  17322. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  17323. }
  17324. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  17325. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17326. }
  17327. if (isAppendObject)
  17328. EmitGCMarkAppended(markValue);
  17329. else
  17330. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17331. return;
  17332. }
  17333. auto methodDef = mCurMethodInstance->mMethodDef;
  17334. if (checkType->IsPayloadEnum())
  17335. {
  17336. for (auto& fieldInst : typeInstance->mFieldInstances)
  17337. {
  17338. if (!fieldInst.mIsEnumPayloadCase)
  17339. continue;
  17340. auto fieldDef = fieldInst.GetFieldDef();
  17341. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17342. }
  17343. return;
  17344. }
  17345. if (typeInstance == NULL)
  17346. return;
  17347. for (auto& fieldInst : typeInstance->mFieldInstances)
  17348. {
  17349. auto fieldDef = fieldInst.GetFieldDef();
  17350. if (fieldDef == NULL)
  17351. continue;
  17352. if (fieldDef->mIsStatic)
  17353. continue;
  17354. if (typeInstance == mCurTypeInstance)
  17355. {
  17356. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  17357. // we may be marking member values that can never contain a value anyway, but this is benign
  17358. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17359. continue;
  17360. }
  17361. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance, fieldInst.IsAppendedObject());
  17362. }
  17363. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  17364. {
  17365. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17366. }
  17367. }
  17368. void BfModule::EmitGCMarkMembers()
  17369. {
  17370. auto methodDef = mCurMethodInstance->mMethodDef;
  17371. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  17372. BfModuleMethodInstance markFromGCThreadMethodInstance;
  17373. if (gcType != NULL)
  17374. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  17375. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  17376. {
  17377. if (mCurTypeInstance->IsBoxed())
  17378. {
  17379. // This already gets filled in by the normal boxed forwarding
  17380. }
  17381. else
  17382. {
  17383. auto thisValue = GetThis();
  17384. if (thisValue.IsSplat())
  17385. {
  17386. BfIRFunction func = mCurMethodInstance->mIRFunction;
  17387. int argIdx = 0;
  17388. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  17389. {
  17390. if (checkType->IsStruct())
  17391. {
  17392. auto checkTypeInstance = checkType->ToTypeInstance();
  17393. if (checkTypeInstance->mBaseType != NULL)
  17394. checkTypeLambda(checkTypeInstance->mBaseType);
  17395. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  17396. {
  17397. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  17398. if (fieldInstance->mDataIdx >= 0)
  17399. checkTypeLambda(fieldInstance->GetResolvedType());
  17400. }
  17401. }
  17402. else if (checkType->IsMethodRef())
  17403. {
  17404. BFMODULE_FATAL(this, "Not handled");
  17405. }
  17406. else if (checkType->WantsGCMarking())
  17407. {
  17408. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  17409. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17410. argIdx++;
  17411. }
  17412. };
  17413. checkTypeLambda(thisValue.mType);
  17414. }
  17415. else if (!methodDef->mIsStatic)
  17416. {
  17417. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  17418. {
  17419. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  17420. if (moduleMethodInst)
  17421. {
  17422. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  17423. bool wantsBaseMarking = true;
  17424. if (methodBaseType == mContext->mBfObjectType)
  17425. {
  17426. wantsBaseMarking = false;
  17427. PopulateType(methodBaseType);
  17428. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  17429. {
  17430. if ((fieldInstance.GetFieldDef()->mDeclaringType->IsExtension()) &&
  17431. (fieldInstance.mResolvedType->WantsGCMarking()))
  17432. wantsBaseMarking = true;
  17433. }
  17434. }
  17435. if (wantsBaseMarking)
  17436. {
  17437. auto thisValue = GetThis();
  17438. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  17439. SizedArray<BfIRValue, 1> args;
  17440. if ((!mIsComptimeModule) && (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1)))
  17441. {
  17442. BfExprEvaluator exprEvaluator(this);
  17443. exprEvaluator.SplatArgs(baseValue, args);
  17444. }
  17445. else
  17446. {
  17447. args.push_back(baseValue.mValue);
  17448. }
  17449. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  17450. }
  17451. }
  17452. }
  17453. }
  17454. if (!methodDef->mIsStatic)
  17455. {
  17456. HashSet<int> objectOffsets;
  17457. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  17458. }
  17459. else
  17460. {
  17461. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17462. {
  17463. if (thisValue.IsSplat())
  17464. break;
  17465. auto fieldDef = fieldInst.GetFieldDef();
  17466. if (fieldDef == NULL)
  17467. continue;
  17468. if (IsThreadLocal(&fieldInst))
  17469. continue;
  17470. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  17471. {
  17472. // For extensions, only handle these fields in the appropriate extension
  17473. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17474. continue;
  17475. if (!fieldInst.mFieldIncluded)
  17476. continue;
  17477. auto fieldType = fieldInst.mResolvedType;
  17478. auto fieldDef = fieldInst.GetFieldDef();
  17479. BfTypedValue markVal;
  17480. if (fieldDef->mIsConst)
  17481. continue;
  17482. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17483. continue;
  17484. mBfIRBuilder->PopulateType(fieldType);
  17485. if (fieldType->IsValuelessType())
  17486. continue;
  17487. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  17488. {
  17489. StringT<512> staticVarName;
  17490. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  17491. if (staticVarName.StartsWith('#'))
  17492. continue;
  17493. markVal = ReferenceStaticField(&fieldInst);
  17494. }
  17495. else if (!fieldDef->mIsStatic)
  17496. {
  17497. if (fieldInst.IsAppendedObject())
  17498. {
  17499. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst.mDataIdx);
  17500. auto val = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  17501. markVal = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst.mResolvedType)), fieldInst.mResolvedType);
  17502. }
  17503. else
  17504. {
  17505. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  17506. }
  17507. }
  17508. if (markVal)
  17509. {
  17510. if (fieldInst.IsAppendedObject())
  17511. EmitGCMarkAppended(markVal);
  17512. else
  17513. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  17514. }
  17515. }
  17516. }
  17517. }
  17518. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17519. CallChainedMethods(mCurMethodInstance, false);
  17520. }
  17521. }
  17522. }
  17523. void BfModule::EmitGCFindTLSMembers()
  17524. {
  17525. auto methodDef = mCurMethodInstance->mMethodDef;
  17526. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  17527. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  17528. BF_ASSERT(reportTLSMark);
  17529. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17530. {
  17531. auto fieldDef = fieldInst.GetFieldDef();
  17532. if (fieldDef == NULL)
  17533. continue;
  17534. if (!IsThreadLocal(&fieldInst))
  17535. continue;
  17536. // For extensions, only handle these fields in the appropriate extension
  17537. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17538. continue;
  17539. if (!fieldInst.mFieldIncluded)
  17540. continue;
  17541. if (fieldDef->mIsConst)
  17542. continue;
  17543. auto fieldType = fieldInst.mResolvedType;
  17544. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17545. continue;
  17546. if (fieldType->IsValuelessType())
  17547. continue;
  17548. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  17549. if (markVal)
  17550. {
  17551. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  17552. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  17553. SizedArray<BfIRValue, 2> llvmArgs;
  17554. llvmArgs.push_back(fieldRefPtr);
  17555. llvmArgs.push_back(markFuncPtr);
  17556. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  17557. }
  17558. }
  17559. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17560. CallChainedMethods(mCurMethodInstance, false);
  17561. }
  17562. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup, bool forceIRWrites)
  17563. {
  17564. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  17565. if (mIsComptimeModule)
  17566. {
  17567. BF_ASSERT(!mCompiler->IsAutocomplete());
  17568. }
  17569. if (mAwaitingInitFinish)
  17570. FinishInit();
  17571. if ((methodInstance->mIsReified) && (!mCompiler->mIsResolveOnly))
  17572. {
  17573. BfLogSysM("REIFIED(ProcessMethod): %s %p Module: %s\n", methodInstance->mMethodDef->mName.c_str(), methodInstance, mModuleName.c_str());
  17574. }
  17575. // Reify types that are actually used - they don't get reified during method declaration
  17576. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  17577. {
  17578. auto _CheckType = [&](BfType* type)
  17579. {
  17580. if (!type->IsReified())
  17581. PopulateType(type, BfPopulateType_Declaration);
  17582. };
  17583. _CheckType(methodInstance->mReturnType);
  17584. for (auto& param : methodInstance->mParams)
  17585. {
  17586. _CheckType(param.mResolvedType);
  17587. }
  17588. }
  17589. if (!methodInstance->mIsReified)
  17590. BF_ASSERT(!mIsReified);
  17591. BF_ASSERT((!methodInstance->GetOwner()->IsUnspecializedTypeVariation()) || (mIsComptimeModule));
  17592. if (methodInstance->mMethodInfoEx != NULL)
  17593. {
  17594. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  17595. {
  17596. if (methodGenericArg->IsMethodRef())
  17597. {
  17598. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  17599. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  17600. }
  17601. }
  17602. }
  17603. if (mBfIRBuilder == NULL)
  17604. {
  17605. BfLogSysM("ProcessMethod %p calling EnsureIRBuilder\n", methodInstance);
  17606. EnsureIRBuilder();
  17607. }
  17608. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, (mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized) && (!forceIRWrites));
  17609. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  17610. {
  17611. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  17612. }
  17613. SetAndRestoreValue<bool> prevIsClassifying;
  17614. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  17615. (mCompiler->mResolvePassData != NULL))
  17616. {
  17617. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  17618. prevIsClassifying.Init(mCompiler->mResolvePassData->mIsClassifying, false);
  17619. }
  17620. if (methodInstance->mHasBeenProcessed)
  17621. {
  17622. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  17623. return;
  17624. }
  17625. if (methodInstance->mFailedConstraints)
  17626. {
  17627. // The only way this should be able to happen is if we fail our generic param check
  17628. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  17629. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  17630. methodInstance->mHasBeenProcessed = true;
  17631. return;
  17632. }
  17633. if (HasExecutedOutput())
  17634. {
  17635. BF_ASSERT(mIsModuleMutable);
  17636. }
  17637. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  17638. if (!mIsComptimeModule)
  17639. {
  17640. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  17641. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  17642. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  17643. {
  17644. auto owningModule = methodInstance->GetOwner()->mModule;
  17645. if (owningModule->mIsScratchModule)
  17646. {
  17647. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  17648. }
  17649. else
  17650. {
  17651. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  17652. if (owningModule->mOnDemandMethodCount > 0)
  17653. owningModule->mOnDemandMethodCount--;
  17654. }
  17655. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  17656. VerifyOnDemandMethods();
  17657. }
  17658. }
  17659. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  17660. // self-referencing append allocations in ctor@calcAppend
  17661. methodInstance->mHasBeenProcessed = true;
  17662. mIncompleteMethodCount--;
  17663. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  17664. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  17665. auto methodDef = methodInstance->mMethodDef;
  17666. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17667. if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  17668. mBfIRBuilder->mIgnoreWrites = true;
  17669. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  17670. {
  17671. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  17672. // so we get the new vdata for it
  17673. methodInstance->GetOwner()->mDirty = true;
  17674. }
  17675. int dependentGenericStartIdx = 0;
  17676. if ((methodDef->mIsLocalMethod) && (mCurMethodState != NULL)) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  17677. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  17678. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  17679. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  17680. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  17681. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  17682. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  17683. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors);
  17684. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, mIsComptimeModule);
  17685. if ((!mIsComptimeModule) && (methodInstance->mIsReified) &&
  17686. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  17687. {
  17688. mCurTypeInstance->mHasBeenInstantiated = true;
  17689. }
  17690. // Warnings are shown in the capture phase
  17691. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  17692. mIgnoreWarnings = true;
  17693. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  17694. UseDefaultSrcPos();
  17695. if ((mIsComptimeModule) && (methodDef->mIsStatic))
  17696. {
  17697. PopulateType(mCurTypeInstance, BfPopulateType_AllowStaticMethods);
  17698. }
  17699. else
  17700. {
  17701. // We may not actually be populated in relatively rare autocompelte cases
  17702. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  17703. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  17704. }
  17705. BfAstNode* nameNode = NULL;
  17706. if (methodDeclaration != NULL)
  17707. {
  17708. nameNode = methodDeclaration->mNameNode;
  17709. if (nameNode == NULL)
  17710. {
  17711. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  17712. nameNode = ctorDeclaration->mThisToken;
  17713. }
  17714. }
  17715. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  17716. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) &&
  17717. (methodDef->mIdx >= 0) && (!methodInstance->mIsForeignMethodDef))
  17718. {
  17719. if (methodInstance->GetExplicitInterface() == NULL)
  17720. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  17721. else
  17722. {
  17723. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  17724. {
  17725. auto ifaceInst = ifaceEntry.mInterfaceType;
  17726. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  17727. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17728. if (methodInstance->GetExplicitInterface() != ifaceInst)
  17729. continue;
  17730. ifaceInst->mTypeDef->PopulateMemberSets();
  17731. BfMethodDef* nextMethod = NULL;
  17732. BfMemberSetEntry* entry = NULL;
  17733. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17734. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17735. while (nextMethod != NULL)
  17736. {
  17737. auto checkMethod = nextMethod;
  17738. nextMethod = nextMethod->mNextWithSameName;
  17739. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  17740. if (implMethodInst == methodInstance)
  17741. {
  17742. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  17743. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  17744. }
  17745. }
  17746. }
  17747. }
  17748. if (methodDef->mIsOverride)
  17749. {
  17750. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  17751. {
  17752. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  17753. if (ventry.mDeclaringMethod.mMethodNum == -1)
  17754. continue;
  17755. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  17756. if (virtMethod != NULL)
  17757. {
  17758. if (virtMethod == methodInstance)
  17759. {
  17760. // Is matching method
  17761. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  17762. {
  17763. auto baseType = mCurTypeInstance->mBaseType;
  17764. if (baseType != NULL)
  17765. {
  17766. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  17767. baseType = baseType->mBaseType;
  17768. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  17769. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  17770. }
  17771. }
  17772. break;
  17773. }
  17774. }
  17775. }
  17776. }
  17777. }
  17778. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d Incomplete:%d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified, mIncompleteMethodCount);
  17779. int importStrNum = -1;
  17780. auto importKind = methodInstance->GetImportKind();
  17781. if ((!mCompiler->mIsResolveOnly) &&
  17782. ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic)))
  17783. {
  17784. if (auto customAttr = methodInstance->GetCustomAttributes()->Get(mCompiler->mImportAttributeTypeDef))
  17785. {
  17786. if (customAttr->mCtorArgs.size() == 1)
  17787. {
  17788. auto fileNameArg = customAttr->mCtorArgs[0];
  17789. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  17790. if (constant != NULL)
  17791. {
  17792. if (!constant->IsNull())
  17793. importStrNum = constant->mInt32;
  17794. }
  17795. else
  17796. {
  17797. importStrNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  17798. }
  17799. if (importStrNum != -1)
  17800. {
  17801. if (!mStringPoolRefs.Contains(importStrNum))
  17802. mStringPoolRefs.Add(importStrNum);
  17803. }
  17804. }
  17805. }
  17806. }
  17807. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  17808. {
  17809. if (mBfIRBuilder->mIgnoreWrites)
  17810. return;
  17811. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  17812. if (!methodInstance->mIRFunction)
  17813. {
  17814. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  17815. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  17816. BF_ASSERT(dllImportGlobalVar || methodInstance->mHasFailed);
  17817. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  17818. }
  17819. if (HasCompiledOutput())
  17820. {
  17821. BfDllImportEntry dllImportEntry;
  17822. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  17823. dllImportEntry.mMethodInstance = mCurMethodInstance;
  17824. mDllImportEntries.push_back(dllImportEntry);
  17825. }
  17826. return;
  17827. }
  17828. StringT<512> mangledName;
  17829. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  17830. if (!methodInstance->mIRFunction)
  17831. {
  17832. bool isIntrinsic = false;
  17833. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  17834. }
  17835. if (methodInstance->mIsIntrinsic)
  17836. return;
  17837. if (mCurTypeInstance->IsFunction())
  17838. return;
  17839. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  17840. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  17841. if (methodDef->mBody != NULL)
  17842. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17843. else if (methodDeclaration != NULL)
  17844. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17845. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17846. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  17847. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17848. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17849. if ((mCurMethodState == NULL) && (!IsInSpecializedSection())) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  17850. {
  17851. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()))
  17852. {
  17853. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(methodDef->mBody))
  17854. {
  17855. SetAndRestoreValue<bool> prevSkipAnonTypes(sourceClassifier->mSkipAnonymousTypes, true);
  17856. sourceClassifier->VisitChildNoRef(methodDef->mBody);
  17857. }
  17858. }
  17859. }
  17860. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  17861. BfMethodState methodState;
  17862. if (mCurMethodState != NULL)
  17863. methodState.mClosureState = mCurMethodState->mClosureState;
  17864. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  17865. {
  17866. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  17867. if (methodInstance->mHotMethod == NULL)
  17868. CheckHotMethod(methodInstance, mangledName);
  17869. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  17870. }
  17871. methodState.mPrevMethodState = mCurMethodState;
  17872. methodState.mMethodInstance = methodInstance;
  17873. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17874. if (methodInstance->GetCustomAttributes() != NULL)
  17875. {
  17876. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  17877. if (typeOptionsIdx != -1)
  17878. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  17879. }
  17880. BfTypeState typeState(mCurTypeInstance);
  17881. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  17882. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  17883. BfMethodInstance* unspecializedMethodInstance = NULL;
  17884. if ((prevMethodState.mPrevVal != NULL) &&
  17885. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  17886. {
  17887. // This is 'inner' (probably a closure) - use binding from outer function
  17888. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  17889. }
  17890. else if ((methodInstance->mIsUnspecialized) ||
  17891. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  17892. {
  17893. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17894. }
  17895. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  17896. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation || mIsComptimeModule) && (!methodInstance->mMethodDef->mIsLocalMethod) && (!methodInstance->mMethodDef->mDeclaringType->IsEmitted()))))
  17897. {
  17898. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  17899. if ((mIsComptimeModule) && (!unspecializedMethodInstance->mHasBeenProcessed))
  17900. {
  17901. // This will have already been populated by CeMachine
  17902. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17903. }
  17904. else
  17905. {
  17906. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  17907. if (!unspecializedMethodInstance->mHasBeenProcessed)
  17908. {
  17909. // Make sure the unspecialized method is processed so we can take its bindings
  17910. // Clear mCurMethodState so we don't think we're in a local method
  17911. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  17912. if (unspecializedMethodInstance->mMethodProcessRequest == NULL)
  17913. unspecializedMethodInstance->mDeclModule->mIncompleteMethodCount++;
  17914. mContext->ProcessMethod(unspecializedMethodInstance);
  17915. }
  17916. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17917. }
  17918. }
  17919. if (methodDef->mMethodType == BfMethodType_Operator)
  17920. {
  17921. auto operatorDef = (BfOperatorDef*) methodDef;
  17922. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  17923. auto paramErrorRefNode = refNode;
  17924. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  17925. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  17926. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  17927. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  17928. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  17929. {
  17930. if (methodDef->mParams.size() != 2)
  17931. {
  17932. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  17933. }
  17934. else
  17935. {
  17936. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17937. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17938. checkParam0 = checkParam0->GetUnderlyingType();
  17939. auto checkParam1 = mCurMethodInstance->GetParamType(1);
  17940. if ((checkParam1->IsRef()) && (!checkParam1->IsOut()))
  17941. checkParam1 = checkParam1->GetUnderlyingType();
  17942. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  17943. (checkParam1 != mCurTypeInstance) && (!checkParam1->IsSelf()))
  17944. {
  17945. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  17946. }
  17947. }
  17948. BfType* wantType = NULL;
  17949. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  17950. {
  17951. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  17952. }
  17953. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  17954. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  17955. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  17956. }
  17957. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  17958. {
  17959. if (methodDef->mIsStatic)
  17960. {
  17961. if (methodDef->mParams.size() != 1)
  17962. {
  17963. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  17964. }
  17965. else
  17966. {
  17967. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17968. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17969. checkParam0 = checkParam0->GetUnderlyingType();
  17970. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()))
  17971. {
  17972. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  17973. }
  17974. }
  17975. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  17976. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  17977. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  17978. {
  17979. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  17980. }
  17981. }
  17982. else
  17983. {
  17984. if (methodDef->mParams.size() != 0)
  17985. {
  17986. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  17987. }
  17988. if (!mCurMethodInstance->mReturnType->IsVoid())
  17989. {
  17990. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  17991. }
  17992. }
  17993. }
  17994. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  17995. {
  17996. if (methodDef->mParams.size() != 1)
  17997. {
  17998. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  17999. }
  18000. if (!mCurMethodInstance->mReturnType->IsVoid())
  18001. {
  18002. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  18003. }
  18004. }
  18005. else // Conversion
  18006. {
  18007. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  18008. {
  18009. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  18010. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  18011. }
  18012. if (methodDef->mParams.size() != 1)
  18013. {
  18014. auto refNode = paramErrorRefNode;
  18015. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  18016. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  18017. Fail("Conversion operators must declare one parameter", refNode);
  18018. }
  18019. else if ((methodInstance->mMethodInfoEx == NULL) ||
  18020. (methodInstance->mMethodInfoEx->mMethodGenericArguments.IsEmpty()) ||
  18021. ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation)))
  18022. {
  18023. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18024. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18025. checkParam0 = checkParam0->GetUnderlyingType();
  18026. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  18027. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  18028. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  18029. if (checkParam0 == mCurMethodInstance->mReturnType)
  18030. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  18031. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  18032. // happened here
  18033. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (checkParam0 != mContext->mBfObjectType)))
  18034. {
  18035. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  18036. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, checkParam0->ToTypeInstance());
  18037. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  18038. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  18039. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  18040. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  18041. }
  18042. }
  18043. }
  18044. }
  18045. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mBfIRBuilder->mIgnoreWrites) && (mHasFullDebugInfo);
  18046. if (methodDef->mMethodType == BfMethodType_Mixin)
  18047. wantsDIData = false;
  18048. if (mCurTypeInstance->IsUnspecializedType())
  18049. wantsDIData = false;
  18050. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  18051. wantsDIData = false;
  18052. bool wantsDIVariables = wantsDIData;
  18053. if (methodDef->mIsExtern)
  18054. wantsDIVariables = false;
  18055. SizedArray<BfIRMDNode, 8> diParams;
  18056. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  18057. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  18058. BfType* thisType = NULL;
  18059. if (!methodDef->mIsStatic)
  18060. {
  18061. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  18062. thisType = methodState.mClosureState->mClosureType;
  18063. else
  18064. thisType = mCurTypeInstance;
  18065. }
  18066. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  18067. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  18068. //////////////////////////////////////////////////////////////////////////
  18069. //
  18070. {
  18071. if (methodDeclaration != NULL)
  18072. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18073. else if (methodDef->mBody != NULL)
  18074. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18075. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18076. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  18077. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18078. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18079. }
  18080. BfIRMDNode diFunction;
  18081. if (wantsDIData)
  18082. {
  18083. BP_ZONE("BfModule::DoMethodDeclaration.DISetup");
  18084. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  18085. int defLine = mCurFilePosition.mCurLine;
  18086. if (mDICompileUnit)
  18087. {
  18088. int flags = 0;
  18089. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  18090. if (methodDef->mProtection == BfProtection_Public)
  18091. flags = llvm::DINode::FlagPublic;
  18092. else if (methodDef->mProtection == BfProtection_Protected)
  18093. flags = llvm::DINode::FlagProtected;
  18094. else
  18095. flags = llvm::DINode::FlagPrivate;
  18096. if (methodDef->mIsOverride)
  18097. {
  18098. //flags |= llvm::DINode::FlagVirtual;
  18099. }
  18100. else if (methodDef->mIsVirtual)
  18101. flags |= llvm::DINode::FlagIntroducedVirtual;
  18102. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  18103. flags |= llvm::DINode::FlagStaticMember;
  18104. else
  18105. {
  18106. if ((mCurTypeInstance->IsValuelessType()) ||
  18107. ((!mIsComptimeModule) && (mCurTypeInstance->IsSplattable())))
  18108. flags |= llvm::DINode::FlagStaticMember;
  18109. }
  18110. flags |= llvm::DINode::FlagPrototyped;
  18111. if (methodDef->mMethodType == BfMethodType_Ctor)
  18112. {
  18113. flags |= llvm::DINode::FlagArtificial;
  18114. }
  18115. auto llvmFunction = methodInstance->mIRFunction;
  18116. SizedArray<BfIRMDNode, 1> genericArgs;
  18117. SizedArray<BfIRValue, 1> genericConstValueArgs;
  18118. String methodName;
  18119. if (methodInstance->GetForeignType() != NULL)
  18120. {
  18121. methodName += TypeToString(methodInstance->GetForeignType());
  18122. methodName += ".";
  18123. }
  18124. if (methodInstance->GetExplicitInterface() != NULL)
  18125. {
  18126. methodName += TypeToString(methodInstance->GetExplicitInterface());
  18127. methodName += ".";
  18128. }
  18129. methodName += methodDef->mName;
  18130. if (methodInstance->GetNumGenericArguments() != 0)
  18131. {
  18132. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  18133. {
  18134. if (genericArg->IsConstExprValue())
  18135. {
  18136. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  18137. while (genericConstValueArgs.size() < genericArgs.size())
  18138. genericConstValueArgs.push_back(BfIRValue());
  18139. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  18140. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  18141. }
  18142. else
  18143. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  18144. }
  18145. methodName += "<";
  18146. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  18147. {
  18148. if (i > 0)
  18149. methodName += ", ";
  18150. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  18151. methodName += TypeToString(type);
  18152. }
  18153. methodName += ">";
  18154. }
  18155. if ((methodName.empty()) && (methodDeclaration != NULL))
  18156. {
  18157. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18158. {
  18159. methodName += "operator";
  18160. if (operatorDecl->mIsConvOperator)
  18161. {
  18162. methodName += " ";
  18163. methodName += TypeToString(methodInstance->mReturnType);
  18164. }
  18165. else if (operatorDecl->mOpTypeToken != NULL)
  18166. methodName += operatorDecl->mOpTypeToken->ToString();
  18167. }
  18168. }
  18169. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  18170. methodName += "$CHK";
  18171. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  18172. methodName += "$UCHK";
  18173. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18174. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18175. // defLine + 1, diFuncType, false, true,
  18176. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  18177. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  18178. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18179. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18180. defLine + 1, diFuncType, false, true,
  18181. llvm::dwarf::DW_VIRTUALITY_none,
  18182. 0,
  18183. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18184. }
  18185. else
  18186. {
  18187. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18188. }
  18189. }
  18190. //////////////////////////////////////////////////////////////////////////
  18191. // Head and Init get rolled into Entry afterwards.
  18192. methodState.mIRFunction = methodInstance->mIRFunction;
  18193. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  18194. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  18195. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  18196. methodState.mCurScope->mDIScope = diFunction;
  18197. auto llvmEntryBlock = methodState.mIREntryBlock;
  18198. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  18199. if (methodDef->mName == "__MALFORMED")
  18200. {
  18201. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  18202. mBfIRBuilder->SetInsertPoint(newBlock);
  18203. }
  18204. if (methodDef->mBody != NULL)
  18205. {
  18206. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18207. }
  18208. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  18209. {
  18210. // We want to be able to step into delegate invokes -- we actually step over them
  18211. if (methodDef->mName != "Invoke")
  18212. {
  18213. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18214. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  18215. }
  18216. }
  18217. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18218. mBfIRBuilder->ClearDebugLocation();
  18219. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  18220. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  18221. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  18222. {
  18223. int localIdx = 0;
  18224. int argIdx = 0;
  18225. Array<BfIRValue> splatAddrValues;
  18226. for ( ; argIdx < irParamCount; localIdx++)
  18227. {
  18228. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18229. if ((isThis) && (thisType->IsValuelessType()))
  18230. isThis = false;
  18231. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() == argIdx))
  18232. {
  18233. argIdx++;
  18234. if (argIdx == irParamCount)
  18235. break;
  18236. }
  18237. BfLocalVariable* paramVar = NULL;
  18238. while (true)
  18239. {
  18240. BF_ASSERT(localIdx < methodState.mLocals.size());
  18241. paramVar = methodState.mLocals[localIdx];
  18242. if ((paramVar->mCompositeCount == -1) &&
  18243. (!paramVar->mIsConst) &&
  18244. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  18245. break;
  18246. localIdx++;
  18247. }
  18248. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  18249. {
  18250. paramVar->mIsReadOnly = true;
  18251. }
  18252. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) ||
  18253. ((!mIsComptimeModule) && (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter)));
  18254. if (paramVar->mResolvedType->IsMethodRef())
  18255. wantsAddr = false;
  18256. // if ((methodDef->mHasAppend) && (argIdx == 1))
  18257. // {
  18258. // BF_ASSERT(paramVar->mName == "appendIdx");
  18259. // wantsAddr = true;
  18260. // }
  18261. if (paramVar->mIsSplat)
  18262. {
  18263. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18264. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18265. BfTypeUtils::SplatIterate([&](BfType* checkType)
  18266. {
  18267. BfIRType splatIRType;
  18268. if (checkType->IsComposite())
  18269. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  18270. else
  18271. splatIRType = mBfIRBuilder->MapType(checkType);
  18272. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  18273. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  18274. if (!paramVar->mAddr)
  18275. paramVar->mAddr = allocaInst;
  18276. if (WantsLifetimes())
  18277. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18278. splatAddrValues.push_back(allocaInst);
  18279. }, paramVar->mResolvedType);
  18280. mBfIRBuilder->SetInsertPoint(prevInsert);
  18281. }
  18282. else if (isThis)
  18283. {
  18284. if (wantsAddr)
  18285. {
  18286. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18287. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18288. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  18289. if (paramVar->mIsSplat)
  18290. {
  18291. //
  18292. }
  18293. else
  18294. {
  18295. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  18296. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  18297. wantPtr = true;
  18298. if (wantPtr)
  18299. {
  18300. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  18301. }
  18302. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  18303. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18304. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  18305. paramVar->mAddr = allocaInst;
  18306. if (WantsLifetimes())
  18307. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18308. }
  18309. mBfIRBuilder->SetInsertPoint(prevInsert);
  18310. }
  18311. }
  18312. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  18313. {
  18314. // Address doesn't change so we don't have to alloca it
  18315. BfIRType allocType;
  18316. int alignSize = mSystem->mPtrSize;
  18317. if (paramVar->mResolvedType->IsRef())
  18318. {
  18319. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18320. }
  18321. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  18322. {
  18323. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18324. alignSize = paramVar->mResolvedType->mAlign;
  18325. }
  18326. else
  18327. {
  18328. paramVar->mHasLocalStructBacking = true;
  18329. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  18330. if (typeInst != NULL)
  18331. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  18332. else
  18333. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  18334. }
  18335. if (wantsAddr)
  18336. {
  18337. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18338. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18339. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18340. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  18341. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18342. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  18343. paramVar->mAddr = allocaInst;
  18344. mBfIRBuilder->SetInsertPoint(prevInsert);
  18345. if (WantsLifetimes())
  18346. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18347. }
  18348. }
  18349. else if (wantsAddr)
  18350. {
  18351. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  18352. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18353. paramVar->mAddr = allocaInst;
  18354. }
  18355. if (paramVar->mIsSplat)
  18356. {
  18357. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18358. }
  18359. else if (paramVar->mIsLowered)
  18360. {
  18361. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18362. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18363. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18364. argIdx++;
  18365. if (loweredTypeCode2 != BfTypeCode_None)
  18366. argIdx++;
  18367. }
  18368. else
  18369. {
  18370. argIdx++;
  18371. }
  18372. }
  18373. if (methodDef->mBody != NULL)
  18374. UpdateSrcPos(methodDef->mBody);
  18375. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18376. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18377. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18378. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  18379. localIdx = 0;
  18380. argIdx = 0;
  18381. int splatAddrIdx = 0;
  18382. while (localIdx < (int)methodState.mLocals.size())
  18383. {
  18384. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  18385. argIdx++;
  18386. int curLocalIdx = localIdx++;
  18387. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  18388. if (paramVar->mIsConst)
  18389. continue;
  18390. if (!paramVar->IsParam())
  18391. continue;
  18392. if (paramVar->mCompositeCount != -1)
  18393. continue;
  18394. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18395. if ((isThis) && (thisType->IsValuelessType()))
  18396. isThis = false;
  18397. if (paramVar->mValue.IsArg())
  18398. BF_ASSERT(paramVar->mValue.mId == argIdx);
  18399. BfIRMDNode diVariable;
  18400. if (wantsDIData)
  18401. {
  18402. String paramName = paramVar->mName;
  18403. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18404. if (isThis)
  18405. {
  18406. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  18407. paramName = "__closure";
  18408. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18409. {
  18410. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18411. bool wantRef = paramVar->mResolvedType->IsComposite();
  18412. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  18413. wantRef = true;
  18414. if (wantRef)
  18415. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18416. }
  18417. else if (!paramVar->mResolvedType->IsValueType())
  18418. {
  18419. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  18420. }
  18421. }
  18422. else
  18423. {
  18424. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18425. {
  18426. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18427. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18428. diType = mBfIRBuilder->DbgCreateConstType(diType);
  18429. }
  18430. }
  18431. if (!paramVar->mIsSplat)
  18432. {
  18433. if ((paramVar->mParamIdx >= 0) && (paramVar->mParamIdx < methodInstance->mDefaultValues.mSize))
  18434. {
  18435. auto defaultValue = methodInstance->mDefaultValues[paramVar->mParamIdx];
  18436. auto constant = mCurTypeInstance->mConstHolder->GetConstant(defaultValue.mValue);
  18437. if ((constant != NULL) &&
  18438. ((BfIRConstHolder::IsIntable(constant->mTypeCode)) || (BfIRConstHolder::IsFloat(constant->mTypeCode))))
  18439. {
  18440. int64 writeVal = constant->mInt64;
  18441. if (constant->mTypeCode == BfTypeCode_Float)
  18442. {
  18443. // We need to do this because Singles are stored in mDouble, so we need to reduce here
  18444. float floatVal = (float)constant->mDouble;
  18445. writeVal = *(uint32*)&floatVal;
  18446. }
  18447. if (writeVal < 0)
  18448. paramName += StrFormat("$_%llu", -writeVal);
  18449. else
  18450. paramName += StrFormat("$%llu", writeVal);
  18451. }
  18452. }
  18453. if (paramVar->mResolvedType->IsValuelessType())
  18454. {
  18455. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  18456. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18457. }
  18458. else if (paramVar->mIsImplicitParam)
  18459. {
  18460. // Annotate this specially?
  18461. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18462. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18463. }
  18464. else
  18465. {
  18466. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18467. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18468. }
  18469. paramVar->mDbgVarInst = diVariable;
  18470. }
  18471. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  18472. {
  18473. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  18474. // {
  18475. // // Only add this placeholder if we don't have any values
  18476. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  18477. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18478. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  18479. // }
  18480. }
  18481. }
  18482. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  18483. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  18484. {
  18485. // Write our argument value into the .addr
  18486. mBfIRBuilder->ClearDebugLocation();
  18487. if (paramVar->mIsSplat)
  18488. {
  18489. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18490. //
  18491. }
  18492. else
  18493. {
  18494. bool handled = false;
  18495. if (paramVar->mIsLowered)
  18496. {
  18497. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18498. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18499. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  18500. {
  18501. BfIRValue targetAddr = paramVar->mAddr;
  18502. bool isTempTarget = false;
  18503. int loweredSize = mBfIRBuilder->GetSize(loweredTypeCode) + mBfIRBuilder->GetSize(loweredTypeCode2);
  18504. if (paramVar->mResolvedType->mSize < loweredSize)
  18505. {
  18506. isTempTarget = true;
  18507. targetAddr = CreateAlloca(GetPrimitiveType(BfTypeCode_Int8), true, NULL, GetConstValue(loweredSize));
  18508. mBfIRBuilder->SetAllocaAlignment(targetAddr,
  18509. BF_MAX(paramVar->mResolvedType->mAlign,
  18510. BF_MAX(mBfIRBuilder->GetSize(loweredTypeCode), mBfIRBuilder->GetSize(loweredTypeCode2))));
  18511. }
  18512. // We have a lowered type coming in, so we have to cast the .addr before storing
  18513. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  18514. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  18515. auto primPtrVal = mBfIRBuilder->CreateBitCast(targetAddr, primPtrType);
  18516. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, mCurTypeInstance->mAlign);
  18517. if (loweredTypeCode2 != BfTypeCode_None)
  18518. {
  18519. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  18520. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  18521. BfIRValue primPtrVal2;
  18522. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  18523. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  18524. else
  18525. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  18526. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  18527. }
  18528. if (isTempTarget)
  18529. {
  18530. auto castedTempPtr = mBfIRBuilder->CreateBitCast(targetAddr, mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType)));
  18531. auto tempVal = mBfIRBuilder->CreateAlignedLoad(castedTempPtr, paramVar->mResolvedType->mAlign);
  18532. mBfIRBuilder->CreateAlignedStore(tempVal, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  18533. }
  18534. // We don't want to allow directly using value
  18535. paramVar->mValue = BfIRValue();
  18536. handled = true;
  18537. }
  18538. else
  18539. {
  18540. BF_ASSERT("Expected lowered");
  18541. }
  18542. }
  18543. if (!handled)
  18544. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  18545. }
  18546. }
  18547. if (methodDef->mBody != NULL)
  18548. UpdateSrcPos(methodDef->mBody);
  18549. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  18550. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  18551. else if (methodDeclaration == NULL)
  18552. UseDefaultSrcPos();
  18553. // Write our argument value into the .addr
  18554. if (paramVar->mIsSplat)
  18555. {
  18556. int splatComponentIdx = 0;
  18557. auto curArgIdx = argIdx;
  18558. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  18559. {
  18560. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  18561. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  18562. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  18563. mBfIRBuilder->ClearDebugLocation(storeInst);
  18564. if (wantsDIData)
  18565. {
  18566. BfIRMDNode diType;
  18567. if (checkType->IsComposite())
  18568. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  18569. else
  18570. diType = mBfIRBuilder->DbgGetType(checkType);
  18571. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18572. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18573. if (wantsDIVariables)
  18574. {
  18575. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  18576. }
  18577. }
  18578. curArgIdx++;
  18579. splatComponentIdx++;
  18580. };
  18581. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  18582. {
  18583. if (checkType->IsStruct())
  18584. {
  18585. auto checkTypeInstance = checkType->ToTypeInstance();
  18586. if (checkTypeInstance->mBaseType != NULL)
  18587. {
  18588. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  18589. }
  18590. if (checkTypeInstance->mIsUnion)
  18591. {
  18592. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  18593. if (!unionInnerType->IsValuelessType())
  18594. {
  18595. _FinishSplatsIterate(unionInnerType, name + "$u");
  18596. }
  18597. if (checkTypeInstance->IsEnum())
  18598. {
  18599. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  18600. _FinishSplatsIterate(dscrType, name + "$d");
  18601. }
  18602. }
  18603. else
  18604. {
  18605. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  18606. {
  18607. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  18608. auto fieldDef = fieldInstance->GetFieldDef();
  18609. if (fieldInstance->mDataIdx >= 0)
  18610. {
  18611. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  18612. }
  18613. }
  18614. }
  18615. }
  18616. else if (checkType->IsMethodRef())
  18617. {
  18618. auto methodRefType = (BfMethodRefType*)checkType;
  18619. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  18620. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  18621. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  18622. // {
  18623. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  18624. // if (!paramType->IsValuelessType())
  18625. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  18626. // }
  18627. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  18628. {
  18629. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  18630. String paramName = methodInstance->GetParamName(paramIdx);
  18631. if (paramName == "this")
  18632. paramName = "__this";
  18633. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  18634. {
  18635. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  18636. }
  18637. else
  18638. {
  18639. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  18640. }
  18641. }
  18642. }
  18643. else if (!checkType->IsValuelessType())
  18644. {
  18645. _FinishSplats(checkType, name);
  18646. }
  18647. };
  18648. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18649. if (!paramVar->mConstValue)
  18650. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  18651. }
  18652. BfIRValue declareCall;
  18653. if (diVariable)
  18654. {
  18655. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  18656. {
  18657. if (!paramVar->mAddr)
  18658. {
  18659. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  18660. {
  18661. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  18662. {
  18663. // We don't need to set the location for this
  18664. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  18665. }
  18666. }
  18667. else
  18668. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  18669. }
  18670. else
  18671. {
  18672. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  18673. }
  18674. }
  18675. }
  18676. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  18677. {
  18678. // We don't allow actually assignment to "this", so we just do a single load
  18679. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  18680. // we need to store it in the stack frame for debugging purposes
  18681. auto loadedThis = mBfIRBuilder->CreateAlignedLoad(paramVar->mAddr/*, "this"*/, paramVar->mResolvedType->mAlign);
  18682. mBfIRBuilder->ClearDebugLocation(loadedThis);
  18683. paramVar->mValue = loadedThis;
  18684. }
  18685. if ((wantsDIData) && (declareCall))
  18686. mBfIRBuilder->UpdateDebugLocation(declareCall);
  18687. if (paramVar->mIsSplat)
  18688. {
  18689. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18690. }
  18691. else if (paramVar->mIsLowered)
  18692. {
  18693. argIdx++;
  18694. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18695. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18696. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18697. if (loweredTypeCode2 != BfTypeCode_None)
  18698. argIdx++;
  18699. }
  18700. else if (!paramVar->mResolvedType->IsValuelessType())
  18701. {
  18702. argIdx++;
  18703. }
  18704. }
  18705. if (wantsDIData)
  18706. {
  18707. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  18708. }
  18709. }
  18710. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  18711. {
  18712. auto paramVar = mCurMethodState->mLocals[varIdx];
  18713. // 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
  18714. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  18715. // if (paramVar->mIsSplat)
  18716. // {
  18717. // if (wantsDIVariables)
  18718. // {
  18719. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  18720. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  18721. // }
  18722. // }
  18723. if (paramVar->mResolvedType->IsValuelessType())
  18724. {
  18725. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  18726. {
  18727. // Only add this placeholder if we don't have any values
  18728. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18729. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  18730. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18731. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  18732. }
  18733. }
  18734. }
  18735. if (IsTargetingBeefBackend())
  18736. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  18737. if (methodState.mClosureState != NULL)
  18738. {
  18739. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  18740. {
  18741. BfLocalVariable* localVar = new BfLocalVariable();
  18742. *localVar = constLocal;
  18743. localVar->mIsBumpAlloc = false;
  18744. AddLocalVariableDef(localVar, true);
  18745. }
  18746. }
  18747. bool wantsRemoveBody = false;
  18748. bool skipBody = false;
  18749. bool skipUpdateSrcPos = false;
  18750. bool skipEndChecks = false;
  18751. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  18752. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18753. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  18754. hasExternSpecifier = true;
  18755. // Allocate, clear, set classVData
  18756. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  18757. {
  18758. CreateStaticCtor();
  18759. }
  18760. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  18761. {
  18762. skipBody = true;
  18763. skipEndChecks = true;
  18764. if (HasExecutedOutput())
  18765. {
  18766. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18767. mBfIRBuilder->ClearDebugLocation();
  18768. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  18769. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  18770. PopulateType(innerType, BfPopulateType_DataAndMethods);
  18771. mBfIRBuilder->PopulateType(mCurTypeInstance);
  18772. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  18773. if (methodInstance->mIsForeignMethodDef)
  18774. {
  18775. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  18776. }
  18777. BfTypeVector methodGenericArguments;
  18778. if (methodInstance->mMethodInfoEx != NULL)
  18779. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  18780. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  18781. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  18782. {
  18783. if (!methodInstance->mReturnType->IsValuelessType())
  18784. {
  18785. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  18786. CreateReturn(retVal);
  18787. }
  18788. else
  18789. mBfIRBuilder->CreateRetVoid();
  18790. }
  18791. else
  18792. {
  18793. auto innerMethodDef = innerMethodInstance.mMethodInstance->mMethodDef;
  18794. if ((innerMethodDef == methodDef != NULL) && (!CompareMethodSignatures(methodInstance, innerMethodInstance.mMethodInstance)))
  18795. {
  18796. InternalError("Boxing method passthrough error");
  18797. }
  18798. else
  18799. {
  18800. SizedArray<BfIRValue, 8> innerParams;
  18801. BfExprEvaluator exprEvaluator(this);
  18802. if (!innerType->IsValuelessType())
  18803. {
  18804. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  18805. BfTypedValue innerVal(thisValue, innerType, true);
  18806. if (boxedType->IsBoxedStructPtr())
  18807. {
  18808. innerVal = LoadValue(innerVal);
  18809. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  18810. }
  18811. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  18812. }
  18813. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  18814. {
  18815. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  18816. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  18817. exprEvaluator.PushArg(localVal, innerParams);
  18818. }
  18819. if (!innerMethodInstance.mFunc)
  18820. {
  18821. BF_ASSERT(innerType->IsUnspecializedType());
  18822. }
  18823. else if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  18824. {
  18825. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  18826. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  18827. exprEvaluator.mReceivingValue = &returnType;
  18828. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  18829. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  18830. mBfIRBuilder->CreateRetVoid();
  18831. }
  18832. else
  18833. {
  18834. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  18835. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  18836. if (mCurMethodInstance->mReturnType->IsValueType())
  18837. retVal = LoadValue(retVal);
  18838. CreateReturn(retVal.mValue);
  18839. }
  18840. }
  18841. }
  18842. }
  18843. mCurMethodState->SetHadReturn(true);
  18844. mCurMethodState->mLeftBlockUncond = true;
  18845. }
  18846. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  18847. {
  18848. SetIllegalSrcPos();
  18849. mBfIRBuilder->ClearDebugLocation();
  18850. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  18851. auto thisVal = GetThis();
  18852. int prevSize = 0;
  18853. if ((mContext->mBfObjectType != NULL) && (mCurTypeInstance->IsObject()))
  18854. {
  18855. prevSize = mContext->mBfObjectType->mInstSize;
  18856. PopulateType(mContext->mBfObjectType);
  18857. // If we have object extensions, clear out starting at the extension
  18858. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  18859. {
  18860. if (fieldInstance.GetFieldDef()->mDeclaringType->IsExtension())
  18861. {
  18862. prevSize = fieldInstance.mDataOffset;
  18863. break;
  18864. }
  18865. }
  18866. }
  18867. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  18868. int curSize = mCurTypeInstance->mInstSize;
  18869. if (curSize > prevSize)
  18870. {
  18871. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  18872. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  18873. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  18874. }
  18875. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  18876. {
  18877. auto useThis = mCurMethodState->mLocals[0]->mValue;
  18878. auto useThisType = mCurTypeInstance;
  18879. auto checkTypeInst = mCurTypeInstance;
  18880. while (checkTypeInst != NULL)
  18881. {
  18882. for (auto& fieldInstance : checkTypeInst->mFieldInstances)
  18883. {
  18884. auto fieldDef = fieldInstance.GetFieldDef();
  18885. if ((fieldDef == NULL) || (fieldDef->mIsStatic))
  18886. continue;
  18887. if (fieldInstance.IsAppendedObject())
  18888. {
  18889. if (checkTypeInst != useThisType)
  18890. {
  18891. useThis = mBfIRBuilder->CreateBitCast(useThis, mBfIRBuilder->MapType(checkTypeInst));
  18892. useThisType = checkTypeInst;
  18893. }
  18894. BfIRValue fieldAddr = mBfIRBuilder->CreateInBoundsGEP(useThis, 0, fieldInstance.mDataIdx);
  18895. auto int8PtrVal = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(int8PtrType));
  18896. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  18897. }
  18898. }
  18899. checkTypeInst = checkTypeInst->mBaseType;
  18900. }
  18901. }
  18902. skipUpdateSrcPos = true;
  18903. }
  18904. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  18905. {
  18906. EmitCtorBody(skipBody);
  18907. }
  18908. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  18909. {
  18910. EmitDtorBody();
  18911. skipBody = true;
  18912. }
  18913. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  18914. {
  18915. EmitIteratorBlock(skipBody);
  18916. }
  18917. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  18918. {
  18919. // We need to be able to mark deleted objects
  18920. mCurMethodState->mIgnoreObjectAccessCheck = true;
  18921. }
  18922. auto customAttributes = methodInstance->GetCustomAttributes();
  18923. if (customAttributes != NULL)
  18924. {
  18925. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  18926. mCurMethodState->mIgnoreObjectAccessCheck = true;
  18927. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  18928. mCurMethodState->mDisableChecks = true;
  18929. }
  18930. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  18931. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  18932. {
  18933. // We chain even non-default ctors to the default ctors
  18934. auto defaultCtor = methodInstance;
  18935. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  18936. CallChainedMethods(defaultCtor, false);
  18937. }
  18938. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  18939. if (!mCompiler->mHasRequiredTypes)
  18940. {
  18941. // Skip processing to avoid errors
  18942. }
  18943. else if (methodDef->mBody == NULL)
  18944. {
  18945. if (methodDeclaration != NULL)
  18946. {
  18947. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18948. {
  18949. if (operatorDeclaration->mIsConvOperator)
  18950. wantsRemoveBody = true;
  18951. }
  18952. }
  18953. bool isDllImport = false;
  18954. if ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic))
  18955. {
  18956. if (importStrNum != -1)
  18957. {
  18958. if (importKind == BfImportKind_Import_Static)
  18959. {
  18960. if (!mImportFileNames.Contains(importStrNum))
  18961. {
  18962. mImportFileNames.Add(importStrNum);
  18963. }
  18964. }
  18965. }
  18966. }
  18967. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  18968. {
  18969. CreateDllImportMethod();
  18970. }
  18971. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  18972. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  18973. {
  18974. if (mCurTypeInstance->mTypeDef->mIsFunction)
  18975. {
  18976. // Emit nothing
  18977. }
  18978. else
  18979. {
  18980. CreateDelegateInvokeMethod();
  18981. mCurMethodState->SetHadReturn(true);
  18982. mCurMethodState->mLeftBlockUncond = true;
  18983. }
  18984. }
  18985. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  18986. {
  18987. if (mCurTypeInstance->IsObject())
  18988. {
  18989. CreateDynamicCastMethod();
  18990. }
  18991. else
  18992. {
  18993. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  18994. mCurMethodState->mHadReturn = true;
  18995. }
  18996. }
  18997. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  18998. {
  18999. BfIRValue ret;
  19000. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  19001. {
  19002. // This can happen if we provide an invalid name
  19003. AssertErrorState();
  19004. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  19005. }
  19006. else
  19007. {
  19008. // Unfortunate DebugLoc shenanigans-
  19009. // 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,
  19010. // so we only set the loc on the CreateRet which gets inlined out
  19011. mBfIRBuilder->SaveDebugLocation();
  19012. mBfIRBuilder->ClearDebugLocation();
  19013. BfIRValue fromBool;
  19014. if ((!mCurTypeInstance->IsTypedPrimitive()) || (mCurTypeInstance->IsValuelessType()))
  19015. {
  19016. fromBool = GetDefaultValue(methodInstance->mReturnType);
  19017. }
  19018. else
  19019. {
  19020. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  19021. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  19022. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  19023. }
  19024. mBfIRBuilder->RestoreDebugLocation();
  19025. ret = mBfIRBuilder->CreateRet(fromBool);
  19026. //ExtendLocalLifetimes(0);
  19027. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19028. }
  19029. mCurMethodState->SetHadReturn(true);
  19030. mCurMethodState->mLeftBlockUncond = true;
  19031. }
  19032. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  19033. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  19034. {
  19035. BfIRValue ret;
  19036. // Unfortunate DebugLoc shenanigans-
  19037. // 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,
  19038. // so we only set the loc on the CreateRet which gets inlined out
  19039. mBfIRBuilder->SaveDebugLocation();
  19040. mBfIRBuilder->ClearDebugLocation();
  19041. BfIRValue fromBool;
  19042. mBfIRBuilder->RestoreDebugLocation();
  19043. if (!mCurTypeInstance->IsValuelessType())
  19044. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  19045. else
  19046. mBfIRBuilder->CreateRetVoid();
  19047. //ExtendLocalLifetimes(0);
  19048. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19049. mCurMethodState->SetHadReturn(true);
  19050. mCurMethodState->mLeftBlockUncond = true;
  19051. }
  19052. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  19053. {
  19054. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  19055. if (HasExecutedOutput())
  19056. {
  19057. EmitEnumToStringBody();
  19058. }
  19059. mBfIRBuilder->CreateRetVoid();
  19060. mCurMethodState->SetHadReturn(true);
  19061. mCurMethodState->mLeftBlockUncond = true;
  19062. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19063. }
  19064. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  19065. {
  19066. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  19067. if (HasExecutedOutput())
  19068. {
  19069. EmitTupleToStringBody();
  19070. }
  19071. mBfIRBuilder->CreateRetVoid();
  19072. mCurMethodState->SetHadReturn(true);
  19073. mCurMethodState->mLeftBlockUncond = true;
  19074. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19075. }
  19076. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  19077. {
  19078. CreateValueTypeEqualsMethod(false);
  19079. skipBody = true;
  19080. skipEndChecks = true;
  19081. }
  19082. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  19083. {
  19084. CreateValueTypeEqualsMethod(true);
  19085. skipBody = true;
  19086. skipEndChecks = true;
  19087. }
  19088. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef->GetDefinition() == mCompiler->mValueTypeTypeDef))
  19089. {
  19090. CreateValueTypeEqualsMethod(false);
  19091. skipBody = true;
  19092. skipEndChecks = true;
  19093. }
  19094. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (mCurTypeInstance->IsDelegate()))
  19095. {
  19096. CreateDelegateEqualsMethod();
  19097. skipBody = true;
  19098. skipEndChecks = true;
  19099. }
  19100. else
  19101. {
  19102. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  19103. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  19104. {
  19105. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  19106. Fail("Body expected", methodDef->mBody);
  19107. }
  19108. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  19109. {
  19110. if ((methodInstance->mReturnType->IsRef()) && (!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  19111. Fail("Auto-implemented ref property getters must declare 'mut'", methodInstance->mMethodDef->GetRefNode());
  19112. if (methodInstance->mReturnType->IsValuelessType())
  19113. {
  19114. mBfIRBuilder->CreateRetVoid();
  19115. }
  19116. else if (HasExecutedOutput())
  19117. {
  19118. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19119. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19120. BfFieldDef* fieldDef = NULL;
  19121. if (fieldInstance != NULL)
  19122. fieldDef = fieldInstance->GetFieldDef();
  19123. BfType* retType = methodInstance->mReturnType;
  19124. if (retType->IsRef())
  19125. retType = retType->GetUnderlyingType();
  19126. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  19127. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19128. {
  19129. BfTypedValue lookupValue;
  19130. if (fieldDef->IsNonConstStatic())
  19131. lookupValue = ReferenceStaticField(fieldInstance);
  19132. else if (mCurTypeInstance->IsObject())
  19133. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  19134. else
  19135. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  19136. if (methodInstance->mReturnType->IsRef())
  19137. {
  19138. if ((!lookupValue.IsAddr()) && (!lookupValue.mType->IsValuelessType()))
  19139. lookupValue = MakeAddressable(lookupValue);
  19140. }
  19141. else
  19142. lookupValue = LoadOrAggregateValue(lookupValue);
  19143. CreateReturn(lookupValue.mValue);
  19144. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19145. }
  19146. else
  19147. {
  19148. // This can happen if we have two properties with the same name but different types
  19149. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19150. EmitDefaultReturn();
  19151. }
  19152. }
  19153. else
  19154. {
  19155. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19156. EmitDefaultReturn();
  19157. }
  19158. mCurMethodState->SetHadReturn(true);
  19159. }
  19160. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  19161. {
  19162. if ((!methodDef->mIsMutating) && (!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  19163. {
  19164. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  19165. }
  19166. else if (!mCompiler->IsAutocomplete())
  19167. {
  19168. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19169. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19170. auto fieldDef = fieldInstance->GetFieldDef();
  19171. auto& lastParam = mCurMethodState->mLocals.back();
  19172. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  19173. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19174. {
  19175. BfIRValue lookupAddr;
  19176. if (fieldDef->IsNonConstStatic())
  19177. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  19178. else
  19179. {
  19180. auto thisValue = GetThis();
  19181. if (thisValue.IsSplat())
  19182. {
  19183. BFMODULE_FATAL(this, "Should not happen");
  19184. }
  19185. if (mCurTypeInstance->IsObject())
  19186. thisValue = LoadValue(thisValue);
  19187. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  19188. }
  19189. BfExprEvaluator exprEvaluator(this);
  19190. auto localVal = exprEvaluator.LoadLocal(lastParam);
  19191. localVal = LoadOrAggregateValue(localVal);
  19192. if (!localVal.mType->IsValuelessType())
  19193. mBfIRBuilder->CreateAlignedStore(localVal.mValue, lookupAddr, localVal.mType->mAlign);
  19194. }
  19195. else if (!fieldInstance->mResolvedType->IsValuelessType())
  19196. {
  19197. // This can happen if we have two properties with the same name but different types
  19198. AssertErrorState();
  19199. }
  19200. }
  19201. }
  19202. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  19203. {
  19204. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19205. {
  19206. if (HasCompiledOutput())
  19207. EmitGCMarkMembers();
  19208. }
  19209. else if (!mCurTypeInstance->IsObject())
  19210. {
  19211. }
  19212. }
  19213. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  19214. {
  19215. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19216. {
  19217. if (HasCompiledOutput())
  19218. EmitGCFindTLSMembers();
  19219. }
  19220. }
  19221. }
  19222. }
  19223. else if (!skipBody)
  19224. {
  19225. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  19226. bool wantsRetVal = true;
  19227. if ((mIsComptimeModule) && (methodDef->mMethodType != BfMethodType_CtorCalcAppend))
  19228. wantsRetVal = false;
  19229. else if (mCurMethodInstance->mReturnType->IsVar())
  19230. wantsRetVal = false;
  19231. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  19232. {
  19233. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  19234. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  19235. {
  19236. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  19237. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  19238. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst, mCurMethodInstance->mReturnType->mAlign);
  19239. mBfIRBuilder->ClearDebugLocation(storeInst);
  19240. mCurMethodState->mRetValAddr = allocaInst;
  19241. }
  19242. else if (wantsRetVal)
  19243. {
  19244. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  19245. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  19246. }
  19247. }
  19248. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19249. {
  19250. mBfIRBuilder->CreateAlignedStore(GetConstValue(0), mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19251. BfGetSymbolReferenceKind prevSymbolKind;
  19252. BfAutoComplete* prevAutoComplete;
  19253. if (mCompiler->mResolvePassData != NULL)
  19254. {
  19255. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  19256. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19257. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  19258. }
  19259. EmitCtorCalcAppend();
  19260. if (mCompiler->mResolvePassData != NULL)
  19261. {
  19262. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  19263. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  19264. }
  19265. }
  19266. else if (!isEmptyBodied)
  19267. {
  19268. if (!mCurMethodState->mIRExitBlock)
  19269. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  19270. bool isExpressionBody = false;
  19271. if (methodDeclaration != NULL)
  19272. {
  19273. if (methodDeclaration->mFatArrowToken != NULL)
  19274. isExpressionBody = true;
  19275. }
  19276. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  19277. {
  19278. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  19279. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  19280. isExpressionBody = true;
  19281. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  19282. {
  19283. isExpressionBody = true;
  19284. }
  19285. }
  19286. else
  19287. {
  19288. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  19289. {
  19290. if (!block->mChildArr.IsEmpty())
  19291. {
  19292. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  19293. {
  19294. if (exprStmt->mTrailingSemicolon == NULL)
  19295. isExpressionBody = true;
  19296. }
  19297. }
  19298. }
  19299. else
  19300. isExpressionBody = true;
  19301. }
  19302. DoCEEmit(methodInstance);
  19303. if (methodInstance->mCeCancelled)
  19304. mIgnoreErrors = true;
  19305. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  19306. {
  19307. while (fieldDtorBody != NULL)
  19308. {
  19309. VisitEmbeddedStatement(fieldDtorBody->mBody);
  19310. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  19311. }
  19312. }
  19313. else if (!isExpressionBody)
  19314. {
  19315. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  19316. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  19317. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  19318. VisitCodeBlock(bodyBlock);
  19319. }
  19320. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  19321. {
  19322. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  19323. // {
  19324. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  19325. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  19326. // }
  19327. auto expectingType = mCurMethodInstance->mReturnType;
  19328. // What was this error for?
  19329. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  19330. // {
  19331. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  19332. // }
  19333. BfEvalExprFlags exprEvalFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_IsExpressionBody);
  19334. if (expectingType->IsVoid())
  19335. {
  19336. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  19337. bool wasReturnGenericParam = false;
  19338. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  19339. {
  19340. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  19341. }
  19342. else
  19343. {
  19344. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  19345. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  19346. wasReturnGenericParam = true;
  19347. }
  19348. // If we the void return was from a generic specialization, allow us to return a void result,
  19349. // otherwise treat expression as though it must be a statement
  19350. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  19351. if (isStatement)
  19352. expectingType = NULL;
  19353. }
  19354. BfExprEvaluator exprEvaluator(this);
  19355. if (mCurMethodInstance->mMethodDef->mIsReadOnly)
  19356. exprEvaluator.mAllowReadOnlyReference = true;
  19357. UpdateSrcPos(expressionBody);
  19358. auto retVal = CreateValueFromExpression(exprEvaluator, expressionBody, expectingType, exprEvalFlags);
  19359. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  19360. {
  19361. mCurMethodState->mHadReturn = true;
  19362. if (!mCurMethodState->mLeftBlockUncond)
  19363. {
  19364. retVal = LoadOrAggregateValue(retVal);
  19365. EmitReturn(retVal);
  19366. }
  19367. }
  19368. }
  19369. }
  19370. }
  19371. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  19372. if (skipUpdateSrcPos)
  19373. {
  19374. // Skip
  19375. }
  19376. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19377. UpdateSrcPos(bodyBlock->mCloseBrace);
  19378. else if (methodDef->mBody != NULL)
  19379. UpdateSrcPos(methodDef->mBody);
  19380. else if (methodDeclaration != NULL)
  19381. UpdateSrcPos(methodDeclaration);
  19382. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  19383. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  19384. else
  19385. UseDefaultSrcPos();
  19386. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19387. {
  19388. if (mCurMethodState->mRetVal)
  19389. {
  19390. mCurMethodState->SetHadReturn(true);
  19391. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  19392. mBfIRBuilder->CreateRet(retVal);
  19393. }
  19394. else
  19395. AssertErrorState();
  19396. }
  19397. mCurMethodState->mHeadScope.mDone = true;
  19398. if (!mCurMethodState->mHadReturn)
  19399. {
  19400. // Clear off the stackallocs that have occurred after a scopeData break
  19401. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  19402. }
  19403. EmitDeferredCallProcessorInstances(&mCurMethodState->mHeadScope);
  19404. if (mCurMethodState->mIRExitBlock)
  19405. {
  19406. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  19407. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  19408. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  19409. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  19410. if ((!mCurMethodState->mDIRetVal) && (wantsDIData))
  19411. CreateDIRetVal();
  19412. }
  19413. for (auto localVar : mCurMethodState->mLocals)
  19414. {
  19415. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  19416. {
  19417. //
  19418. }
  19419. else if ((skipEndChecks) || (methodDef->mBody == NULL))
  19420. break;
  19421. LocalVariableDone(localVar, true);
  19422. }
  19423. if (mCurMethodState->mIRExitBlock)
  19424. {
  19425. if ((mCurMethodState->mRetVal) &&
  19426. ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() == -1)))
  19427. {
  19428. auto loadedVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19429. CreateReturn(loadedVal);
  19430. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19431. if (mCurMethodState->mDIRetVal)
  19432. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19433. }
  19434. else
  19435. {
  19436. // Have something on the last line to step onto
  19437. if (mHasFullDebugInfo)
  19438. {
  19439. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19440. UpdateSrcPos(bodyBlock->mCloseBrace);
  19441. EmitEnsureInstructionAt();
  19442. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19443. {
  19444. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19445. mBfIRBuilder->EnsureFunctionPatchable();
  19446. }
  19447. }
  19448. mBfIRBuilder->CreateRetVoid();
  19449. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19450. if (mCurMethodState->mDIRetVal)
  19451. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19452. }
  19453. }
  19454. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  19455. {
  19456. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  19457. {
  19458. if ((!mIsComptimeModule) && (irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19459. {
  19460. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19461. mBfIRBuilder->EnsureFunctionPatchable();
  19462. }
  19463. mBfIRBuilder->CreateRetVoid();
  19464. }
  19465. }
  19466. else
  19467. {
  19468. if (!mCurMethodState->mHadReturn)
  19469. {
  19470. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  19471. if (bodyBlock != NULL)
  19472. {
  19473. if (bodyBlock->mCloseBrace != NULL)
  19474. {
  19475. BfAstNode* target = bodyBlock->mCloseBrace;
  19476. if (!mCompiler->mHasRequiredTypes)
  19477. {
  19478. AddFailType(mCurTypeInstance);
  19479. mHadBuildError = true;
  19480. }
  19481. else
  19482. Fail("Method must return value", target);
  19483. }
  19484. else
  19485. {
  19486. // It's possible to not have a closing brace if the method ends in an EOF
  19487. AssertErrorState();
  19488. }
  19489. }
  19490. }
  19491. }
  19492. // Move 'init' into 'entry'
  19493. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  19494. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  19495. if (((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType())) &&
  19496. (!mIsComptimeModule))
  19497. {
  19498. // Don't keep instructions for unspecialized types
  19499. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19500. }
  19501. // Avoid linking any internal funcs that were just supposed to be comptime-accessible
  19502. /*if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  19503. wantsRemoveBody = true;*/
  19504. if ((hasExternSpecifier) && (!skipBody))
  19505. {
  19506. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  19507. // incase it gets called later by some hot-loaded coded
  19508. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()) && (mCurTypeInstance != mContext->mBfObjectType))
  19509. {
  19510. if (!mCurMethodInstance->mMethodDef->mName.StartsWith("Comptime_"))
  19511. CreateFakeCallerMethod(mangledName);
  19512. }
  19513. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19514. }
  19515. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  19516. {
  19517. // We only need the DLL stub when we may be hot swapping
  19518. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19519. }
  19520. else if (wantsRemoveBody)
  19521. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19522. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  19523. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  19524. // unspecialized types
  19525. if (((mCurTypeInstance->IsUnspecializedType()) && (!mIsComptimeModule)) ||
  19526. (mCurTypeInstance->IsInterface()))
  19527. {
  19528. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  19529. methodInstance->mIRFunction = BfIRFunction();
  19530. }
  19531. CheckAddFailType();
  19532. if (mHadBuildError)
  19533. prevHadBuildError.CancelRestore();
  19534. if (mHadBuildWarning)
  19535. prevHadWarning.CancelRestore();
  19536. if (!methodDef->mIsLocalMethod)
  19537. ProcessMethod_ProcessDeferredLocals();
  19538. prevIgnoreWrites.Restore();
  19539. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  19540. if (methodState.mHotDataReferenceBuilder != NULL)
  19541. {
  19542. AddHotDataReferences(&hotDataReferenceBuilder);
  19543. }
  19544. else
  19545. {
  19546. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  19547. {
  19548. // Remove the hot method data
  19549. auto hotMethod = methodInstance->mHotMethod;
  19550. auto prevMethod = hotMethod->mPrevVersion;
  19551. if (prevMethod != NULL)
  19552. {
  19553. // If there's a prev method then pull its data into the main HotMethod.
  19554. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  19555. // over to the main HotMethod definition to keep the HotMethod address
  19556. // invariant
  19557. for (auto ref : hotMethod->mReferences)
  19558. ref->Deref();
  19559. hotMethod->mReferences.Clear();
  19560. BF_ASSERT(prevMethod->mRefCount == 1);
  19561. hotMethod->mReferences = prevMethod->mReferences;
  19562. if (hotMethod->mSrcTypeVersion != NULL)
  19563. hotMethod->mSrcTypeVersion->Deref();
  19564. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  19565. prevMethod->mSrcTypeVersion = NULL;
  19566. prevMethod->mReferences.Clear();
  19567. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  19568. prevMethod->mPrevVersion = NULL;
  19569. prevMethod->Deref();
  19570. }
  19571. hotMethod->Deref();
  19572. methodInstance->mHotMethod = NULL;
  19573. }
  19574. }
  19575. }
  19576. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  19577. {
  19578. String name;
  19579. bool found = false;
  19580. auto checkMethodState = mCurMethodState;
  19581. while (checkMethodState != NULL)
  19582. {
  19583. if (checkMethodState->mClosureState == NULL)
  19584. break;
  19585. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  19586. {
  19587. found = true;
  19588. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  19589. break;
  19590. }
  19591. checkMethodState = checkMethodState->mPrevMethodState;
  19592. }
  19593. if (!found)
  19594. name += mCurMethodInstance->mMethodDef->mName;
  19595. int prevSepPos = (int)name.LastIndexOf('$');
  19596. if (prevSepPos != -1)
  19597. {
  19598. name.RemoveToEnd(prevSepPos);
  19599. }
  19600. name += "@";
  19601. name += baseName;
  19602. HashContext hashCtx;
  19603. if (anchorNode != NULL)
  19604. {
  19605. hashCtx.Mixin(anchorNode->GetStartCharId());
  19606. }
  19607. //
  19608. {
  19609. auto checkMethodState = declMethodState;
  19610. auto checkMixinState = declMixinState;
  19611. while (checkMethodState != NULL)
  19612. {
  19613. if (checkMixinState != NULL)
  19614. {
  19615. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  19616. }
  19617. checkMethodState = checkMethodState->mPrevMethodState;
  19618. if (checkMethodState != NULL)
  19619. checkMixinState = checkMethodState->mMixinState;
  19620. }
  19621. }
  19622. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19623. if ((rootMethodState != NULL) && (rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19624. {
  19625. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  19626. {
  19627. StringT<512> genericTypeName;
  19628. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  19629. hashCtx.MixinStr(genericTypeName);
  19630. }
  19631. }
  19632. uint64 hashVal = hashCtx.Finish64();
  19633. name += "$";
  19634. name += BfTypeUtils::HashEncode64(hashVal);
  19635. return name;
  19636. }
  19637. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  19638. {
  19639. if (localMethod->mMethodDef != NULL)
  19640. return localMethod->mMethodDef;
  19641. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19642. auto declMethodState = localMethod->mDeclMethodState;
  19643. auto declMixinState = localMethod->mDeclMixinState;
  19644. auto typeInst = mCurTypeInstance;
  19645. BfAstNode* body = NULL;
  19646. BfAstNode* anchorNode = NULL;
  19647. auto _AllocDirectTypeRef = [&](BfType* type)
  19648. {
  19649. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  19650. directTypeRef->Init(type);
  19651. return directTypeRef;
  19652. };
  19653. auto methodDeclaration = localMethod->mMethodDeclaration;
  19654. if (methodDeclaration != NULL)
  19655. {
  19656. body = methodDeclaration->mBody;
  19657. anchorNode = methodDeclaration->mOpenParen;
  19658. }
  19659. else
  19660. {
  19661. body = localMethod->mLambdaBindExpr->mBody;
  19662. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  19663. }
  19664. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  19665. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  19666. BfMethodDef* methodDef;
  19667. BfMethodDef* outerMethodDef = NULL;
  19668. if (localMethod->mOuterLocalMethod != NULL)
  19669. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  19670. else if (rootMethodState->mMethodInstance != NULL)
  19671. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  19672. if (methodDeclaration != NULL)
  19673. {
  19674. BfDefBuilder defBuilder(mCompiler->mSystem);
  19675. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  19676. defBuilder.mPassInstance = mCompiler->mPassInstance;
  19677. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  19678. defBuilder.mCurDeclaringTypeDef = defBuilder.mCurTypeDef;
  19679. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  19680. }
  19681. else
  19682. {
  19683. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  19684. methodDef = new BfMethodDef();
  19685. methodDef->mName = localMethod->mMethodName;
  19686. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  19687. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  19688. methodDef->mBody = body;
  19689. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  19690. {
  19691. auto paramType = invokeMethod->GetParamType(paramIdx);
  19692. String paramName;
  19693. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  19694. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  19695. else
  19696. paramName = invokeMethod->GetParamName(paramIdx);
  19697. auto paramDef = new BfParameterDef();
  19698. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  19699. paramDef->mName = paramName;
  19700. methodDef->mParams.Add(paramDef);
  19701. }
  19702. if (outerMethodDef != NULL)
  19703. {
  19704. for (auto genericParam : outerMethodDef->mGenericParams)
  19705. {
  19706. auto* copiedGenericParamDef = new BfGenericParamDef();
  19707. *copiedGenericParamDef = *genericParam;
  19708. methodDef->mGenericParams.Add(copiedGenericParamDef);
  19709. }
  19710. }
  19711. }
  19712. methodDef->mIdx = ~methodLocalIdx;
  19713. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  19714. methodDef->mName = localMethod->mExpectedFullName;
  19715. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  19716. //
  19717. // if (!localMethod->mExpectedFullName.IsEmpty())
  19718. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  19719. methodDef->mIsStatic = true;
  19720. methodDef->mIsLocalMethod = true;
  19721. methodDef->mIsVirtual = false;
  19722. localMethod->mMethodDef = methodDef;
  19723. auto methodInstanceGroup = new BfMethodInstanceGroup();
  19724. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  19725. methodInstanceGroup->mMethodIdx = -1;
  19726. methodInstanceGroup->mOwner = mCurTypeInstance;
  19727. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  19728. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  19729. {
  19730. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  19731. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  19732. }
  19733. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  19734. {
  19735. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  19736. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19737. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  19738. {
  19739. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  19740. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  19741. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  19742. autoComplete->mDefType = typeInst->mTypeDef;
  19743. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  19744. autoComplete->mReplaceLocalId = methodLocalIdx;
  19745. }
  19746. }
  19747. return localMethod->mMethodDef;
  19748. }
  19749. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  19750. {
  19751. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  19752. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  19753. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19754. auto declMethodState = localMethod->mDeclMethodState;
  19755. auto declMixinState = localMethod->mDeclMixinState;
  19756. auto callerMethodState = mCurMethodState;
  19757. auto typeInst = mCurTypeInstance;
  19758. if (mCurMethodState->mMixinState != NULL)
  19759. {
  19760. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  19761. }
  19762. auto methodDef = GetLocalMethodDef(localMethod);
  19763. BfAstNode* body = NULL;
  19764. auto methodDeclaration = localMethod->mMethodDeclaration;
  19765. if (methodDeclaration != NULL)
  19766. {
  19767. body = methodDeclaration->mBody;
  19768. }
  19769. else
  19770. {
  19771. body = localMethod->mLambdaBindExpr->mBody;
  19772. }
  19773. bool hadConcreteInterfaceGenericArgument = false;
  19774. BfTypeVector sanitizedMethodGenericArguments;
  19775. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  19776. // version of this method for this pass through the outermost method
  19777. int dependentGenericStartIdx = 0;
  19778. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19779. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  19780. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  19781. if (methodGenericArguments.size() == 0)
  19782. {
  19783. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19784. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  19785. }
  19786. else
  19787. {
  19788. int genericArgIdx = 0;
  19789. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  19790. // {
  19791. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  19792. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  19793. // }
  19794. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  19795. {
  19796. auto genericArgType = methodGenericArguments[genericArgIdx];
  19797. BF_ASSERT(!genericArgType->IsRef());
  19798. if (genericArgType->IsConcreteInterfaceType())
  19799. {
  19800. hadConcreteInterfaceGenericArgument = true;
  19801. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  19802. genericArgType = concreteInterfaceType->mInterface;
  19803. }
  19804. sanitizedMethodGenericArguments.push_back(genericArgType);
  19805. }
  19806. }
  19807. bool wantPrematureMethodInstance = false;
  19808. if (!force)
  19809. {
  19810. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  19811. }
  19812. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  19813. bool isDefaultPass = true;
  19814. BfTypeVector lookupMethodGenericArguments;
  19815. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  19816. {
  19817. auto genericArgType = methodGenericArguments[genericArgIdx];
  19818. BF_ASSERT(!genericArgType->IsRef());
  19819. lookupMethodGenericArguments.Add(genericArgType);
  19820. if (genericArgType->IsGenericParam())
  19821. {
  19822. auto genericParam = (BfGenericParamType*)genericArgType;
  19823. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  19824. isDefaultPass = false;
  19825. }
  19826. else
  19827. {
  19828. isDefaultPass = false;
  19829. }
  19830. }
  19831. bool hadExistingMethodInstance = false;
  19832. if (methodInstance != NULL)
  19833. {
  19834. hadExistingMethodInstance = true;
  19835. }
  19836. else
  19837. {
  19838. if (isDefaultPass)
  19839. {
  19840. methodInstance = methodInstGroup->mDefault;
  19841. if (methodInstance != NULL)
  19842. {
  19843. hadExistingMethodInstance = true;
  19844. }
  19845. else
  19846. {
  19847. methodInstance = new BfMethodInstance();
  19848. methodInstGroup->mDefault = methodInstance;
  19849. }
  19850. }
  19851. else
  19852. {
  19853. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  19854. if (methodInstGroup->mMethodSpecializationMap == NULL)
  19855. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  19856. BfMethodInstance** methodInstancePtr = NULL;
  19857. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  19858. {
  19859. methodInstance = *methodInstancePtr;
  19860. hadExistingMethodInstance = true;
  19861. }
  19862. else
  19863. {
  19864. methodInstance = new BfMethodInstance();
  19865. *methodInstancePtr = methodInstance;
  19866. }
  19867. }
  19868. }
  19869. if (hadExistingMethodInstance)
  19870. {
  19871. if ((!methodInstance->mDisallowCalling) ||
  19872. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  19873. return BfModuleMethodInstance(methodInstance);
  19874. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  19875. }
  19876. else
  19877. {
  19878. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  19879. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  19880. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  19881. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  19882. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  19883. methodInstance->mMethodDef = methodDef;
  19884. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  19885. if (hadConcreteInterfaceGenericArgument)
  19886. methodInstance->mIgnoreBody = true;
  19887. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  19888. for (auto genericArg : sanitizedMethodGenericArguments)
  19889. {
  19890. if (genericArg->IsPrimitiveType())
  19891. genericArg = GetWrappedStructType(genericArg);
  19892. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  19893. }
  19894. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  19895. {
  19896. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  19897. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  19898. }
  19899. SetupMethodIdHash(methodInstance);
  19900. }
  19901. auto _SetupMethodInstance = [&]()
  19902. {
  19903. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  19904. // Generic constraints
  19905. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  19906. {
  19907. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  19908. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  19909. }
  19910. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  19911. {
  19912. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  19913. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  19914. }
  19915. };
  19916. //////////////////////////////////////////////////////////////////////////
  19917. auto _VisitLambdaBody = [&]()
  19918. {
  19919. if (localMethod->mDeclOnly)
  19920. return;
  19921. if (mCompiler->mCanceling)
  19922. return;
  19923. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  19924. {
  19925. VisitCodeBlock(blockBody);
  19926. }
  19927. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  19928. {
  19929. BfType* expectType = NULL;
  19930. if (!methodInstance->mReturnType->IsVoid())
  19931. expectType = methodInstance->mReturnType;
  19932. CreateValueFromExpression(bodyExpr, expectType, BfEvalExprFlags_AllowRefExpr);
  19933. }
  19934. };
  19935. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  19936. {
  19937. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  19938. auto result = ResolveTypeRef(typeRef);
  19939. if (result == NULL)
  19940. result = mContext->mBfObjectType;
  19941. return result;
  19942. };
  19943. BfTypeInstance* outerClosure = NULL;
  19944. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  19945. outerClosure = declMethodState->mClosureState->mClosureType;
  19946. BfMethodState methodState;
  19947. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  19948. BfIRFunctionType funcType;
  19949. auto voidType = GetPrimitiveType(BfTypeCode_None);
  19950. SizedArray<BfIRType, 0> paramTypes;
  19951. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  19952. mBfIRBuilder->SaveDebugLocation();
  19953. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  19954. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  19955. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  19956. BfDeferredLocalAssignData deferredLocalAssignData;
  19957. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  19958. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  19959. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  19960. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  19961. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  19962. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  19963. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  19964. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  19965. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  19966. methodState.mIRFunction = declMethodState->mIRFunction;
  19967. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  19968. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  19969. {
  19970. methodState.mCurScope->mAstBlock = blockBody;
  19971. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  19972. }
  19973. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  19974. BfClosureState closureState;
  19975. if (methodDef->mMethodType == BfMethodType_Mixin)
  19976. {
  19977. if (declMethodState != NULL)
  19978. {
  19979. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  19980. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  19981. else if (declMethodState->mMethodInstance != NULL)
  19982. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  19983. }
  19984. }
  19985. if (closureState.mReturnType == NULL)
  19986. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  19987. closureState.mCapturing = true;
  19988. closureState.mLocalMethod = localMethod;
  19989. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  19990. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  19991. methodState.mClosureState = &closureState;
  19992. closureState.mClosureType = outerClosure;
  19993. int outerLocalsCount = (int)methodState.mLocals.size();
  19994. if (!hadExistingMethodInstance)
  19995. {
  19996. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  19997. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  19998. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  19999. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  20000. auto declareModule = this;
  20001. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  20002. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  20003. BF_ASSERT(declareModule != NULL);
  20004. methodInstance->mDeclModule = declareModule;
  20005. _SetupMethodInstance();
  20006. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  20007. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  20008. }
  20009. if (wantPrematureMethodInstance)
  20010. {
  20011. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  20012. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  20013. // its true method instance
  20014. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  20015. //BF_ASSERT(moduleMethodInstance);
  20016. return BfModuleMethodInstance(methodInstance);
  20017. }
  20018. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  20019. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  20020. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  20021. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  20022. closureState.mClosureMethodDef = methodDef;
  20023. bool wantsVisitBody = true;
  20024. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  20025. wantsVisitBody = false;
  20026. if (methodInstance->IsOrInUnspecializedVariation())
  20027. wantsVisitBody = false;
  20028. bool allowCapture = (methodDeclaration == NULL) || (methodDeclaration->mStaticSpecifier == NULL);
  20029. if (wantsVisitBody)
  20030. {
  20031. BP_ZONE("VisitLambdaBody");
  20032. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  20033. // this capture stage for each of those times
  20034. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  20035. /*
  20036. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  20037. // that will not occur during the actual lambda method generation, for example: returning a value
  20038. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  20039. // our AST nodes will still be visited
  20040. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  20041. */
  20042. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20043. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  20044. mBfIRBuilder->SaveDebugLocation();
  20045. closureState.mCaptureVisitingBody = true;
  20046. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  20047. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  20048. methodState.mMethodInstance = methodInstance;
  20049. NewScopeState();
  20050. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  20051. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  20052. {
  20053. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  20054. for (auto localDef : methodState.mLocals)
  20055. {
  20056. if (localDef->mResolvedType->IsVar())
  20057. continue;
  20058. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  20059. }
  20060. }
  20061. // Keep outs from being marked as assigned
  20062. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20063. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  20064. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  20065. auto prevDLA = rootMethodState->mDeferredLocalAssignData;
  20066. while ((prevDLA != NULL) && (prevDLA->mIsChained))
  20067. prevDLA = prevDLA->mChainedAssignData;
  20068. if (prevDLA != NULL)
  20069. {
  20070. deferredLocalAssignData.mAssignedLocals = prevDLA->mAssignedLocals;
  20071. deferredLocalAssignData.mLeftBlockUncond = prevDLA->mLeftBlockUncond;
  20072. }
  20073. SetAndRestoreValue<BfDeferredLocalAssignData*> sarDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  20074. if (!mIgnoreErrors)
  20075. localMethod->mDidBodyErrorPass = true;
  20076. _VisitLambdaBody();
  20077. RestoreScopeState();
  20078. closureState.mCaptureVisitingBody = false;
  20079. mBfIRBuilder->RestoreDebugLocation();
  20080. }
  20081. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  20082. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  20083. {
  20084. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  20085. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  20086. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  20087. }
  20088. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  20089. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  20090. closureState.mClosureMethodDef = NULL;
  20091. for (auto methodInstance : closureState.mLocalMethodRefs)
  20092. {
  20093. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  20094. }
  20095. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  20096. prevIgnoreWrites.Restore();
  20097. std::multiset<BfClosureCapturedEntry> capturedEntries;
  20098. //
  20099. {
  20100. auto varMethodState = declMethodState;
  20101. while (varMethodState != NULL)
  20102. {
  20103. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  20104. {
  20105. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  20106. methodDef->mIsStatic = false;
  20107. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20108. methodDef->mIsMutating = true;
  20109. }
  20110. bool copyOuterCaptures = false;
  20111. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  20112. {
  20113. auto localVar = varMethodState->mLocals[localIdx];
  20114. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20115. {
  20116. if (!allowCapture)
  20117. {
  20118. if ((!localVar->mIsStatic) && (!localVar->mConstValue))
  20119. continue;
  20120. }
  20121. if (localVar->mIsThis)
  20122. {
  20123. // We can only set mutating if our owning type is mutating
  20124. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  20125. {
  20126. if (typeInst->IsValueType())
  20127. {
  20128. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20129. methodDef->mIsMutating = true;
  20130. }
  20131. }
  20132. methodDef->mIsStatic = false;
  20133. continue;
  20134. }
  20135. if ((localVar->mIsThis) && (outerClosure != NULL))
  20136. {
  20137. continue;
  20138. }
  20139. if ((localVar->mConstValue) || (localVar->mIsStatic) || (localVar->mResolvedType->IsValuelessType()))
  20140. {
  20141. closureState.mConstLocals.push_back(*localVar);
  20142. continue;
  20143. }
  20144. BfClosureCapturedEntry capturedEntry;
  20145. auto capturedType = localVar->mResolvedType;
  20146. bool captureByRef = false;
  20147. if (!capturedType->IsRef())
  20148. {
  20149. if (localVar->mIsThis)
  20150. {
  20151. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  20152. captureByRef = true;
  20153. }
  20154. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20155. captureByRef = true;
  20156. }
  20157. else
  20158. {
  20159. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  20160. {
  20161. capturedType = ((BfRefType*)capturedType)->mElementType;
  20162. }
  20163. }
  20164. if (captureByRef)
  20165. {
  20166. //capturedEntry.mIsByReference = true;
  20167. capturedType = CreateRefType(capturedType);
  20168. }
  20169. else
  20170. {
  20171. //capturedEntry.mIsByReference = false;
  20172. }
  20173. capturedEntry.mNameNode = localVar->mNameNode;
  20174. capturedEntry.mType = capturedType;
  20175. capturedEntry.mName = localVar->mName;
  20176. //capturedEntry.mLocalVarDef = localVar;
  20177. capturedEntries.insert(capturedEntry);
  20178. }
  20179. }
  20180. varMethodState = varMethodState->mPrevMethodState;
  20181. if ((varMethodState == NULL) ||
  20182. (varMethodState->mMixinState != NULL) ||
  20183. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  20184. break;
  20185. }
  20186. }
  20187. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  20188. {
  20189. auto fieldDef = copyField->GetFieldDef();
  20190. BfClosureCapturedEntry capturedEntry;
  20191. capturedEntry.mName = copyField->GetFieldDef()->mName;
  20192. capturedEntry.mType = copyField->mResolvedType;
  20193. if (capturedEntry.mType->IsRef())
  20194. {
  20195. // Keep by ref
  20196. }
  20197. else if (!fieldDef->mIsReadOnly)
  20198. {
  20199. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  20200. }
  20201. capturedEntries.insert(capturedEntry);
  20202. }
  20203. int captureIdx = 0;
  20204. for (auto& capturedEntry : capturedEntries)
  20205. {
  20206. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  20207. }
  20208. /*if (isDefaultPass)
  20209. {
  20210. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  20211. int captureIdx = 0;
  20212. for (auto& capturedEntry : capturedEntries)
  20213. {
  20214. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  20215. BfParameterDef* paramDef = new BfParameterDef();
  20216. paramDef->mName = capturedEntry.mName;
  20217. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  20218. directTypeRef->mType = capturedEntry.mType;
  20219. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  20220. paramDef->mTypeRef = directTypeRef;
  20221. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  20222. methodDef->mParams.Insert(captureIdx, paramDef);
  20223. captureIdx++;
  20224. }
  20225. }
  20226. else
  20227. {
  20228. auto defaultMethodInstance = methodInstGroup->mDefault;
  20229. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  20230. }*/
  20231. methodState.Reset();
  20232. closureState.mCapturing = false;
  20233. //////////////////////////////////////////////////////////////////////////
  20234. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  20235. if (methodInstance->mReturnType != NULL)
  20236. {
  20237. BF_ASSERT(methodInstance->mDisallowCalling);
  20238. // We did a premature declaration (without captures)
  20239. methodInstance->UndoDeclaration();
  20240. methodInstance->mDisallowCalling = false;
  20241. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  20242. }
  20243. auto declareModule = this;
  20244. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  20245. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  20246. BF_ASSERT(declareModule != NULL);
  20247. methodInstance->mDeclModule = declareModule;
  20248. _SetupMethodInstance();
  20249. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  20250. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  20251. closureState.mReturnType = methodInstance->mReturnType;
  20252. mCompiler->mStats.mMethodsQueued++;
  20253. mCompiler->UpdateCompletion();
  20254. declareModule->mIncompleteMethodCount++;
  20255. mCompiler->mStats.mMethodsProcessed++;
  20256. if (!methodInstance->mIsReified)
  20257. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  20258. auto deferMethodState = rootMethodState;
  20259. // 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)
  20260. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  20261. (methodDef->mMethodType != BfMethodType_Mixin) &&
  20262. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)) &&
  20263. (!mCompiler->IsDataResolvePass()))
  20264. {
  20265. BP_ZONE("BfDeferredLocalMethod:create");
  20266. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  20267. deferredLocalMethod->mLocalMethod = localMethod;
  20268. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  20269. deferredLocalMethod->mMethodInstance = methodInstance;
  20270. auto checkMethodState = declMethodState;
  20271. while (checkMethodState != NULL)
  20272. {
  20273. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  20274. {
  20275. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  20276. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20277. }
  20278. if (checkMethodState->mMixinState != NULL)
  20279. {
  20280. BfMixinRecord mixinRecord;
  20281. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  20282. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20283. }
  20284. checkMethodState = checkMethodState->mPrevMethodState;
  20285. }
  20286. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  20287. }
  20288. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  20289. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  20290. mBfIRBuilder->RestoreDebugLocation();
  20291. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  20292. {
  20293. auto checkMethodState = mCurMethodState;
  20294. while (checkMethodState != NULL)
  20295. {
  20296. BfLocalMethod* nextLocalMethod = NULL;
  20297. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  20298. {
  20299. while (nextLocalMethod != NULL)
  20300. {
  20301. auto checkLocalMethod = nextLocalMethod;
  20302. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  20303. if (checkLocalMethod == localMethod)
  20304. continue;
  20305. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  20306. continue;
  20307. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  20308. if (checkMethodInstance == NULL)
  20309. continue; // Not generated yet
  20310. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  20311. {
  20312. String error = "Method already declared with the same parameter types";
  20313. auto bfError = Fail(error, methodInstance->mMethodDef->GetRefNode(), true);
  20314. if ((bfError != NULL) && (methodInstance->mMethodDef->GetRefNode() != checkMethodInstance->mMethodDef->GetRefNode()))
  20315. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  20316. }
  20317. }
  20318. }
  20319. checkMethodState = checkMethodState->mPrevMethodState;
  20320. }
  20321. }
  20322. return BfModuleMethodInstance(methodInstance);
  20323. }
  20324. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  20325. {
  20326. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  20327. return 0;
  20328. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20329. int rootMethodGenericParamCount = 0;
  20330. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  20331. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  20332. if (mCurMethodInstance == NULL)
  20333. return rootMethodGenericParamCount;
  20334. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  20335. return rootMethodGenericParamCount;
  20336. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  20337. if (callerLocalMethod == NULL)
  20338. return rootMethodGenericParamCount;
  20339. BfLocalMethod* calledLocalMethod = NULL;
  20340. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  20341. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  20342. {
  20343. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  20344. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  20345. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  20346. }
  20347. return rootMethodGenericParamCount;
  20348. }
  20349. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  20350. {
  20351. auto methodDef = methodInstance->mMethodDef;
  20352. auto customAttributes = methodInstance->GetCustomAttributes();
  20353. if (customAttributes != NULL)
  20354. return;
  20355. auto methodDeclaration = methodDef->GetMethodDeclaration();
  20356. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  20357. auto typeInstance = methodInstance->GetOwner();
  20358. if (typeInstance->IsInstanceOf(mCompiler->mValueTypeTypeDef))
  20359. return;
  20360. BfTypeState typeState(typeInstance);
  20361. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20362. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  20363. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20364. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  20365. BfAttributeDirective* attributeDirective = NULL;
  20366. if (methodDeclaration != NULL)
  20367. attributeDirective = methodDeclaration->mAttributes;
  20368. else if (propertyMethodDeclaration != NULL)
  20369. {
  20370. attributeDirective = propertyMethodDeclaration->mAttributes;
  20371. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  20372. {
  20373. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  20374. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  20375. }
  20376. }
  20377. if (attributeDirective != NULL)
  20378. {
  20379. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20380. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20381. if ((methodInstance == methodInstance->mMethodInstanceGroup->mDefault) && (methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes != NULL))
  20382. {
  20383. // Take over previously-generated custom attributes
  20384. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes;
  20385. methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes = NULL;
  20386. }
  20387. else
  20388. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  20389. }
  20390. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mPropertyDeclaration->mAttributes != NULL) && ((attrTarget & BfAttributeTargets_Property) == 0))
  20391. {
  20392. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes != NULL)
  20393. {
  20394. GetCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20395. }
  20396. else
  20397. {
  20398. methodInstance->GetMethodInfoEx()->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20399. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20400. }
  20401. }
  20402. if (methodDeclaration != NULL)
  20403. {
  20404. if (auto inlineTypeRef = BfNodeDynCast<BfInlineTypeReference>(methodDeclaration->mReturnType))
  20405. {
  20406. if (inlineTypeRef->mTypeDeclaration->mAttributes != NULL)
  20407. {
  20408. // Apply multiuse attributes from anonymous return type
  20409. auto returnType = ResolveTypeRef(inlineTypeRef);
  20410. if ((returnType != NULL) && (returnType->ToTypeInstance()))
  20411. {
  20412. auto returnTypeInst = returnType->ToTypeInstance();
  20413. if ((returnTypeInst->IsAnonymous()) && (returnTypeInst->mCustomAttributes != NULL))
  20414. {
  20415. bool hasPendingAttributes = false;
  20416. for (const auto& customAttribute : returnTypeInst->mCustomAttributes->mAttributes)
  20417. {
  20418. if (customAttribute.mAwaitingValidation)
  20419. {
  20420. hasPendingAttributes = true;
  20421. break;
  20422. }
  20423. }
  20424. if (hasPendingAttributes)
  20425. {
  20426. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20427. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20428. if (methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes == NULL)
  20429. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = new BfCustomAttributes();
  20430. for (const auto& customAttribute : returnTypeInst->mCustomAttributes->mAttributes)
  20431. {
  20432. if (!customAttribute.mAwaitingValidation)
  20433. continue;
  20434. BfCustomAttribute copiedCustomAttribute = customAttribute;
  20435. copiedCustomAttribute.mIsMultiUse = false;
  20436. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes.Add(copiedCustomAttribute);
  20437. }
  20438. ValidateCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, attrTarget);
  20439. }
  20440. }
  20441. }
  20442. }
  20443. }
  20444. }
  20445. customAttributes = methodInstance->GetCustomAttributes();
  20446. if (customAttributes == NULL)
  20447. {
  20448. auto owner = methodInstance->GetOwner();
  20449. if ((owner->IsDelegate()) || (owner->IsFunction()))
  20450. customAttributes = owner->mCustomAttributes;
  20451. }
  20452. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  20453. if (customAttributes != NULL)
  20454. {
  20455. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  20456. if (linkNameAttr != NULL)
  20457. {
  20458. if (linkNameAttr->mCtorArgs.size() == 1)
  20459. {
  20460. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  20461. if (constant != NULL)
  20462. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  20463. }
  20464. }
  20465. if (methodDef->mHasComptime)
  20466. methodInstance->mComptimeFlags = BfComptimeFlag_Comptime;
  20467. auto comptimeAttr = customAttributes->Get(mCompiler->mComptimeAttributeTypeDef);
  20468. if (comptimeAttr != NULL)
  20469. {
  20470. for (auto setProp : comptimeAttr->mSetProperties)
  20471. {
  20472. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  20473. if (propertyDef->mName == "OnlyFromComptime")
  20474. {
  20475. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  20476. if ((constant != NULL) && (constant->mBool))
  20477. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_OnlyFromComptime);
  20478. }
  20479. else if (propertyDef->mName == "ConstEval")
  20480. {
  20481. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  20482. if ((constant != NULL) && (constant->mBool))
  20483. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_ConstEval);
  20484. }
  20485. }
  20486. }
  20487. }
  20488. auto delegateInfo = typeInstance->GetDelegateInfo();
  20489. if ((delegateInfo != NULL) && (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) && (methodInstance->mMethodDef->mName == "Invoke"))
  20490. methodInstance->mCallingConvention = delegateInfo->mCallingConvention;
  20491. }
  20492. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  20493. {
  20494. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  20495. {
  20496. // Don't create a func
  20497. return;
  20498. }
  20499. auto typeInstance = methodInstance->GetOwner();
  20500. auto methodDef = methodInstance->mMethodDef;
  20501. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  20502. if (isTemporaryFunc)
  20503. {
  20504. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  20505. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  20506. mangledName = "autocomplete_tmp";
  20507. }
  20508. if (!mBfIRBuilder->mIgnoreWrites)
  20509. {
  20510. BfIRFunction prevFunc;
  20511. // Remove old version (if we have one)
  20512. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  20513. if (prevFunc)
  20514. {
  20515. if ((methodDef->mIsOverride) && (mCurTypeInstance->mTypeDef->mIsCombinedPartial))
  20516. {
  20517. bool takeover = false;
  20518. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  20519. BfMethodDef* nextMethod = NULL;
  20520. BfMemberSetEntry* entry = NULL;
  20521. if (mCurTypeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  20522. nextMethod = (BfMethodDef*)entry->mMemberDef;
  20523. while (nextMethod != NULL)
  20524. {
  20525. auto checkMethod = nextMethod;
  20526. nextMethod = nextMethod->mNextWithSameName;
  20527. if (checkMethod == methodDef)
  20528. continue;
  20529. if (checkMethod->mIsOverride)
  20530. {
  20531. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20532. if (checkMethodInstance == NULL)
  20533. continue;
  20534. if ((checkMethodInstance->mIRFunction == prevFunc) &&
  20535. (checkMethodInstance->mMethodDef->mMethodDeclaration != NULL) &&
  20536. (checkMethodInstance->mVirtualTableIdx < 0))
  20537. {
  20538. BfAstNode* refNode = methodDef->GetRefNode();
  20539. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  20540. refNode = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  20541. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  20542. refNode = methodDeclaration->mVirtualSpecifier;
  20543. auto error = Fail(StrFormat("Conflicting extension override method '%s'", MethodToString(mCurMethodInstance).c_str()), refNode);
  20544. if (error != NULL)
  20545. mCompiler->mPassInstance->MoreInfo("See previous override", checkMethod->GetRefNode());
  20546. takeover = false;
  20547. break;
  20548. }
  20549. }
  20550. if (!checkMethod->mIsExtern)
  20551. continue;
  20552. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20553. if (checkMethodInstance == NULL)
  20554. continue;
  20555. if (!CompareMethodSignatures(checkMethodInstance, mCurMethodInstance))
  20556. continue;
  20557. // Take over function
  20558. takeover = true;
  20559. }
  20560. if (takeover)
  20561. mCurMethodInstance->mIRFunction = prevFunc;
  20562. if (!mCurMethodInstance->mIRFunction)
  20563. {
  20564. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  20565. if (!mIsComptimeModule)
  20566. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  20567. }
  20568. }
  20569. else if (methodDef->mIsExtern)
  20570. {
  20571. // Allow this
  20572. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  20573. }
  20574. else if (typeInstance->IsIRFuncUsed(prevFunc))
  20575. {
  20576. // We can have a collision of names when we have generic methods that differ only in
  20577. // their constraints, but they should only collide in their unspecialized form
  20578. // since only one will be chosen for a given concrete type
  20579. if (!mIsComptimeModule)
  20580. mCurMethodInstance->mMangleWithIdx = true;
  20581. mangledName.Clear();
  20582. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  20583. BfLogSysM("Function collision forced mangleWithIdx for %p: %d GenericArgs: %d Unspecialized: %d\n", methodInstance, prevFunc.mId, methodInstance->GetNumGenericArguments(), methodInstance->mIsUnspecialized);
  20584. }
  20585. else
  20586. {
  20587. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  20588. if (!mIsComptimeModule)
  20589. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  20590. }
  20591. }
  20592. }
  20593. if (typeInstance != mContext->mBfObjectType)
  20594. {
  20595. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  20596. GetMethodCustomAttributes(methodInstance);
  20597. }
  20598. // if (prevFunc)
  20599. // {
  20600. // if (methodDef->mIsExtern)
  20601. // {
  20602. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  20603. // methodInstance->mIRFunction = prevFunc;
  20604. // }
  20605. // else
  20606. // {
  20607. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  20608. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  20609. // {
  20610. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  20611. // BfLogSysM("Ignoring function name collision\n");
  20612. // }
  20613. // else
  20614. // {
  20615. // if (methodDef->mMethodDeclaration == NULL)
  20616. // {
  20617. // AssertErrorState();
  20618. // }
  20619. // else
  20620. // {
  20621. // BF_ASSERT(mIsSpecialModule);
  20622. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  20623. // {
  20624. // // We shouldn't have name collisions on the first run!
  20625. // AssertErrorState();
  20626. // }
  20627. // }
  20628. // }
  20629. // BfLogSysM("Before erase\n");
  20630. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  20631. // }
  20632. // }
  20633. bool isIntrinsic = false;
  20634. if (!methodInstance->mIRFunction)
  20635. {
  20636. BfIRFunction func;
  20637. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType() || (mIsComptimeModule)) &&
  20638. (!methodDef->IsEmptyPartial())) && (funcType);
  20639. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  20640. {
  20641. if (!mIsReified)
  20642. wantsLLVMFunc = false;
  20643. }*/
  20644. if (wantsLLVMFunc)
  20645. {
  20646. func = GetIntrinsic(methodInstance, true);
  20647. if (func)
  20648. {
  20649. isIntrinsic = true;
  20650. }
  20651. else
  20652. {
  20653. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  20654. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  20655. if (methodInstance->mAlwaysInline)
  20656. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  20657. // if (prevFunc)
  20658. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  20659. }
  20660. methodInstance->mIRFunction = func;
  20661. //if (!ignoreWrites)
  20662. //BF_ASSERT(!func.IsFake());
  20663. }
  20664. }
  20665. if (outIsIntrinsic != NULL)
  20666. *outIsIntrinsic = isIntrinsic;
  20667. if (!isIntrinsic)
  20668. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  20669. }
  20670. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  20671. {
  20672. if (methodInstance->mHotMethod != NULL)
  20673. return;
  20674. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  20675. {
  20676. auto srcTypeInst = methodInstance->GetOwner();
  20677. if (srcTypeInst->mHotTypeData == NULL)
  20678. return;
  20679. StringT<128> mangledName = inMangledName;
  20680. if (mangledName.IsEmpty())
  20681. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  20682. // We always keep the current primary method at the same address
  20683. BfHotMethod* hotMethod;
  20684. BfHotMethod** hotMethodPtr;
  20685. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  20686. {
  20687. hotMethod = new BfHotMethod();
  20688. *hotMethodPtr = hotMethod;
  20689. hotMethod->mRefCount = 1;
  20690. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20691. #ifdef BF_DBG_HOTMETHOD_IDX
  20692. static int sMethodIdx = 0;
  20693. hotMethod->mMethodIdx = sMethodIdx++;
  20694. #endif
  20695. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20696. }
  20697. else
  20698. {
  20699. hotMethod = *hotMethodPtr;
  20700. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  20701. {
  20702. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  20703. auto prevHotMethod = *hotMethodPtr;
  20704. hotMethod = new BfHotMethod();
  20705. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20706. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  20707. hotDupMethod->mRefCount++;
  20708. prevHotMethod->mReferences.Add(hotDupMethod);
  20709. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  20710. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20711. }
  20712. else if (mCompiler->IsHotCompile())
  20713. {
  20714. // Link the previous version into the mPrevVersion
  20715. BfHotMethod* prevMethod = new BfHotMethod();
  20716. prevMethod->mRefCount = 1;
  20717. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  20718. hotMethod->mPrevVersion = prevMethod;
  20719. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  20720. hotMethod->mSrcTypeVersion = NULL;
  20721. prevMethod->mFlags = hotMethod->mFlags;
  20722. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  20723. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  20724. #ifdef BF_DBG_HOTMETHOD_NAME
  20725. prevMethod->mMangledName = hotMethod->mMangledName;
  20726. #endif
  20727. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  20728. }
  20729. else
  20730. {
  20731. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20732. hotMethod->Clear(true);
  20733. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20734. }
  20735. }
  20736. if (methodInstance->mIsClosure)
  20737. {
  20738. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  20739. }
  20740. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  20741. hotMethod->mSrcTypeVersion->mRefCount++;
  20742. hotMethod->mRefCount++;
  20743. #ifdef BF_DBG_HOTMETHOD_NAME
  20744. hotMethod->mMangledName = mangledName;
  20745. #endif
  20746. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!IsHotCompile()))
  20747. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  20748. methodInstance->mHotMethod = hotMethod;
  20749. }
  20750. }
  20751. static void StackOverflow()
  20752. {
  20753. int i = 0;
  20754. if (i == 0)
  20755. StackOverflow();
  20756. }
  20757. void BfModule::StartMethodDeclaration(BfMethodInstance* methodInstance, BfMethodState* prevMethodState)
  20758. {
  20759. methodInstance->mHasStartedDeclaration = true;
  20760. auto methodDef = methodInstance->mMethodDef;
  20761. auto typeInstance = methodInstance->GetOwner();
  20762. bool hasNonGenericParams = false;
  20763. bool hasGenericParams = false;
  20764. int dependentGenericStartIdx = 0;
  20765. if (methodDef->mIsLocalMethod)
  20766. {
  20767. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  20768. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  20769. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  20770. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  20771. // over the local method each time
  20772. auto rootMethodInstance = prevMethodState->GetRootMethodState()->mMethodInstance;
  20773. dependentGenericStartIdx = 0;
  20774. if (rootMethodInstance != NULL)
  20775. {
  20776. if (rootMethodInstance->mMethodInfoEx != NULL)
  20777. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  20778. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  20779. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  20780. }
  20781. }
  20782. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodInstance->GetNumGenericArguments(); genericArgIdx++)
  20783. {
  20784. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  20785. if (genericArgType->IsGenericParam())
  20786. {
  20787. hasGenericParams = true;
  20788. auto genericParam = (BfGenericParamType*)genericArgType;
  20789. methodInstance->mIsUnspecialized = true;
  20790. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  20791. methodInstance->mIsUnspecializedVariation = true;
  20792. }
  20793. else
  20794. {
  20795. hasNonGenericParams = true;
  20796. if (genericArgType->IsUnspecializedType())
  20797. {
  20798. methodInstance->mIsUnspecialized = true;
  20799. methodInstance->mIsUnspecializedVariation = true;
  20800. }
  20801. }
  20802. }
  20803. if ((hasGenericParams) && (hasNonGenericParams))
  20804. {
  20805. methodInstance->mIsUnspecializedVariation = true;
  20806. }
  20807. if (typeInstance->IsUnspecializedType())
  20808. {
  20809. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  20810. // actually want to do method processing on it
  20811. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  20812. methodInstance->mIsUnspecializedVariation = true;
  20813. methodInstance->mIsUnspecialized = true;
  20814. }
  20815. if (methodInstance->mIsUnspecializedVariation)
  20816. BF_ASSERT(methodInstance->mIsUnspecialized);
  20817. //TODO: Why did we do this?
  20818. if (methodDef->mMethodType == BfMethodType_Mixin)
  20819. {
  20820. if (methodInstance->IsSpecializedGenericMethod())
  20821. methodInstance->mIsUnspecializedVariation = true;
  20822. methodInstance->mIsUnspecialized = true;
  20823. }
  20824. }
  20825. // methodDeclaration is NULL for default constructors
  20826. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  20827. {
  20828. BF_ASSERT((mCompiler->mCeMachine == NULL) || (!mCompiler->mCeMachine->mDbgPaused));
  20829. BP_ZONE("BfModule::DoMethodDeclaration");
  20830. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  20831. // to effectively make mIgnoreWrites method-scoped
  20832. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  20833. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  20834. SetAndRestoreValue<bool> prevAllowLockYield(mContext->mAllowLockYield, false);
  20835. BfTypeState typeState(mCurTypeInstance);
  20836. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20837. BfModule* resolveModule = mContext->mUnreifiedModule;
  20838. if (mCompiler->IsAutocomplete())
  20839. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  20840. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  20841. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  20842. BfMethodState methodState;
  20843. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  20844. methodState.mTempKind = BfMethodState::TempKind_Static;
  20845. defer({ mCurMethodInstance->mHasBeenDeclared = true; });
  20846. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  20847. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  20848. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  20849. // if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  20850. // {
  20851. // BF_ASSERT(mContext->mResolvingVarField);
  20852. // isTemporaryFunc = true;
  20853. // }
  20854. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  20855. FinishInit();
  20856. auto typeInstance = mCurTypeInstance;
  20857. auto typeDef = typeInstance->mTypeDef;
  20858. auto methodDef = mCurMethodInstance->mMethodDef;
  20859. if (methodDef->mName.StartsWith('_'))
  20860. {
  20861. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  20862. if (methodDef->mName == "__FATALERRORNAME")
  20863. BFMODULE_FATAL(this, "__FATALERRORNAME");
  20864. if (methodDef->mName == "__STACKOVERFLOW")
  20865. StackOverflow();
  20866. if (methodDef->mName == "__INTERNALERROR")
  20867. InternalError("Bad method name", methodDef->GetRefNode());
  20868. }
  20869. if (typeInstance->IsClosure())
  20870. {
  20871. if (methodDef->mName == "Invoke")
  20872. return;
  20873. }
  20874. auto methodInstance = mCurMethodInstance;
  20875. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  20876. addToWorkList = false;
  20877. if (!methodInstance->mHasStartedDeclaration)
  20878. StartMethodDeclaration(methodInstance, prevMethodState.mPrevVal);
  20879. BfAutoComplete* bfAutocomplete = NULL;
  20880. if (mCompiler->mResolvePassData != NULL)
  20881. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  20882. if (methodInstance->mMethodInfoEx != NULL)
  20883. {
  20884. BfTypeInstance* unspecializedTypeInstance = NULL;
  20885. Array<BfTypeReference*> deferredResolveTypes;
  20886. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  20887. {
  20888. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  20889. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  20890. {
  20891. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  20892. }
  20893. else
  20894. {
  20895. auto externConstraintDef = genericParam->GetExternConstraintDef();
  20896. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  20897. auto autoComplete = mCompiler->GetAutoComplete();
  20898. if (autoComplete != NULL)
  20899. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  20900. if (genericParam->mExternType != NULL)
  20901. {
  20902. //
  20903. }
  20904. else
  20905. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  20906. }
  20907. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized, &deferredResolveTypes);
  20908. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  20909. {
  20910. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  20911. if (bfAutocomplete != NULL)
  20912. {
  20913. for (auto nameNode : genericParamDef->mNameNodes)
  20914. {
  20915. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  20916. }
  20917. }
  20918. }
  20919. }
  20920. for (auto typeRef : deferredResolveTypes)
  20921. auto constraintType = ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_None);
  20922. if (methodInstance->mMethodInfoEx != NULL)
  20923. {
  20924. ValidateGenericParams(BfGenericParamKind_Method,
  20925. Span<BfGenericParamInstance*>((BfGenericParamInstance**)methodInstance->mMethodInfoEx->mGenericParams.mVals,
  20926. methodInstance->mMethodInfoEx->mGenericParams.mSize));
  20927. }
  20928. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  20929. AddDependency(genericParam, mCurTypeInstance);
  20930. }
  20931. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  20932. {
  20933. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  20934. BfAstNode* nameNode = methodDeclaration->mNameNode;
  20935. if (nameNode == NULL)
  20936. {
  20937. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  20938. nameNode = ctorDeclaration->mThisToken;
  20939. }
  20940. if ((autoComplete->IsAutocompleteNode(nameNode)) && (autoComplete->mResolveType != BfResolveType_Autocomplete))
  20941. {
  20942. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  20943. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  20944. autoComplete->mDefType = typeDef;
  20945. autoComplete->mDefMethod = methodDef;
  20946. autoComplete->SetDefinitionLocation(nameNode);
  20947. if (methodDef->mIsOverride)
  20948. {
  20949. bool found = false;
  20950. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  20951. {
  20952. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  20953. if (ventry.mDeclaringMethod.mMethodNum == -1)
  20954. continue;
  20955. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  20956. if (virtMethod != NULL)
  20957. {
  20958. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  20959. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  20960. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  20961. {
  20962. // Is matching method
  20963. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  20964. {
  20965. auto baseType = typeInstance->mBaseType;
  20966. if (baseType != NULL)
  20967. {
  20968. found = true;
  20969. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  20970. baseType = baseType->mBaseType;
  20971. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  20972. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  20973. autoComplete->mDefType = baseType->mTypeDef;
  20974. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  20975. }
  20976. }
  20977. break;
  20978. }
  20979. }
  20980. }
  20981. if ((!found) && (autoComplete->mIsGetDefinition) && (methodDef->mDeclaringType->IsExtension()))
  20982. {
  20983. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  20984. {
  20985. auto defaultMethod = methodGroup.mDefault;
  20986. if (defaultMethod == NULL)
  20987. continue;
  20988. if (!defaultMethod->mMethodDef->mIsExtern)
  20989. continue;
  20990. if (!CompareMethodSignatures(defaultMethod, methodInstance))
  20991. continue;
  20992. autoComplete->SetDefinitionLocation(defaultMethod->mMethodDef->GetRefNode(), true);
  20993. autoComplete->mDefType = typeInstance->mTypeDef;
  20994. autoComplete->mDefMethod = defaultMethod->mMethodDef;
  20995. }
  20996. }
  20997. }
  20998. }
  20999. }
  21000. bool reportErrors = true;
  21001. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  21002. reportErrors = true;
  21003. // Only the defining contexts needs to report errors here
  21004. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  21005. if (methodDef->mMethodType == BfMethodType_Dtor)
  21006. {
  21007. if (methodDef->mIsStatic)
  21008. {
  21009. }
  21010. else
  21011. {
  21012. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  21013. {
  21014. BfAstNode* refNode = methodDeclaration;
  21015. if (refNode == NULL)
  21016. {
  21017. // Whatever caused this ctor to be generated should have caused another failure
  21018. // But that failure might not be generated until the ctor is generated
  21019. }
  21020. else
  21021. {
  21022. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  21023. if (dtorDecl != NULL)
  21024. refNode = dtorDecl->mThisToken;
  21025. Fail("Structs cannot have destructors", refNode);
  21026. }
  21027. }
  21028. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21029. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  21030. (mCurTypeInstance != mContext->mBfObjectType))
  21031. {
  21032. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  21033. }
  21034. }
  21035. }
  21036. BfType* resolvedReturnType = NULL;
  21037. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  21038. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  21039. (methodDef->mReturnTypeRef != NULL))
  21040. {
  21041. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  21042. if (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>())
  21043. {
  21044. // An invalid 'var' error would not have been caught in the original property type pass
  21045. mIgnoreErrors = false;
  21046. }
  21047. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_NoReify);
  21048. if ((((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0) || (methodInstance->mIsAutocompleteMethod))
  21049. && (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>()))
  21050. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  21051. else
  21052. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration, flags);
  21053. if (resolvedReturnType == NULL)
  21054. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  21055. if ((methodDef->mIsReadOnly) && (!resolvedReturnType->IsRef()))
  21056. {
  21057. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration))
  21058. if (methodDeclaration->mReadOnlySpecifier != NULL)
  21059. Fail("Readonly specifier is only valid on 'ref' return types", methodDeclaration->mReadOnlySpecifier);
  21060. }
  21061. }
  21062. else
  21063. {
  21064. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  21065. }
  21066. BF_ASSERT(resolvedReturnType != NULL);
  21067. mCurMethodInstance->mReturnType = resolvedReturnType;
  21068. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  21069. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  21070. //if (!methodInstance->IsSpecializedGenericMethod())
  21071. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21072. if (methodDef->mExplicitInterface != NULL)
  21073. {
  21074. auto autoComplete = mCompiler->GetAutoComplete();
  21075. if (autoComplete != NULL)
  21076. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  21077. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  21078. BfTypeInstance* explicitInterface = NULL;
  21079. if (explicitType != NULL)
  21080. explicitInterface = explicitType->ToTypeInstance();
  21081. if (explicitInterface != NULL)
  21082. {
  21083. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  21084. if (autoComplete != NULL)
  21085. {
  21086. BfTokenNode* dotToken = NULL;
  21087. BfAstNode* nameNode = NULL;
  21088. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  21089. {
  21090. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  21091. nameNode = methodDeclaration->mNameNode;
  21092. }
  21093. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  21094. }
  21095. }
  21096. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  21097. {
  21098. bool interfaceFound = false;
  21099. for (auto ifaceInst : typeInstance->mInterfaces)
  21100. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  21101. if ((!interfaceFound) && (!typeInstance->mTypeFailed))
  21102. {
  21103. if (methodDef->mMethodDeclaration != NULL)
  21104. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  21105. else
  21106. {
  21107. // For property decls, we should have already given the error during type population
  21108. if (mCompiler->mRevision == 1)
  21109. AssertErrorState();
  21110. }
  21111. }
  21112. }
  21113. }
  21114. bool isThisStruct = mCurTypeInstance->IsStruct();
  21115. BfType* thisType = NULL;
  21116. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  21117. {
  21118. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  21119. {
  21120. thisType = mCurTypeInstance;
  21121. if (thisType == NULL)
  21122. return;
  21123. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  21124. {
  21125. BfTypeUtils::SplatIterate([&](BfType* checkType)
  21126. {
  21127. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  21128. }, thisType);
  21129. }
  21130. }
  21131. else
  21132. {
  21133. thisType = mCurTypeInstance;
  21134. resolveModule->PopulateType(thisType, BfPopulateType_Declaration);
  21135. }
  21136. }
  21137. int implicitParamCount = 0;
  21138. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  21139. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  21140. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  21141. bool hadDelegateParams = false;
  21142. bool hadParams = false;
  21143. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  21144. {
  21145. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  21146. BfParameterDef* paramDef = NULL;
  21147. int paramDefIdx = -1;
  21148. if (paramIdx < implicitParamCount)
  21149. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  21150. else
  21151. {
  21152. paramDefIdx = paramIdx - implicitParamCount;
  21153. paramDef = methodDef->mParams[paramDefIdx];
  21154. }
  21155. if (hadParams)
  21156. break;
  21157. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  21158. continue;
  21159. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  21160. (paramDef->mParamKind != BfParamKind_AppendIdx))
  21161. {
  21162. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  21163. if (mCompiler->mResolvePassData->mAutoComplete->IsAutocompleteNode(paramDef->mTypeRef))
  21164. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("token", "in"), paramDef->mTypeRef->ToString());
  21165. }
  21166. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  21167. {
  21168. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  21169. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  21170. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  21171. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  21172. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  21173. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  21174. }
  21175. BfType* resolvedParamType = NULL;
  21176. if (closureCaptureEntry != NULL)
  21177. resolvedParamType = closureCaptureEntry->mType;
  21178. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfLetTypeReference>()))
  21179. {
  21180. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  21181. resolvedParamType = mContext->mBfObjectType;
  21182. }
  21183. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfVarTypeReference>()))
  21184. {
  21185. if (methodDef->mMethodType != BfMethodType_Mixin)
  21186. {
  21187. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  21188. resolvedParamType = mContext->mBfObjectType;
  21189. }
  21190. else
  21191. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21192. }
  21193. BfType* unresolvedParamType = resolvedParamType;
  21194. bool wasGenericParam = false;
  21195. if (resolvedParamType == NULL)
  21196. {
  21197. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue | BfResolveTypeRefFlag_NoReify);
  21198. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  21199. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  21200. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  21201. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  21202. resolvedParamType = resolvedParamType->GetUnderlyingType();
  21203. }
  21204. if (resolvedParamType == NULL)
  21205. {
  21206. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21207. unresolvedParamType = resolvedParamType;
  21208. if (mCurTypeInstance->IsBoxed())
  21209. {
  21210. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  21211. // If we failed a lookup here then we better have also failed it in the original type
  21212. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.ContainsKey(boxedType->mElementType->ToTypeInstance()));
  21213. }
  21214. }
  21215. BF_ASSERT(!resolvedParamType->IsDeleting());
  21216. if (!methodInstance->IsSpecializedGenericMethod())
  21217. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21218. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  21219. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  21220. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  21221. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  21222. {
  21223. if (paramDef->mParamKind == BfParamKind_Params)
  21224. {
  21225. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  21226. if (refNode != NULL)
  21227. refNode = paramDef->mParamDeclaration->mModToken;
  21228. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  21229. }
  21230. BfTypedValue defaultValue;
  21231. if (resolvedParamType->IsConstExprValue())
  21232. {
  21233. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  21234. BfExprEvaluator exprEvaluator(this);
  21235. exprEvaluator.mExpectingType = constExprType->mType;
  21236. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  21237. defaultValue = exprEvaluator.GetResult();
  21238. }
  21239. else
  21240. {
  21241. BfTypeState typeState;
  21242. typeState.mType = mCurTypeInstance;
  21243. typeState.mCurTypeDef = methodDef->mDeclaringType;
  21244. //typeState.mCurMethodDef = methodDef;
  21245. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  21246. BfConstResolver constResolver(this);
  21247. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  21248. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  21249. {
  21250. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  21251. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  21252. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  21253. {
  21254. defaultValue = castedDefaultValue; // Good!
  21255. }
  21256. else if (!CanCast(defaultValue, resolvedParamType))
  21257. {
  21258. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  21259. // a conversion operator.
  21260. // This should throw an error
  21261. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  21262. AssertErrorState();
  21263. if (!defaultValue.mValue.IsConst())
  21264. defaultValue = BfTypedValue();
  21265. }
  21266. }
  21267. }
  21268. if (!defaultValue)
  21269. {
  21270. defaultValue = GetDefaultTypedValue(resolvedParamType);
  21271. if (!defaultValue.mValue.IsConst())
  21272. defaultValue = BfTypedValue();
  21273. }
  21274. if (defaultValue)
  21275. {
  21276. if (defaultValue.mType->IsVar())
  21277. {
  21278. AssertErrorState();
  21279. }
  21280. else
  21281. {
  21282. BF_ASSERT(defaultValue.mValue.IsConst());
  21283. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  21284. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  21285. CurrentAddToConstHolder(defaultValue.mValue);
  21286. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  21287. }
  21288. }
  21289. }
  21290. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  21291. {
  21292. bool addParams = true;
  21293. bool isValid = false;
  21294. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  21295. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->IsInstanceOf(mCompiler->mSpanTypeDef)))
  21296. {
  21297. // Span<T>
  21298. isValid = true;
  21299. }
  21300. else if (resolvedParamType->IsArray())
  21301. {
  21302. // Array is the 'normal' params type
  21303. isValid = true;
  21304. }
  21305. else if (resolvedParamType->IsSizedArray())
  21306. {
  21307. isValid = true;
  21308. }
  21309. else if (resolvedParamType->IsVar())
  21310. {
  21311. isValid = true;
  21312. }
  21313. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()) || (resolvedParamType->IsMethodRef()))
  21314. {
  21315. hadDelegateParams = true;
  21316. // This means we copy the params from a delegate
  21317. BfMethodParam methodParam;
  21318. methodParam.mResolvedType = resolvedParamType;
  21319. methodParam.mParamDefIdx = paramDefIdx;
  21320. methodParam.mDelegateParamIdx = 0;
  21321. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21322. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  21323. {
  21324. methodParam.mDelegateParamIdx = delegateParamIdx;
  21325. mCurMethodInstance->mParams.Add(methodParam);
  21326. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  21327. if (!methodInstance->IsSpecializedGenericMethod())
  21328. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21329. }
  21330. isValid = true;
  21331. addParams = false;
  21332. }
  21333. else if (resolvedParamType->IsGenericParam())
  21334. {
  21335. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  21336. if (genericParamInstance->mTypeConstraint != NULL)
  21337. {
  21338. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  21339. if ((genericParamInstance->mTypeConstraint->IsArray()) || (genericParamInstance->mTypeConstraint->IsSizedArray()))
  21340. {
  21341. BfMethodParam methodParam;
  21342. methodParam.mResolvedType = resolvedParamType;
  21343. methodParam.mParamDefIdx = paramDefIdx;
  21344. mCurMethodInstance->mParams.Add(methodParam);
  21345. isValid = true;
  21346. }
  21347. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  21348. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  21349. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  21350. {
  21351. mCurMethodInstance->mHadGenericDelegateParams = true;
  21352. isValid = true;
  21353. addParams = false;
  21354. }
  21355. }
  21356. }
  21357. else
  21358. {
  21359. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  21360. if ((paramTypeInst != NULL) &&
  21361. ((paramTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef))))
  21362. {
  21363. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  21364. isValid = true;
  21365. addParams = false;
  21366. }
  21367. }
  21368. if (!isValid)
  21369. {
  21370. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  21371. // Failure case, make it an Object[]
  21372. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  21373. }
  21374. if ((addParams) && (resolvedParamType != NULL))
  21375. {
  21376. BfMethodParam methodParam;
  21377. methodParam.mResolvedType = resolvedParamType;
  21378. methodParam.mParamDefIdx = paramDefIdx;
  21379. mCurMethodInstance->mParams.push_back(methodParam);
  21380. }
  21381. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  21382. {
  21383. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  21384. }
  21385. }
  21386. else
  21387. {
  21388. BfMethodParam methodParam;
  21389. methodParam.mResolvedType = resolvedParamType;
  21390. methodParam.mParamDefIdx = paramDefIdx;
  21391. mCurMethodInstance->mParams.Add(methodParam);
  21392. }
  21393. }
  21394. if (hadDelegateParams)
  21395. {
  21396. HashSet<String> usedNames;
  21397. Dictionary<int, int> usedParamDefIdx;
  21398. for (auto methodParam : methodDef->mParams)
  21399. {
  21400. usedNames.Add(methodParam->mName);
  21401. }
  21402. for (auto& methodParam : mCurMethodInstance->mParams)
  21403. {
  21404. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  21405. {
  21406. int* refCount = NULL;
  21407. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  21408. (*refCount)++;
  21409. }
  21410. }
  21411. for (auto& methodParam : mCurMethodInstance->mParams)
  21412. {
  21413. if (methodParam.mDelegateParamIdx != -1)
  21414. {
  21415. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  21416. methodParam.mDelegateParamNameCombine = true;
  21417. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21418. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  21419. if (usedNames.Contains(paramName))
  21420. methodParam.mDelegateParamNameCombine = true;
  21421. }
  21422. }
  21423. }
  21424. int argIdx = 0;
  21425. resolveModule->PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  21426. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  21427. {
  21428. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  21429. auto thisType = methodInstance->GetOwner();
  21430. if (methodInstance->GetParamIsSplat(thisIdx))
  21431. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  21432. else if (!thisType->IsValuelessType())
  21433. {
  21434. BfTypeCode loweredTypeCode = BfTypeCode_None;
  21435. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  21436. if ((!mIsComptimeModule) && (!methodDef->mIsMutating))
  21437. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  21438. argIdx++;
  21439. if (loweredTypeCode2 != BfTypeCode_None)
  21440. argIdx++;
  21441. }
  21442. }
  21443. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  21444. argIdx++;
  21445. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  21446. {
  21447. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  21448. BfType* checkType = methodParam.mResolvedType;
  21449. int checkArgIdx = argIdx;
  21450. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  21451. {
  21452. checkArgIdx = 0;
  21453. checkType = methodInstance->GetThisType();
  21454. }
  21455. if (checkType->IsMethodRef())
  21456. {
  21457. methodParam.mIsSplat = true;
  21458. }
  21459. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting(paramIdx)))
  21460. {
  21461. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  21462. if (checkType->IsSplattable())
  21463. {
  21464. bool isSplat = false;
  21465. auto checkTypeInstance = checkType->ToTypeInstance();
  21466. if ((checkTypeInstance != NULL) && (checkTypeInstance->mIsCRepr))
  21467. isSplat = true;
  21468. int splatCount = checkType->GetSplatCount();
  21469. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  21470. isSplat = true;
  21471. if (isSplat)
  21472. {
  21473. methodParam.mIsSplat = true;
  21474. argIdx += splatCount;
  21475. continue;
  21476. }
  21477. }
  21478. else if (!checkType->IsValuelessType())
  21479. {
  21480. BfTypeCode loweredTypeCode = BfTypeCode_None;
  21481. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  21482. if (!mIsComptimeModule)
  21483. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  21484. argIdx++;
  21485. if (loweredTypeCode2 != BfTypeCode_None)
  21486. argIdx++;
  21487. continue;
  21488. }
  21489. }
  21490. argIdx++;
  21491. }
  21492. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  21493. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  21494. {
  21495. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  21496. }
  21497. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  21498. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  21499. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  21500. (!methodDef->mIsSkipCall))
  21501. {
  21502. if (methodDeclaration->mEndSemicolon == NULL)
  21503. {
  21504. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  21505. {
  21506. //
  21507. }
  21508. else
  21509. AssertParseErrorState();
  21510. }
  21511. else
  21512. {
  21513. bool isError = true;
  21514. if (typeInstance->IsTypedPrimitive())
  21515. {
  21516. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  21517. {
  21518. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  21519. {
  21520. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  21521. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  21522. {
  21523. isError = false;
  21524. }
  21525. }
  21526. }
  21527. }
  21528. if (isError)
  21529. {
  21530. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  21531. MethodToString(methodInstance).c_str()),
  21532. methodDef->GetRefNode());
  21533. }
  21534. }
  21535. }
  21536. if (methodDef->IsEmptyPartial())
  21537. hasExternSpecifier = true;
  21538. if (!methodInstance->IsAutocompleteMethod())
  21539. {
  21540. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  21541. int implicitParamCount = methodInstance->GetImplicitParamCount();
  21542. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  21543. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  21544. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  21545. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  21546. int paramIdx = 0;
  21547. int defaultParamIdx = 0;
  21548. while (true)
  21549. {
  21550. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  21551. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  21552. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  21553. {
  21554. paramIdx++;
  21555. continue;
  21556. }
  21557. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  21558. {
  21559. defaultParamIdx++;
  21560. continue;
  21561. }
  21562. if ((isDone) || (isDefaultDone))
  21563. {
  21564. // 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
  21565. // to cause us to throw an assertion in the declaration here
  21566. if ((!defaultMethodInstance->mHadGenericDelegateParams) && (!methodInstance->mHasFailed) && (!defaultMethodInstance->mHasFailed))
  21567. BF_ASSERT((isDone) && (isDefaultDone));
  21568. break;
  21569. }
  21570. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  21571. if (paramType->IsRef())
  21572. paramType = paramType->GetUnderlyingType();
  21573. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  21574. paramIdx++;
  21575. defaultParamIdx++;
  21576. }
  21577. }
  21578. StringT<4096> mangledName;
  21579. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  21580. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  21581. {
  21582. auto paramType = methodInstance->GetParamType(paramIdx);
  21583. if (paramType->IsComposite())
  21584. resolveModule->PopulateType(paramType, BfPopulateType_Data);
  21585. if (!methodInstance->IsParamSkipped(paramIdx))
  21586. {
  21587. if (paramType->IsStruct())
  21588. {
  21589. //
  21590. }
  21591. else
  21592. {
  21593. PopulateType(paramType, BfPopulateType_Declaration);
  21594. }
  21595. }
  21596. }
  21597. // Only process method in default unspecialized mode, not in variations
  21598. if (methodInstance->mIsUnspecializedVariation)
  21599. return;
  21600. resolveModule->PopulateType(resolvedReturnType, BfPopulateType_Data);
  21601. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  21602. if (resolvedReturnType->IsValuelessType())
  21603. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  21604. if (!mBfIRBuilder->mIgnoreWrites)
  21605. {
  21606. bool isIntrinsic = false;
  21607. if (!methodInstance->mIRFunction)
  21608. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  21609. if (isIntrinsic)
  21610. {
  21611. addToWorkList = false;
  21612. }
  21613. }
  21614. else
  21615. {
  21616. GetMethodCustomAttributes(methodInstance);
  21617. }
  21618. auto func = methodInstance->mIRFunction;
  21619. // if (methodInstance->mIsReified)
  21620. // CheckHotMethod(methodInstance, mangledName);
  21621. for (auto& param : methodInstance->mParams)
  21622. {
  21623. BF_ASSERT(!param.mResolvedType->IsDeleting());
  21624. }
  21625. 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);
  21626. SizedArray<BfIRMDNode, 8> diParams;
  21627. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  21628. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  21629. {
  21630. //CS0708
  21631. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  21632. }
  21633. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  21634. {
  21635. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  21636. methodDef->mIsVirtual = false;
  21637. }
  21638. BfAstNode* mutSpecifier = NULL;
  21639. if (methodDeclaration != NULL)
  21640. mutSpecifier = methodDeclaration->mMutSpecifier;
  21641. else if (methodDef->GetPropertyMethodDeclaration() != NULL)
  21642. {
  21643. mutSpecifier = methodDef->GetPropertyMethodDeclaration()->mMutSpecifier;
  21644. if (mutSpecifier == NULL)
  21645. {
  21646. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21647. if (propertyDeclaration != NULL)
  21648. {
  21649. if (auto propExprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  21650. mutSpecifier = propExprBody->mMutSpecifier;
  21651. }
  21652. }
  21653. }
  21654. if ((mutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  21655. {
  21656. if (methodDef->mIsStatic)
  21657. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", mutSpecifier);
  21658. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  21659. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", mutSpecifier);
  21660. else if (methodDef->mMethodType == BfMethodType_Ctor)
  21661. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", mutSpecifier);
  21662. else if (methodDef->mMethodType == BfMethodType_Dtor)
  21663. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", mutSpecifier);
  21664. }
  21665. if (isTemporaryFunc)
  21666. {
  21667. // This handles temporary methods for autocomplete types
  21668. //BF_ASSERT(mIsScratchModule);
  21669. //BF_ASSERT(mCompiler->IsAutocomplete());
  21670. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  21671. return; // Bail out early for autocomplete pass
  21672. }
  21673. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  21674. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  21675. // autocompleter. Why did we have this check anyway?
  21676. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  21677. {
  21678. AddMethodReference(methodInstance);
  21679. mFuncReferences[methodInstance] = func;
  21680. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  21681. }*/
  21682. if (mParentModule != NULL)
  21683. {
  21684. // For extension modules we need to keep track of our own methods so we can know which methods
  21685. // we have defined ourselves and which are from the parent module or other extensions
  21686. if (!func.IsFake())
  21687. {
  21688. if (func)
  21689. mFuncReferences[methodInstance] = func;
  21690. }
  21691. }
  21692. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  21693. {
  21694. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  21695. auto owningModule = methodInstance->GetOwner()->mModule;
  21696. if (!owningModule->mIsScratchModule)
  21697. owningModule->mOnDemandMethodCount++;
  21698. VerifyOnDemandMethods();
  21699. }
  21700. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  21701. if (wasAwaitingDecl)
  21702. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  21703. if (addToWorkList)
  21704. {
  21705. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  21706. {
  21707. AddMethodToWorkList(methodInstance);
  21708. }
  21709. else
  21710. {
  21711. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  21712. methodInstance->mIgnoreBody = true;
  21713. if (typeInstance->IsUnspecializedType())
  21714. {
  21715. // Don't hold on to actual Function for unspecialized types
  21716. methodInstance->mIRFunction = BfIRFunction();
  21717. }
  21718. }
  21719. }
  21720. else
  21721. {
  21722. //BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  21723. }
  21724. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  21725. (!methodDef->mIsLocalMethod) &&
  21726. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  21727. (!methodDef->mReturnTypeRef->IsTemporary()))
  21728. {
  21729. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  21730. {
  21731. //TODO:
  21732. //CS0053
  21733. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  21734. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  21735. methodDef->mReturnTypeRef, true);
  21736. }
  21737. else
  21738. {
  21739. //CS0050
  21740. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  21741. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  21742. methodDef->mReturnTypeRef, true);
  21743. }
  21744. }
  21745. if (typeInstance->IsInterface())
  21746. {
  21747. if (methodDef->mMethodType == BfMethodType_Ctor)
  21748. Fail("Interfaces cannot contain constructors", methodDeclaration);
  21749. if (methodDeclaration != NULL)
  21750. {
  21751. if (methodDef->mBody == NULL)
  21752. {
  21753. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  21754. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  21755. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  21756. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  21757. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  21758. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  21759. }
  21760. }
  21761. }
  21762. bool foundHiddenMethod = false;
  21763. BfTokenNode* virtualToken = NULL;
  21764. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21765. if (propertyDeclaration != NULL)
  21766. virtualToken = propertyDeclaration->mVirtualSpecifier;
  21767. else if (methodDeclaration != NULL)
  21768. virtualToken = methodDeclaration->mVirtualSpecifier;
  21769. // Don't compare specialized generic methods against normal methods
  21770. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  21771. (!methodDef->mIsLocalMethod) && (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  21772. {
  21773. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  21774. {
  21775. typeDef->PopulateMemberSets();
  21776. BfMethodDef* nextMethod = NULL;
  21777. BfMemberSetEntry* entry = NULL;
  21778. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21779. nextMethod = (BfMethodDef*)entry->mMemberDef;
  21780. while (nextMethod != NULL)
  21781. {
  21782. auto checkMethod = nextMethod;
  21783. nextMethod = nextMethod->mNextWithSameName;
  21784. if (checkMethod == methodDef)
  21785. continue;
  21786. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21787. if (checkMethodInstance == NULL)
  21788. {
  21789. if ((methodDef->mDeclaringType->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension()))
  21790. checkMethodInstance = GetRawMethodInstanceAtIdx(typeInstance, checkMethod->mIdx);
  21791. if (checkMethodInstance == NULL)
  21792. continue;
  21793. }
  21794. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  21795. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  21796. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  21797. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  21798. {
  21799. bool canChain = false;
  21800. if ((methodDef->mParams.empty()) &&
  21801. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  21802. {
  21803. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  21804. canChain = true;
  21805. else if (methodDef->mMethodType == BfMethodType_Normal)
  21806. {
  21807. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  21808. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  21809. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  21810. canChain = true;
  21811. }
  21812. }
  21813. if (canChain)
  21814. {
  21815. bool isBetter;
  21816. bool isWorse;
  21817. CompareDeclTypes(typeInstance, checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  21818. if (isBetter && !isWorse)
  21819. {
  21820. methodInstance->mChainType = BfMethodChainType_ChainHead;
  21821. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  21822. }
  21823. else
  21824. {
  21825. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  21826. methodInstance->mChainType = BfMethodChainType_ChainMember;
  21827. }
  21828. }
  21829. else
  21830. {
  21831. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  21832. continue;
  21833. bool silentlyAllow = false;
  21834. bool extensionWarn = false;
  21835. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  21836. {
  21837. if (typeInstance->IsInterface())
  21838. {
  21839. if (methodDef->mIsOverride)
  21840. silentlyAllow = true;
  21841. }
  21842. else
  21843. {
  21844. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  21845. {
  21846. silentlyAllow = true;
  21847. methodInstance->mIsInnerOverride = true;
  21848. CheckOverridenMethod(methodInstance, checkMethodInstance);
  21849. }
  21850. else if (!checkMethod->mDeclaringType->IsExtension())
  21851. {
  21852. foundHiddenMethod = true;
  21853. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  21854. silentlyAllow = true;
  21855. else if (methodDef->mIsNew)
  21856. {
  21857. silentlyAllow = true;
  21858. }
  21859. else if (checkMethod->GetMethodDeclaration() == NULL)
  21860. silentlyAllow = true;
  21861. else if (methodDef->mIsOverride)
  21862. silentlyAllow = true;
  21863. else
  21864. extensionWarn = true;
  21865. }
  21866. else
  21867. silentlyAllow = true;
  21868. }
  21869. }
  21870. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  21871. silentlyAllow = true;
  21872. if (checkMethod->mMethodDeclaration == NULL)
  21873. {
  21874. // This can allow emission of a default ctor if we've already auto-added a default ctor
  21875. silentlyAllow = true;
  21876. }
  21877. if (!silentlyAllow)
  21878. {
  21879. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  21880. {
  21881. auto refNode = methodDef->GetRefNode();
  21882. BfError* bfError;
  21883. if (extensionWarn)
  21884. {
  21885. if (methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject)
  21886. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  21887. 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'.",
  21888. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  21889. else
  21890. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  21891. "This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional.", refNode);
  21892. }
  21893. else
  21894. {
  21895. bfError = Fail(StrFormat("Method '%s' already declared with the same parameter types", MethodToString(checkMethodInstance).c_str()), refNode, true);
  21896. }
  21897. if ((bfError != NULL) && (checkMethod->GetRefNode() != refNode))
  21898. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  21899. }
  21900. }
  21901. }
  21902. }
  21903. }
  21904. }
  21905. // Virtual methods give their error while slotting
  21906. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  21907. (!methodDef->mIsLocalMethod) &&
  21908. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  21909. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  21910. {
  21911. auto baseType = typeInstance->mBaseType;
  21912. while (baseType != NULL)
  21913. {
  21914. auto baseTypeDef = baseType->mTypeDef;
  21915. baseTypeDef->PopulateMemberSets();
  21916. BfMethodDef* checkMethod = NULL;
  21917. BfMemberSetEntry* entry = NULL;
  21918. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21919. checkMethod = (BfMethodDef*)entry->mMemberDef;
  21920. while (checkMethod != NULL)
  21921. {
  21922. if (checkMethod->mMethodDeclaration == NULL)
  21923. {
  21924. checkMethod = checkMethod->mNextWithSameName;
  21925. continue;
  21926. }
  21927. if (baseType->mMethodInstanceGroups.size() == 0)
  21928. {
  21929. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  21930. break;
  21931. }
  21932. if (checkMethod == methodDef)
  21933. {
  21934. checkMethod = checkMethod->mNextWithSameName;
  21935. continue;
  21936. }
  21937. if (checkMethod->mName != methodDef->mName)
  21938. {
  21939. checkMethod = checkMethod->mNextWithSameName;
  21940. continue;
  21941. }
  21942. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  21943. if (checkMethodInstance != NULL)
  21944. {
  21945. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  21946. (checkMethod->mProtection != BfProtection_Private) &&
  21947. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  21948. {
  21949. if ((!methodDef->mIsNew) && (!checkMethod->mDeclaringType->IsExtension()))
  21950. {
  21951. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  21952. if (refNode != NULL)
  21953. {
  21954. 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?
  21955. if (bfError != NULL)
  21956. {
  21957. bfError->mIsPersistent = true;
  21958. mCompiler->mPassInstance->MoreInfo("See inherited method", checkMethod->GetRefNode());
  21959. }
  21960. }
  21961. }
  21962. foundHiddenMethod = true;
  21963. break;
  21964. }
  21965. }
  21966. checkMethod = checkMethod->mNextWithSameName;
  21967. }
  21968. if (foundHiddenMethod)
  21969. break;
  21970. baseType = baseType->mBaseType;
  21971. }
  21972. if ((methodDef->mIsNew) && (!foundHiddenMethod) && (!mCurTypeInstance->IsSpecializedType()))
  21973. {
  21974. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21975. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  21976. methodDeclaration->mNewSpecifier;
  21977. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  21978. }
  21979. }
  21980. }
  21981. if ((methodDef->mIsConcrete) && (!methodInstance->mIsForeignMethodDef) && (!mCurTypeInstance->IsInterface()))
  21982. {
  21983. Fail("Only interfaces methods can be declared as 'concrete'", methodDeclaration->mVirtualSpecifier);
  21984. }
  21985. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic) && (!methodInstance->mIsInnerOverride))
  21986. {
  21987. if ((virtualToken != NULL) && (virtualToken->mToken == BfToken_Override) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  21988. Fail("No suitable method found to override", virtualToken, true);
  21989. else
  21990. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  21991. }
  21992. else if (methodDef->mIsVirtual)
  21993. {
  21994. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  21995. Fail("Virtual or abstract members cannot be 'private'", virtualToken, true);
  21996. if ((methodDef->mProtection == BfProtection_Internal) && (virtualToken != NULL))
  21997. Fail("Virtual or abstract members cannot be 'internal'. Consider using the 'protected internal' access specifier.", virtualToken, true);
  21998. }
  21999. mCompiler->mStats.mMethodDeclarations++;
  22000. mCompiler->UpdateCompletion();
  22001. }
  22002. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  22003. {
  22004. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  22005. auto typeInstance = mCurTypeInstance;
  22006. auto methodDef = methodInstance->mMethodDef;
  22007. int virtualMethodMatchIdx = -1;
  22008. if (typeInstance->mHotTypeData != NULL)
  22009. {
  22010. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  22011. {
  22012. BF_ASSERT(mCompiler->IsHotCompile());
  22013. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  22014. // may slot this override anyway (?)
  22015. int vTableStart = 0;
  22016. auto implBaseType = typeInstance->GetImplBaseType();
  22017. if (implBaseType != NULL)
  22018. vTableStart = implBaseType->mVirtualMethodTableSize;
  22019. StringT<512> mangledName;
  22020. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  22021. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  22022. {
  22023. // O(1) checking when virtual methods haven't changed
  22024. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  22025. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  22026. if (mangledName == entry.mFuncName)
  22027. {
  22028. virtualMethodMatchIdx = vTableStart + checkIdx;
  22029. break;
  22030. }
  22031. }
  22032. if (virtualMethodMatchIdx != -1)
  22033. {
  22034. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22035. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  22036. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  22037. }
  22038. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  22039. }
  22040. }
  22041. if (virtualMethodMatchIdx == -1)
  22042. {
  22043. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  22044. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  22045. typeInstance->mVirtualMethodTable.push_back(entry);
  22046. }
  22047. }
  22048. void BfModule::CompareDeclTypes(BfTypeInstance* typeInst, BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  22049. {
  22050. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  22051. {
  22052. // When we provide an extension override in the same project a root type override
  22053. isBetter = true;
  22054. isWorse = false;
  22055. }
  22056. else
  22057. {
  22058. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22059. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22060. }
  22061. if ((isBetter == isWorse) && (typeInst != NULL) && (newDeclType->IsExtension()) && (prevDeclType->IsExtension()))
  22062. {
  22063. if ((typeInst->mGenericTypeInfo != NULL) && (typeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL))
  22064. {
  22065. isBetter = false;
  22066. isWorse = false;
  22067. auto newConstraints = typeInst->GetGenericParamsVector(newDeclType);
  22068. auto prevConstraints = typeInst->GetGenericParamsVector(prevDeclType);
  22069. for (int genericIdx = 0; genericIdx < (int)newConstraints->size(); genericIdx++)
  22070. {
  22071. auto newConstraint = (*newConstraints)[genericIdx];
  22072. auto prevConstraint = (*prevConstraints)[genericIdx];
  22073. bool newIsSubset = AreConstraintsSubset(newConstraint, prevConstraint);
  22074. bool prevIsSubset = AreConstraintsSubset(prevConstraint, newConstraint);
  22075. if ((prevIsSubset) && (!newIsSubset))
  22076. isBetter = true;
  22077. if ((!prevIsSubset) && (newIsSubset))
  22078. isWorse = true;
  22079. }
  22080. }
  22081. }
  22082. }
  22083. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  22084. {
  22085. BP_ZONE("BfModule::SlotVirtualMethod");
  22086. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  22087. return false;
  22088. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  22089. {
  22090. if (!mCompiler->mOptions.mAllowHotSwapping)
  22091. return;
  22092. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  22093. return;
  22094. if (methodInstance->mHotMethod == NULL)
  22095. CheckHotMethod(methodInstance, "");
  22096. if (methodInstance->mHotMethod == NULL)
  22097. return;
  22098. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  22099. if (declMethodInstance->mHotMethod == NULL)
  22100. CheckHotMethod(declMethodInstance, "");
  22101. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  22102. virtualDecl->mRefCount++;
  22103. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  22104. };
  22105. auto typeInstance = mCurTypeInstance;
  22106. auto typeDef = typeInstance->mTypeDef;
  22107. auto methodDef = methodInstance->mMethodDef;
  22108. auto methodDeclaration = methodDef->GetMethodDeclaration();
  22109. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22110. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  22111. if (methodInstance->mIsInnerOverride)
  22112. return false;
  22113. BfAstNode* declaringNode = methodDeclaration;
  22114. if (propertyMethodDeclaration != NULL)
  22115. declaringNode = propertyMethodDeclaration->mNameNode;
  22116. BfMethodInstance* methodOverriden = NULL;
  22117. bool usedMethod = false;
  22118. BfTokenNode* virtualToken = NULL;
  22119. if (propertyDeclaration != NULL)
  22120. virtualToken = propertyDeclaration->mVirtualSpecifier;
  22121. else if (methodDeclaration != NULL)
  22122. virtualToken = methodDeclaration->mVirtualSpecifier;
  22123. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  22124. {
  22125. //Fail: Static members cannot be marked as override, virtual, or abstract
  22126. }
  22127. else if (methodDef->mIsVirtual)
  22128. {
  22129. if (IsHotCompile())
  22130. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  22131. BfTypeInstance* checkBase = typeInstance;
  22132. // If we are in an extension, look in ourselves first
  22133. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  22134. checkBase = checkBase->mBaseType;
  22135. if (typeInstance->IsValueType())
  22136. {
  22137. if (typeInstance->mBaseType == NULL)
  22138. return false; // It's actually ValueType
  22139. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  22140. if (!methodDef->mIsOverride)
  22141. {
  22142. Fail("Structs cannot have virtual methods", virtualToken, true);
  22143. return false;
  22144. }
  22145. checkBase = mContext->mBfObjectType;
  22146. if (checkBase->mVirtualMethodTableSize == 0)
  22147. PopulateType(checkBase, BfPopulateType_Full);
  22148. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  22149. return false; // System circular ref, don't do struct checking on those
  22150. }
  22151. int virtualMethodMatchIdx = -1;
  22152. bool hadHidingError = false;
  22153. BfMethodInstance* bestOverrideMethodInstance = NULL;
  22154. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  22155. int bestOverrideMethodIdx = -1;
  22156. int ambiguousOverrideMethodIdx = -1;
  22157. if (checkBase != NULL)
  22158. {
  22159. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22160. auto lookupType = checkBase;
  22161. while (lookupType != NULL)
  22162. {
  22163. lookupType->mTypeDef->PopulateMemberSets();
  22164. BfMethodDef* nextMethodDef = NULL;
  22165. BfMemberSetEntry* entry;
  22166. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  22167. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  22168. while (nextMethodDef != NULL)
  22169. {
  22170. auto checkMethodDef = nextMethodDef;
  22171. nextMethodDef = nextMethodDef->mNextWithSameName;
  22172. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  22173. continue;
  22174. BfMethodInstance* baseMethodInstance = NULL;
  22175. int checkMethodIdx = -1;
  22176. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  22177. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  22178. {
  22179. if (lookupType->IsUnspecializedTypeVariation())
  22180. {
  22181. if (!lookupMethodInstance->mMethodDef->mIsOverride)
  22182. {
  22183. baseMethodInstance = lookupMethodInstance;
  22184. checkMethodIdx = -2;
  22185. }
  22186. }
  22187. if (baseMethodInstance == NULL)
  22188. continue;
  22189. }
  22190. if (baseMethodInstance == NULL)
  22191. {
  22192. checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  22193. if (checkMethodIdx >= baseVirtualMethodTable.mSize)
  22194. {
  22195. Fail("SlotVirtualMethod out of bounds", checkMethodDef->GetRefNode());
  22196. continue;
  22197. }
  22198. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22199. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22200. {
  22201. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22202. continue;
  22203. }
  22204. baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22205. if (baseMethodInstance == NULL)
  22206. {
  22207. AssertErrorState();
  22208. continue;
  22209. }
  22210. }
  22211. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22212. {
  22213. if (methodDef->mIsOverride)
  22214. {
  22215. BfMethodInstance* checkMethodInstance;
  22216. if (checkMethodIdx == -2)
  22217. checkMethodInstance = baseMethodInstance;
  22218. else if (typeInstance->IsValueType())
  22219. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22220. else
  22221. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22222. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22223. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22224. continue;
  22225. if (bestOverrideMethodInstance != NULL)
  22226. {
  22227. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22228. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22229. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22230. if (isBetter == isWorse)
  22231. {
  22232. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22233. }
  22234. else
  22235. {
  22236. if (isWorse)
  22237. continue;
  22238. ambiguousOverrideMethodInstance = NULL;
  22239. }
  22240. }
  22241. bestOverrideMethodInstance = checkMethodInstance;
  22242. bestOverrideMethodIdx = checkMethodIdx;
  22243. }
  22244. else
  22245. {
  22246. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22247. {
  22248. if (!hadHidingError)
  22249. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22250. hadHidingError = true;
  22251. }
  22252. }
  22253. }
  22254. }
  22255. lookupType = lookupType->mBaseType;
  22256. }
  22257. }
  22258. //TODO:
  22259. if ((checkBase != NULL)
  22260. && (false)
  22261. )
  22262. {
  22263. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22264. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  22265. {
  22266. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22267. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22268. {
  22269. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22270. continue;
  22271. }
  22272. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22273. if (baseMethodInstance == NULL)
  22274. {
  22275. AssertErrorState();
  22276. continue;
  22277. }
  22278. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22279. {
  22280. if (methodDef->mIsOverride)
  22281. {
  22282. BfMethodInstance* checkMethodInstance;
  22283. if (typeInstance->IsValueType())
  22284. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22285. else
  22286. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22287. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22288. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22289. continue;
  22290. if (bestOverrideMethodInstance != NULL)
  22291. {
  22292. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22293. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22294. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22295. if (isBetter == isWorse)
  22296. {
  22297. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22298. }
  22299. else
  22300. {
  22301. if (isWorse)
  22302. continue;
  22303. ambiguousOverrideMethodInstance = NULL;
  22304. }
  22305. }
  22306. bestOverrideMethodInstance = checkMethodInstance;
  22307. bestOverrideMethodIdx = checkMethodIdx;
  22308. }
  22309. else
  22310. {
  22311. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22312. {
  22313. if (!hadHidingError)
  22314. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22315. hadHidingError = true;
  22316. }
  22317. }
  22318. }
  22319. }
  22320. }
  22321. if (bestOverrideMethodInstance != NULL)
  22322. {
  22323. if (ambiguousOverrideMethodInstance != NULL)
  22324. {
  22325. bool allow = false;
  22326. // 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.
  22327. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  22328. bool canSeeEachOther = false;
  22329. //
  22330. {
  22331. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  22332. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  22333. canSeeEachOther = true;
  22334. }
  22335. //
  22336. {
  22337. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  22338. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  22339. canSeeEachOther = true;
  22340. }
  22341. if (!canSeeEachOther)
  22342. {
  22343. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  22344. }
  22345. else
  22346. {
  22347. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  22348. if (error != NULL)
  22349. {
  22350. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  22351. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  22352. }
  22353. }
  22354. }
  22355. }
  22356. if (bestOverrideMethodIdx == -2)
  22357. {
  22358. // Comes from an unspecialized variation
  22359. virtualMethodMatchIdx = bestOverrideMethodIdx;
  22360. }
  22361. else if ((bestOverrideMethodInstance != NULL) && (bestOverrideMethodIdx != -1))
  22362. {
  22363. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22364. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  22365. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  22366. {
  22367. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  22368. {
  22369. BfTypeReference* returnTypeRef;
  22370. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22371. {
  22372. returnTypeRef = propertyDeclaration->mTypeRef;
  22373. Fail("Property differs from overridden property by type", returnTypeRef, true);
  22374. }
  22375. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22376. {
  22377. returnTypeRef = methodDeclaration->mReturnType;
  22378. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  22379. }
  22380. else
  22381. {
  22382. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  22383. }
  22384. return usedMethod;
  22385. }
  22386. }
  22387. if (methodDef->mIsOverride)
  22388. {
  22389. // We can have multiple matches when a virtual method is used to implement interface methods
  22390. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  22391. // vtable entries for this method signature
  22392. virtualMethodMatchIdx = bestOverrideMethodIdx;
  22393. if (!typeInstance->IsValueType())
  22394. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22395. if (typeInstance->IsValueType())
  22396. {
  22397. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22398. }
  22399. else
  22400. {
  22401. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22402. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  22403. BfMethodInstance* setMethodInstance = methodInstance;
  22404. bool doOverride = false;
  22405. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22406. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  22407. {
  22408. methodOverriden = overridenRef;
  22409. doOverride = true;
  22410. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  22411. {
  22412. bool isBetter = false;
  22413. bool isWorse = false;
  22414. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  22415. if (isBetter == isWorse)
  22416. {
  22417. // We have to resolve later per-project
  22418. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  22419. {
  22420. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22421. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  22422. }
  22423. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  22424. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  22425. doOverride = false;
  22426. }
  22427. else
  22428. {
  22429. if ((isBetter) && (ambiguityContext != NULL))
  22430. {
  22431. ambiguityContext->Remove(virtualMethodMatchIdx);
  22432. }
  22433. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  22434. {
  22435. if (preferRootDefinition)
  22436. {
  22437. // Leave the master GCMarkMember
  22438. isBetter = false;
  22439. isWorse = true;
  22440. }
  22441. }
  22442. doOverride = isBetter;
  22443. }
  22444. }
  22445. }
  22446. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  22447. {
  22448. methodOverriden = overridenRef;
  22449. doOverride = true;
  22450. }
  22451. if (doOverride)
  22452. {
  22453. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22454. _AddVirtualDecl(declMethodInstance);
  22455. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22456. auto& implMethodRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22457. if ((!mCompiler->mIsResolveOnly) && (implMethodRef.mMethodNum >= 0) &&
  22458. (implMethodRef.mTypeInstance == typeInstance) && (methodInstance->GetOwner() == typeInstance))
  22459. {
  22460. auto prevImplMethodInstance = (BfMethodInstance*)implMethodRef;
  22461. if (prevImplMethodInstance->mMethodDef->mDeclaringType->mProject != methodInstance->mMethodDef->mDeclaringType->mProject)
  22462. {
  22463. // We may need to have to previous method reified when we must re-slot in another project during vdata creation
  22464. BfReifyMethodDependency dep;
  22465. dep.mDepMethod = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22466. dep.mMethodIdx = implMethodRef.mMethodNum;
  22467. typeInstance->mReifyMethodDependencies.Add(dep);
  22468. }
  22469. if (!methodInstance->mMangleWithIdx)
  22470. {
  22471. // Keep mangled names from conflicting
  22472. methodInstance->mMangleWithIdx = true;
  22473. if ((methodInstance->mIRFunction) && (methodInstance->mDeclModule->mIsModuleMutable))
  22474. {
  22475. StringT<4096> mangledName;
  22476. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  22477. methodInstance->mDeclModule->mBfIRBuilder->SetFunctionName(methodInstance->mIRFunction, mangledName);
  22478. }
  22479. }
  22480. }
  22481. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  22482. }
  22483. }
  22484. if (methodOverriden != NULL)
  22485. {
  22486. CheckOverridenMethod(methodInstance, methodOverriden);
  22487. }
  22488. }
  22489. }
  22490. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  22491. {
  22492. if (methodDef->mIsOverride)
  22493. {
  22494. BfTokenNode* overrideToken = NULL;
  22495. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  22496. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  22497. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22498. overrideToken = methodDeclaration->mVirtualSpecifier;
  22499. if (overrideToken != NULL)
  22500. {
  22501. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  22502. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  22503. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  22504. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  22505. else
  22506. Fail("No suitable method found to override", overrideToken, true);
  22507. }
  22508. return usedMethod;
  22509. }
  22510. UniqueSlotVirtualMethod(methodInstance);
  22511. }
  22512. else
  22513. usedMethod = true;
  22514. if (typeInstance->IsValueType())
  22515. return usedMethod;
  22516. }
  22517. bool foundInterface = false;
  22518. bool hadAnyMatch = false;
  22519. // See if this method matches interfaces
  22520. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  22521. {
  22522. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  22523. if (ifaceInst->IsIncomplete())
  22524. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  22525. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  22526. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  22527. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  22528. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  22529. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  22530. continue;
  22531. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  22532. continue;
  22533. bool hadMatch = false;
  22534. BfMethodInstance* hadNameMatch = NULL;
  22535. BfType* expectedReturnType = NULL;
  22536. bool showedError = false;
  22537. // We go through our VTable looking for NULL entries within the interface sections
  22538. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  22539. // because a normal method declared in this type could have matched earlier
  22540. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  22541. ifaceInst->mTypeDef->PopulateMemberSets();
  22542. BfMethodDef* checkMethodDef = NULL;
  22543. BfMemberSetEntry* entry;
  22544. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  22545. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  22546. while (checkMethodDef != NULL)
  22547. {
  22548. int iMethodIdx = checkMethodDef->mIdx;
  22549. int iTableIdx = iMethodIdx + startIdx;
  22550. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  22551. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  22552. bool storeIFaceMethod = false;
  22553. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  22554. {
  22555. checkMethodDef = checkMethodDef->mNextWithSameName;
  22556. continue;
  22557. }
  22558. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  22559. auto iMethodInst = iMethodGroup.mDefault;
  22560. if (iMethodInst == NULL)
  22561. {
  22562. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  22563. AssertErrorState();
  22564. checkMethodDef = checkMethodDef->mNextWithSameName;
  22565. continue;
  22566. }
  22567. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  22568. hadNameMatch = iMethodInst;
  22569. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  22570. if ((!doesMethodSignatureMatch) && (interfaceMethodEntry->mMethodRef.IsNull()))
  22571. {
  22572. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  22573. }
  22574. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  22575. {
  22576. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  22577. {
  22578. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  22579. {
  22580. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  22581. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  22582. if (error != NULL)
  22583. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  22584. showedError = true;
  22585. }
  22586. }
  22587. }
  22588. if (doesMethodSignatureMatch)
  22589. {
  22590. usedMethod = true;
  22591. hadMatch = true;
  22592. hadAnyMatch = true;
  22593. storeIFaceMethod = true;
  22594. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  22595. {
  22596. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  22597. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance) && (!mIsComptimeModule))
  22598. {
  22599. // When autocompletion regenerates a single method body but not the whole type then
  22600. // we will see ourselves in the vtable already
  22601. return usedMethod;
  22602. }
  22603. bool isBetter = false;
  22604. bool isWorse = false;
  22605. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  22606. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  22607. if (isBetter == isWorse)
  22608. {
  22609. isBetter = methodInstance->mReturnType == iMethodInst->mReturnType;
  22610. isWorse = prevMethod->mReturnType == iMethodInst->mReturnType;
  22611. }
  22612. if (isBetter == isWorse)
  22613. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  22614. if (isBetter == isWorse)
  22615. {
  22616. if (ambiguityContext != NULL)
  22617. {
  22618. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  22619. }
  22620. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  22621. storeIFaceMethod = true;
  22622. }
  22623. else
  22624. {
  22625. if ((isBetter) && (ambiguityContext != NULL))
  22626. ambiguityContext->Remove(~iTableIdx);
  22627. storeIFaceMethod = isBetter;
  22628. }
  22629. }
  22630. }
  22631. if (storeIFaceMethod)
  22632. {
  22633. if (methodInstance->GetNumGenericParams() != 0)
  22634. _AddVirtualDecl(iMethodInst);
  22635. *iMethodPtr = methodInstance;
  22636. }
  22637. checkMethodDef = checkMethodDef->mNextWithSameName;
  22638. }
  22639. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  22640. {
  22641. if (expectedReturnType != NULL)
  22642. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  22643. else if (hadNameMatch != NULL)
  22644. {
  22645. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  22646. if (error != NULL)
  22647. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  22648. }
  22649. else
  22650. {
  22651. auto propertyDecl = methodDef->GetPropertyDeclaration();
  22652. if (propertyDecl != NULL)
  22653. {
  22654. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  22655. String name;
  22656. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  22657. name = "this[]";
  22658. else if (propertyDecl->mNameNode != NULL)
  22659. propertyDecl->mNameNode->ToString(name);
  22660. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  22661. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  22662. }
  22663. else
  22664. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  22665. }
  22666. }
  22667. }
  22668. // Any overriden virtual methods that were used in interfaces also need to be replaced
  22669. if (methodOverriden != NULL)
  22670. {
  22671. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  22672. {
  22673. if (methodEntry.mMethodRef == methodOverriden)
  22674. methodEntry.mMethodRef = methodInstance;
  22675. }
  22676. }
  22677. return usedMethod;
  22678. }
  22679. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  22680. {
  22681. auto methodDef = methodInstance->mMethodDef;
  22682. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  22683. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  22684. {
  22685. const char* protectionNames[] = { "disabled", "hidden", "private", "internal", "protected", "protected internal", "public" };
  22686. BF_STATIC_ASSERT(BF_ARRAY_COUNT(protectionNames) == BfProtection_COUNT);
  22687. BfAstNode* protectionRefNode = NULL;
  22688. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  22689. {
  22690. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  22691. if (protectionRefNode == NULL)
  22692. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  22693. if (protectionRefNode == NULL)
  22694. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  22695. }
  22696. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22697. {
  22698. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  22699. if (protectionRefNode == NULL)
  22700. protectionRefNode = methodDeclaration->mNameNode;
  22701. }
  22702. if (protectionRefNode != NULL)
  22703. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  22704. }
  22705. }
  22706. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  22707. {
  22708. auto typeInstance = mCurTypeInstance;
  22709. auto methodDef = methodInstance->mMethodDef;
  22710. if (methodDef->mMethodType == BfMethodType_Ctor)
  22711. return true;
  22712. bool foundOverride = false;
  22713. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  22714. {
  22715. auto methodDeclaration = methodDef->GetMethodDeclaration();
  22716. BfAstNode* refNode = NULL;
  22717. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22718. refNode = propertyDeclaration->mProtectionSpecifier;
  22719. else if (methodDeclaration != NULL)
  22720. refNode = methodDeclaration->mProtectionSpecifier;
  22721. Fail("Private interface methods must provide a body", refNode);
  22722. }
  22723. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  22724. {
  22725. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  22726. }
  22727. BfAstNode* declaringNode = methodDef->GetRefNode();
  22728. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  22729. {
  22730. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  22731. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  22732. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  22733. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  22734. continue;
  22735. ifaceInst->mTypeDef->PopulateMemberSets();
  22736. BfMethodDef* nextMethod = NULL;
  22737. BfMemberSetEntry* entry = NULL;
  22738. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22739. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22740. while (nextMethod != NULL)
  22741. {
  22742. auto checkMethod = nextMethod;
  22743. nextMethod = nextMethod->mNextWithSameName;
  22744. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22745. if (ifaceMethod == NULL)
  22746. continue;
  22747. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22748. {
  22749. if (methodDef->mIsOverride)
  22750. {
  22751. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  22752. {
  22753. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  22754. if (error != NULL)
  22755. {
  22756. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  22757. }
  22758. }
  22759. foundOverride = true;
  22760. }
  22761. else if (!methodDef->mIsNew)
  22762. {
  22763. 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);
  22764. if (error != NULL)
  22765. {
  22766. mCompiler->mPassInstance->MoreInfo("See inherited method", ifaceMethod->mMethodDef->GetRefNode());
  22767. }
  22768. }
  22769. }
  22770. }
  22771. }
  22772. if ((methodDef->mIsOverride) && (!foundOverride))
  22773. {
  22774. // This allows us to declare a method in the base definition or in an extension and then provide
  22775. // an implementation in a more-specific extension
  22776. typeInstance->mTypeDef->PopulateMemberSets();
  22777. BfMethodDef* nextMethod = NULL;
  22778. BfMemberSetEntry* entry = NULL;
  22779. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22780. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22781. while (nextMethod != NULL)
  22782. {
  22783. auto checkMethod = nextMethod;
  22784. nextMethod = nextMethod->mNextWithSameName;
  22785. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22786. if (ifaceMethod == NULL)
  22787. continue;
  22788. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  22789. continue;
  22790. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22791. {
  22792. foundOverride = true;
  22793. }
  22794. }
  22795. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  22796. // {
  22797. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  22798. // if (ifaceMethod == NULL)
  22799. // continue;
  22800. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  22801. // continue;
  22802. //
  22803. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22804. // {
  22805. // foundOverride = true;
  22806. // }
  22807. // }
  22808. }
  22809. if (methodDef->mIsOverride)
  22810. {
  22811. if (!foundOverride)
  22812. {
  22813. BfTokenNode* overrideToken = NULL;
  22814. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22815. overrideToken = propertyDeclaration->mVirtualSpecifier;
  22816. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22817. overrideToken = methodDeclaration->mVirtualSpecifier;
  22818. if (overrideToken != NULL)
  22819. {
  22820. Fail("No suitable method found to override", overrideToken, true);
  22821. }
  22822. else
  22823. {
  22824. // Possible cause - DTOR with params
  22825. AssertErrorState();
  22826. }
  22827. }
  22828. return true;
  22829. }
  22830. // Generic methods can't be called virtually
  22831. if (methodInstance->GetNumGenericParams() != 0)
  22832. return true;
  22833. // Only public methods can be called virtually
  22834. if (methodDef->mProtection != BfProtection_Public)
  22835. return true;
  22836. UniqueSlotVirtualMethod(methodInstance);
  22837. return true;
  22838. }
  22839. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  22840. {
  22841. if (methodInstance->mMethodInfoEx == NULL)
  22842. return;
  22843. int wantMinDepth = -1;
  22844. if (mCurTypeInstance != NULL)
  22845. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  22846. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  22847. {
  22848. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  22849. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  22850. wantMinDepth = wantTypeMinDepth;
  22851. }
  22852. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  22853. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  22854. }
  22855. void BfModule::DbgFinish()
  22856. {
  22857. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  22858. return;
  22859. if (mAwaitingInitFinish)
  22860. FinishInit();
  22861. if (mHasForceLinkMarker)
  22862. return;
  22863. String markerName;
  22864. BfIRValue linkMarker;
  22865. if (mBfIRBuilder->DbgHasInfo())
  22866. {
  22867. bool needForceLinking = false;
  22868. if (WantsDebugHelpers())
  22869. {
  22870. for (auto& ownedType : mOwnedTypeInstances)
  22871. {
  22872. bool hasConfirmedReference = false;
  22873. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  22874. {
  22875. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  22876. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  22877. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)) &&
  22878. (methodInstGroup.mHasEmittedReference))
  22879. {
  22880. hasConfirmedReference = true;
  22881. }
  22882. }
  22883. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  22884. needForceLinking = true;
  22885. }
  22886. }
  22887. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  22888. {
  22889. BfMethodState methodState;
  22890. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  22891. methodState.mTempKind = BfMethodState::TempKind_Static;
  22892. mHasForceLinkMarker = true;
  22893. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  22894. SizedArray<BfIRType, 0> paramTypes;
  22895. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  22896. String linkName = "FORCELINKMOD_" + mModuleName;
  22897. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  22898. mBfIRBuilder->SetActiveFunction(func);
  22899. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  22900. mBfIRBuilder->SetInsertPoint(entryBlock);
  22901. auto firstType = mOwnedTypeInstances[0];
  22902. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  22903. SizedArray<BfIRMDNode, 1> diParamTypes;
  22904. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  22905. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  22906. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  22907. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  22908. methodState.mCurScope->mDIScope = diScope;
  22909. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  22910. SizedArray<BfIRValue, 8> args;
  22911. BfExprEvaluator exprEvaluator(this);
  22912. for (auto& ownedType : mOwnedTypeInstances)
  22913. {
  22914. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  22915. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  22916. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  22917. }
  22918. mBfIRBuilder->CreateRetVoid();
  22919. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  22920. }
  22921. }
  22922. }
  22923. bool BfModule::Finish()
  22924. {
  22925. BP_ZONE("BfModule::Finish");
  22926. BfLogSysM("BfModule finish: %p\n", this);
  22927. if (mHadBuildError)
  22928. {
  22929. // Don't AssertErrorState here, this current pass may not have failed but
  22930. // the module was still queued in mFinishedModuleWorkList
  22931. ClearModule();
  22932. return true;
  22933. }
  22934. if (mUsedSlotCount != -1)
  22935. {
  22936. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  22937. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  22938. }
  22939. if ((!mGeneratesCode) && (!mAddedToCount))
  22940. return true;
  22941. BF_ASSERT(mAddedToCount);
  22942. mAddedToCount = false;
  22943. mAwaitingFinish = false;
  22944. mCompiler->mStats.mModulesFinished++;
  22945. if (HasCompiledOutput())
  22946. {
  22947. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  22948. DbgFinish();
  22949. if (mAwaitingInitFinish)
  22950. FinishInit();
  22951. for (auto ownedTypeInst : mOwnedTypeInstances)
  22952. {
  22953. // Generate dbg info and add global variables if we haven't already
  22954. mBfIRBuilder->PopulateType(ownedTypeInst);
  22955. }
  22956. if (mBfIRBuilder->DbgHasInfo())
  22957. {
  22958. mBfIRBuilder->DbgFinalize();
  22959. }
  22960. String objOutputPath;
  22961. String irOutputPath;
  22962. mIsModuleMutable = false;
  22963. //mOutFileNames.Clear();
  22964. BF_ASSERT(((int)mOutFileNames.size() >= mExtensionCount) || (mParentModule != NULL));
  22965. bool writeModule = mBfIRBuilder->HasExports();
  22966. String outputPath;
  22967. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  22968. auto& compilerOpts = mCompiler->mOptions;
  22969. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  22970. auto moduleOptions = GetModuleOptions();
  22971. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  22972. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  22973. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  22974. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  22975. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  22976. codeGenOptions.mVirtualMethodOfs = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  22977. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  22978. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  22979. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  22980. bool allowWriteToLib = true;
  22981. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  22982. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  22983. {
  22984. codeGenOptions.mWriteToLib = true;
  22985. mWroteToLib = true;
  22986. }
  22987. else
  22988. {
  22989. mWroteToLib = false;
  22990. }
  22991. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  22992. {
  22993. outputPath = mModuleName;
  22994. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  22995. BfModuleFileName moduleFileName;
  22996. if (mParentModule != NULL)
  22997. {
  22998. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  22999. {
  23000. if (checkPair.mValue == this)
  23001. moduleFileName.mProjects = checkPair.mKey;
  23002. }
  23003. }
  23004. moduleFileName.mProjects.Add(mProject);
  23005. if (fileIdx > 0)
  23006. outputPath += StrFormat("@%d", fileIdx + 1);
  23007. if (mCompiler->mOptions.mWriteIR)
  23008. irOutputPath = outputPath + ".ll";
  23009. if (mCompiler->mOptions.mGenerateObj)
  23010. {
  23011. objOutputPath = outputPath + BF_OBJ_EXT;
  23012. moduleFileName.mFileName = objOutputPath;
  23013. }
  23014. else if (mCompiler->mOptions.mWriteIR)
  23015. {
  23016. moduleFileName.mFileName = irOutputPath;
  23017. }
  23018. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  23019. {
  23020. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  23021. }
  23022. moduleFileName.mModuleWritten = writeModule;
  23023. moduleFileName.mWroteToLib = mWroteToLib;
  23024. if (!mOutFileNames.Contains(moduleFileName))
  23025. mOutFileNames.Add(moduleFileName);
  23026. }
  23027. if (mCompiler->IsHotCompile())
  23028. {
  23029. codeGenOptions.mIsHotCompile = true;
  23030. if (mParentModule != NULL)
  23031. mParentModule->mHadHotObjectWrites = true;
  23032. mHadHotObjectWrites = true;
  23033. }
  23034. //TODO: Testing VDATA
  23035. /*if (mModuleName == "vdata")
  23036. {
  23037. codeGenOptions.mOptLevel = 4;
  23038. }*/
  23039. codeGenOptions.GenerateHash();
  23040. BP_ZONE("BfModule::Finish.WriteObjectFile");
  23041. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  23042. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  23043. mLastModuleWrittenRevision = mCompiler->mRevision;
  23044. }
  23045. else
  23046. {
  23047. for (auto type : mOwnedTypeInstances)
  23048. {
  23049. BF_ASSERT((!type->IsIncomplete()) || (type->IsSpecializedByAutoCompleteMethod()));
  23050. }
  23051. }
  23052. for (auto& specModulePair : mSpecializedMethodModules)
  23053. {
  23054. auto specModule = specModulePair.mValue;
  23055. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  23056. {
  23057. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  23058. }
  23059. }
  23060. CleanupFileInstances();
  23061. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  23062. return true;
  23063. }
  23064. void BfModule::ReportMemory(MemReporter* memReporter)
  23065. {
  23066. memReporter->Add(sizeof(BfModule));
  23067. if (mBfIRBuilder != NULL)
  23068. {
  23069. memReporter->BeginSection("IRBuilder_ConstData");
  23070. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  23071. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  23072. memReporter->EndSection();
  23073. memReporter->BeginSection("IRBuilder_BFIR");
  23074. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  23075. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  23076. memReporter->EndSection();
  23077. memReporter->Add(sizeof(BfIRBuilder));
  23078. }
  23079. memReporter->BeginSection("FileInstanceMap");
  23080. memReporter->AddMap(mFileInstanceMap);
  23081. memReporter->AddMap(mNamedFileInstanceMap);
  23082. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  23083. memReporter->EndSection();
  23084. memReporter->AddVec(mOwnedTypeInstances, false);
  23085. memReporter->AddVec(mSpecializedMethodModules, false);
  23086. memReporter->AddVec(mOutFileNames, false);
  23087. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  23088. memReporter->AddMap(mInterfaceSlotRefs, false);
  23089. memReporter->AddMap(mStaticFieldRefs, false);
  23090. memReporter->AddMap(mClassVDataRefs, false);
  23091. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  23092. memReporter->AddMap(mTypeDataRefs, false);
  23093. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  23094. memReporter->AddMap(mDeferredMethodCallData, false);
  23095. memReporter->AddHashSet(mDeferredMethodIds, false);
  23096. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  23097. }
  23098. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  23099. // be transient through the next compile
  23100. void BfModule::ClearModuleData(bool clearTransientData)
  23101. {
  23102. BfLogSysM("ClearModuleData %p\n", this);
  23103. if (mAddedToCount)
  23104. {
  23105. mCompiler->mStats.mModulesFinished++;
  23106. mAddedToCount = false;
  23107. }
  23108. mDICompileUnit = BfIRMDNode();
  23109. if (clearTransientData)
  23110. mIncompleteMethodCount = 0;
  23111. mHasGenericMethods = false;
  23112. // We don't want to clear these because we want it to persist through module extensions-
  23113. // otherwise we may think an extension succeeds even though the base module failed
  23114. //mHadBuildError = false;
  23115. //mHadBuildWarning = false;
  23116. mClassVDataRefs.Clear();
  23117. mClassVDataExtRefs.Clear();
  23118. for (auto& kv : mTypeDataRefs)
  23119. kv.mValue = BfIRValue();
  23120. mStringCharPtrPool.Clear();
  23121. mStringObjectPool.Clear();
  23122. mStaticFieldRefs.Clear();
  23123. BF_ASSERT(!mIgnoreErrors);
  23124. for (auto prevIRBuilder : mPrevIRBuilders)
  23125. delete prevIRBuilder;
  23126. mPrevIRBuilders.Clear();
  23127. for (auto& specPair : mSpecializedMethodModules)
  23128. {
  23129. auto specModule = specPair.mValue;
  23130. specModule->ClearModuleData();
  23131. }
  23132. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  23133. mBuiltInFuncs[i] = BfIRFunction();
  23134. if (mNextAltModule != NULL)
  23135. mNextAltModule->ClearModuleData();
  23136. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  23137. mIsModuleMutable = false;
  23138. delete mBfIRBuilder;
  23139. mBfIRBuilder = NULL;
  23140. mWantsIRIgnoreWrites = false;
  23141. }
  23142. void BfModule::DisownMethods()
  23143. {
  23144. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  23145. mBuiltInFuncs[i] = BfIRFunction();
  23146. BfModule* methodModule = this;
  23147. if (mParentModule != NULL)
  23148. methodModule = mParentModule;
  23149. for (auto typeInst : methodModule->mOwnedTypeInstances)
  23150. {
  23151. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  23152. {
  23153. if (methodGroup.mDefault != NULL)
  23154. {
  23155. if (methodGroup.mDefault->mIRFunction)
  23156. {
  23157. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  23158. if (methodGroup.mDefault->mDeclModule == this)
  23159. {
  23160. methodGroup.mDefault->mIRFunction = BfIRFunction();
  23161. }
  23162. }
  23163. }
  23164. if (methodGroup.mMethodSpecializationMap != NULL)
  23165. {
  23166. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  23167. {
  23168. auto methodInstance = mapPair.mValue;
  23169. if (methodInstance->mDeclModule == this)
  23170. {
  23171. methodInstance->mIRFunction = BfIRFunction();
  23172. }
  23173. }
  23174. }
  23175. }
  23176. }
  23177. }
  23178. void BfModule::ClearModule()
  23179. {
  23180. ClearModuleData();
  23181. DisownMethods();
  23182. for (auto& specPair : mSpecializedMethodModules)
  23183. {
  23184. auto specModule = specPair.mValue;
  23185. specModule->ClearModule();
  23186. }
  23187. if (mNextAltModule != NULL)
  23188. mNextAltModule->ClearModule();
  23189. }