BfModule.cpp 901 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515
  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, 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 == "vdata")
  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. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1523. {
  1524. if (constHolder == NULL)
  1525. constHolder = mBfIRBuilder;
  1526. auto constant = constHolder->GetConstant(constantStr);
  1527. if (constant == NULL)
  1528. return -1;
  1529. if (constant->mTypeCode == BfTypeCode_StringId)
  1530. {
  1531. return constant->mInt32;
  1532. }
  1533. while (constant->mConstType == BfConstType_BitCast)
  1534. {
  1535. auto constBitCast = (BfConstantBitCast*)constant;
  1536. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1537. }
  1538. if (constant->mConstType == BfConstType_GEP32_2)
  1539. {
  1540. auto constGEP = (BfConstantGEP32_2*)constant;
  1541. constant = constHolder->GetConstantById(constGEP->mTarget);
  1542. }
  1543. if (constant->mConstType == BfConstType_GlobalVar)
  1544. {
  1545. auto constGV = (BfGlobalVar*)constant;
  1546. const char* strDataPrefix = "__bfStrData";
  1547. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1548. return atoi(constGV->mName + strlen(strDataPrefix));
  1549. const char* strObjPrefix = "__bfStrObj";
  1550. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1551. return atoi(constGV->mName + strlen(strObjPrefix));
  1552. }
  1553. return -1;
  1554. }
  1555. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1556. {
  1557. int strId = GetStringPoolIdx(constantStr, constHolder);
  1558. if (strId != -1)
  1559. {
  1560. auto& entry = mContext->mStringObjectIdMap[strId];
  1561. return &entry.mString;
  1562. }
  1563. return NULL;
  1564. }
  1565. CeDbgState* BfModule::GetCeDbgState()
  1566. {
  1567. if (!mIsComptimeModule)
  1568. return NULL;
  1569. if ((mCompiler->mCeMachine != NULL) && (mCompiler->mCeMachine->mDebugger != NULL))
  1570. return mCompiler->mCeMachine->mDebugger->mCurDbgState;
  1571. return NULL;
  1572. }
  1573. BfIRValue BfModule::GetStringCharPtr(int stringId, bool force)
  1574. {
  1575. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1576. {
  1577. mUnreifiedStringPoolRefs.Add(stringId);
  1578. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, stringId);
  1579. }
  1580. BfIRValue* irValue = NULL;
  1581. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1582. return *irValue;
  1583. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1584. if (!mStringObjectPool.ContainsKey(stringId))
  1585. mStringPoolRefs.Add(stringId);
  1586. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1587. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1588. *irValue = strCharPtrConst;
  1589. return strCharPtrConst;
  1590. }
  1591. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue, bool force)
  1592. {
  1593. if (strValue.IsConst())
  1594. {
  1595. int stringId = GetStringPoolIdx(strValue);
  1596. BF_ASSERT(stringId != -1);
  1597. return GetStringCharPtr(stringId, force);
  1598. }
  1599. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1600. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1601. return charPtr;
  1602. }
  1603. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str, bool force)
  1604. {
  1605. return GetStringCharPtr(GetStringObjectValue(str, force), force);
  1606. }
  1607. BfIRValue BfModule::GetStringObjectValue(int strId, bool define, bool force)
  1608. {
  1609. BfIRValue* objValue;
  1610. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1611. return *objValue;
  1612. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1613. return GetStringObjectValue(stringPoolEntry.mString, define, force);
  1614. }
  1615. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define, bool force)
  1616. {
  1617. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1618. mBfIRBuilder->PopulateType(stringType);
  1619. int strId = mContext->GetStringLiteralId(str);
  1620. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1621. {
  1622. auto refModule = this;
  1623. if ((this == mContext->mUnreifiedModule) && (mCurTypeInstance != NULL))
  1624. refModule = mCurTypeInstance->mModule;
  1625. refModule->mUnreifiedStringPoolRefs.Add(strId);
  1626. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, strId);
  1627. }
  1628. BfIRValue* irValuePtr = NULL;
  1629. if (mStringObjectPool.TryGetValue(strId, &irValuePtr))
  1630. return *irValuePtr;
  1631. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1632. if (!mStringCharPtrPool.ContainsKey(strId))
  1633. mStringPoolRefs.Add(strId);
  1634. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1635. mStringObjectPool[strId] = strObject;
  1636. mStringPoolRefs.Add(strId);
  1637. return strObject;
  1638. }
  1639. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1640. {
  1641. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1642. type,
  1643. true,
  1644. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1645. constant,
  1646. name.c_str());
  1647. return newConst;
  1648. }
  1649. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1650. {
  1651. auto curScope = mCurMethodState->mCurScope;
  1652. if (curScope->mLabelNode != NULL)
  1653. {
  1654. curScope->mLabelNode->ToString(curScope->mLabel);
  1655. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1656. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1657. auto autoComplete = mCompiler->GetAutoComplete();
  1658. if (autoComplete != NULL)
  1659. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1660. }
  1661. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1662. {
  1663. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1664. while (checkScope != NULL)
  1665. {
  1666. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1667. {
  1668. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1669. if (errorNode != NULL)
  1670. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1671. break;
  1672. }
  1673. checkScope = checkScope->mPrevScope;
  1674. }
  1675. }
  1676. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1677. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1678. {
  1679. if (prevScope->mHadScopeValueRetain)
  1680. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1681. else
  1682. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1683. }
  1684. mCurMethodState->mBlockNestLevel++;
  1685. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1686. {
  1687. // DIScope could be NULL if we're in an unspecialized method (for example)
  1688. if (mCurMethodState->mCurScope->mDIScope)
  1689. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1690. }
  1691. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1692. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1693. mCurMethodState->mCurScope->mMixinState = mCurMethodState->mMixinState;
  1694. }
  1695. void BfModule::RestoreScoreState_LocalVariables(int localVarStart)
  1696. {
  1697. while (localVarStart < (int)mCurMethodState->mLocals.size())
  1698. {
  1699. auto localVar = mCurMethodState->mLocals.back();
  1700. LocalVariableDone(localVar, false);
  1701. mCurMethodState->mLocals.pop_back();
  1702. if (localVar->mShadowedLocal != NULL)
  1703. {
  1704. BfLocalVarEntry* localVarEntryPtr;
  1705. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1706. {
  1707. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1708. }
  1709. }
  1710. else
  1711. {
  1712. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1713. }
  1714. if (localVar->mIsBumpAlloc)
  1715. localVar->~BfLocalVariable();
  1716. else
  1717. delete localVar;
  1718. }
  1719. }
  1720. void BfModule::RestoreScopeState()
  1721. {
  1722. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1723. mCurMethodState->mBlockNestLevel--;
  1724. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1725. {
  1726. BfIRBlock afterEndBlock;
  1727. if (!mCurMethodState->mLeftBlockUncond)
  1728. {
  1729. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1730. mBfIRBuilder->CreateBr(afterEndBlock);
  1731. mBfIRBuilder->ClearDebugLocation_Last();
  1732. }
  1733. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1734. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1735. if (afterEndBlock)
  1736. {
  1737. mBfIRBuilder->AddBlock(afterEndBlock);
  1738. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1739. }
  1740. }
  1741. mCurMethodState->mCurScope->mDone = true;
  1742. if (!mCurMethodState->mLeftBlockUncond)
  1743. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1744. EmitDeferredCallProcessorInstances(mCurMethodState->mCurScope);
  1745. RestoreScoreState_LocalVariables(mCurMethodState->mCurScope->mLocalVarStart);
  1746. if (mCurMethodState->mCurScope->mValueScopeStart)
  1747. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1748. mCurMethodState->mCurScope = prevScopeData;
  1749. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1750. }
  1751. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1752. {
  1753. if (mBfIRBuilder->mIgnoreWrites)
  1754. return mBfIRBuilder->GetFakeVal();
  1755. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1756. mBfIRBuilder->PopulateType(type);
  1757. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1758. if (!mBfIRBuilder->mIgnoreWrites)
  1759. BF_ASSERT(!prevInsertBlock.IsFake());
  1760. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1761. BfIRValue allocaInst;
  1762. if (arraySize)
  1763. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1764. else
  1765. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1766. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1767. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1768. if (name != NULL)
  1769. mBfIRBuilder->SetName(allocaInst, name);
  1770. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1771. if ((addLifetime) && (WantsLifetimes()))
  1772. {
  1773. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1774. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1775. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1776. }
  1777. return allocaInst;
  1778. }
  1779. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1780. {
  1781. if (mBfIRBuilder->mIgnoreWrites)
  1782. return mBfIRBuilder->GetFakeVal();
  1783. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1784. mBfIRBuilder->PopulateType(typeInst);
  1785. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1786. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1787. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1788. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1789. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1790. if (name != NULL)
  1791. mBfIRBuilder->SetName(allocaInst, name);
  1792. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1793. if ((addLifetime) && (WantsLifetimes()))
  1794. {
  1795. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1796. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1797. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1798. }
  1799. return allocaInst;
  1800. }
  1801. BfDeferredCallEntry* BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape, BfIRBlock valBlock)
  1802. {
  1803. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1804. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1805. /*if (mCurMethodState->mInHeadScope)
  1806. isScopeAlloc = true;*/
  1807. if (scopeData == NULL)
  1808. return NULL;
  1809. auto checkBaseType = val.mType->ToTypeInstance();
  1810. if ((checkBaseType != NULL) && (checkBaseType->IsObject()) && (!arraySize))
  1811. {
  1812. bool hadDtorCall = false;
  1813. while (checkBaseType != NULL)
  1814. {
  1815. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  1816. if (dtorMethodDef != NULL)
  1817. {
  1818. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  1819. if (dtorMethodInstance)
  1820. {
  1821. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1822. BfIRValue useVal = val.mValue;
  1823. BfIRBlock prevBlock = mBfIRBuilder->GetInsertBlock();
  1824. if (valBlock)
  1825. mBfIRBuilder->SetInsertPoint(valBlock);
  1826. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1827. if (!useVal.IsConst())
  1828. mBfIRBuilder->ClearDebugLocation(useVal);
  1829. if (valBlock)
  1830. mBfIRBuilder->SetInsertPoint(prevBlock);
  1831. if (isDynAlloc)
  1832. {
  1833. //
  1834. }
  1835. else if (condAlloca)
  1836. {
  1837. BF_ASSERT(!IsTargetingBeefBackend());
  1838. BF_ASSERT(!isDynAlloc);
  1839. auto valPtr = CreateAlloca(checkBaseType);
  1840. mBfIRBuilder->ClearDebugLocation_Last();
  1841. mBfIRBuilder->CreateAlignedStore(useVal, valPtr, checkBaseType->mAlign);
  1842. mBfIRBuilder->ClearDebugLocation_Last();
  1843. useVal = valPtr;
  1844. }
  1845. SizedArray<BfIRValue, 1> llvmArgs;
  1846. llvmArgs.push_back(useVal);
  1847. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1848. if (deferredCall != NULL)
  1849. {
  1850. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1851. if (condAlloca)
  1852. deferredCall->mArgsNeedLoad = true;
  1853. }
  1854. hadDtorCall = true;
  1855. break;
  1856. }
  1857. }
  1858. checkBaseType = checkBaseType->mBaseType;
  1859. }
  1860. return NULL;
  1861. }
  1862. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1863. if (mayEscape)
  1864. {
  1865. if ((!IsOptimized()) && (!mIsComptimeModule) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1866. {
  1867. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1868. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1869. if (!isDyn)
  1870. {
  1871. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1872. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1873. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1874. if (!dtorMethodInstance.mMethodInstance)
  1875. {
  1876. Fail(StrFormat("Unable to find %s", methodName));
  1877. }
  1878. else
  1879. {
  1880. SizedArray<BfIRValue, 1> llvmArgs;
  1881. if (IsTargetingBeefBackend())
  1882. {
  1883. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1884. //mBfIRBuilder->ClearDebugLocation_Last();
  1885. }
  1886. else
  1887. llvmArgs.push_back(val.mValue);
  1888. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1889. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1890. if (arraySize)
  1891. llvmArgs.push_back(arraySize);
  1892. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1893. }
  1894. }
  1895. else
  1896. {
  1897. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1898. {
  1899. BfIRValue clearSize = arraySize;
  1900. if (val.mType->GetStride() > 1)
  1901. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1902. const char* methodName = "SetDeletedX";
  1903. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1904. BF_ASSERT(dtorMethodInstance);
  1905. if (!dtorMethodInstance)
  1906. {
  1907. Fail(StrFormat("Unable to find %s", methodName));
  1908. }
  1909. else
  1910. {
  1911. SizedArray<BfIRValue, 1> llvmArgs;
  1912. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1913. //mBfIRBuilder->ClearDebugLocation_Last();
  1914. llvmArgs.push_back(clearSize);
  1915. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1916. }
  1917. }
  1918. else
  1919. {
  1920. intptr clearSize = val.mType->mSize;
  1921. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1922. if (constant != NULL)
  1923. clearSize = (intptr)(clearSize * constant->mInt64);
  1924. const char* funcName = "SetDeleted1";
  1925. if (clearSize >= 16)
  1926. funcName = "SetDeleted16";
  1927. else if (clearSize >= 8)
  1928. funcName = "SetDeleted8";
  1929. else if (clearSize >= 4)
  1930. funcName = "SetDeleted4";
  1931. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1932. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1933. if (!dtorMethodInstance)
  1934. {
  1935. Fail(StrFormat("Unable to find %s", funcName));
  1936. }
  1937. else
  1938. {
  1939. SizedArray<BfIRValue, 1> llvmArgs;
  1940. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1941. //mBfIRBuilder->ClearDebugLocation_Last();
  1942. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1943. }
  1944. }
  1945. }
  1946. }
  1947. }
  1948. return NULL;
  1949. }
  1950. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1951. {
  1952. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1953. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1954. return false;
  1955. auto checkTypeInstance = startTypeInstance;
  1956. while (checkTypeInstance != NULL)
  1957. {
  1958. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1959. {
  1960. if (fieldInstance.mMergedDataIdx != -1)
  1961. {
  1962. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1963. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1964. {
  1965. // For fields added in extensions, we automatically initialize those if necessary
  1966. auto fieldDef = fieldInstance.GetFieldDef();
  1967. if (!fieldDef->mDeclaringType->IsExtension())
  1968. return false;
  1969. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  1970. {
  1971. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1972. mBfIRBuilder->SaveDebugLocation();
  1973. if (localVar->IsParam())
  1974. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1975. else
  1976. {
  1977. BF_ASSERT(localVar->mDeclBlock);
  1978. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1979. }
  1980. mBfIRBuilder->ClearDebugLocation();
  1981. BfIRValue curVal;
  1982. if (localVar->mIsThis)
  1983. curVal = mBfIRBuilder->GetArgument(0);
  1984. else
  1985. curVal = localVar->mAddr;
  1986. auto subTypeInstance = startTypeInstance;
  1987. while (subTypeInstance != checkTypeInstance)
  1988. {
  1989. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1990. subTypeInstance = subTypeInstance->mBaseType;
  1991. }
  1992. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1993. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1994. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1995. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1996. mBfIRBuilder->RestoreDebugLocation();
  1997. }
  1998. localVar->mUnassignedFieldFlags &= ~checkMask;
  1999. if (localVar->mUnassignedFieldFlags == 0)
  2000. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2001. }
  2002. }
  2003. }
  2004. checkTypeInstance = checkTypeInstance->mBaseType;
  2005. }
  2006. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  2007. }
  2008. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  2009. {
  2010. BfAstNode* localNameNode = localVar->mNameNode;
  2011. if (localVar->mIsThis)
  2012. {
  2013. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  2014. }
  2015. if (localNameNode != NULL)
  2016. {
  2017. bool isOut = false;
  2018. if (localVar->mResolvedType->IsRef())
  2019. {
  2020. auto refType = (BfRefType*)localVar->mResolvedType;
  2021. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  2022. }
  2023. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  2024. {
  2025. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  2026. TryLocalVariableInit(localVar);
  2027. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  2028. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  2029. // We may have init blocks that we aren't processing here...
  2030. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  2031. deferFullAnalysis = true;
  2032. //bool deferFullAnalysis = true;
  2033. bool deferUsageWarning = deferFullAnalysis && (mCompiler->IsAutocomplete()) &&
  2034. (mCompiler->mResolvePassData->mAutoComplete->mResolveType != BfResolveType_GetFixits);
  2035. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  2036. (!localVar->mIsImplicitParam))
  2037. {
  2038. if (deferUsageWarning)
  2039. {
  2040. // Ignore
  2041. }
  2042. else if (localVar->mIsThis)
  2043. {
  2044. bool foundFields = false;
  2045. auto checkTypeInstance = mCurTypeInstance;
  2046. while (checkTypeInstance != NULL)
  2047. {
  2048. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  2049. {
  2050. if (fieldInstance.mMergedDataIdx == -1)
  2051. continue;
  2052. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  2053. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  2054. {
  2055. auto fieldDef = fieldInstance.GetFieldDef();
  2056. if (mCurMethodInstance->mMethodDef->mDeclaringType->mIsPartial)
  2057. {
  2058. if (mCurMethodInstance->mMethodDef->mDeclaringType != fieldInstance.GetFieldDef()->mDeclaringType)
  2059. {
  2060. // This extension is only responsible for its own fields
  2061. foundFields = true;
  2062. continue;
  2063. }
  2064. if (fieldDef->GetInitializer() != NULL)
  2065. {
  2066. // This initializer was handled in CtorNoBody
  2067. foundFields = true;
  2068. continue;
  2069. }
  2070. }
  2071. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  2072. {
  2073. String propName;
  2074. if (propertyDeclaration->mNameNode != NULL)
  2075. propertyDeclaration->mNameNode->ToString(propName);
  2076. if (checkTypeInstance == mCurTypeInstance)
  2077. {
  2078. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  2079. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2080. }
  2081. else
  2082. {
  2083. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  2084. TypeToString(checkTypeInstance).c_str(),
  2085. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2086. }
  2087. }
  2088. else
  2089. {
  2090. if (checkTypeInstance == mCurTypeInstance)
  2091. {
  2092. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  2093. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2094. }
  2095. else
  2096. {
  2097. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  2098. TypeToString(checkTypeInstance).c_str(),
  2099. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2100. }
  2101. }
  2102. foundFields = true;
  2103. }
  2104. }
  2105. checkTypeInstance = checkTypeInstance->mBaseType;
  2106. }
  2107. if (!foundFields)
  2108. {
  2109. if (mCurTypeInstance->mInstSize > 0)
  2110. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  2111. }
  2112. }
  2113. else if (localVar->IsParam())
  2114. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  2115. else if (!deferUsageWarning)
  2116. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2117. }
  2118. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  2119. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2120. }
  2121. }
  2122. }
  2123. void BfModule::CreateRetValLocal()
  2124. {
  2125. if (mCurMethodState->mRetVal)
  2126. {
  2127. BfLocalVariable* localDef = new BfLocalVariable();
  2128. localDef->mName = "return";
  2129. localDef->mResolvedType = mCurMethodState->mRetVal.mType;
  2130. localDef->mAddr = mCurMethodState->mRetVal.mValue;
  2131. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2132. AddLocalVariableDef(localDef);
  2133. }
  2134. else if (mCurMethodState->mRetValAddr)
  2135. {
  2136. BfLocalVariable* localDef = new BfLocalVariable();
  2137. localDef->mName = "return";
  2138. localDef->mResolvedType = CreateRefType(mCurMethodInstance->mReturnType);
  2139. localDef->mAddr = mCurMethodState->mRetValAddr;
  2140. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2141. AddLocalVariableDef(localDef);
  2142. }
  2143. }
  2144. void BfModule::MarkDynStack(BfScopeData* scopeData)
  2145. {
  2146. auto checkScope = mCurMethodState->mCurScope;
  2147. while (true)
  2148. {
  2149. if (checkScope == scopeData)
  2150. break;
  2151. checkScope->mHadOuterDynStack = true;
  2152. checkScope = checkScope->mPrevScope;
  2153. }
  2154. }
  2155. void BfModule::SaveStackState(BfScopeData* scopeData)
  2156. {
  2157. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  2158. // scopes within scopeData restore the stack
  2159. auto checkScope = mCurMethodState->mCurScope;
  2160. while (true)
  2161. {
  2162. if (checkScope == scopeData)
  2163. {
  2164. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  2165. {
  2166. if (mBfIRBuilder->mHasDebugInfo)
  2167. mBfIRBuilder->SaveDebugLocation();
  2168. auto prevPos = mBfIRBuilder->GetInsertBlock();
  2169. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  2170. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  2171. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  2172. mBfIRBuilder->SetInsertPoint(prevPos);
  2173. if (mBfIRBuilder->mHasDebugInfo)
  2174. mBfIRBuilder->RestoreDebugLocation();
  2175. }
  2176. break;
  2177. }
  2178. if (checkScope->mSavedStack)
  2179. {
  2180. for (auto usage : checkScope->mSavedStackUses)
  2181. mBfIRBuilder->EraseInstFromParent(usage);
  2182. checkScope->mSavedStackUses.Clear();
  2183. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  2184. checkScope->mSavedStack = BfIRValue();
  2185. }
  2186. checkScope = checkScope->mPrevScope;
  2187. }
  2188. }
  2189. BfIRValue BfModule::ValueScopeStart()
  2190. {
  2191. if (IsTargetingBeefBackend())
  2192. return mBfIRBuilder->CreateValueScopeStart();
  2193. return BfIRValue();
  2194. }
  2195. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  2196. {
  2197. if (valueScopeStart)
  2198. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  2199. }
  2200. BfProjectSet* BfModule::GetVisibleProjectSet()
  2201. {
  2202. if (mCurMethodState == NULL)
  2203. return NULL;
  2204. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  2205. {
  2206. HashSet<BfType*> seenTypes;
  2207. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  2208. {
  2209. if (mCurMethodState->mVisibleProjectSet.Add(project))
  2210. {
  2211. for (auto dep : project->mDependencies)
  2212. _AddProject(dep);
  2213. }
  2214. };
  2215. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  2216. {
  2217. auto typeInstance = type->ToTypeInstance();
  2218. if (typeInstance == NULL)
  2219. {
  2220. if (type->IsSizedArray())
  2221. _AddType(type->GetUnderlyingType());
  2222. return;
  2223. }
  2224. if (typeInstance->IsTuple())
  2225. {
  2226. for (auto& fieldInst : typeInstance->mFieldInstances)
  2227. {
  2228. if (fieldInst.mDataIdx != -1)
  2229. _AddType(fieldInst.mResolvedType);
  2230. }
  2231. }
  2232. _AddProject(typeInstance->mTypeDef->mProject);
  2233. if (typeInstance->mGenericTypeInfo == NULL)
  2234. return;
  2235. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2236. {
  2237. if (seenTypes.Add(type))
  2238. _AddType(type);
  2239. }
  2240. };
  2241. if (mCurTypeInstance != NULL)
  2242. _AddType(mCurTypeInstance);
  2243. auto methodState = mCurMethodState;
  2244. while (methodState != NULL)
  2245. {
  2246. if (methodState->mMethodInstance != NULL)
  2247. {
  2248. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  2249. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  2250. {
  2251. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2252. _AddType(type);
  2253. }
  2254. }
  2255. methodState = methodState->mPrevMethodState;
  2256. }
  2257. }
  2258. return &mCurMethodState->mVisibleProjectSet;
  2259. }
  2260. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2261. {
  2262. auto bfParser = astNode->GetSourceData()->ToParserData();
  2263. if (bfParser == NULL)
  2264. return NULL;
  2265. BfFileInstance** fileInstancePtr = NULL;
  2266. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2267. {
  2268. return *fileInstancePtr;
  2269. }
  2270. else
  2271. {
  2272. // It's possible two parsers have the same file name (ie: mNextRevision)
  2273. BfFileInstance** namedFileInstancePtr = NULL;
  2274. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2275. {
  2276. auto bfFileInstance = *namedFileInstancePtr;
  2277. *fileInstancePtr = bfFileInstance;
  2278. return bfFileInstance;
  2279. }
  2280. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2281. auto bfFileInstance = new BfFileInstance();
  2282. *fileInstancePtr = bfFileInstance;
  2283. *namedFileInstancePtr = bfFileInstance;
  2284. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2285. bfFileInstance->mParser = bfParser;
  2286. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2287. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasLineInfo()))
  2288. {
  2289. String fileName = bfParser->mFileName;
  2290. for (int i = 0; i < (int)fileName.length(); i++)
  2291. {
  2292. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2293. fileName[i] = DIR_SEP_CHAR;
  2294. }
  2295. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, BF_MAX(slashPos, 0)), bfParser->mMD5Hash);
  2296. }
  2297. return bfFileInstance;
  2298. }
  2299. }
  2300. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2301. {
  2302. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2303. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2304. return;
  2305. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2306. if (astNode == NULL)
  2307. return;
  2308. auto bfParser = astNode->GetSourceData()->ToParserData();
  2309. if (bfParser == NULL)
  2310. return;
  2311. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2312. {
  2313. if (mCurFilePosition.mFileInstance != NULL)
  2314. {
  2315. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2316. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2317. }
  2318. auto bfFileInstance = GetFileFromNode(astNode);
  2319. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2320. {
  2321. mCurFilePosition = bfFileInstance->mPrevPosition;
  2322. }
  2323. else
  2324. {
  2325. mCurFilePosition.mFileInstance = bfFileInstance;
  2326. mCurFilePosition.mCurLine = 0;
  2327. mCurFilePosition.mCurColumn = 0;
  2328. mCurFilePosition.mCurSrcPos = 0;
  2329. }
  2330. }
  2331. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2332. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2333. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2334. if (jumpEntry->mCharIdx > srcPos)
  2335. jumpEntry--;
  2336. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2337. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2338. mCurFilePosition.mCurColumn = 0;
  2339. while (mCurFilePosition.mCurSrcPos < srcPos)
  2340. {
  2341. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2342. {
  2343. mCurFilePosition.mCurLine++;
  2344. mCurFilePosition.mCurColumn = 0;
  2345. }
  2346. else
  2347. {
  2348. mCurFilePosition.mCurColumn++;
  2349. }
  2350. mCurFilePosition.mCurSrcPos++;
  2351. }
  2352. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2353. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasLineInfo()) && (mCurMethodState != NULL))
  2354. {
  2355. int column = mCurFilePosition.mCurColumn + 1;
  2356. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2357. {
  2358. // Set to illegal position
  2359. column = 0;
  2360. }
  2361. if (mSetIllegalSrcPosition)
  2362. column = 0;
  2363. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2364. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2365. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2366. {
  2367. // This is from a different scope...
  2368. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2369. {
  2370. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2371. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2372. }
  2373. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2374. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2375. }
  2376. else
  2377. {
  2378. if (mCurMethodState->mCurScope->mAltDIFile)
  2379. {
  2380. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2381. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2382. }
  2383. }
  2384. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2385. if (mCurMethodState->mCrossingMixin)
  2386. inlineAt = BfIRMDNode();
  2387. if ((!useDIScope) && (mIsComptimeModule))
  2388. useDIScope = wantDIFile;
  2389. if (!useDIScope)
  2390. mBfIRBuilder->ClearDebugLocation();
  2391. else
  2392. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2393. if ((flags & BfSrcPosFlag_Expression) == 0)
  2394. mBfIRBuilder->CreateStatementStart();
  2395. }
  2396. }
  2397. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2398. {
  2399. // We've turned off expr src pos (for now?)
  2400. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2401. }
  2402. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2403. {
  2404. if (mCompiler->mBfObjectTypeDef != NULL)
  2405. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2406. SetIllegalSrcPos();
  2407. }
  2408. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2409. {
  2410. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2411. {
  2412. auto curScope = mCurMethodState->mCurScope->mDIScope;
  2413. if (curScope)
  2414. {
  2415. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2416. {
  2417. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2418. mBfIRBuilder->SetCurrentDebugLocation(0, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2419. }
  2420. else
  2421. {
  2422. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2423. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2424. }
  2425. }
  2426. if ((flags & BfSrcPosFlag_Expression) == 0)
  2427. mBfIRBuilder->CreateStatementStart();
  2428. }
  2429. }
  2430. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2431. {
  2432. // We've turned off expr src pos (for now?)
  2433. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2434. }
  2435. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2436. {
  2437. if ((protection == BfProtection_Public) ||
  2438. (((protection == BfProtection_Protected) || (protection == BfProtection_ProtectedInternal)) && (allowProtected)) ||
  2439. ((protection == BfProtection_Private) && (allowPrivate)))
  2440. return true;
  2441. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2442. {
  2443. mAttributeState->mUsed = true;
  2444. return true;
  2445. }
  2446. if (((protection == BfProtection_Internal) || (protection == BfProtection_ProtectedInternal)) && (checkType != NULL))
  2447. {
  2448. if (CheckInternalProtection(checkType))
  2449. return true;
  2450. }
  2451. return false;
  2452. }
  2453. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2454. {
  2455. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2456. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2457. {
  2458. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2459. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2460. }
  2461. allowProtected = allowPrivate;
  2462. }
  2463. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2464. {
  2465. if (memberProtection == BfProtection_Hidden)
  2466. return false;
  2467. if (memberProtection == BfProtection_Public)
  2468. return true;
  2469. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2470. {
  2471. BfTypeInstance* curCheckType = mCurTypeInstance;
  2472. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2473. {
  2474. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2475. curCheckType = mixinOwner;
  2476. }
  2477. bool allowPrivate = (curCheckType != NULL) && (memberOwner->IsInstanceOf(curCheckType->mTypeDef));
  2478. if (curCheckType != NULL)
  2479. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2480. if (allowPrivate)
  2481. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2482. else
  2483. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2484. }
  2485. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2486. return true;
  2487. if ((memberProtection == BfProtection_Protected) || (memberProtection == BfProtection_ProtectedInternal))
  2488. {
  2489. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2490. {
  2491. bool allowProtected = false;
  2492. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2493. auto curCheckType = mCurTypeInstance;
  2494. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2495. {
  2496. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2497. curCheckType = mixinOwner;
  2498. }
  2499. if ((flags & BfProtectionCheckFlag_InstanceLookup) != 0)
  2500. {
  2501. auto lookupCheckType = lookupStartType;
  2502. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2503. {
  2504. if (lookupCheckType == curCheckType)
  2505. {
  2506. allowProtected = true;
  2507. break;
  2508. }
  2509. if (lookupCheckType == memberOwner)
  2510. break;
  2511. lookupCheckType = lookupCheckType->mBaseType;
  2512. if (lookupCheckType == NULL)
  2513. break;
  2514. }
  2515. }
  2516. else
  2517. {
  2518. auto lookupCheckType = curCheckType;
  2519. while (lookupCheckType->mInheritDepth >= memberOwner->mInheritDepth)
  2520. {
  2521. if (lookupCheckType == memberOwner)
  2522. {
  2523. allowProtected = true;
  2524. break;
  2525. }
  2526. lookupCheckType = lookupCheckType->mBaseType;
  2527. if (lookupCheckType == NULL)
  2528. break;
  2529. }
  2530. }
  2531. if (!allowProtected)
  2532. {
  2533. // It's possible our outer type is derived from 'memberOwner'
  2534. while (curCheckType->mTypeDef->mNestDepth > 0)
  2535. {
  2536. curCheckType = GetOuterType(curCheckType);
  2537. if (curCheckType == NULL)
  2538. break;
  2539. auto lookupCheckType = lookupStartType;
  2540. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2541. {
  2542. if (lookupCheckType == curCheckType)
  2543. {
  2544. allowProtected = true;
  2545. break;
  2546. }
  2547. if (lookupCheckType == memberOwner)
  2548. break;
  2549. lookupCheckType = lookupCheckType->mBaseType;
  2550. if (lookupCheckType == NULL)
  2551. break;
  2552. }
  2553. }
  2554. }
  2555. if (allowProtected)
  2556. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2557. else
  2558. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2559. }
  2560. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2561. return true;
  2562. }
  2563. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2564. {
  2565. mAttributeState->mUsed = true;
  2566. return true;
  2567. }
  2568. if (((memberProtection == BfProtection_Internal) || (memberProtection == BfProtection_ProtectedInternal)) && (memberOwner != NULL))
  2569. {
  2570. if (CheckInternalProtection(memberOwner->mTypeDef))
  2571. return true;
  2572. }
  2573. return false;
  2574. }
  2575. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2576. {
  2577. if (mCompiler->mResolvePassData != NULL)
  2578. {
  2579. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2580. sourceClassifier->SetElementType(astNode, elementType);
  2581. }
  2582. }
  2583. bool BfModule::PreFail()
  2584. {
  2585. if (!mIgnoreErrors)
  2586. return true;
  2587. SetFail();
  2588. return false;
  2589. }
  2590. void BfModule::SetFail()
  2591. {
  2592. if (mIgnoreErrors)
  2593. {
  2594. if (mAttributeState != NULL)
  2595. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2596. }
  2597. }
  2598. void BfModule::VerifyOnDemandMethods()
  2599. {
  2600. #ifdef _DEBUG
  2601. // if (mParentModule != NULL)
  2602. // {
  2603. // BF_ASSERT(mOnDemandMethodCount == 0);
  2604. // mParentModule->VerifyOnDemandMethods();
  2605. // return;
  2606. // }
  2607. //
  2608. // int onDemandCount = 0;
  2609. // for (auto type : mOwnedTypeInstances)
  2610. // {
  2611. // auto typeInst = type->ToTypeInstance();
  2612. // for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  2613. // {
  2614. // if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  2615. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  2616. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  2617. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  2618. // onDemandCount++;
  2619. // }
  2620. // }
  2621. //
  2622. // BF_ASSERT(mOnDemandMethodCount == onDemandCount);
  2623. #endif
  2624. }
  2625. bool BfModule::IsSkippingExtraResolveChecks()
  2626. {
  2627. if (mIsComptimeModule)
  2628. return false;
  2629. return mCompiler->IsSkippingExtraResolveChecks();
  2630. }
  2631. bool BfModule::AddErrorContext(StringImpl& errorString, BfAstNode* refNode, BfWhileSpecializingFlags& isWhileSpecializing, bool isWarning)
  2632. {
  2633. bool isWhileSpecializingMethod = false;
  2634. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2635. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2636. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2637. errorString += StrFormat("\n while generating append size calculating method");
  2638. else if (refNode == NULL)
  2639. {
  2640. if (mCurTypeInstance != NULL)
  2641. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2642. else if (mProject != NULL)
  2643. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2644. }
  2645. if (mCurTypeInstance != NULL)
  2646. {
  2647. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2648. {
  2649. // Propogate the fail all the way to the main method (assuming we're in a local method or lambda)
  2650. if (isWarning)
  2651. methodInstance->mHasWarning = true;
  2652. else
  2653. methodInstance->mHasFailed = true;
  2654. if (!methodInstance->mHasStartedDeclaration)
  2655. StartMethodDeclaration(methodInstance, NULL);
  2656. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2657. if (isSpecializedMethod)
  2658. {
  2659. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2660. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2661. if (unspecializedMethod == methodInstance)
  2662. {
  2663. // This is a local method inside a generic method
  2664. BF_ASSERT(methodInstance->mMethodDef->mIsLocalMethod);
  2665. }
  2666. else
  2667. {
  2668. if (isWarning)
  2669. {
  2670. if (unspecializedMethod->mHasWarning)
  2671. return false; // At least SOME error has already been reported
  2672. }
  2673. else
  2674. {
  2675. if (unspecializedMethod->mHasFailed)
  2676. return false; // At least SOME error has already been reported
  2677. }
  2678. }
  2679. }
  2680. if (isSpecializedMethod)
  2681. {
  2682. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2683. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2684. isWhileSpecializingMethod = true;
  2685. }
  2686. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2687. {
  2688. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2689. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2690. isWhileSpecializingMethod = true;
  2691. }
  2692. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2693. {
  2694. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2695. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2696. }
  2697. return true;
  2698. };
  2699. bool hadMethodInstance = false;
  2700. if (mCurMethodState != NULL)
  2701. {
  2702. auto checkMethodState = mCurMethodState;
  2703. while (checkMethodState != NULL)
  2704. {
  2705. auto methodInstance = checkMethodState->mMethodInstance;
  2706. if (methodInstance == NULL)
  2707. {
  2708. checkMethodState = checkMethodState->mPrevMethodState;
  2709. continue;
  2710. }
  2711. hadMethodInstance = true;
  2712. if (!_CheckMethodInstance(methodInstance))
  2713. return false;
  2714. checkMethodState = checkMethodState->mPrevMethodState;
  2715. }
  2716. }
  2717. if ((!hadMethodInstance) && (mCurMethodInstance != NULL))
  2718. {
  2719. if (!_CheckMethodInstance(mCurMethodInstance))
  2720. return false;
  2721. }
  2722. }
  2723. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2724. {
  2725. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2726. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2727. }
  2728. return true;
  2729. }
  2730. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent, bool deferError)
  2731. {
  2732. BP_ZONE("BfModule::Fail");
  2733. if (mIgnoreErrors)
  2734. {
  2735. mHadIgnoredError = true;
  2736. if (mAttributeState != NULL)
  2737. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2738. return NULL;
  2739. }
  2740. if (!mReportErrors)
  2741. {
  2742. mCompiler->mPassInstance->SilentFail();
  2743. return NULL;
  2744. }
  2745. if (refNode != NULL)
  2746. refNode = BfNodeToNonTemporary(refNode);
  2747. //BF_ASSERT(refNode != NULL);
  2748. if (mIsComptimeModule)
  2749. {
  2750. if (auto ceDbgState = GetCeDbgState())
  2751. {
  2752. // Follow normal fail path
  2753. }
  2754. else
  2755. {
  2756. mHadBuildError = true;
  2757. if ((mCompiler->mCeMachine->mCurContext != NULL) && (mCompiler->mCeMachine->mCurContext->mCurCallSource != NULL) &&
  2758. (mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode != NULL))
  2759. {
  2760. BfError* bfError = mCompiler->mPassInstance->Fail("Comptime method generation had errors",
  2761. mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode);
  2762. if (bfError != NULL)
  2763. mCompiler->mPassInstance->MoreInfo(error, refNode);
  2764. return bfError;
  2765. }
  2766. return NULL;
  2767. }
  2768. }
  2769. if ((mCurMethodState != NULL) && (mCurMethodState->mConstResolveState != NULL) && (mCurMethodState->mConstResolveState->mInCalcAppend))
  2770. {
  2771. mCurMethodState->mConstResolveState->mFailed = true;
  2772. return NULL;
  2773. }
  2774. if (mCurMethodInstance != NULL)
  2775. mCurMethodInstance->mHasFailed = true;
  2776. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2777. return NULL;
  2778. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2779. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2780. if (!mHadBuildError)
  2781. mHadBuildError = true;
  2782. if (mParentModule != NULL)
  2783. mParentModule->mHadBuildError = true;
  2784. if (mCurTypeInstance != NULL)
  2785. AddFailType(mCurTypeInstance);
  2786. BfLogSysM("BfModule::Fail module %p type %p %s @ %s\n", this, mCurTypeInstance, error.c_str(), (refNode != NULL) ? refNode->LocationToString().c_str() : "???");
  2787. String errorString = error;
  2788. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2789. if (!AddErrorContext(errorString, refNode, isWhileSpecializing, false))
  2790. return NULL;
  2791. BfError* bfError = NULL;
  2792. if (isWhileSpecializing)
  2793. deferError = true;
  2794. if (!mHadBuildError)
  2795. mHadBuildError = true;
  2796. // Check mixins
  2797. {
  2798. auto checkMethodState = mCurMethodState;
  2799. while (checkMethodState != NULL)
  2800. {
  2801. auto rootMixinState = checkMethodState->GetRootMixinState();
  2802. if (rootMixinState != NULL)
  2803. {
  2804. String mixinErr = StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str());
  2805. if (deferError)
  2806. bfError = mCompiler->mPassInstance->DeferFail(mixinErr, rootMixinState->mSource);
  2807. else
  2808. bfError = mCompiler->mPassInstance->Fail(mixinErr, rootMixinState->mSource);
  2809. if (bfError == NULL)
  2810. return NULL;
  2811. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2812. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2813. auto mixinState = checkMethodState->mMixinState;
  2814. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2815. {
  2816. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2817. mixinState = mixinState->mPrevMixinState;
  2818. }
  2819. return bfError;
  2820. }
  2821. checkMethodState = checkMethodState->mPrevMethodState;
  2822. }
  2823. }
  2824. if (deferError)
  2825. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2826. else if (refNode == NULL)
  2827. bfError = mCompiler->mPassInstance->Fail(errorString);
  2828. else
  2829. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2830. if (bfError != NULL)
  2831. {
  2832. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2833. bfError->mProject = mProject;
  2834. bfError->mIsPersistent = isPersistent;
  2835. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2836. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2837. else if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2838. mCompiler->mPassInstance->MoreInfo("Error in emitted code", mCurMethodState->mEmitRefNode);
  2839. }
  2840. return bfError;
  2841. }
  2842. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2843. {
  2844. if (mHadBuildError)
  2845. return NULL;
  2846. return Fail(error, refNode);
  2847. }
  2848. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2849. {
  2850. if (mIgnoreErrors)
  2851. return NULL;
  2852. if (refNode != NULL)
  2853. refNode = BfNodeToNonTemporary(refNode);
  2854. mHadBuildError = true;
  2855. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2856. if (bfError != NULL)
  2857. bfError->mProject = mProject;
  2858. return bfError;
  2859. }
  2860. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent, bool showInSpecialized)
  2861. {
  2862. if (mIgnoreErrors || mIgnoreWarnings)
  2863. return NULL;
  2864. if (!mReportErrors)
  2865. {
  2866. mCompiler->mPassInstance->SilentFail();
  2867. return NULL;
  2868. }
  2869. BfAstNode* unwarnNode = refNode;
  2870. //
  2871. {
  2872. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2873. while (parentNodeEntry != NULL)
  2874. {
  2875. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2876. break;
  2877. unwarnNode = parentNodeEntry->mNode;
  2878. parentNodeEntry = parentNodeEntry->mPrev;
  2879. }
  2880. }
  2881. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2882. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2883. {
  2884. return NULL;
  2885. }
  2886. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2887. if (mCurMethodInstance != NULL)
  2888. {
  2889. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2890. {
  2891. if (!showInSpecialized)
  2892. return NULL;
  2893. }
  2894. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2895. return NULL; // No ctorCalcAppend warnings
  2896. }
  2897. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2898. {
  2899. if (!showInSpecialized)
  2900. return NULL;
  2901. }
  2902. if (refNode != NULL)
  2903. refNode = BfNodeToNonTemporary(refNode);
  2904. String warningString = warning;
  2905. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2906. if (!AddErrorContext(warningString, refNode, isWhileSpecializing, true))
  2907. return NULL;
  2908. bool deferWarning = isWhileSpecializing != BfWhileSpecializingFlag_None;
  2909. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2910. {
  2911. // We used to bubble up warnings into the mixin injection site, BUT
  2912. // we are now assuming any relevant warnings will be given at the declaration site
  2913. return NULL;
  2914. }
  2915. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2916. {
  2917. BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Emitted code had errors", mCurMethodState->mEmitRefNode);
  2918. if (bfError != NULL)
  2919. mCompiler->mPassInstance->MoreInfo(warningString, refNode);
  2920. return bfError;
  2921. }
  2922. BfError* bfError;
  2923. if (refNode != NULL)
  2924. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warningString, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2925. else
  2926. bfError = mCompiler->mPassInstance->Warn(warningNum, warningString);
  2927. if (bfError != NULL)
  2928. {
  2929. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2930. bfError->mProject = mProject;
  2931. AddFailType(mCurTypeInstance);
  2932. mHadBuildWarning = true;
  2933. bfError->mIsPersistent = isPersistent;
  2934. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2935. {
  2936. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2937. if (parser != NULL)
  2938. {
  2939. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2940. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2941. if (warningNum != 0)
  2942. {
  2943. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  2944. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  2945. }
  2946. }
  2947. }
  2948. }
  2949. return bfError;
  2950. }
  2951. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfFieldInstance* fieldInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  2952. {
  2953. if (customAttributes == NULL)
  2954. return;
  2955. auto _AddDeclarationMoreInfo = [&]()
  2956. {
  2957. if (methodInstance != NULL)
  2958. {
  2959. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  2960. mCompiler->mPassInstance->MoreInfo(
  2961. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  2962. methodInstance->mMethodDef->GetRefNode());
  2963. }
  2964. else
  2965. {
  2966. mCompiler->mPassInstance->MoreInfo(
  2967. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  2968. typeInstance->mTypeDef->GetRefNode());
  2969. }
  2970. };
  2971. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  2972. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  2973. if ((customAttribute != NULL) && (targetSrc != NULL))
  2974. {
  2975. String err;
  2976. if (fieldInstance != NULL)
  2977. err = StrFormat("'%s' is obsolete", FieldToString(fieldInstance).c_str());
  2978. else if (methodInstance != NULL)
  2979. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  2980. else
  2981. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2982. bool isError = false;
  2983. if (customAttribute->mCtorArgs.size() >= 1)
  2984. {
  2985. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  2986. if (constant->mTypeCode == BfTypeCode_Boolean)
  2987. {
  2988. isError = constant->mBool;
  2989. }
  2990. else if (constant->mTypeCode == BfTypeCode_StringId)
  2991. {
  2992. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2993. if (str != NULL)
  2994. {
  2995. err += ":\n '";
  2996. err += *str;
  2997. err += "'";
  2998. }
  2999. if (customAttribute->mCtorArgs.size() >= 2)
  3000. {
  3001. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  3002. isError = constant->mBool;
  3003. }
  3004. }
  3005. }
  3006. BfError* error = NULL;
  3007. if (isError)
  3008. error = Fail(err, targetSrc);
  3009. else
  3010. error = Warn(0, err, targetSrc, false, true);
  3011. if (error != NULL)
  3012. _AddDeclarationMoreInfo();
  3013. }
  3014. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  3015. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3016. {
  3017. String err;
  3018. if (fieldInstance != NULL)
  3019. err += StrFormat("Method error: '", FieldToString(fieldInstance).c_str());
  3020. else if (methodInstance != NULL)
  3021. err += StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  3022. else
  3023. err += StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3024. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3025. if (str != NULL)
  3026. err += *str;
  3027. err += "'";
  3028. if (Fail(err, targetSrc) != NULL)
  3029. _AddDeclarationMoreInfo();
  3030. }
  3031. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  3032. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  3033. {
  3034. String err;
  3035. if (fieldInstance != NULL)
  3036. err += StrFormat("Field warning: '", FieldToString(fieldInstance).c_str());
  3037. else if (methodInstance != NULL)
  3038. err += StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  3039. else
  3040. err += StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3041. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3042. if (str != NULL)
  3043. err += *str;
  3044. err += "'";
  3045. if (Warn(0, err, targetSrc, false, true) != NULL)
  3046. _AddDeclarationMoreInfo();
  3047. }
  3048. }
  3049. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  3050. {
  3051. if (mBfIRBuilder->mOpFailed)
  3052. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  3053. }
  3054. void BfModule::FatalError(const StringImpl& error, const char* file, int line, int column)
  3055. {
  3056. static bool sHadFatalError = false;
  3057. static bool sHadReentrancy = false;
  3058. if (sHadFatalError)
  3059. {
  3060. return;
  3061. sHadReentrancy = true;
  3062. }
  3063. sHadFatalError = true;
  3064. String fullError = error;
  3065. if (file != NULL)
  3066. {
  3067. fullError += StrFormat(" at %s:%d", file, line);
  3068. if (column != -1)
  3069. fullError += StrFormat(":%d", column);
  3070. }
  3071. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3072. if (mCurTypeInstance != NULL)
  3073. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3074. if (mCurMethodInstance != NULL)
  3075. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3076. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3077. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3078. if (sHadReentrancy)
  3079. fullError += "\nError had reentrancy";
  3080. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  3081. }
  3082. void BfModule::FatalError(const StringImpl& error, BfAstNode* refNode)
  3083. {
  3084. if (refNode != NULL)
  3085. {
  3086. auto parser = refNode->GetParserData();
  3087. if (parser != NULL)
  3088. {
  3089. int line = -1;
  3090. int lineChar = -1;
  3091. parser->GetLineCharAtIdx(refNode->mSrcStart, line, lineChar);
  3092. if (line != -1)
  3093. FatalError(error, parser->mFileName.c_str(), line, lineChar);
  3094. }
  3095. }
  3096. FatalError(error);
  3097. }
  3098. void BfModule::InternalError(const StringImpl& error, BfAstNode* refNode, const char* file, int line)
  3099. {
  3100. String fullError = error;
  3101. if (file != NULL)
  3102. fullError += StrFormat(" at %s:%d", file, line);
  3103. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3104. if (mCurTypeInstance != NULL)
  3105. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3106. if (mCurMethodInstance != NULL)
  3107. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3108. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3109. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3110. Fail(String("INTERNAL ERROR: ") + fullError, refNode);
  3111. }
  3112. void BfModule::NotImpl(BfAstNode* astNode)
  3113. {
  3114. Fail("INTERNAL ERROR: Not implemented", astNode);
  3115. }
  3116. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  3117. {
  3118. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  3119. if (!allowPrivate)
  3120. allowPrivate |= memberType->IsInterface();
  3121. bool allowProtected = allowPrivate;
  3122. //TODO: We had this commented out, but this makes accessing protected properties fail
  3123. if (mCurTypeInstance != NULL)
  3124. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  3125. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  3126. {
  3127. return false;
  3128. }
  3129. return true;
  3130. }
  3131. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  3132. {
  3133. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  3134. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  3135. auto memberTypeInstance = memberType->ToTypeInstance();
  3136. if (memberTypeInstance == NULL)
  3137. {
  3138. auto underlyingType = memberType->GetUnderlyingType();
  3139. if (underlyingType != NULL)
  3140. return CheckDefineMemberProtection(protection, underlyingType);
  3141. return true;
  3142. }
  3143. if (memberTypeInstance->mTypeDef->mProtection < protection)
  3144. return false;
  3145. if (memberTypeInstance->IsGenericTypeInstance())
  3146. {
  3147. // When we're a generic struct, our data layout can depend on our generic parameters as well
  3148. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  3149. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3150. {
  3151. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  3152. return false;
  3153. }
  3154. }
  3155. return true;
  3156. }
  3157. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags, BfDepContext* depContext)
  3158. {
  3159. if (usedType == userType)
  3160. return;
  3161. if (((flags & BfDependencyMap::DependencyFlag_ConstValue) != 0) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_FieldType))
  3162. {
  3163. // This can be an `int32[UsedType.cVal]` type reference
  3164. flags = (BfDependencyMap::DependencyFlags)(flags | BfDependencyMap::DependencyFlag_ValueTypeSizeDep);
  3165. }
  3166. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  3167. {
  3168. if (userType->IsMethodRef())
  3169. {
  3170. // We cannot short-circuit dependencies because of method group ref counting
  3171. }
  3172. else
  3173. return;
  3174. }
  3175. if (usedType->IsSpecializedByAutoCompleteMethod())
  3176. {
  3177. if ((flags & (BfDependencyMap::DependencyFlag_TypeGenericArg | BfDependencyMap::DependencyFlag_MethodGenericArg |
  3178. BfDependencyMap::DependencyFlag_OuterType | BfDependencyMap::DependencyFlag_DerivedFrom)) == 0)
  3179. return;
  3180. }
  3181. // if (usedType->IsBoxed())
  3182. // {
  3183. // NOP;
  3184. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  3185. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  3186. // {
  3187. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  3188. // }
  3189. // }
  3190. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  3191. // BfType* origUsedType = usedType;
  3192. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  3193. // if (isDataAccess)
  3194. // {
  3195. // while (true)
  3196. // {
  3197. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  3198. // usedType = usedType->GetUnderlyingType();
  3199. // else if (usedType->IsArray())
  3200. // {
  3201. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  3202. // }
  3203. // else
  3204. // break;
  3205. // }
  3206. // }
  3207. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  3208. {
  3209. bool addType = true;
  3210. auto checkType = usedType;
  3211. PopulateType(checkType, BfPopulateType_Data);
  3212. if (checkType->IsValuelessType())
  3213. addType = false;
  3214. else if (checkType->IsPrimitiveType())
  3215. addType = false;
  3216. else
  3217. {
  3218. auto checkTypeInst = checkType->ToTypeInstance();
  3219. if (checkTypeInst == NULL)
  3220. {
  3221. addType = false;
  3222. }
  3223. else
  3224. {
  3225. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  3226. addType = false;
  3227. }
  3228. }
  3229. if (addType)
  3230. {
  3231. auto checkTypeInst = checkType->ToTypeInstance();
  3232. if (checkTypeInst->mHotTypeData != NULL)
  3233. {
  3234. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  3235. BF_ASSERT(hotTypeVersion != NULL);
  3236. if (hotTypeVersion != NULL)
  3237. {
  3238. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  3239. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  3240. (checkType->IsComposite()))
  3241. isAllocation = true;
  3242. if (isAllocation)
  3243. {
  3244. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  3245. }
  3246. else
  3247. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  3248. }
  3249. }
  3250. }
  3251. }
  3252. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  3253. {
  3254. auto usingModule = userType->GetModule();
  3255. BfModule* usedModule;
  3256. if (usedType->IsFunction())
  3257. {
  3258. if (mCompiler->mFunctionTypeDef != NULL)
  3259. {
  3260. auto functionType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  3261. usedModule = functionType->GetModule();
  3262. }
  3263. }
  3264. else
  3265. usedModule = usedType->GetModule();
  3266. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  3267. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  3268. {
  3269. if ((flags & ~(BfDependencyMap::DependencyFlag_OuterType)) == 0)
  3270. {
  3271. // Not a 'use' dependency
  3272. }
  3273. else
  3274. {
  3275. usingModule->mModuleRefs.Add(usedModule);
  3276. }
  3277. }
  3278. }
  3279. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  3280. {
  3281. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  3282. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  3283. if (genericArg == usedType)
  3284. return;
  3285. }
  3286. auto depFlag = flags;
  3287. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  3288. {
  3289. if (usedType->IsDependendType())
  3290. {
  3291. // Cause a rebuild but not an outright deletion of the type
  3292. // We can only do this if the 'usedType' can actually hold the dependency which can actually trigger a deletion chain
  3293. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef;
  3294. }
  3295. }
  3296. if (usedType->IsTypeAlias())
  3297. {
  3298. auto underlyingType = usedType->GetUnderlyingType();
  3299. if (underlyingType != NULL)
  3300. {
  3301. BfDepContext newDepContext;
  3302. if (depContext == NULL)
  3303. depContext = &newDepContext;
  3304. if (++depContext->mAliasDepth > 8)
  3305. {
  3306. if (!depContext->mDeepSeenAliases.Add(underlyingType))
  3307. return; // Circular!
  3308. }
  3309. AddDependency(underlyingType, userType, depFlag);
  3310. }
  3311. }
  3312. else if (!usedType->IsGenericTypeInstance())
  3313. {
  3314. auto underlyingType = usedType->GetUnderlyingType();
  3315. if (underlyingType != NULL)
  3316. AddDependency(underlyingType, userType, depFlag);
  3317. }
  3318. BfDependedType* checkDType = usedType->ToDependedType();
  3319. if (checkDType == NULL)
  3320. return;
  3321. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  3322. mContext->MarkAsReferenced(checkDType);
  3323. #ifdef _DEBUG
  3324. // If a MethodRef depends ON US, that means it's a local method that we own
  3325. if (userType->IsMethodRef())
  3326. {
  3327. auto methodRefType = (BfMethodRefType*)userType;
  3328. BF_ASSERT(methodRefType->mOwner == checkDType);
  3329. }
  3330. #endif
  3331. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  3332. return;
  3333. if ((checkDType->IsGenericTypeInstance()) && (!userType->IsMethodRef()))
  3334. {
  3335. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  3336. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3337. {
  3338. AddDependency(genericArg, userType, depFlag);
  3339. }
  3340. }
  3341. if (checkDType->IsTuple())
  3342. {
  3343. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  3344. {
  3345. if (field.mDataIdx != -1)
  3346. AddDependency(field.mResolvedType, userType, depFlag);
  3347. }
  3348. }
  3349. }
  3350. void BfModule::AddDependency(BfGenericParamInstance* genericParam, BfTypeInstance* usingType)
  3351. {
  3352. if ((genericParam->mExternType != NULL) && (!genericParam->mExternType->IsGenericParam()))
  3353. AddDependency(genericParam->mExternType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3354. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  3355. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3356. for (auto& operatorConstraint : genericParam->mOperatorConstraints)
  3357. {
  3358. if (operatorConstraint.mLeftType != NULL)
  3359. AddDependency(operatorConstraint.mLeftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3360. if (operatorConstraint.mRightType != NULL)
  3361. AddDependency(operatorConstraint.mRightType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3362. }
  3363. if (genericParam->mTypeConstraint != NULL)
  3364. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3365. }
  3366. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  3367. {
  3368. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  3369. {
  3370. if (methodInstance->mHotMethod == NULL)
  3371. CheckHotMethod(methodInstance, "");
  3372. BF_ASSERT(methodInstance->mHotMethod != NULL);
  3373. if (devirtualized)
  3374. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  3375. else
  3376. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  3377. }
  3378. }
  3379. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  3380. {
  3381. auto checkTypeInst = typeInst;
  3382. while (checkTypeInst != NULL)
  3383. {
  3384. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  3385. return true;
  3386. checkTypeInst = checkTypeInst->mBaseType;
  3387. }
  3388. return false;
  3389. }
  3390. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  3391. {
  3392. if (mContext->mCurTypeState == NULL)
  3393. return;
  3394. BP_ZONE("PopulateGlobalContainersList");
  3395. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  3396. if ((userTypeDef == NULL) && (mCurMethodInstance != NULL))
  3397. userTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  3398. if (userTypeDef == NULL)
  3399. userTypeDef = mCurTypeInstance->mTypeDef;
  3400. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  3401. {
  3402. mContext->mCurTypeState->mGlobalContainers.Clear();
  3403. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  3404. {
  3405. BfAtomComposite findStr;
  3406. if (namespaceIdx != -1)
  3407. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  3408. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  3409. while (typeDefItr)
  3410. {
  3411. auto typeDef = *typeDefItr;
  3412. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  3413. {
  3414. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  3415. {
  3416. BfGlobalContainerEntry globalEntry;
  3417. globalEntry.mTypeDef = typeDef;
  3418. globalEntry.mTypeInst = NULL;
  3419. typeDef->PopulateMemberSets();
  3420. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  3421. }
  3422. }
  3423. else if (!typeDef->mIsPartial)
  3424. {
  3425. //break;
  3426. }
  3427. typeDefItr.MoveToNextHashMatch();
  3428. }
  3429. }
  3430. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  3431. }
  3432. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  3433. // reifing types
  3434. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  3435. {
  3436. if (globalEntry.mTypeInst == NULL)
  3437. {
  3438. bool include = false;
  3439. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  3440. include = true;
  3441. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  3442. {
  3443. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  3444. include = true;
  3445. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  3446. include = true;
  3447. }
  3448. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  3449. {
  3450. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  3451. include = true;
  3452. }
  3453. if (include)
  3454. {
  3455. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  3456. if (type != NULL)
  3457. globalEntry.mTypeInst = type->ToTypeInstance();
  3458. }
  3459. }
  3460. }
  3461. }
  3462. BfStaticSearch* BfModule::GetStaticSearch()
  3463. {
  3464. auto activeTypeDef = GetActiveTypeDef();
  3465. BfStaticSearch* staticSearch = NULL;
  3466. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3467. return staticSearch;
  3468. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3469. return staticSearch;
  3470. return NULL;
  3471. }
  3472. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  3473. {
  3474. auto activeTypeDef = GetActiveTypeDef();
  3475. BfInternalAccessSet* internalAccessSet = NULL;
  3476. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3477. return internalAccessSet;
  3478. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3479. return internalAccessSet;
  3480. return NULL;
  3481. }
  3482. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  3483. {
  3484. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  3485. return true;
  3486. if ((mCurMethodInstance != NULL) &&
  3487. ((mCurMethodInstance->mIsUnspecializedVariation) || (mCurMethodInstance->IsSpecializedGenericMethod())))
  3488. return true;
  3489. auto internalAccessSet = GetInternalAccessSet();
  3490. if (internalAccessSet == NULL)
  3491. return false;
  3492. for (auto& nameComposite : internalAccessSet->mNamespaces)
  3493. {
  3494. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  3495. return true;
  3496. }
  3497. for (auto internalType : internalAccessSet->mTypes)
  3498. {
  3499. auto checkTypeDef = usingTypeDef->GetDefinition();
  3500. while (checkTypeDef != NULL)
  3501. {
  3502. if (checkTypeDef == internalType->mTypeDef->GetDefinition())
  3503. return true;
  3504. checkTypeDef = checkTypeDef->mOuterType;
  3505. }
  3506. }
  3507. return false;
  3508. }
  3509. void PrintUsers(llvm::MDNode* md);
  3510. BfModuleOptions BfModule::GetModuleOptions()
  3511. {
  3512. if (mIsScratchModule)
  3513. return BfModuleOptions();
  3514. if (mModuleOptions != NULL)
  3515. return *mModuleOptions;
  3516. BfModuleOptions moduleOptions;
  3517. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3518. if (mProject != NULL)
  3519. {
  3520. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3521. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3522. }
  3523. auto headModule = this;
  3524. while (headModule->mParentModule != NULL)
  3525. headModule = headModule->mParentModule;
  3526. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata") || mIsSpecialModule);
  3527. if (headModule->mOwnedTypeInstances.size() > 0)
  3528. {
  3529. auto typeInst = headModule->mOwnedTypeInstances[0];
  3530. if (typeInst->mTypeOptionsIdx == -2)
  3531. PopulateType(typeInst);
  3532. if (typeInst->mTypeOptionsIdx != -1)
  3533. {
  3534. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3535. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3536. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3537. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3538. }
  3539. }
  3540. return moduleOptions;
  3541. }
  3542. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3543. {
  3544. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3545. return BfCheckedKind_Unchecked;
  3546. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3547. auto typeOptions = GetTypeOptions();
  3548. if (typeOptions != NULL)
  3549. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3550. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3551. }
  3552. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3553. {
  3554. BF_ASSERT(typeInstance != NULL);
  3555. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_InFailTypes) != 0)
  3556. return;
  3557. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_InFailTypes);
  3558. mContext->mFailTypes.TryAdd(typeInstance, BfFailKind_Normal);
  3559. }
  3560. void BfModule::DeferRebuildType(BfTypeInstance* typeInstance)
  3561. {
  3562. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_RebuildQueued) != 0)
  3563. return;
  3564. mCompiler->mHasQueuedTypeRebuilds = true;
  3565. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_RebuildQueued);
  3566. AddFailType(typeInstance);
  3567. }
  3568. void BfModule::CheckAddFailType()
  3569. {
  3570. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3571. // but we still need to add the owning type to the FailTypes list
  3572. //.. OLD:
  3573. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3574. /*if (mCurTypeInstance->mModule != this)
  3575. return;*/
  3576. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3577. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3578. // being recompiled. This forces types with warnings to be recompiled.
  3579. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3580. // constantly warning-aware
  3581. if ((mHadBuildError) ||
  3582. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3583. {
  3584. //mContext->mFailTypes.Add(mCurTypeInstance);
  3585. }
  3586. }
  3587. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3588. {
  3589. if (!mCompiler->IsHotCompile())
  3590. return;
  3591. typeInst->mDirty = true;
  3592. for (auto& dep : typeInst->mDependencyMap)
  3593. {
  3594. auto depType = dep.mKey;
  3595. auto depFlags = dep.mValue.mFlags;
  3596. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3597. {
  3598. MarkDerivedDirty(depType->ToTypeInstance());
  3599. }
  3600. }
  3601. }
  3602. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3603. {
  3604. auto fieldType = fieldInstance->GetResolvedType();
  3605. auto field = fieldInstance->GetFieldDef();
  3606. if (fieldType->IsVar())
  3607. return;
  3608. BfIRValue initValue;
  3609. if (field->mIsConst)
  3610. {
  3611. if (fieldType->IsPointer())
  3612. fieldType = fieldType->GetUnderlyingType();
  3613. }
  3614. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3615. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3616. storageKind = BfIRStorageKind_Export;
  3617. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3618. storageKind = BfIRStorageKind_Import;
  3619. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3620. initValue = GetDefaultValue(fieldType);
  3621. if (fieldInstance->mOwner->IsUnspecializedType())
  3622. {
  3623. // Placeholder
  3624. auto ptrVal = CreatePointerType(fieldType);
  3625. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3626. }
  3627. else
  3628. {
  3629. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3630. StringT<4096> staticVarName;
  3631. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3632. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3633. {
  3634. BfIRType irType;
  3635. if (fieldInstance->IsAppendedObject())
  3636. {
  3637. irType = mBfIRBuilder->MapTypeInst(fieldType->ToTypeInstance(), BfIRPopulateType_Eventually_Full);
  3638. initValue = mBfIRBuilder->CreateConstAggZero(irType);
  3639. }
  3640. else
  3641. irType = mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full);
  3642. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3643. irType,
  3644. false,
  3645. BfIRLinkageType_External,
  3646. initValue,
  3647. staticVarName,
  3648. isThreadLocal);
  3649. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3650. if (storageKind != BfIRStorageKind_Normal)
  3651. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3652. BF_ASSERT(globalVar);
  3653. mStaticFieldRefs[fieldInstance] = globalVar;
  3654. }
  3655. }
  3656. }
  3657. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3658. {
  3659. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3660. BfType* fieldType = NULL;
  3661. if (fieldInstance != NULL)
  3662. {
  3663. fieldType = fieldInstance->GetResolvedType();
  3664. if (fieldType == NULL)
  3665. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3666. }
  3667. else
  3668. {
  3669. BF_ASSERT(mCompiler->IsAutocomplete());
  3670. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3671. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3672. {
  3673. fieldType = typeInstance;
  3674. }
  3675. else
  3676. {
  3677. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3678. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3679. if (isLet || isVar)
  3680. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3681. else
  3682. fieldType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  3683. if (fieldType == NULL)
  3684. fieldType = mContext->mBfObjectType;
  3685. }
  3686. }
  3687. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3688. return;
  3689. if (mContext->mFieldResolveReentrys.size() > 1)
  3690. {
  3691. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3692. {
  3693. String failStr = "Circular data reference detected between the following fields:";
  3694. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3695. {
  3696. if (i > 1)
  3697. failStr += ",";
  3698. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3699. }
  3700. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3701. if (err)
  3702. err->mIsPersistent = true;
  3703. return;
  3704. }
  3705. }
  3706. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3707. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3708. if (fieldInstance == NULL)
  3709. popTypeResolveReentry.Pop();
  3710. auto typeDef = typeInstance->mTypeDef;
  3711. BfIRValue constValue;
  3712. if (fieldDef->mIsExtern)
  3713. {
  3714. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3715. {
  3716. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3717. Fail("Extern consts must be pointer types", fieldDef->mTypeRef);
  3718. }
  3719. if (fieldDef->GetInitializer() != NULL)
  3720. {
  3721. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3722. Fail("Extern consts cannot have initializers", fieldDef->GetNameNode());
  3723. }
  3724. }
  3725. else if (fieldDef->GetInitializer() == NULL)
  3726. {
  3727. if (fieldDef->IsEnumCaseEntry())
  3728. {
  3729. if (typeInstance->IsTypedPrimitive())
  3730. {
  3731. BfFieldInstance* prevFieldInstance = NULL;
  3732. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3733. {
  3734. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3735. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3736. {
  3737. prevFieldInstance = checkFieldInst;
  3738. break;
  3739. }
  3740. }
  3741. if (prevFieldInstance == NULL)
  3742. constValue = GetConstValue(0, typeInstance);
  3743. else
  3744. {
  3745. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3746. if (prevFieldInstance->mConstIdx == -1)
  3747. {
  3748. if (!mCompiler->IsAutocomplete())
  3749. AssertErrorState();
  3750. constValue = GetConstValue(0, typeInstance);
  3751. }
  3752. else
  3753. {
  3754. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3755. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3756. }
  3757. }
  3758. }
  3759. }
  3760. else
  3761. {
  3762. Fail("Const requires initializer", fieldDef->GetNameNode());
  3763. }
  3764. }
  3765. else if (mBfIRBuilder != NULL)
  3766. {
  3767. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3768. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3769. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3770. BfMethodState methodState;
  3771. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3772. methodState.mTempKind = BfMethodState::TempKind_Static;
  3773. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3774. if ((fieldType->IsVar()) || (fieldType->IsUndefSizedArray()))
  3775. {
  3776. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3777. if (!initValue)
  3778. {
  3779. AssertErrorState();
  3780. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3781. }
  3782. if (fieldInstance != NULL)
  3783. {
  3784. if (fieldType->IsUndefSizedArray())
  3785. {
  3786. if ((initValue.mType->IsSizedArray()) && (initValue.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3787. {
  3788. fieldInstance->mResolvedType = initValue.mType;
  3789. }
  3790. }
  3791. else
  3792. fieldInstance->mResolvedType = initValue.mType;
  3793. }
  3794. constValue = initValue.mValue;
  3795. }
  3796. else
  3797. {
  3798. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3799. constValue = uncastedInitValue.mValue;
  3800. }
  3801. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3802. {
  3803. // Illegal
  3804. constValue = BfIRValue();
  3805. }
  3806. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3807. }
  3808. if (fieldInstance != NULL)
  3809. {
  3810. fieldType = fieldInstance->GetResolvedType();
  3811. if ((fieldType == NULL) || (fieldType->IsVar()))
  3812. {
  3813. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3814. AssertErrorState();
  3815. // Default const type is 'int'
  3816. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3817. if (fieldInstance != NULL)
  3818. {
  3819. fieldInstance->mResolvedType = initValue.mType;
  3820. }
  3821. constValue = initValue.mValue;
  3822. }
  3823. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3824. {
  3825. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3826. CurrentAddToConstHolder(constValue);
  3827. fieldInstance->mConstIdx = constValue.mId;
  3828. }
  3829. }
  3830. }
  3831. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3832. {
  3833. bool isDeclType = (field->mFieldDeclaration != NULL) && BfNodeDynCastExact<BfExprModTypeRef>(field->mTypeRef) != NULL;
  3834. auto fieldType = fieldInstance->GetResolvedType();
  3835. if ((field->mIsConst) && (!isDeclType))
  3836. {
  3837. ResolveConstField(typeInstance, fieldInstance, field);
  3838. return fieldInstance->GetResolvedType();
  3839. }
  3840. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3841. if (!fieldInstance->mIsInferredType)
  3842. return fieldType;
  3843. if ((!fieldType->IsVar()) && (!fieldType->IsUndefSizedArray()))
  3844. return fieldType;
  3845. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3846. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3847. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mType != typeInstance);
  3848. auto typeDef = typeInstance->mTypeDef;
  3849. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3850. {
  3851. AssertErrorState();
  3852. return fieldType;
  3853. }
  3854. bool hadInferenceCycle = false;
  3855. if (mContext->mFieldResolveReentrys.size() > 1)
  3856. {
  3857. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3858. {
  3859. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3860. {
  3861. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3862. auto fieldDef = fieldInst->GetFieldDef();
  3863. auto fieldOwner = fieldInst->mOwner;
  3864. auto fieldModule = fieldOwner->mModule;
  3865. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3866. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3867. }
  3868. return fieldType;
  3869. }
  3870. }
  3871. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3872. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3873. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3874. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3875. if ((field->GetInitializer() == NULL) && (!isDeclType))
  3876. {
  3877. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3878. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3879. return fieldType;
  3880. }
  3881. BfType* resolvedType = NULL;
  3882. if (!hadInferenceCycle)
  3883. {
  3884. BfTypeState typeState;
  3885. typeState.mPrevState = mContext->mCurTypeState;
  3886. typeState.mType = typeInstance;
  3887. typeState.mCurFieldDef = field;
  3888. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3889. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3890. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3891. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3892. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3893. BfMethodState methodState;
  3894. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3895. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3896. if (!staticOnly)
  3897. {
  3898. //BfLocalVariable localVar;
  3899. //methodState.mLocals.push_back(localVar);
  3900. }
  3901. if (isDeclType)
  3902. {
  3903. auto fieldDef = fieldInstance->GetFieldDef();
  3904. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3905. }
  3906. else
  3907. {
  3908. BfTypedValue valueFromExpr;
  3909. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3910. FixIntUnknown(valueFromExpr);
  3911. if (fieldType->IsUndefSizedArray())
  3912. {
  3913. if ((valueFromExpr.mType != NULL) && (valueFromExpr.mType->IsSizedArray()) && (valueFromExpr.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3914. resolvedType = valueFromExpr.mType;
  3915. }
  3916. else
  3917. resolvedType = valueFromExpr.mType;
  3918. }
  3919. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3920. }
  3921. if (resolvedType == NULL)
  3922. return fieldType;
  3923. fieldInstance->SetResolvedType(resolvedType);
  3924. if (field->mIsStatic)
  3925. {
  3926. }
  3927. else if (fieldInstance->mDataIdx >= 0)
  3928. {
  3929. }
  3930. else
  3931. {
  3932. BF_ASSERT(typeInstance->IsIncomplete());
  3933. }
  3934. return resolvedType;
  3935. }
  3936. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3937. {
  3938. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3939. auto fieldType = fieldInstance->GetResolvedType();
  3940. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3941. {
  3942. int fieldIdx = 0;
  3943. int fieldCount = 0;
  3944. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  3945. fieldIdx--;
  3946. int count = fieldCount;
  3947. if (fieldIdx == -1)
  3948. count = 1;
  3949. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3950. auto thisVariable = GetThisVariable();
  3951. if (thisVariable != NULL)
  3952. {
  3953. for (int i = 0; i < count; i++)
  3954. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  3955. }
  3956. }
  3957. }
  3958. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3959. {
  3960. if (fieldInstance->mCustomAttributes == NULL)
  3961. return false;
  3962. auto fieldDef = fieldInstance->GetFieldDef();
  3963. if (!fieldDef->mIsStatic)
  3964. return false;
  3965. bool isThreadLocal = false;
  3966. if (fieldInstance->mCustomAttributes != NULL)
  3967. {
  3968. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3969. {
  3970. if (customAttr.mType->ToTypeInstance()->IsInstanceOf(mCompiler->mThreadStaticAttributeTypeDef))
  3971. return true;
  3972. }
  3973. }
  3974. return false;
  3975. }
  3976. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  3977. {
  3978. if (fieldDef == NULL)
  3979. fieldDef = fieldInstance->GetFieldDef();
  3980. if (fieldType == NULL)
  3981. fieldType = fieldInstance->GetResolvedType();
  3982. if (initializer == NULL)
  3983. {
  3984. if (fieldDef == NULL)
  3985. return BfTypedValue();
  3986. initializer = fieldDef->GetInitializer();
  3987. }
  3988. BfTypedValue staticVarRef;
  3989. BfTypedValue result;
  3990. if (initializer == NULL)
  3991. {
  3992. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3993. }
  3994. else
  3995. {
  3996. if (mCompiler->mIsResolveOnly)
  3997. {
  3998. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  3999. {
  4000. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  4001. sourceClassifier->VisitChildNoRef(initializer);
  4002. }
  4003. }
  4004. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  4005. {
  4006. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  4007. BfConstResolver constResolver(this);
  4008. constResolver.Resolve(initializer);
  4009. return GetDefaultTypedValue(fieldType);
  4010. }
  4011. else if (mCurTypeInstance->IsUnspecializedTypeVariation())
  4012. {
  4013. return GetDefaultTypedValue(fieldType);
  4014. }
  4015. else if (fieldDef->mIsConst)
  4016. {
  4017. int ceExecuteId = -1;
  4018. if (mCompiler->mCeMachine != NULL)
  4019. ceExecuteId = mCompiler->mCeMachine->mExecuteId;
  4020. BfTypeState typeState;
  4021. typeState.mType = mCurTypeInstance;
  4022. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  4023. typeState.mCurFieldDef = fieldDef;
  4024. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  4025. BfConstResolver constResolver(this);
  4026. if (fieldType->IsVar())
  4027. return constResolver.Resolve(initializer);
  4028. else
  4029. {
  4030. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  4031. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  4032. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  4033. {
  4034. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  4035. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  4036. resolveFlags = BfConstResolveFlag_NoCast;
  4037. }
  4038. UpdateSrcPos(initializer);
  4039. auto result = constResolver.Resolve(initializer, fieldType, resolveFlags);
  4040. if ((mCompiler->mCeMachine != NULL) && (fieldInstance != NULL))
  4041. {
  4042. if (mCompiler->mCeMachine->mExecuteId != ceExecuteId)
  4043. fieldInstance->mHadConstEval = true;
  4044. }
  4045. return result;
  4046. }
  4047. }
  4048. BfExprEvaluator exprEvaluator(this);
  4049. if (doStore)
  4050. {
  4051. staticVarRef = ReferenceStaticField(fieldInstance);
  4052. exprEvaluator.mReceivingValue = &staticVarRef;
  4053. }
  4054. if (fieldType->IsVar())
  4055. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4056. else
  4057. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4058. if (doStore)
  4059. {
  4060. if (exprEvaluator.mReceivingValue == NULL)
  4061. doStore = false; // Already stored
  4062. }
  4063. }
  4064. if (fieldInstance != NULL)
  4065. MarkFieldInitialized(fieldInstance);
  4066. if ((doStore) && (result))
  4067. {
  4068. if (fieldInstance->mResolvedType->IsUndefSizedArray())
  4069. {
  4070. if ((!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mFastFinish))
  4071. AssertErrorState();
  4072. }
  4073. else
  4074. {
  4075. result = LoadValue(result);
  4076. if (!result.mType->IsValuelessType())
  4077. mBfIRBuilder->CreateAlignedStore(result.mValue, staticVarRef.mValue, result.mType->mAlign);
  4078. }
  4079. }
  4080. return result;
  4081. }
  4082. void BfModule::AppendedObjectInit(BfFieldInstance* fieldInst)
  4083. {
  4084. BfExprEvaluator exprEvaluator(this);
  4085. bool failed = false;
  4086. auto fieldDef = fieldInst->GetFieldDef();
  4087. auto initializer = fieldDef->GetInitializer();
  4088. BfResolvedArgs resolvedArgs;
  4089. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(initializer))
  4090. {
  4091. bool isDot = false;
  4092. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  4093. isDot = (memberRefExpr->mTarget == NULL) && (memberRefExpr->mMemberName == NULL);
  4094. if (!isDot)
  4095. {
  4096. auto resolvedType = ResolveTypeRef(invocationExpr->mTarget, {});
  4097. if ((resolvedType == NULL) || (resolvedType != fieldInst->mResolvedType))
  4098. failed = true;
  4099. }
  4100. SetAndRestoreValue<BfType*> prevExpectingType(exprEvaluator.mExpectingType, fieldInst->mResolvedType);
  4101. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  4102. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  4103. }
  4104. else if (initializer != NULL)
  4105. {
  4106. GetFieldInitializerValue(fieldInst);
  4107. failed = true;
  4108. }
  4109. if (failed)
  4110. Fail("Append fields can only be initialized with a call to their constructor", initializer);
  4111. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  4112. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4113. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4114. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  4115. auto fieldTypeInst = fieldInst->mResolvedType->ToTypeInstance();
  4116. BfIRValue fieldAddr;
  4117. if (fieldDef->mIsStatic)
  4118. {
  4119. fieldAddr = ReferenceStaticField(fieldInst).mValue;
  4120. }
  4121. else
  4122. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  4123. auto thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  4124. auto indexVal = BfTypedValue(CreateAlloca(intType), CreateRefType(intType));
  4125. auto intThisVal = mBfIRBuilder->CreatePtrToInt(thisValue.mValue, (intType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  4126. auto curValPtr = mBfIRBuilder->CreateAdd(intThisVal, GetConstValue(fieldTypeInst->mInstSize, intType));
  4127. mBfIRBuilder->CreateStore(curValPtr, indexVal.mValue);
  4128. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 0);
  4129. auto vDataRef = CreateClassVDataGlobal(fieldInst->mResolvedType->ToTypeInstance());
  4130. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  4131. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  4132. mBfIRBuilder->CreateStore(srcVal, destAddr);
  4133. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  4134. {
  4135. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4136. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4137. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(thisValue.mValue, ptrType);
  4138. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_AppendAlloc), thisFlagsPtr);
  4139. }
  4140. exprEvaluator.MatchConstructor(fieldDef->GetNameNode(), NULL, thisValue, fieldInst->mResolvedType->ToTypeInstance(), resolvedArgs, false, true, &indexVal);
  4141. }
  4142. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  4143. {
  4144. }
  4145. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  4146. {
  4147. PopulateType(classType);
  4148. if (isInterfacePass)
  4149. {
  4150. for (auto ifaceInst : classType->mInterfaces)
  4151. {
  4152. if (exChecks->Contains(ifaceInst.mInterfaceType))
  4153. continue;
  4154. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  4155. continue;
  4156. if (ifaceInst.mDeclaringType->IsExtension())
  4157. {
  4158. bool needsExCheck = false;
  4159. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  4160. {
  4161. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  4162. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  4163. {
  4164. exChecks->push_back(ifaceInst.mInterfaceType);
  4165. continue;
  4166. }
  4167. else
  4168. {
  4169. // We can only do an 'exCheck' if we're actually going to slot this interface
  4170. }
  4171. }
  4172. }
  4173. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  4174. }
  4175. }
  4176. else
  4177. {
  4178. outVals->push_back(classType->mTypeId);
  4179. }
  4180. if (classType->mBaseType != NULL)
  4181. {
  4182. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  4183. }
  4184. }
  4185. void BfModule::CreateDynamicCastMethod()
  4186. {
  4187. auto objType = mContext->mBfObjectType;
  4188. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  4189. {
  4190. // The main reason to punt on this method for ResolveOnly is because types can be created
  4191. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  4192. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  4193. // remove this punt when we recycle typeId's
  4194. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  4195. mCurMethodState->mHadReturn = true;
  4196. return;
  4197. }
  4198. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  4199. auto func = mCurMethodState->mIRFunction;
  4200. auto thisValue = mBfIRBuilder->GetArgument(0);
  4201. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  4202. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4203. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  4204. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  4205. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  4206. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  4207. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  4208. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4209. SizedArray<int, 8> typeMatches;
  4210. SizedArray<BfTypeInstance*, 8> exChecks;
  4211. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  4212. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  4213. {
  4214. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  4215. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  4216. BfTypeVector genericArgs;
  4217. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  4218. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  4219. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef->GetDefinition(), genericArgs, BfPopulateType_Declaration);
  4220. typeMatches.push_back(unboundType->mTypeId);
  4221. }
  4222. if (mCurTypeInstance->IsBoxed())
  4223. {
  4224. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  4225. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  4226. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  4227. if (innerType->IsTypedPrimitive())
  4228. {
  4229. auto underlyingType = innerType->GetUnderlyingType();
  4230. typeMatches.push_back(underlyingType->mTypeId);
  4231. }
  4232. auto innerTypeInst = innerType->ToTypeInstance();
  4233. if ((innerTypeInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef)) ||
  4234. (innerTypeInst->IsInstanceOf(mCompiler->mPointerTTypeDef)) ||
  4235. (innerTypeInst->IsInstanceOf(mCompiler->mMethodRefTypeDef)))
  4236. {
  4237. PopulateType(innerTypeInst);
  4238. //TODO: What case was this supposed to handle?
  4239. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  4240. }
  4241. }
  4242. auto curBlock = mBfIRBuilder->GetInsertBlock();
  4243. BfIRValue vDataPtr;
  4244. if (!exChecks.empty())
  4245. {
  4246. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4247. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  4248. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  4249. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4250. }
  4251. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  4252. for (auto typeMatch : typeMatches)
  4253. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  4254. Array<BfIRValue> incomingFalses;
  4255. for (auto ifaceTypeInst : exChecks)
  4256. {
  4257. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  4258. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  4259. mBfIRBuilder->SetInsertPoint(nextBB);
  4260. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  4261. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4262. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4263. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4264. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  4265. incomingFalses.push_back(nextBB);
  4266. }
  4267. mBfIRBuilder->AddBlock(trueBB);
  4268. mBfIRBuilder->SetInsertPoint(trueBB);
  4269. mBfIRBuilder->CreateBr(exitBB);
  4270. mBfIRBuilder->AddBlock(exitBB);
  4271. mBfIRBuilder->SetInsertPoint(exitBB);
  4272. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  4273. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  4274. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  4275. for (auto incomingFalseBlock : incomingFalses)
  4276. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  4277. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  4278. mBfIRBuilder->CreateRet(phi);
  4279. mCurMethodState->mHadReturn = true;
  4280. }
  4281. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  4282. {
  4283. BfExprEvaluator exprEvaluator(this);
  4284. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  4285. auto typeInst = rightValue.mType->ToTypeInstance();
  4286. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  4287. BfTypedValue result = exprEvaluator.GetResult();
  4288. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  4289. {
  4290. // Fail?
  4291. }
  4292. if ((result) && (!result.mType->IsVar()))
  4293. {
  4294. auto nextBB = mBfIRBuilder->CreateBlock("next");
  4295. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  4296. mBfIRBuilder->AddBlock(nextBB);
  4297. mBfIRBuilder->SetInsertPoint(nextBB);
  4298. }
  4299. }
  4300. void BfModule::CreateFakeCallerMethod(const String& funcName)
  4301. {
  4302. if (mCurMethodInstance->mHasFailed)
  4303. return;
  4304. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  4305. return;
  4306. BF_ASSERT(mCurMethodInstance->mIRFunction);
  4307. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  4308. SizedArray<BfIRType, 4> paramTypes;
  4309. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  4310. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  4311. mBfIRBuilder->SetActiveFunction(func);
  4312. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  4313. mBfIRBuilder->SetInsertPoint(entryBlock);
  4314. BfMethodState methodState;
  4315. methodState.mIRHeadBlock = entryBlock;
  4316. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4317. SizedArray<BfIRValue, 8> args;
  4318. BfExprEvaluator exprEvaluator(this);
  4319. if (mCurMethodInstance->GetStructRetIdx() == 0)
  4320. {
  4321. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4322. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4323. }
  4324. if (mCurMethodInstance->HasThis())
  4325. {
  4326. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  4327. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  4328. }
  4329. if (mCurMethodInstance->GetStructRetIdx() == 1)
  4330. {
  4331. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4332. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4333. }
  4334. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  4335. {
  4336. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  4337. if (paramType->IsValuelessType())
  4338. continue;
  4339. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  4340. }
  4341. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  4342. mBfIRBuilder->CreateRetVoid();
  4343. }
  4344. void BfModule::CreateDelegateEqualsMethod()
  4345. {
  4346. if (mBfIRBuilder->mIgnoreWrites)
  4347. return;
  4348. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4349. if (refNode == NULL)
  4350. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4351. UpdateSrcPos(refNode);
  4352. SetIllegalSrcPos();
  4353. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4354. auto resultVal = CreateAlloca(boolType);
  4355. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4356. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4357. auto delegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  4358. mBfIRBuilder->PopulateType(delegateType);
  4359. BfExprEvaluator exprEvaluator(this);
  4360. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4361. BfTypedValue lhsDelegate = BfTypedValue(mBfIRBuilder->CreateBitCast(leftTypedVal.mValue, mBfIRBuilder->MapType(delegateType)), delegateType);
  4362. BfTypedValue rhsDelegate = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4363. rhsDelegate = LoadValue(rhsDelegate);
  4364. BfTypedValue rightTypedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(rhsDelegate.mValue, mBfIRBuilder->MapType(mCurTypeInstance)), mCurTypeInstance);
  4365. auto& targetFieldInstance = delegateType->mFieldInstances[0];
  4366. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(lhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4367. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4368. leftValue = LoadValue(leftValue);
  4369. rightValue = LoadValue(rightValue);
  4370. EmitEquals(leftValue, rightValue, exitBB, false);
  4371. bool hadComparison = false;
  4372. for (auto& fieldRef : mCurTypeInstance->mFieldInstances)
  4373. {
  4374. BfFieldInstance* fieldInstance = &fieldRef;
  4375. if (fieldInstance->mDataOffset == -1)
  4376. continue;
  4377. auto fieldType = fieldInstance->mResolvedType;
  4378. if (fieldType->IsValuelessType())
  4379. continue;
  4380. if (fieldType->IsVar())
  4381. continue;
  4382. if (fieldType->IsMethodRef())
  4383. continue;
  4384. if (fieldType->IsRef())
  4385. fieldType = CreatePointerType(fieldType->GetUnderlyingType());
  4386. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(leftTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4387. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rightTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4388. if (!fieldInstance->mResolvedType->IsComposite())
  4389. {
  4390. leftValue = LoadValue(leftValue);
  4391. rightValue = LoadValue(rightValue);
  4392. }
  4393. EmitEquals(leftValue, rightValue, exitBB, false);
  4394. }
  4395. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4396. mBfIRBuilder->CreateBr(exitBB);
  4397. mBfIRBuilder->AddBlock(exitBB);
  4398. mBfIRBuilder->SetInsertPoint(exitBB);
  4399. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4400. ClearLifetimeEnds();
  4401. mBfIRBuilder->CreateRet(loadedResult);
  4402. mCurMethodState->mHadReturn = true;
  4403. }
  4404. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  4405. {
  4406. if (mCurMethodInstance->mIsUnspecialized)
  4407. return;
  4408. if (mBfIRBuilder->mIgnoreWrites)
  4409. return;
  4410. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  4411. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  4412. bool isValid = true;
  4413. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4414. if (compareType->IsValuelessType())
  4415. {
  4416. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4417. return;
  4418. }
  4419. if (compareType->IsTypedPrimitive())
  4420. {
  4421. BfExprEvaluator exprEvaluator(this);
  4422. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  4423. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  4424. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  4425. mBfIRBuilder->CreateRet(cmpResult);
  4426. return;
  4427. }
  4428. auto compareDType = compareType->ToDependedType();
  4429. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  4430. if (compareTypeInst != NULL)
  4431. {
  4432. if (compareType->IsPrimitiveType())
  4433. compareTypeInst = GetWrappedStructType(compareType);
  4434. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  4435. {
  4436. isValid = false;
  4437. }
  4438. mBfIRBuilder->PopulateType(compareTypeInst);
  4439. }
  4440. if (!isValid)
  4441. {
  4442. ClearLifetimeEnds();
  4443. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4444. return;
  4445. }
  4446. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  4447. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4448. if (refNode == NULL)
  4449. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4450. UpdateSrcPos(refNode);
  4451. SetIllegalSrcPos();
  4452. auto resultVal = CreateAlloca(boolType);
  4453. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4454. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4455. if (compareType->IsValuelessType())
  4456. {
  4457. // Always equal, nothing to do
  4458. }
  4459. else if (compareType->IsSizedArray())
  4460. {
  4461. auto sizedArrayType = (BfSizedArrayType*)compareType;
  4462. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  4463. {
  4464. BfTypedValue result;
  4465. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index, true);
  4466. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4467. if (!result.mType->IsValueType())
  4468. result = LoadValue(result);
  4469. return result;
  4470. };
  4471. if (sizedArrayType->mElementCount > 6)
  4472. {
  4473. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4474. auto itr = CreateAlloca(intPtrType);
  4475. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  4476. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  4477. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  4478. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  4479. mBfIRBuilder->CreateBr(loopBB);
  4480. mBfIRBuilder->SetInsertPoint(loopBB);
  4481. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  4482. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  4483. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  4484. mBfIRBuilder->SetInsertPoint(bodyBB);
  4485. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  4486. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  4487. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4488. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  4489. mBfIRBuilder->CreateStore(incValue, itr);
  4490. mBfIRBuilder->CreateBr(loopBB);
  4491. mBfIRBuilder->SetInsertPoint(doneBB);
  4492. }
  4493. else
  4494. {
  4495. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  4496. {
  4497. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4498. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4499. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4500. }
  4501. }
  4502. }
  4503. else if (compareType->IsMethodRef())
  4504. {
  4505. auto methodRefType = (BfMethodRefType*)compareType;
  4506. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  4507. BfExprEvaluator exprEvaluator(this);
  4508. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4509. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4510. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  4511. // values for the same method reference -- they will always refer back to the same local variables.
  4512. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  4513. if (dataIdx != -1)
  4514. {
  4515. bool failed = false;
  4516. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  4517. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  4518. BF_ASSERT(!failed);
  4519. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4520. }
  4521. }
  4522. else if (compareTypeInst->IsEnum())
  4523. {
  4524. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4525. BfExprEvaluator exprEvaluator(this);
  4526. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4527. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4528. auto dscrType = compareTypeInst->GetDiscriminatorType();
  4529. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  4530. leftValue = LoadValue(leftValue);
  4531. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  4532. rightValue = LoadValue(rightValue);
  4533. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  4534. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  4535. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4536. int enumCount = 0;
  4537. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4538. {
  4539. BfFieldInstance* fieldInstance = &fieldRef;
  4540. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4541. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4542. {
  4543. enumCount = -fieldInstance->mDataIdx;
  4544. }
  4545. }
  4546. if (enumCount > 0)
  4547. {
  4548. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  4549. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  4550. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4551. {
  4552. BfFieldInstance* fieldInstance = &fieldRef;
  4553. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4554. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4555. {
  4556. int enumIdx = -fieldInstance->mDataIdx - 1;
  4557. if (fieldInstance->mResolvedType->mSize == 0)
  4558. {
  4559. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  4560. }
  4561. else
  4562. {
  4563. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  4564. mBfIRBuilder->SetInsertPoint(caseBlock);
  4565. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  4566. BfTypedValue leftTuple;
  4567. BfTypedValue rightTuple;
  4568. if (leftPayload.IsAddr())
  4569. {
  4570. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4571. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4572. }
  4573. else
  4574. {
  4575. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4576. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4577. }
  4578. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  4579. mBfIRBuilder->CreateBr(matchedBlock);
  4580. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  4581. }
  4582. }
  4583. }
  4584. mBfIRBuilder->AddBlock(matchedBlock);
  4585. mBfIRBuilder->SetInsertPoint(matchedBlock);
  4586. }
  4587. }
  4588. else if (compareTypeInst->IsUnion())
  4589. {
  4590. auto innerType = compareTypeInst->GetUnionInnerType();
  4591. if (!innerType->IsValuelessType())
  4592. {
  4593. BfExprEvaluator exprEvaluator(this);
  4594. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4595. leftTypedVal = AggregateSplat(leftTypedVal);
  4596. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  4597. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4598. rightTypedVal = AggregateSplat(rightTypedVal);
  4599. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  4600. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  4601. }
  4602. }
  4603. else
  4604. {
  4605. BfExprEvaluator exprEvaluator(this);
  4606. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4607. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4608. bool hadComparison = false;
  4609. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4610. {
  4611. BfFieldInstance* fieldInstance = &fieldRef;
  4612. if (fieldInstance->mDataOffset == -1)
  4613. continue;
  4614. if (fieldInstance->mResolvedType->IsValuelessType())
  4615. continue;
  4616. if (fieldInstance->mResolvedType->IsVar())
  4617. continue;
  4618. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4619. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4620. if (!fieldInstance->mResolvedType->IsComposite())
  4621. {
  4622. leftValue = LoadValue(leftValue);
  4623. rightValue = LoadValue(rightValue);
  4624. }
  4625. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4626. }
  4627. auto baseTypeInst = compareTypeInst->mBaseType;
  4628. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  4629. {
  4630. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  4631. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  4632. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4633. }
  4634. }
  4635. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4636. mBfIRBuilder->CreateBr(exitBB);
  4637. mBfIRBuilder->AddBlock(exitBB);
  4638. mBfIRBuilder->SetInsertPoint(exitBB);
  4639. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4640. ClearLifetimeEnds();
  4641. mBfIRBuilder->CreateRet(loadedResult);
  4642. mCurMethodState->mHadReturn = true;
  4643. }
  4644. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  4645. {
  4646. if (mBfIRBuilder->mIgnoreWrites)
  4647. return mBfIRBuilder->GetFakeVal();
  4648. PopulateType(typeInstance, mIsComptimeModule ? BfPopulateType_Data : BfPopulateType_DataAndMethods);
  4649. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4650. if (mIsComptimeModule)
  4651. {
  4652. auto idVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, typeInstance->mTypeId);
  4653. return mBfIRBuilder->CreateIntToPtr(idVal, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4654. }
  4655. BfIRValue* globalVariablePtr = NULL;
  4656. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  4657. int numElements = 1;
  4658. if (mSystem->mPtrSize == 4)
  4659. numElements++;
  4660. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  4661. {
  4662. numElements += mCompiler->mMaxInterfaceSlots;
  4663. auto maxIFaceVirtIdx = 0;
  4664. if (!typeInstance->IsInterface())
  4665. {
  4666. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4667. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4668. numElements += typeInstance->GetOrigVTableSize();
  4669. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  4670. if (typeInstance->mHotTypeData != NULL)
  4671. {
  4672. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4673. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4674. }
  4675. numElements += ifaceMethodLen;
  4676. }
  4677. if (outNumElements != NULL)
  4678. *outNumElements = numElements;
  4679. }
  4680. StringT<128> classVDataName;
  4681. String memberName = "sBfClassVData";
  4682. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  4683. {
  4684. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  4685. memberName += "_";
  4686. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  4687. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  4688. }
  4689. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  4690. if (outMangledName != NULL)
  4691. *outMangledName = classVDataName;
  4692. BfIRValue globalVariable;
  4693. if (globalVariablePtr != NULL)
  4694. {
  4695. globalVariable = *globalVariablePtr;
  4696. }
  4697. else
  4698. {
  4699. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4700. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4701. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4702. arrayType,
  4703. true,
  4704. BfIRLinkageType_External,
  4705. BfIRValue(),
  4706. classVDataName);
  4707. mClassVDataRefs[typeInstance] = globalVariable;
  4708. }
  4709. return globalVariable;
  4710. }
  4711. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4712. {
  4713. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4714. if (mIsComptimeModule)
  4715. return mBfIRBuilder->Comptime_GetBfType(typeInstance->mTypeId, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4716. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4717. }
  4718. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4719. {
  4720. if (mBfIRBuilder->mIgnoreWrites)
  4721. return mBfIRBuilder->GetFakeVal();
  4722. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4723. BF_ASSERT(numElements >= 0);
  4724. if (numElements <= 0)
  4725. return BfIRValue();
  4726. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4727. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4728. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4729. BF_ASSERT(declTypeInst == implTypeInst);
  4730. else
  4731. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4732. if (declTypeInst != implTypeInst)
  4733. {
  4734. BfTypeInstance* highestImpl = declTypeInst;
  4735. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4736. {
  4737. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4738. break; // Start of an ext entry for another type
  4739. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4740. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4741. highestImpl = checkImplTypeInst;
  4742. }
  4743. if (highestImpl != implTypeInst)
  4744. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4745. }
  4746. BfVDataExtEntry mapEntry;
  4747. mapEntry.mDeclTypeInst = declTypeInst;
  4748. mapEntry.mImplTypeInst = implTypeInst;
  4749. BfIRValue* irValuePtr = NULL;
  4750. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4751. return *irValuePtr;
  4752. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4753. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4754. StringT<512> classVDataName;
  4755. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4756. if (declTypeInst != implTypeInst)
  4757. {
  4758. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4759. }
  4760. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4761. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4762. SizedArray<BfIRValue, 32> vData;
  4763. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4764. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4765. {
  4766. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4767. break; // Start of an ext entry for another type
  4768. BfIRValue vValue;
  4769. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4770. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4771. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4772. {
  4773. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4774. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4775. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4776. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4777. {
  4778. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4779. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4780. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4781. vValue = funcPtr;
  4782. }
  4783. }
  4784. if (!vValue)
  4785. vValue = voidPtrNull;
  4786. vData.Add(vValue);
  4787. }
  4788. BF_ASSERT((int)vData.size() == numElements);
  4789. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4790. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4791. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4792. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4793. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4794. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, vData);
  4795. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4796. mClassVDataExtRefs[mapEntry] = globalVariable;
  4797. return globalVariable;
  4798. }
  4799. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  4800. {
  4801. if (mBfIRBuilder->mIgnoreWrites)
  4802. {
  4803. return mBfIRBuilder->CreateTypeOf(type);
  4804. }
  4805. if (mIsComptimeModule)
  4806. {
  4807. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4808. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4809. return mBfIRBuilder->Comptime_GetReflectType(type->mTypeId, mBfIRBuilder->MapType(typeTypeInst));
  4810. }
  4811. PopulateType(type);
  4812. BfIRValue globalVariable;
  4813. BfIRValue* globalVariablePtr = NULL;
  4814. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  4815. {
  4816. if (*globalVariablePtr)
  4817. return mBfIRBuilder->CreateTypeOf(type, *globalVariablePtr);
  4818. }
  4819. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4820. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4821. auto typeInstance = type->ToTypeInstance();
  4822. StringT<4096> typeDataName;
  4823. if (typeInstance != NULL)
  4824. {
  4825. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4826. }
  4827. else
  4828. {
  4829. typeDataName += "sBfTypeData.";
  4830. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  4831. }
  4832. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  4833. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  4834. mBfIRBuilder->SetReflectTypeData(mBfIRBuilder->MapType(type), globalVariable);
  4835. mTypeDataRefs[type] = globalVariable;
  4836. return mBfIRBuilder->CreateTypeOf(type, globalVariable);
  4837. }
  4838. void BfModule::EncodeAttributeData(BfTypeInstance* typeInstance, BfType* argType, BfIRValue arg, SizedArrayImpl<uint8>& data, Dictionary<int, int>& usedStringIdMap)
  4839. {
  4840. #define PUSH_INT8(val) data.push_back((uint8)val)
  4841. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4842. #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); }
  4843. #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); \
  4844. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4845. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4846. bool handled = false;
  4847. if (constant == NULL)
  4848. {
  4849. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  4850. return;
  4851. }
  4852. if (argType->IsObject())
  4853. {
  4854. if ((argType->IsInstanceOf(mCompiler->mStringTypeDef)) || (argType == mContext->mBfObjectType))
  4855. {
  4856. if (constant->mTypeCode == BfTypeCode_StringId)
  4857. {
  4858. int stringId = constant->mInt32;
  4859. int* orderedIdPtr;
  4860. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4861. {
  4862. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4863. }
  4864. GetStringObjectValue(stringId, true, true);
  4865. PUSH_INT8(0xFF); // String
  4866. PUSH_INT32(*orderedIdPtr);
  4867. return;
  4868. }
  4869. }
  4870. }
  4871. if (argType->IsPointer())
  4872. {
  4873. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  4874. {
  4875. if (constant->mTypeCode == BfTypeCode_StringId)
  4876. {
  4877. int stringId = constant->mInt32;
  4878. int* orderedIdPtr;
  4879. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4880. {
  4881. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4882. }
  4883. GetStringObjectValue(stringId, true, true);
  4884. PUSH_INT8(0xFF); // String
  4885. PUSH_INT32(*orderedIdPtr);
  4886. return;
  4887. }
  4888. }
  4889. }
  4890. if (constant->mConstType == BfConstType_BitCastNull)
  4891. {
  4892. PUSH_INT8(BfTypeCode_NullPtr);
  4893. return;
  4894. }
  4895. if (constant->mConstType == BfConstType_BitCast)
  4896. {
  4897. auto bitcast = (BfConstantBitCast*)constant;
  4898. EncodeAttributeData(typeInstance, argType, BfIRValue(BfIRValueFlags_Const, bitcast->mTarget), data, usedStringIdMap);
  4899. return;
  4900. }
  4901. PUSH_INT8(constant->mTypeCode);
  4902. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4903. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4904. (constant->mTypeCode == BfTypeCode_Double))
  4905. {
  4906. PUSH_INT64(constant->mInt64);
  4907. }
  4908. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4909. (constant->mTypeCode == BfTypeCode_UInt32) ||
  4910. (constant->mTypeCode == BfTypeCode_Char32))
  4911. {
  4912. PUSH_INT32(constant->mInt32);
  4913. }
  4914. else if (constant->mTypeCode == BfTypeCode_Float)
  4915. {
  4916. float val = (float)constant->mDouble;
  4917. PUSH_INT32(*(int*)&val);
  4918. }
  4919. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4920. (constant->mTypeCode == BfTypeCode_UInt16) ||
  4921. (constant->mTypeCode == BfTypeCode_Char16))
  4922. {
  4923. PUSH_INT16(constant->mInt16);
  4924. }
  4925. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4926. (constant->mTypeCode == BfTypeCode_UInt8) ||
  4927. (constant->mTypeCode == BfTypeCode_Boolean) ||
  4928. (constant->mTypeCode == BfTypeCode_Char8))
  4929. {
  4930. PUSH_INT8(constant->mInt8);
  4931. }
  4932. else if (constant->mConstType == BfConstType_TypeOf)
  4933. {
  4934. auto typeOf = (BfTypeOf_Const*)constant;
  4935. PUSH_INT32(typeOf->mType->mTypeId);
  4936. }
  4937. else if (constant->mConstType == BfConstType_AggZero)
  4938. {
  4939. for (int i = 0; i < argType->mSize; i++)
  4940. data.Add(0);
  4941. }
  4942. else if (constant->mConstType == BfConstType_Box)
  4943. {
  4944. auto box = (BfConstantBox*)constant;
  4945. PUSH_INT32(box->mToType.mId);
  4946. BfType* resultType = NULL;
  4947. if (box->mToType.mKind == BfIRTypeData::TypeKind_TypeId)
  4948. resultType = mContext->FindTypeById(box->mToType.mId);
  4949. if ((resultType != NULL) && (resultType->IsBoxed()))
  4950. {
  4951. auto boxedType = (BfBoxedType*)resultType;
  4952. int dataOffset = 0;
  4953. if (!boxedType->mFieldInstances.IsEmpty())
  4954. dataOffset = BF_MAX(boxedType->mFieldInstances.back().mDataOffset, 0);
  4955. int dataSize = boxedType->mInstSize - dataOffset;
  4956. for (int i = 0; i < dataSize; i++)
  4957. data.Add(0);
  4958. typeInstance->mConstHolder->WriteConstant(BfIRValue(BfIRValueFlags_Const, box->mTarget), &data[data.mSize - dataSize], boxedType->GetUnderlyingType());
  4959. return;
  4960. }
  4961. //int dataOffset =
  4962. //mBfIRBuilder->WriteConstant()
  4963. // BfType* resultType = NULL;
  4964. // if (box->mToType.mKind == BfIRTypeData::TypeKind_TypeId)
  4965. // resultType = mContext->FindTypeById(box->mToType.mId);
  4966. //
  4967. // if ((resultType != NULL) && (resultType->IsBoxed()))
  4968. // {
  4969. // auto boxedType = (BfBoxedType*)resultType;
  4970. // EncodeAttributeData(typeInstance, boxedType->GetUnderlyingType(), BfIRValue(BfIRValueFlags_Const, box->mTarget), data, usedStringIdMap);
  4971. // return;
  4972. // }
  4973. Fail(StrFormat("Unhandled constant box in '%s'", TypeToString(typeInstance).c_str()));
  4974. }
  4975. // else if (constant->mConstType == BfConstType_Agg)
  4976. // {
  4977. // BF_ASSERT(argType->IsComposite());
  4978. // if (argType->IsSizedArray())
  4979. // {
  4980. // auto argSizedArrayType = (BfSizedArrayType*)argType;
  4981. // }
  4982. // else
  4983. // {
  4984. // auto argTypeInstance = argType->ToTypeInstance();
  4985. // }
  4986. // }
  4987. else
  4988. {
  4989. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  4990. }
  4991. }
  4992. BfIRValue BfModule::CreateFieldData(BfFieldInstance* fieldInstance, int customAttrIdx)
  4993. {
  4994. bool isComptimeArg = mBfIRBuilder->mIgnoreWrites;
  4995. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4996. auto typeInstance = fieldInstance->mOwner;
  4997. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  4998. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4999. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5000. BfType* typeIdType = intType;
  5001. BfTypeInstance* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef)->ToTypeInstance();
  5002. BfIRValue emptyValueType = mBfIRBuilder->mIgnoreWrites ?
  5003. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>()) :
  5004. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>());
  5005. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, !mIsComptimeModule);
  5006. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  5007. int typeId = 0;
  5008. auto fieldType = fieldInstance->GetResolvedType();
  5009. if (fieldType->IsGenericParam())
  5010. {
  5011. //TODO:
  5012. }
  5013. else
  5014. typeId = fieldType->mTypeId;
  5015. BfFieldFlags fieldFlags = (BfFieldFlags)0;
  5016. if (fieldDef->mProtection == BfProtection_Protected)
  5017. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Protected);
  5018. if (fieldDef->mProtection == BfProtection_Public)
  5019. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Public);
  5020. if (fieldDef->mIsStatic)
  5021. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Static);
  5022. if (fieldDef->mIsConst)
  5023. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Const);
  5024. if (fieldDef->IsEnumCaseEntry())
  5025. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_EnumCase);
  5026. if (fieldDef->mIsReadOnly)
  5027. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_ReadOnly);
  5028. if (fieldInstance->IsAppendedObject())
  5029. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Appended);
  5030. BfIRValue constValue;
  5031. BfIRValue constValue2;
  5032. if (fieldInstance->mIsEnumPayloadCase)
  5033. {
  5034. int tagId = -fieldInstance->mDataIdx - 1;
  5035. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, tagId);
  5036. }
  5037. else if (fieldInstance->GetFieldDef()->mIsConst)
  5038. {
  5039. if (fieldInstance->mConstIdx != -1)
  5040. {
  5041. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  5042. uint64 val = constant->mUInt64;
  5043. if (constant->mTypeCode == BfTypeCode_Float)
  5044. {
  5045. float f = (float)*(double*)&val;
  5046. val = *(uint32*)&f;
  5047. }
  5048. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5049. if (is32Bit)
  5050. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val >> 32);
  5051. }
  5052. }
  5053. else if (fieldInstance->GetFieldDef()->mIsStatic)
  5054. {
  5055. BfTypedValue refVal;
  5056. if (mIsComptimeModule)
  5057. {
  5058. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mFieldIdx);
  5059. }
  5060. else
  5061. {
  5062. refVal = ReferenceStaticField(fieldInstance);
  5063. }
  5064. if (refVal.mValue.IsConst())
  5065. {
  5066. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  5067. if (constant->mConstType == BfConstType_GlobalVar)
  5068. {
  5069. auto globalVar = (BfGlobalVar*)constant;
  5070. if (globalVar->mName[0] == '#')
  5071. refVal = BfTypedValue();
  5072. }
  5073. }
  5074. if (!isComptimeArg)
  5075. {
  5076. if (refVal.IsAddr())
  5077. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5078. else if ((fieldInstance->IsAppendedObject()) && (refVal))
  5079. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5080. }
  5081. }
  5082. if (!constValue)
  5083. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  5084. BfIRValue result;
  5085. if (is32Bit)
  5086. {
  5087. if (!constValue2)
  5088. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  5089. SizedArray<BfIRValue, 8> fieldVals =
  5090. {
  5091. emptyValueType,
  5092. fieldNameConst, // mName
  5093. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5094. constValue, // mData
  5095. constValue2, // mDataHi
  5096. GetConstValue(fieldFlags, shortType), // mFlags
  5097. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5098. };
  5099. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5100. result = isComptimeArg ?
  5101. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5102. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5103. }
  5104. else
  5105. {
  5106. SizedArray<BfIRValue, 8> fieldVals =
  5107. {
  5108. emptyValueType,
  5109. fieldNameConst, // mName
  5110. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5111. constValue, // mData
  5112. GetConstValue(fieldFlags, shortType), // mFlags
  5113. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5114. };
  5115. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5116. result = isComptimeArg ?
  5117. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5118. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5119. }
  5120. return result;
  5121. }
  5122. void BfModule::CreateSlotOfs(BfTypeInstance* typeInstance)
  5123. {
  5124. int virtSlotIdx = -1;
  5125. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5126. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5127. // For interfaces we ONLY emit the slot num
  5128. StringT<512> slotVarName;
  5129. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  5130. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  5131. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  5132. GetConstValue32(virtSlotIdx), slotVarName);
  5133. }
  5134. BfIRValue BfModule::CreateTypeData(BfType* type, BfCreateTypeDataContext& ctx, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  5135. {
  5136. if ((IsHotCompile()) && (!type->mDirty))
  5137. return BfIRValue();
  5138. BfIRValue* irValuePtr = NULL;
  5139. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  5140. {
  5141. return *irValuePtr;
  5142. }
  5143. BfTypeInstance* typeInstance = type->ToTypeInstance();
  5144. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  5145. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  5146. if (typeInstanceType == NULL)
  5147. {
  5148. AssertErrorState();
  5149. return BfIRValue();
  5150. }
  5151. BfIRValue typeTypeData;
  5152. int typeFlags = 0;
  5153. if (needsTypeData)
  5154. {
  5155. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  5156. BfTypeInstance* typeDataSource = NULL;
  5157. if (typeInstance != NULL)
  5158. {
  5159. if (typeInstance->IsUnspecializedType())
  5160. {
  5161. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  5162. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  5163. }
  5164. else if (typeInstance->IsArray())
  5165. {
  5166. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  5167. typeFlags |= BfTypeFlags_Array;
  5168. }
  5169. else if (typeInstance->IsGenericTypeInstance())
  5170. {
  5171. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  5172. typeFlags |= BfTypeFlags_SpecializedGeneric;
  5173. }
  5174. else
  5175. typeDataSource = typeInstanceTypeInstance;
  5176. }
  5177. else if (type->IsPointer())
  5178. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5179. else if (type->IsRef())
  5180. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5181. else if (type->IsSizedArray())
  5182. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5183. else if (type->IsConstExprValue())
  5184. typeDataSource = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5185. else if (type->IsGenericParam())
  5186. {
  5187. typeFlags |= BfTypeFlags_GenericParam;
  5188. typeDataSource = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5189. }
  5190. else
  5191. typeDataSource = mContext->mBfTypeType;
  5192. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type) && (!mIsComptimeModule))
  5193. {
  5194. CreateTypeData(typeDataSource, ctx, false, true, needsTypeNames, true);
  5195. }
  5196. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  5197. ctx.mReflectTypeSet.Add(typeDataSource);
  5198. }
  5199. else
  5200. {
  5201. //typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  5202. typeTypeData = mBfIRBuilder->CreateConstNull();
  5203. }
  5204. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5205. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5206. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5207. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5208. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5209. BfType* typeIdType = intType;
  5210. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  5211. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  5212. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  5213. auto voidPtrNull = GetDefaultValue(voidPtrType);
  5214. SizedArray<BfIRValue, 4> typeValueParams;
  5215. GetConstClassValueParam(typeTypeData, typeValueParams);
  5216. FixConstValueParams(mContext->mBfObjectType, typeValueParams);
  5217. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5218. StringT<512> typeDataName;
  5219. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  5220. {
  5221. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  5222. if (typeInstance->mTypeDef->IsGlobalsContainer())
  5223. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  5224. }
  5225. else
  5226. {
  5227. typeDataName += "sBfTypeData.";
  5228. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  5229. }
  5230. int typeCode = BfTypeCode_None;
  5231. if (typeInstance != NULL)
  5232. {
  5233. BF_ASSERT((type->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || mIsComptimeModule);
  5234. typeCode = typeInstance->mTypeDef->mTypeCode;
  5235. if (typeInstance->IsBoxed())
  5236. typeCode = BfTypeCode_Object;
  5237. }
  5238. else if (type->IsPrimitiveType())
  5239. {
  5240. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  5241. typeCode = primType->mTypeDef->mTypeCode;
  5242. }
  5243. else if (type->IsPointer())
  5244. {
  5245. typeCode = BfTypeCode_Pointer;
  5246. typeFlags |= BfTypeFlags_Pointer;
  5247. }
  5248. else if (type->IsRef())
  5249. {
  5250. typeCode = BfTypeCode_Pointer;
  5251. typeFlags |= BfTypeFlags_Pointer;
  5252. }
  5253. if (type->IsObject())
  5254. {
  5255. typeFlags |= BfTypeFlags_Object;
  5256. if (typeInstance->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted)
  5257. {
  5258. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  5259. if ((methodInstance != NULL) && (methodInstance->GetOwner() != mContext->mBfObjectType))
  5260. typeFlags |= BfTypeFlags_HasDestructor;
  5261. }
  5262. }
  5263. if (type->IsStruct())
  5264. typeFlags |= BfTypeFlags_Struct;
  5265. if (type->IsInterface())
  5266. typeFlags |= BfTypeFlags_Interface;
  5267. if (type->IsBoxed())
  5268. {
  5269. typeFlags |= BfTypeFlags_Boxed;
  5270. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  5271. typeFlags |= BfTypeFlags_Pointer;
  5272. }
  5273. if (type->IsPrimitiveType())
  5274. typeFlags |= BfTypeFlags_Primitive;
  5275. if (type->IsTypedPrimitive())
  5276. typeFlags |= BfTypeFlags_TypedPrimitive;
  5277. if (type->IsTuple())
  5278. typeFlags |= BfTypeFlags_Tuple;
  5279. if (type->IsNullable())
  5280. typeFlags |= BfTypeFlags_Nullable;
  5281. if (type->IsSizedArray())
  5282. typeFlags |= BfTypeFlags_SizedArray;
  5283. if (type->IsConstExprValue())
  5284. typeFlags |= BfTypeFlags_ConstExpr;
  5285. if (type->IsSplattable())
  5286. typeFlags |= BfTypeFlags_Splattable;
  5287. if (type->IsUnion())
  5288. typeFlags |= BfTypeFlags_Union;
  5289. if (type->IsDelegate())
  5290. typeFlags |= BfTypeFlags_Delegate;
  5291. if (type->IsFunction())
  5292. typeFlags |= BfTypeFlags_Function;
  5293. if ((type->mDefineState != BfTypeDefineState_CETypeInit) && (type->WantsGCMarking()))
  5294. typeFlags |= BfTypeFlags_WantsMarking;
  5295. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsStatic))
  5296. typeFlags |= BfTypeFlags_Static;
  5297. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  5298. typeFlags |= BfTypeFlags_Abstract;
  5299. int virtSlotIdx = -1;
  5300. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5301. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5302. int memberDataOffset = 0;
  5303. if (type->IsInterface())
  5304. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  5305. else if (typeInstance != NULL)
  5306. {
  5307. for (auto& fieldInstance : typeInstance->mFieldInstances)
  5308. {
  5309. if (fieldInstance.mDataOffset != -1)
  5310. {
  5311. memberDataOffset = fieldInstance.mDataOffset;
  5312. break;
  5313. }
  5314. }
  5315. }
  5316. int boxedTypeId = 0;
  5317. if ((type->IsValueType()) || (type->IsWrappableType()))
  5318. {
  5319. auto boxedType = CreateBoxedType(type, false);
  5320. if ((boxedType != NULL) && (boxedType->mIsReified))
  5321. boxedTypeId = boxedType->mTypeId;
  5322. }
  5323. int stackCount = 0;
  5324. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  5325. {
  5326. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5327. if (typeOptions->mAllocStackTraceDepth != -1)
  5328. stackCount = BF_MIN(0xFF, BF_MAX(0x01, typeOptions->mAllocStackTraceDepth));
  5329. }
  5330. SizedArray<BfIRValue, 9> typeDataParams =
  5331. {
  5332. objectData,
  5333. GetConstValue(type->mSize, intType), // mSize
  5334. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5335. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  5336. GetConstValue(typeFlags, intType), // mTypeFlags
  5337. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  5338. GetConstValue(typeCode, byteType), // mTypeCode
  5339. GetConstValue(type->mAlign, byteType), // mAlign
  5340. GetConstValue(stackCount, byteType), // mAllocStackCountOverride
  5341. };
  5342. FixConstValueParams(mContext->mBfTypeType, typeDataParams);
  5343. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  5344. if (typeInstance == NULL)
  5345. {
  5346. BfIRValue typeDataVar;
  5347. if (needsTypeData)
  5348. {
  5349. if (type->IsPointer())
  5350. {
  5351. auto pointerType = (BfPointerType*)type;
  5352. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  5353. {
  5354. typeData,
  5355. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  5356. };
  5357. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5358. FixConstValueParams(reflectPointerType, pointerTypeDataParms);
  5359. auto pointerTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  5360. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  5361. BfIRLinkageType_External, pointerTypeData, typeDataName);
  5362. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5363. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5364. }
  5365. else if (type->IsRef())
  5366. {
  5367. auto refType = (BfRefType*)type;
  5368. SizedArray<BfIRValue, 3> refTypeDataParms =
  5369. {
  5370. typeData,
  5371. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  5372. GetConstValue((int8)refType->mRefKind, byteType),
  5373. };
  5374. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5375. FixConstValueParams(reflectRefType, refTypeDataParms);
  5376. auto refTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  5377. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  5378. BfIRLinkageType_External, refTypeData, typeDataName);
  5379. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5380. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5381. }
  5382. else if (type->IsSizedArray())
  5383. {
  5384. auto sizedArrayType = (BfSizedArrayType*)type;
  5385. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  5386. {
  5387. typeData,
  5388. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  5389. GetConstValue(sizedArrayType->mElementCount, intType)
  5390. };
  5391. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5392. FixConstValueParams(reflectSizedArrayType, sizedArrayTypeDataParms);
  5393. auto sizedArrayTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  5394. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  5395. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  5396. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5397. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5398. }
  5399. else if (type->IsConstExprValue())
  5400. {
  5401. auto constExprType = (BfConstExprValueType*)type;
  5402. SizedArray<BfIRValue, 3> constExprTypeDataParms =
  5403. {
  5404. typeData,
  5405. GetConstValue(constExprType->mType->mTypeId, typeIdType),
  5406. GetConstValue(constExprType->mValue.mInt64, longType)
  5407. };
  5408. auto reflectConstExprType = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5409. FixConstValueParams(reflectConstExprType, constExprTypeDataParms);
  5410. auto ConstExprTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectConstExprType, BfIRPopulateType_Full), constExprTypeDataParms);
  5411. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectConstExprType), true,
  5412. BfIRLinkageType_External, ConstExprTypeData, typeDataName);
  5413. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5414. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5415. }
  5416. else if (type->IsGenericParam())
  5417. {
  5418. auto genericParamType = (BfGenericParamType*)type;
  5419. SizedArray<BfIRValue, 3> genericParamTypeDataParms =
  5420. {
  5421. typeData
  5422. };
  5423. auto reflectGenericParamType = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5424. FixConstValueParams(reflectGenericParamType, genericParamTypeDataParms);
  5425. auto genericParamTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectGenericParamType, BfIRPopulateType_Full), genericParamTypeDataParms);
  5426. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectGenericParamType), true,
  5427. BfIRLinkageType_External, genericParamTypeData, typeDataName);
  5428. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5429. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5430. }
  5431. else
  5432. {
  5433. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  5434. BfIRLinkageType_External, typeData, typeDataName);
  5435. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5436. }
  5437. }
  5438. else
  5439. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5440. mTypeDataRefs[type] = typeDataVar;
  5441. return typeDataVar;
  5442. }
  5443. // Reserve position
  5444. mTypeDataRefs[typeInstance] = BfIRValue();
  5445. if ((typeInstance->IsReified()) && (!mIsComptimeModule))
  5446. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5447. BfTypeDef* typeDef = typeInstance->mTypeDef;
  5448. StringT<512> mangledName;
  5449. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  5450. if (!mIsComptimeModule)
  5451. {
  5452. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5453. {
  5454. auto methodDef = typeDef->mMethods[methodIdx];
  5455. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  5456. if (methodInstance == NULL)
  5457. continue;
  5458. if (typeInstance->IsUnspecializedType())
  5459. continue;
  5460. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5461. {
  5462. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  5463. {
  5464. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  5465. // We need to create an empty thunk for this chained method
  5466. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  5467. mBfIRBuilder->SetActiveFunction(func);
  5468. auto block = mBfIRBuilder->CreateBlock("entry", true);
  5469. mBfIRBuilder->SetInsertPoint(block);
  5470. mBfIRBuilder->CreateRetVoid();
  5471. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  5472. }
  5473. }
  5474. }
  5475. }
  5476. SizedArray<BfIRValue, 32> vData;
  5477. BfIRValue classVDataVar;
  5478. String classVDataName;
  5479. if (typeInstance->mSlotNum >= 0)
  5480. {
  5481. CreateSlotOfs(typeInstance);
  5482. }
  5483. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  5484. {
  5485. int dynCastDataElems = 0;
  5486. int numElements = 1;
  5487. int vDataOfs = mCompiler->GetVDataPrefixDataCount(); // The number of intptrs before the iface slot map
  5488. numElements += mCompiler->mMaxInterfaceSlots;
  5489. if (!typeInstance->IsInterface())
  5490. {
  5491. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  5492. numElements += mCompiler->GetDynCastVDataCount();
  5493. numElements += typeInstance->mVirtualMethodTableSize;
  5494. }
  5495. int expectNumElements = 0;
  5496. if (!typeDef->mIsStatic)
  5497. {
  5498. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  5499. }
  5500. for (int i = 0; i < mCompiler->GetVDataPrefixDataCount(); i++)
  5501. vData.push_back(BfIRValue()); // Type
  5502. SizedArray<BfIRValue, 1> extVTableData;
  5503. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  5504. if (!typeInstance->IsInterface())
  5505. {
  5506. Array<int32> dynCastData;
  5507. if (typeInstance->IsBoxed())
  5508. {
  5509. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  5510. dynCastData.Add(underlyingType->mInheritanceId);
  5511. }
  5512. else
  5513. dynCastData.Add(typeInstance->mInheritanceId);
  5514. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  5515. dynCastData.Add(0);
  5516. dynCastData.Add(0);
  5517. auto checkTypeInst = typeInstance;
  5518. while (checkTypeInst != NULL)
  5519. {
  5520. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5521. {
  5522. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  5523. {
  5524. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  5525. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  5526. }
  5527. }
  5528. checkTypeInst = checkTypeInst->GetImplBaseType();
  5529. }
  5530. if (mSystem->mPtrSize == 8)
  5531. {
  5532. int intPtrCount = (dynCastDataElems + 1) / 2;
  5533. vDataOfs += intPtrCount;
  5534. uint64* intPtrData = (uint64*)&dynCastData[0];
  5535. for (int i = 0; i < intPtrCount; i++)
  5536. {
  5537. uint64 val = intPtrData[i];
  5538. if (val == 0)
  5539. {
  5540. vData.push_back(voidPtrNull);
  5541. }
  5542. else
  5543. {
  5544. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5545. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5546. }
  5547. }
  5548. }
  5549. else
  5550. {
  5551. int intPtrCount = dynCastDataElems;
  5552. vDataOfs += intPtrCount;
  5553. uint32* intPtrData = (uint32*)&dynCastData[0];
  5554. for (int i = 0; i < intPtrCount; i++)
  5555. {
  5556. uint32 val = intPtrData[i];
  5557. if (val == 0)
  5558. {
  5559. vData.push_back(voidPtrNull);
  5560. }
  5561. else
  5562. {
  5563. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  5564. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5565. }
  5566. }
  5567. }
  5568. }
  5569. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  5570. vData.push_back(voidPtrNull);
  5571. struct _InterfaceMatchEntry
  5572. {
  5573. BfTypeInterfaceEntry* mEntry;
  5574. BfTypeInstance* mEntrySource;
  5575. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  5576. };
  5577. int highestIFaceVirtIdx = 0;
  5578. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  5579. auto checkTypeInst = typeInstance;
  5580. bool forceInterfaceSet = false;
  5581. while (checkTypeInst != NULL)
  5582. {
  5583. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5584. {
  5585. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  5586. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject)))
  5587. continue;
  5588. _InterfaceMatchEntry* matchEntry = NULL;
  5589. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  5590. {
  5591. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  5592. if (compareCheckTypeInst->IsBoxed())
  5593. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  5594. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  5595. if (compareEntrySource->IsBoxed())
  5596. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  5597. auto prevEntry = matchEntry->mEntry;
  5598. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  5599. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  5600. if ((!isBetter) && (!isWorse))
  5601. {
  5602. // Unboxed comparison to Object fix
  5603. if (compareCheckTypeInst == mContext->mBfObjectType)
  5604. isWorse = true;
  5605. else if (compareEntrySource == mContext->mBfObjectType)
  5606. isBetter = true;
  5607. }
  5608. if (forceInterfaceSet)
  5609. {
  5610. isBetter = true;
  5611. isWorse = false;
  5612. }
  5613. if (isBetter == isWorse)
  5614. CompareDeclTypes(checkTypeInst, interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  5615. if (isBetter == isWorse)
  5616. {
  5617. if (matchEntry->mAmbiguousEntries.empty())
  5618. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  5619. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  5620. continue;
  5621. }
  5622. else if (isBetter)
  5623. {
  5624. matchEntry->mEntry = &interfaceEntry;
  5625. matchEntry->mEntrySource = checkTypeInst;
  5626. matchEntry->mAmbiguousEntries.Clear();
  5627. }
  5628. else
  5629. continue;
  5630. }
  5631. else
  5632. {
  5633. _InterfaceMatchEntry matchEntry;
  5634. matchEntry.mEntry = &interfaceEntry;
  5635. matchEntry.mEntrySource = checkTypeInst;
  5636. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  5637. }
  5638. }
  5639. checkTypeInst = checkTypeInst->GetImplBaseType();
  5640. }
  5641. for (auto interfacePair : interfaceMap)
  5642. {
  5643. auto& interfaceMatchEntry = interfacePair.mValue;
  5644. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  5645. {
  5646. 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());
  5647. if (error != NULL)
  5648. {
  5649. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  5650. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  5651. }
  5652. }
  5653. }
  5654. if ((!mIsComptimeModule) && (!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  5655. {
  5656. int startTabIdx = (int)vData.size();
  5657. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  5658. BfTypeInstance* checkTypeInst = typeInstance;
  5659. while (checkTypeInst != NULL)
  5660. {
  5661. origVirtTypeStack.push_back(checkTypeInst);
  5662. checkTypeInst = checkTypeInst->GetImplBaseType();
  5663. }
  5664. Array<BfVirtualMethodEntry> origVTable;
  5665. int origVirtIdx = 0;
  5666. if (typeInstance->mTypeDef->mIsCombinedPartial)
  5667. {
  5668. HashSet<String> reslotNames;
  5669. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5670. {
  5671. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5672. if (entry.mDeclaringMethod.mMethodNum == -1)
  5673. continue;
  5674. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5675. if ((methodInstance == NULL) ||
  5676. ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))))
  5677. {
  5678. if (origVTable.empty())
  5679. origVTable = typeInstance->mVirtualMethodTable;
  5680. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  5681. if (declMethodInstance != NULL)
  5682. {
  5683. if ((mIsComptimeModule) || (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject)))
  5684. {
  5685. // Prepare to reslot...
  5686. entry.mImplementingMethod = entry.mDeclaringMethod;
  5687. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  5688. }
  5689. else
  5690. {
  5691. // Decl isn't accessible, null out entry
  5692. entry.mImplementingMethod = BfMethodRef();
  5693. }
  5694. }
  5695. }
  5696. }
  5697. if (!reslotNames.IsEmpty())
  5698. {
  5699. BfAmbiguityContext ambiguityContext;
  5700. ambiguityContext.mTypeInstance = typeInstance;
  5701. ambiguityContext.mModule = this;
  5702. ambiguityContext.mIsProjectSpecific = true;
  5703. ambiguityContext.mIsReslotting = true;
  5704. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5705. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  5706. {
  5707. auto methodInstance = methodGroup.mDefault;
  5708. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  5709. continue;
  5710. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  5711. continue;
  5712. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  5713. continue;
  5714. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  5715. continue;
  5716. SlotVirtualMethod(methodInstance, &ambiguityContext);
  5717. }
  5718. ambiguityContext.Finish();
  5719. }
  5720. }
  5721. bool isInExts = false;
  5722. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5723. {
  5724. BfIRValue vValue = voidPtrNull;
  5725. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5726. BfModuleMethodInstance moduleMethodInst;
  5727. if (entry.mDeclaringMethod.mMethodNum == -1)
  5728. {
  5729. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  5730. isInExts = true;
  5731. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  5732. if (vExt)
  5733. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  5734. }
  5735. else
  5736. {
  5737. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  5738. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  5739. {
  5740. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  5741. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  5742. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5743. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5744. {
  5745. BF_ASSERT((mIsComptimeModule) || typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  5746. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5747. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5748. vValue = funcPtr;
  5749. }
  5750. }
  5751. }
  5752. while (origVirtTypeStack.size() != 0)
  5753. {
  5754. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  5755. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  5756. {
  5757. // Moved past current base vtable size
  5758. origVirtTypeStack.pop_back();
  5759. continue;
  5760. }
  5761. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  5762. {
  5763. // We are within the original vtable size
  5764. int idx = startTabIdx + origVirtIdx;
  5765. origVirtIdx++;
  5766. vData.push_back(vValue);
  5767. }
  5768. else
  5769. {
  5770. // This is a new entry, it only gets added to the ext
  5771. BF_ASSERT(isInExts);
  5772. }
  5773. break;
  5774. }
  5775. }
  5776. if (!origVTable.empty())
  5777. typeInstance->mVirtualMethodTable = origVTable;
  5778. }
  5779. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  5780. if (typeInstance->mHotTypeData != NULL)
  5781. {
  5782. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  5783. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  5784. }
  5785. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  5786. int iFaceMethodStartIdx = (int)vData.size();
  5787. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  5788. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  5789. vData[i] = voidPtrNull;
  5790. if (expectNumElements != 0)
  5791. BF_ASSERT(expectNumElements == vData.size());
  5792. //BF_ASSERT(vData.size() == expectNumElements);
  5793. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  5794. // ifaceMethodExtData.Add(voidPtrNull);
  5795. int ifaceEntryIdx = iFaceMethodStartIdx;
  5796. for (auto& interfacePair : interfaceMap)
  5797. {
  5798. auto interfaceEntry = interfacePair.mValue.mEntry;
  5799. if (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  5800. {
  5801. BF_ASSERT(mIsComptimeModule);
  5802. break;
  5803. }
  5804. bool makeEmpty = false;
  5805. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject)))
  5806. makeEmpty = true;
  5807. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5808. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  5809. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5810. {
  5811. BfIRValue pushValue;
  5812. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5813. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5814. continue;
  5815. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5816. continue;
  5817. if (makeEmpty)
  5818. {
  5819. pushValue = voidPtrNull;
  5820. }
  5821. else
  5822. {
  5823. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5824. auto methodInstance = (BfMethodInstance*)methodRef;
  5825. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5826. {
  5827. BF_ASSERT(methodInstance->mIsReified);
  5828. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5829. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5830. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5831. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5832. pushValue = funcPtr;
  5833. }
  5834. else
  5835. {
  5836. pushValue = voidPtrNull;
  5837. }
  5838. }
  5839. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5840. if (idx < ifaceMethodExtStart)
  5841. {
  5842. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  5843. vData[iFaceMethodStartIdx + idx] = pushValue;
  5844. }
  5845. else
  5846. {
  5847. BF_ASSERT(useExt);
  5848. int extIdx = idx - ifaceMethodExtStart;
  5849. while (extIdx >= ifaceMethodExtData.size())
  5850. ifaceMethodExtData.Add(voidPtrNull);
  5851. ifaceMethodExtData[extIdx] = pushValue;
  5852. }
  5853. }
  5854. }
  5855. if (typeInstance->IsBoxed())
  5856. {
  5857. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  5858. if (boxedType->IsBoxedStructPtr())
  5859. {
  5860. // Force override of GetHashCode so we use the pointer address as the hash code
  5861. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  5862. // Force override of GetHashCode so we use the pointer address as the hash code
  5863. for (auto& checkIFace : checkTypeInst->mInterfaces)
  5864. {
  5865. if (checkIFace.mStartVirtualIdx < 0)
  5866. continue;
  5867. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5868. {
  5869. BfIRValue pushValue;
  5870. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5871. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5872. continue;
  5873. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5874. continue;
  5875. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5876. auto methodInstance = (BfMethodInstance*)methodRef;
  5877. BF_ASSERT(methodInstance->mIsReified);
  5878. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5879. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5880. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5881. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5882. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5883. vData[iFaceMethodStartIdx + idx] = funcPtr;
  5884. }
  5885. }
  5886. }
  5887. }
  5888. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic) && (!mIsComptimeModule))
  5889. {
  5890. BfIRValue ifaceMethodExtVar;
  5891. if ((!ifaceMethodExtData.IsEmpty()) && (!mIsComptimeModule))
  5892. {
  5893. StringT<512> classVDataName;
  5894. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  5895. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  5896. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  5897. BfIRLinkageType_External, BfIRValue(), classVDataName);
  5898. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  5899. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, ifaceMethodExtData);
  5900. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  5901. }
  5902. for (auto& ifaceInstPair : interfaceMap)
  5903. {
  5904. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  5905. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  5906. if (slotNum >= 0)
  5907. {
  5908. BfIRValue vtablePtr;
  5909. int idx = interfaceEntry->mStartVirtualIdx;
  5910. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5911. if ((endVirtualIdx > ifaceMethodExtStart) && (ifaceMethodExtVar))
  5912. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  5913. else
  5914. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  5915. int slotVirtIdx = slotNum + vDataOfs;
  5916. if (vData[slotVirtIdx] == voidPtrNull)
  5917. {
  5918. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  5919. }
  5920. else
  5921. {
  5922. if (mCompiler->IsHotCompile())
  5923. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  5924. else
  5925. Fail("Interface slot collision error", typeDef->GetRefNode());
  5926. }
  5927. }
  5928. }
  5929. }
  5930. }
  5931. BfIRValue typeNameConst;
  5932. BfIRValue namespaceConst;
  5933. if (needsTypeNames)
  5934. {
  5935. typeNameConst = GetStringObjectValue(typeDef->mName->mString, !mIsComptimeModule);
  5936. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), !mIsComptimeModule);
  5937. }
  5938. else
  5939. {
  5940. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  5941. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5942. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5943. }
  5944. int baseTypeId = 0;
  5945. if (typeInstance->mBaseType != NULL)
  5946. {
  5947. baseTypeId = typeInstance->mBaseType->mTypeId;
  5948. }
  5949. BfTypeOptions* typeOptions = NULL;
  5950. if (typeInstance->mTypeOptionsIdx >= 0)
  5951. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5952. SizedArray<BfIRValue, 16> customAttrs;
  5953. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  5954. BfIRValue castedClassVData;
  5955. if (classVDataVar)
  5956. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  5957. else
  5958. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  5959. bool freflectIncludeTypeData = false;
  5960. bool reflectIncludeAllFields = false;
  5961. bool reflectIncludeAllMethods = false;
  5962. if (TypeIsSubTypeOf(typeInstance, attributeType))
  5963. {
  5964. reflectIncludeAllFields = true;
  5965. reflectIncludeAllMethods = true;
  5966. }
  5967. BfReflectKind reflectKind = BfReflectKind_Type;
  5968. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  5969. {
  5970. BfReflectKind reflectKind = BfReflectKind_None;
  5971. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  5972. if (customAttrs != NULL)
  5973. {
  5974. for (auto& attr : customAttrs->mAttributes)
  5975. {
  5976. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  5977. }
  5978. delete customAttrs;
  5979. }
  5980. return reflectKind;
  5981. };
  5982. reflectKind = GetReflectKind(reflectKind, typeInstance);
  5983. // Fields
  5984. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  5985. BfIRValue emptyValueType = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  5986. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  5987. {
  5988. if (customAttributes == NULL)
  5989. return -1;
  5990. Array<BfCustomAttribute*> reflectAttributes;
  5991. for (auto& attr : customAttributes->mAttributes)
  5992. {
  5993. bool wantAttribute = false;
  5994. if (attr.mType->mCustomAttributes != NULL)
  5995. {
  5996. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  5997. if (usageAttribute != NULL)
  5998. {
  5999. // Check for Flags arg
  6000. if (usageAttribute->mCtorArgs.size() < 2)
  6001. continue;
  6002. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  6003. if (constant == NULL)
  6004. continue;
  6005. if (constant->mTypeCode == BfTypeCode_Boolean)
  6006. continue;
  6007. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  6008. wantAttribute = true;
  6009. }
  6010. }
  6011. if ((wantAttribute) && (attr.mType->mIsReified))
  6012. {
  6013. reflectAttributes.Add(&attr);
  6014. }
  6015. }
  6016. if (reflectAttributes.size() == 0)
  6017. return -1;
  6018. #define PUSH_INT8(val) data.push_back((uint8)val)
  6019. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  6020. #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); }
  6021. SizedArray<uint8, 16> data;
  6022. int customAttrIdx = (int)customAttrs.size();
  6023. data.push_back((uint8)reflectAttributes.size());
  6024. for (auto attr : reflectAttributes)
  6025. {
  6026. // Size prefix
  6027. int sizeIdx = (int)data.size();
  6028. PUSH_INT16(0); // mSize
  6029. PUSH_INT32(attr->mType->mTypeId); // mType
  6030. int ctorIdx = -1;
  6031. int ctorCount = 0;
  6032. attr->mType->mTypeDef->PopulateMemberSets();
  6033. BfMemberSetEntry* entry;
  6034. if (attr->mType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  6035. {
  6036. BfMethodDef* nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6037. while (nextMethodDef != NULL)
  6038. {
  6039. if (nextMethodDef == attr->mCtor)
  6040. ctorIdx = ctorCount;
  6041. nextMethodDef = nextMethodDef->mNextWithSameName;
  6042. ctorCount++;
  6043. }
  6044. }
  6045. BF_ASSERT(ctorIdx != -1);
  6046. if (ctorIdx != -1)
  6047. ctorIdx = (ctorCount - 1) - ctorIdx;
  6048. PUSH_INT16(ctorIdx);
  6049. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  6050. int argIdx = 0;
  6051. for (auto arg : attr->mCtorArgs)
  6052. {
  6053. auto argType = ctorMethodInstance->GetParamType(argIdx);
  6054. EncodeAttributeData(typeInstance, argType, arg, data, ctx.mUsedStringIdMap);
  6055. argIdx++;
  6056. }
  6057. int size = (int)data.size() - sizeIdx;
  6058. *((uint16*)&data[sizeIdx]) = size;
  6059. }
  6060. #undef PUSH_INT8
  6061. #undef PUSH_INT16
  6062. #undef PUSH_INT32
  6063. SizedArray<BfIRValue, 16> dataValues;
  6064. for (uint8 val : data)
  6065. dataValues.push_back(GetConstValue8(val));
  6066. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  6067. auto customAttrConst = mBfIRBuilder->CreateConstAgg_Value(dataArrayType, dataValues);
  6068. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  6069. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  6070. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  6071. customAttrs.push_back(customAttrArrayPtr);
  6072. return customAttrIdx;
  6073. };
  6074. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  6075. SizedArray<int, 16> reflectFieldIndices;
  6076. for (int pass = 0; pass < 2; pass++)
  6077. {
  6078. bool skippedField = false;
  6079. reflectFieldIndices.clear();
  6080. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  6081. {
  6082. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6083. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  6084. if (fieldDef == NULL)
  6085. continue;
  6086. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6087. bool includeField = reflectIncludeAllFields;
  6088. if (fieldInstance->mCustomAttributes != NULL)
  6089. {
  6090. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  6091. {
  6092. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6093. {
  6094. includeField = true;
  6095. }
  6096. else
  6097. {
  6098. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6099. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  6100. }
  6101. }
  6102. }
  6103. if ((fieldReflectKind & BfReflectKind_User) != 0)
  6104. includeField = true;
  6105. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  6106. includeField = true;
  6107. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  6108. includeField = true;
  6109. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  6110. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  6111. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  6112. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  6113. includeField |= forceReflectFields;
  6114. if (!includeField)
  6115. {
  6116. skippedField = true;
  6117. continue;
  6118. }
  6119. reflectFieldIndices.Add(fieldIdx);
  6120. }
  6121. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  6122. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  6123. // possible because we write out a SplatData structure containing just TypeIds in that case
  6124. if (pass == 0)
  6125. {
  6126. if (!typeInstance->IsSplattable())
  6127. break;
  6128. if (!skippedField)
  6129. break;
  6130. if (reflectFieldIndices.size() == 0)
  6131. break;
  6132. }
  6133. }
  6134. SizedArray<BfIRValue, 16> fieldTypes;
  6135. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  6136. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  6137. {
  6138. BfType* payloadType = typeInstance->GetUnionInnerType();
  6139. if (!payloadType->IsValuelessType())
  6140. {
  6141. BfIRValue payloadNameConst = GetStringObjectValue("$payload", !mIsComptimeModule);
  6142. SizedArray<BfIRValue, 8> payloadFieldVals;
  6143. if (is32Bit)
  6144. {
  6145. payloadFieldVals =
  6146. {
  6147. emptyValueType,
  6148. payloadNameConst, // mName
  6149. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6150. GetConstValue(0, intPtrType), // mData
  6151. GetConstValue(0, intPtrType), // mDataHi
  6152. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6153. GetConstValue(-1, intType), // mCustomAttributesIdx
  6154. };
  6155. }
  6156. else
  6157. {
  6158. payloadFieldVals =
  6159. {
  6160. emptyValueType,
  6161. payloadNameConst, // mName
  6162. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6163. GetConstValue(0, intPtrType), // mData
  6164. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6165. GetConstValue(-1, intType), // mCustomAttributesIdx
  6166. };
  6167. }
  6168. FixConstValueParams(reflectFieldDataType->ToTypeInstance(), payloadFieldVals);
  6169. auto payloadFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  6170. fieldTypes.push_back(payloadFieldData);
  6171. }
  6172. BfType* dscrType = typeInstance->GetDiscriminatorType();
  6173. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", !mIsComptimeModule);
  6174. SizedArray<BfIRValue, 8> dscrFieldVals;
  6175. if (is32Bit)
  6176. {
  6177. dscrFieldVals =
  6178. {
  6179. emptyValueType,
  6180. dscrNameConst, // mName
  6181. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6182. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6183. GetConstValue(0, intPtrType), // mDataHi
  6184. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6185. GetConstValue(-1, intType), // mCustomAttributesIdx
  6186. };
  6187. }
  6188. else
  6189. {
  6190. dscrFieldVals =
  6191. {
  6192. emptyValueType,
  6193. dscrNameConst, // mName
  6194. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6195. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6196. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6197. GetConstValue(-1, intType), // mCustomAttributesIdx
  6198. };
  6199. }
  6200. auto dscrFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  6201. fieldTypes.push_back(dscrFieldData);
  6202. }
  6203. for (auto fieldIdx : reflectFieldIndices)
  6204. {
  6205. if (!needsTypeData)
  6206. break;
  6207. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6208. fieldTypes.push_back(CreateFieldData(fieldInstance, _HandleCustomAttrs(fieldInstance->mCustomAttributes)));
  6209. }
  6210. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  6211. BfIRValue fieldDataPtr;
  6212. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  6213. if (fieldTypes.size() == 0)
  6214. {
  6215. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  6216. {
  6217. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  6218. SizedArray<BfIRValue, 3> splatTypes;
  6219. SizedArray<BfIRValue, 3> splatOffsets;
  6220. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  6221. {
  6222. auto checkTypeInstance = checkType->ToTypeInstance();
  6223. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  6224. PopulateType(checkTypeInstance);
  6225. if (checkType->IsStruct())
  6226. {
  6227. int dataEnd = offset;
  6228. if (checkTypeInstance->mBaseType != NULL)
  6229. _CheckSplat(checkTypeInstance->mBaseType, offset);
  6230. if (checkTypeInstance->mIsUnion)
  6231. {
  6232. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  6233. _CheckSplat(unionInnerType, offset);
  6234. }
  6235. else
  6236. {
  6237. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  6238. {
  6239. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  6240. if (fieldInstance->mDataIdx >= 0)
  6241. {
  6242. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  6243. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  6244. }
  6245. }
  6246. }
  6247. if (checkTypeInstance->IsEnum())
  6248. {
  6249. // Add discriminator
  6250. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  6251. if (checkTypeInstance->mPacking > 0)
  6252. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  6253. _CheckSplat(dscrType, dataEnd);
  6254. }
  6255. }
  6256. else if (checkType->IsMethodRef())
  6257. {
  6258. // auto methodRefType = (BfMethodRefType*)checkType;
  6259. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6260. // {
  6261. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6262. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  6263. // else
  6264. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  6265. // }
  6266. }
  6267. else if (!checkType->IsValuelessType())
  6268. {
  6269. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  6270. splatOffsets.Add(GetConstValue(offset, intType));
  6271. }
  6272. };
  6273. _CheckSplat(type, 0);
  6274. while (splatTypes.size() < 3)
  6275. {
  6276. splatTypes.Add(GetConstValue(0, typeIdType));
  6277. splatOffsets.Add(GetConstValue(0, intType));
  6278. }
  6279. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  6280. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  6281. SizedArray<BfIRValue, 8> splatVals =
  6282. {
  6283. emptyValueType,
  6284. splatTypesConst,
  6285. splatOffsetsConst
  6286. };
  6287. auto fieldSplatData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  6288. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  6289. fieldSplatData, typeDataName + ".splats");
  6290. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6291. }
  6292. else
  6293. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  6294. }
  6295. else
  6296. {
  6297. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  6298. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstAgg_Value(fieldDataConstType, fieldTypes);
  6299. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  6300. fieldDataConst, "fields." + typeDataName);
  6301. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6302. }
  6303. /// Methods
  6304. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  6305. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  6306. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  6307. struct _SortedMethodInfo
  6308. {
  6309. BfMethodDef* mMethodDef;
  6310. BfMethodCustomAttributes* mMethodCustomAttributes;
  6311. };
  6312. Array<_SortedMethodInfo> sortedMethodList;
  6313. SizedArray<BfIRValue, 16> methodTypes;
  6314. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  6315. {
  6316. if (!needsTypeData)
  6317. break;
  6318. // Disable const method reflection info for now
  6319. if (mIsComptimeModule)
  6320. break;
  6321. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6322. if (!methodInstanceGroup->IsImplemented())
  6323. continue;
  6324. auto methodDef = typeDef->mMethods[methodIdx];
  6325. if (methodDef->mIsNoReflect)
  6326. continue;
  6327. if (methodDef->mHasComptime)
  6328. continue;
  6329. auto defaultMethod = methodInstanceGroup->mDefault;
  6330. if (defaultMethod == NULL)
  6331. continue;
  6332. if (defaultMethod->mIsUnspecialized)
  6333. continue;
  6334. if (!defaultMethod->mIsReified)
  6335. continue;
  6336. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  6337. continue;
  6338. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  6339. continue;
  6340. if (!defaultMethod->mMethodDef->CanReflect())
  6341. continue;
  6342. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6343. bool includeMethod = reflectIncludeAllMethods;
  6344. if (typeInstance->IsDelegateOrFunction())
  6345. includeMethod = true;
  6346. BfMethodCustomAttributes* methodCustomAttributes = NULL;
  6347. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  6348. {
  6349. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes;
  6350. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  6351. {
  6352. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6353. {
  6354. includeMethod = true;
  6355. }
  6356. else
  6357. {
  6358. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6359. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  6360. }
  6361. }
  6362. }
  6363. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject)))
  6364. continue;
  6365. //
  6366. {
  6367. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  6368. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  6369. {
  6370. BfTypeState typeState;
  6371. typeState.mPrevState = mContext->mCurTypeState;
  6372. typeState.mForceActiveTypeDef = methodDef->mDeclaringType;
  6373. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  6374. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  6375. {
  6376. if (paramDecl->mAttributes != NULL)
  6377. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  6378. }
  6379. }
  6380. }
  6381. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  6382. includeMethod = true;
  6383. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  6384. includeMethod = true;
  6385. if ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend))
  6386. {
  6387. if ((methodReflectKind & BfReflectKind_Constructors) != 0)
  6388. includeMethod = true;
  6389. if ((methodDef->IsDefaultCtor()) && ((methodReflectKind & BfReflectKind_DefaultConstructor) != 0))
  6390. includeMethod = true;
  6391. }
  6392. if ((!includeMethod) && (typeOptions != NULL))
  6393. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  6394. if (!includeMethod)
  6395. continue;
  6396. sortedMethodList.Add({ methodDef, methodCustomAttributes });
  6397. }
  6398. auto _GetMethodKind = [](BfMethodDef* methodDef)
  6399. {
  6400. if (methodDef->mMethodType == BfMethodType_Ctor)
  6401. return 0;
  6402. return 1;
  6403. };
  6404. std::sort(sortedMethodList.begin(), sortedMethodList.end(), [_GetMethodKind](const _SortedMethodInfo& lhs, const _SortedMethodInfo& rhs)
  6405. {
  6406. int lhsKind = _GetMethodKind(lhs.mMethodDef);
  6407. int rhsKind = _GetMethodKind(rhs.mMethodDef);
  6408. if (lhsKind != rhsKind)
  6409. return lhsKind < rhsKind;
  6410. if (lhs.mMethodDef->mName != rhs.mMethodDef->mName)
  6411. return lhs.mMethodDef->mName < rhs.mMethodDef->mName;
  6412. return lhs.mMethodDef->mIdx < rhs.mMethodDef->mIdx;
  6413. });
  6414. for (auto& methodInfo : sortedMethodList)
  6415. {
  6416. auto methodDef = methodInfo.mMethodDef;
  6417. int methodIdx = methodDef->mIdx;
  6418. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6419. auto defaultMethod = methodInstanceGroup->mDefault;
  6420. BfModuleMethodInstance moduleMethodInstance;
  6421. BfIRValue funcVal = voidPtrNull;
  6422. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  6423. (!typeInstance->IsUnspecializedType()) &&
  6424. (methodDef->mMethodType != BfMethodType_Ignore) &&
  6425. (methodDef->mMethodType != BfMethodType_Mixin) &&
  6426. (!methodDef->mIsAbstract) &&
  6427. (methodDef->mGenericParams.size() == 0))
  6428. {
  6429. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6430. if (moduleMethodInstance.mFunc)
  6431. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6432. }
  6433. BfIRValue methodNameConst = GetStringObjectValue(methodDef->GetReflectName(), !mIsComptimeModule);
  6434. BfMethodFlags methodFlags = defaultMethod->GetMethodFlags();
  6435. int customAttrIdx = -1;
  6436. int returnCustomAttrIdx = -1;
  6437. if (methodInfo.mMethodCustomAttributes != NULL)
  6438. {
  6439. customAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mCustomAttributes);
  6440. returnCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mReturnCustomAttributes);
  6441. }
  6442. enum ParamFlags
  6443. {
  6444. ParamFlag_None = 0,
  6445. ParamFlag_Splat = 1,
  6446. ParamFlag_Implicit = 2,
  6447. ParamFlag_AppendIdx = 4,
  6448. ParamFlag_Params = 8
  6449. };
  6450. SizedArray<BfIRValue, 8> paramVals;
  6451. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  6452. {
  6453. String paramName = defaultMethod->GetParamName(paramIdx);
  6454. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  6455. ParamFlags paramFlags = ParamFlag_None;
  6456. if (defaultMethod->GetParamIsSplat(paramIdx))
  6457. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  6458. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  6459. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Implicit | ParamFlag_AppendIdx);
  6460. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_Params)
  6461. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Params);
  6462. BfIRValue paramNameConst = GetStringObjectValue(paramName, !mIsComptimeModule);
  6463. int paramCustomAttrIdx = -1;
  6464. if ((methodInfo.mMethodCustomAttributes != NULL) && (paramIdx < (int)methodInfo.mMethodCustomAttributes->mParamCustomAttributes.mSize))
  6465. paramCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mParamCustomAttributes[paramIdx]);
  6466. SizedArray<BfIRValue, 8> paramDataVals =
  6467. {
  6468. emptyValueType,
  6469. paramNameConst,
  6470. GetConstValue(paramType->mTypeId, typeIdType),
  6471. GetConstValue((int32)paramFlags, shortType),
  6472. GetConstValue(-1, intType), // defaultIdx
  6473. GetConstValue(paramCustomAttrIdx, intType) // customAttrIdx
  6474. };
  6475. auto paramData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  6476. paramVals.Add(paramData);
  6477. }
  6478. BfIRValue paramsVal;
  6479. if (paramVals.size() > 0)
  6480. {
  6481. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  6482. BfIRValue paramDataConst = mBfIRBuilder->CreateConstAgg_Value(paramDataArrayType, paramVals);
  6483. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  6484. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  6485. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  6486. }
  6487. else
  6488. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  6489. int vDataVal = -1;
  6490. if (defaultMethod->mVirtualTableIdx != -1)
  6491. {
  6492. int vDataIdx = -1;
  6493. if (type->IsInterface())
  6494. {
  6495. vDataIdx = defaultMethod->mVirtualTableIdx;
  6496. }
  6497. else
  6498. {
  6499. vDataIdx = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  6500. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  6501. {
  6502. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  6503. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6504. if (extMethodIdx >= 0)
  6505. {
  6506. // Extension?
  6507. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6508. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  6509. }
  6510. else
  6511. {
  6512. // Map this new virtual index back to the original index
  6513. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  6514. }
  6515. }
  6516. else
  6517. {
  6518. vDataIdx += defaultMethod->mVirtualTableIdx;
  6519. }
  6520. }
  6521. if (vDataVal == -1)
  6522. vDataVal = vDataIdx * mSystem->mPtrSize;
  6523. }
  6524. SizedArray<BfIRValue, 8> methodDataVals =
  6525. {
  6526. emptyValueType,
  6527. methodNameConst, // mName
  6528. funcVal, // mFuncPtr
  6529. paramsVal,
  6530. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  6531. GetConstValue((int)paramVals.size(), shortType),
  6532. GetConstValue(methodFlags, shortType),
  6533. GetConstValue(methodIdx, intType),
  6534. GetConstValue(vDataVal, intType),
  6535. GetConstValue(customAttrIdx, intType),
  6536. GetConstValue(returnCustomAttrIdx, intType),
  6537. };
  6538. auto methodData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  6539. methodTypes.push_back(methodData);
  6540. }
  6541. BfIRValue methodDataPtr;
  6542. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  6543. if (methodTypes.size() == 0)
  6544. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  6545. else
  6546. {
  6547. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  6548. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methodTypes);
  6549. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6550. methodDataConst, "methods." + typeDataName);
  6551. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  6552. }
  6553. /////
  6554. int interfaceCount = 0;
  6555. BfIRValue interfaceDataPtr;
  6556. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  6557. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  6558. Array<bool> wantsIfaceMethod;
  6559. bool wantsIfaceMethods = false;
  6560. if ((typeInstance->mInterfaces.IsEmpty()) || (!needsTypeData))
  6561. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  6562. else
  6563. {
  6564. SizedArray<BfIRValue, 16> interfaces;
  6565. for (auto& interface : typeInstance->mInterfaces)
  6566. {
  6567. SizedArray<BfIRValue, 8> interfaceDataVals =
  6568. {
  6569. emptyValueType,
  6570. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  6571. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  6572. GetConstValue(interface.mStartVirtualIdx, intType),
  6573. };
  6574. auto interfaceData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  6575. interfaces.push_back(interfaceData);
  6576. if (!mIsComptimeModule)
  6577. {
  6578. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6579. {
  6580. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  6581. if (ifaceMethodGroup->mExplicitlyReflected)
  6582. {
  6583. wantsIfaceMethods = true;
  6584. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  6585. while (tableIdx >= wantsIfaceMethod.size())
  6586. wantsIfaceMethod.Add(false);
  6587. wantsIfaceMethod[tableIdx] = true;
  6588. }
  6589. }
  6590. }
  6591. }
  6592. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  6593. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstAgg_Value(interfaceDataArrayType, interfaces);
  6594. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  6595. interfaceDataConst, "interfaces." + typeDataName);
  6596. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  6597. interfaceCount = (int)interfaces.size();
  6598. }
  6599. BfIRValue interfaceMethodTable;
  6600. int ifaceMethodTableSize = 0;
  6601. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  6602. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  6603. {
  6604. SizedArray<BfIRValue, 16> methods;
  6605. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  6606. {
  6607. BfIRValue funcVal = voidPtrNull;
  6608. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  6609. {
  6610. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  6611. if (!methodEntry.mMethodRef.IsNull())
  6612. {
  6613. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  6614. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  6615. (!methodInstance->mMethodDef->mIsAbstract))
  6616. {
  6617. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  6618. if (moduleMethodInstance.mFunc)
  6619. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6620. }
  6621. }
  6622. }
  6623. methods.Add(funcVal);
  6624. }
  6625. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  6626. methods.pop_back();
  6627. if (!methods.IsEmpty())
  6628. {
  6629. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  6630. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methods);
  6631. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6632. methodDataConst, "imethods." + typeDataName);
  6633. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  6634. ifaceMethodTableSize = (int)methods.size();
  6635. }
  6636. }
  6637. if (!interfaceMethodTable)
  6638. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6639. /////
  6640. int underlyingType = 0;
  6641. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  6642. {
  6643. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  6644. }
  6645. int outerTypeId = 0;
  6646. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  6647. if (outerType != NULL)
  6648. {
  6649. outerTypeId = outerType->mTypeId;
  6650. }
  6651. //
  6652. BfIRValue customAttrDataPtr;
  6653. if (customAttrs.size() > 0)
  6654. {
  6655. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  6656. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstAgg_Value(customAttrsArrayType, customAttrs);
  6657. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  6658. customAttrsConst, "customAttrs." + typeDataName);
  6659. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  6660. }
  6661. else
  6662. {
  6663. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6664. }
  6665. SizedArray<BfIRValue, 32> typeDataVals =
  6666. {
  6667. typeData,
  6668. castedClassVData, // mTypeClassVData
  6669. typeNameConst, // mName
  6670. namespaceConst, // mNamespace
  6671. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  6672. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  6673. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  6674. GetConstValue(baseTypeId, typeIdType), // mBaseType
  6675. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  6676. GetConstValue(outerTypeId, typeIdType), // mOuterType
  6677. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  6678. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  6679. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  6680. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  6681. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  6682. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  6683. GetConstValue(0, shortType), // mPropertyDataCount
  6684. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  6685. interfaceDataPtr, // mInterfaceDataPtr
  6686. interfaceMethodTable, // mInterfaceMethodTable
  6687. methodDataPtr, // mMethodDataPtr
  6688. voidPtrNull, // mPropertyDataPtr
  6689. fieldDataPtr, // mFieldDataPtr
  6690. customAttrDataPtr, // mCustomAttrDataPtr
  6691. };
  6692. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  6693. FixConstValueParams(typeInstanceType->ToTypeInstance(), typeDataVals);
  6694. auto typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, typeDataVals);
  6695. if (!needsTypeData)
  6696. {
  6697. // No need for anything beyond typeInstanceData
  6698. }
  6699. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  6700. {
  6701. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6702. SizedArray<BfIRValue, 4> unspecializedData =
  6703. {
  6704. typeInstanceData,
  6705. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  6706. };
  6707. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  6708. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6709. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, unspecializedData);
  6710. }
  6711. else if (typeInstance->IsGenericTypeInstance())
  6712. {
  6713. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6714. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  6715. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef->GetDefinition());
  6716. SizedArray<BfIRValue, 4> resolvedTypes;
  6717. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  6718. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  6719. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  6720. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  6721. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  6722. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstAgg_Value(genericArrayType, resolvedTypes);
  6723. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  6724. resolvedTypesConst, "resolvedTypes." + typeDataName);
  6725. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  6726. SizedArray<BfIRValue, 3> specGenericData =
  6727. {
  6728. typeInstanceData,
  6729. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  6730. resovledTypesPtr, // mFieldDataPtr
  6731. };
  6732. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6733. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, specGenericData);
  6734. if (typeInstance->IsArray())
  6735. {
  6736. auto arrayType = (BfArrayType*)typeInstance;
  6737. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  6738. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  6739. SizedArray<BfIRValue, 4> arrayData =
  6740. {
  6741. typeInstanceData,
  6742. GetConstValue(elementType->mSize, intType), // mElementSize
  6743. GetConstValue(1, byteType), // mRank
  6744. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  6745. };
  6746. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  6747. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  6748. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, arrayData);
  6749. }
  6750. }
  6751. BfIRValue typeDataVar;
  6752. if (needsTypeData)
  6753. {
  6754. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  6755. BfIRLinkageType_External, typeInstanceData, typeDataName);
  6756. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  6757. if (mBfIRBuilder->DbgHasInfo())
  6758. {
  6759. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  6760. }
  6761. }
  6762. else
  6763. {
  6764. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  6765. }
  6766. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  6767. mTypeDataRefs[typeInstance] = typeDataVar;
  6768. if ((!mIsComptimeModule) && (classVDataVar))
  6769. {
  6770. BF_ASSERT(!classVDataName.IsEmpty());
  6771. //vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  6772. int unboxedTypeId = type->mTypeId;
  6773. if (type->IsBoxed())
  6774. unboxedTypeId = type->GetUnderlyingType()->mTypeId;
  6775. if (mSystem->mPtrSize == 4)
  6776. {
  6777. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(type->mTypeId, intPtrType), voidPtrIRType);
  6778. vData[1] = mBfIRBuilder->CreateIntToPtr(GetConstValue(unboxedTypeId, intPtrType), voidPtrIRType);
  6779. }
  6780. else
  6781. {
  6782. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(((int64)unboxedTypeId << 32) | type->mTypeId, intPtrType), voidPtrIRType);
  6783. }
  6784. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  6785. auto classVDataConstData = mBfIRBuilder->CreateConstAgg_Value(classVDataConstDataType, vData);
  6786. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  6787. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6788. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  6789. else
  6790. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  6791. if (mBfIRBuilder->DbgHasInfo())
  6792. {
  6793. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6794. BfType* voidPtrType = CreatePointerType(voidType);
  6795. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6796. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  6797. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  6798. }
  6799. }
  6800. return typeDataVar;
  6801. }
  6802. BfIRValue BfModule::FixClassVData(BfIRValue value)
  6803. {
  6804. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  6805. return value;
  6806. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  6807. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  6808. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  6809. }
  6810. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  6811. {
  6812. // Note: this is not just for perf, it fixes a field var-type resolution issue
  6813. if (mBfIRBuilder->mIgnoreWrites)
  6814. return;
  6815. if (mIsComptimeModule)
  6816. return;
  6817. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  6818. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  6819. // When we access classes with static constructors FROM a static constructor,
  6820. // we call that other class's static constructor first. Recursion cannot occur, since
  6821. // we simply ignore subsequent attempts to re-enter the constructor
  6822. if (!typeInstance->mHasStaticInitMethod)
  6823. return;
  6824. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  6825. return;
  6826. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  6827. return;
  6828. auto checkTypeDef = typeInstance->mTypeDef;
  6829. checkTypeDef->PopulateMemberSets();
  6830. BfMethodDef* nextMethodDef = NULL;
  6831. BfMemberSetEntry* entry;
  6832. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  6833. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6834. while (nextMethodDef != NULL)
  6835. {
  6836. auto checkMethod = nextMethodDef;
  6837. nextMethodDef = nextMethodDef->mNextWithSameName;
  6838. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  6839. if (methodModule)
  6840. {
  6841. auto methodInstance = methodModule.mMethodInstance;
  6842. if ((methodInstance != NULL) &&
  6843. (methodInstance->mMethodDef->mIsStatic) &&
  6844. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  6845. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  6846. {
  6847. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  6848. break;
  6849. }
  6850. }
  6851. }
  6852. }
  6853. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  6854. {
  6855. auto methodOwner = methodInstance->GetOwner();
  6856. auto methodDef = methodInstance->mMethodDef;
  6857. auto methodDeclaration = methodDef->GetMethodDeclaration();
  6858. if (!methodDef->mIsExtern)
  6859. return BfIRFunction();
  6860. if (methodInstance->GetCustomAttributes() == NULL)
  6861. return BfIRFunction();
  6862. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  6863. {
  6864. String typeName = TypeToString(customAttribute.mType);
  6865. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  6866. {
  6867. methodInstance->mIsIntrinsic = true;
  6868. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  6869. String error;
  6870. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  6871. {
  6872. int stringId = constant->mInt32;
  6873. auto entry = mContext->mStringObjectIdMap[stringId];
  6874. String intrinName = entry.mString;
  6875. // if (intrinName.StartsWith(":"))
  6876. // {
  6877. // SizedArray<BfIRType, 2> paramTypes;
  6878. // for (auto& param : methodInstance->mParams)
  6879. // paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6880. // return mBfIRBuilder->GetIntrinsic(intrinName.Substring(1), mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6881. // }
  6882. // else
  6883. {
  6884. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  6885. if (intrinId != -1)
  6886. {
  6887. if (intrinId == BfIRIntrinsic_Malloc)
  6888. {
  6889. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6890. }
  6891. else if (intrinId == BfIRIntrinsic_Free)
  6892. {
  6893. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  6894. }
  6895. SizedArray<BfIRType, 2> paramTypes;
  6896. for (auto& param : methodInstance->mParams)
  6897. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6898. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6899. }
  6900. else if (reportFailure)
  6901. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  6902. }
  6903. }
  6904. else if (reportFailure)
  6905. error = "Intrinsic name must be a constant string";
  6906. if (reportFailure)
  6907. {
  6908. Fail(error, customAttribute.mRef);
  6909. }
  6910. }
  6911. }
  6912. return BfIRFunction();
  6913. }
  6914. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  6915. {
  6916. if (mBfIRBuilder->mIgnoreWrites)
  6917. return mBfIRBuilder->GetFakeFunction();
  6918. if (!mBuiltInFuncs[(int)funcTypeId])
  6919. {
  6920. SizedArray<BfIRType, 4> paramTypes;
  6921. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  6922. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6923. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  6924. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6925. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  6926. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  6927. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  6928. BfIRFunctionType funcType;
  6929. BfIRFunction func;
  6930. switch (funcTypeId)
  6931. {
  6932. case BfBuiltInFuncType_PrintF:
  6933. paramTypes.Add(nullPtrType);
  6934. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  6935. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  6936. break;
  6937. case BfBuiltInFuncType_Malloc:
  6938. {
  6939. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6940. {
  6941. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  6942. }
  6943. else
  6944. {
  6945. String funcName = mCompiler->mOptions.mMallocLinkName;
  6946. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  6947. funcName = "malloc";
  6948. func = mBfIRBuilder->GetFunction(funcName);
  6949. if (!func)
  6950. {
  6951. paramTypes.clear();
  6952. paramTypes.push_back(intType);
  6953. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  6954. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6955. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  6956. }
  6957. }
  6958. }
  6959. break;
  6960. case BfBuiltInFuncType_Free:
  6961. {
  6962. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6963. {
  6964. func = GetInternalMethod("Dbg_RawFree").mFunc;
  6965. }
  6966. else
  6967. {
  6968. String funcName = mCompiler->mOptions.mFreeLinkName;
  6969. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  6970. funcName = "free";
  6971. func = mBfIRBuilder->GetFunction(funcName);
  6972. if (!func)
  6973. {
  6974. paramTypes.clear();
  6975. paramTypes.push_back(nullPtrType);
  6976. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  6977. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6978. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  6979. }
  6980. }
  6981. }
  6982. break;
  6983. case BfBuiltInFuncType_LoadSharedLibraries:
  6984. paramTypes.clear();
  6985. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  6986. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  6987. break;
  6988. default: break;
  6989. }
  6990. mBuiltInFuncs[(int)funcTypeId] = func;
  6991. return func;
  6992. }
  6993. return mBuiltInFuncs[(int)funcTypeId];
  6994. }
  6995. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized, Array<BfTypeReference*>* deferredResolveTypes)
  6996. {
  6997. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  6998. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  6999. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  7000. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  7001. BfAutoComplete* bfAutocomplete = NULL;
  7002. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  7003. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  7004. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  7005. {
  7006. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  7007. {
  7008. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  7009. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  7010. {
  7011. String filter = nameNode->ToString();
  7012. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  7013. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  7014. if (nameIdx != 0)
  7015. {
  7016. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  7017. }
  7018. }
  7019. }
  7020. }
  7021. for (auto constraint : constraintDef->mConstraints)
  7022. {
  7023. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  7024. {
  7025. BfGenericOperatorConstraintInstance opConstraintInstance;
  7026. if (opConstraint->mLeftType != NULL)
  7027. {
  7028. if (bfAutocomplete != NULL)
  7029. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  7030. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces_All);
  7031. if (opConstraintInstance.mLeftType == NULL)
  7032. continue;
  7033. }
  7034. if (opConstraint->mRightType == NULL)
  7035. {
  7036. // We had a failure in parsing
  7037. continue;
  7038. }
  7039. if (opConstraint->mRightType != NULL)
  7040. {
  7041. if (bfAutocomplete != NULL)
  7042. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  7043. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces_All);
  7044. if (opConstraintInstance.mRightType == NULL)
  7045. continue;
  7046. }
  7047. if (opConstraint->mOpToken == NULL)
  7048. {
  7049. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  7050. continue;
  7051. }
  7052. if (opConstraint->mLeftType != NULL)
  7053. {
  7054. if (opConstraint->mRightType == NULL)
  7055. {
  7056. // Parse should have failed
  7057. continue;
  7058. }
  7059. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  7060. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  7061. {
  7062. Fail("Invalid binary operator", opConstraint->mOpToken);
  7063. continue;
  7064. }
  7065. }
  7066. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  7067. {
  7068. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  7069. }
  7070. else
  7071. {
  7072. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  7073. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  7074. {
  7075. Fail("Invalid unary operator", opConstraint->mOpToken);
  7076. continue;
  7077. }
  7078. }
  7079. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  7080. continue;
  7081. }
  7082. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  7083. if (bfAutocomplete != NULL)
  7084. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  7085. //TODO: Constraints may refer to other generic params (of either type or method)
  7086. // TO allow resolution, perhaps move this generic param initialization into GetMethodInstance (passing a genericPass bool)
  7087. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_AllowGenericMethodParamConstValue;
  7088. if (isUnspecialized)
  7089. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_DisallowComptime);
  7090. // We we have a deferredResolveTypes then we defer the generic validation, because we may have a case like
  7091. // `where T : Dictionay<TElem, int> and TElem : IHashable` and we don't want to throw the error on `T` before we build `TElem`
  7092. BfType* constraintType;
  7093. if (constraintTypeRef->IsA<BfVarTypeReference>())
  7094. constraintType = GetPrimitiveType(BfTypeCode_Var);
  7095. else
  7096. constraintType = ResolveTypeRef(constraintTypeRef, (deferredResolveTypes != NULL) ? BfPopulateType_Identity : BfPopulateType_Declaration, resolveFlags);
  7097. if (constraintType != NULL)
  7098. {
  7099. if (deferredResolveTypes != NULL)
  7100. {
  7101. PopulateType(constraintType, BfPopulateType_Declaration);
  7102. if (constraintType->IsUnspecializedTypeVariation())
  7103. deferredResolveTypes->Add(constraintTypeRef);
  7104. }
  7105. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7106. {
  7107. bool isValidTypeCode = false;
  7108. BfTypeCode typeCode = BfTypeCode_None;
  7109. if (constraintType->IsTypedPrimitive())
  7110. {
  7111. auto underlyingType = constraintType->GetUnderlyingType();
  7112. if (underlyingType->IsPrimitiveType())
  7113. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  7114. }
  7115. if (constraintType->IsPrimitiveType())
  7116. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  7117. if (constraintType->IsInstanceOf(mCompiler->mStringTypeDef))
  7118. isValidTypeCode = true;
  7119. if (constraintType->IsValueType())
  7120. isValidTypeCode = true;
  7121. if (constraintType->IsVar())
  7122. isValidTypeCode = true;
  7123. switch (typeCode)
  7124. {
  7125. case BfTypeCode_StringId:
  7126. case BfTypeCode_Boolean:
  7127. case BfTypeCode_Int8:
  7128. case BfTypeCode_UInt8:
  7129. case BfTypeCode_Int16:
  7130. case BfTypeCode_UInt16:
  7131. case BfTypeCode_Int32:
  7132. case BfTypeCode_UInt32:
  7133. case BfTypeCode_Int64:
  7134. case BfTypeCode_UInt64:
  7135. case BfTypeCode_IntPtr:
  7136. case BfTypeCode_UIntPtr:
  7137. case BfTypeCode_IntUnknown:
  7138. case BfTypeCode_UIntUnknown:
  7139. case BfTypeCode_Float:
  7140. case BfTypeCode_Double:
  7141. case BfTypeCode_Char8:
  7142. case BfTypeCode_Char16:
  7143. case BfTypeCode_Char32:
  7144. isValidTypeCode = true;
  7145. break;
  7146. default: break;
  7147. }
  7148. if (isValidTypeCode)
  7149. {
  7150. genericParamInstance->mTypeConstraint = constraintType;
  7151. }
  7152. else
  7153. {
  7154. Fail("Const constraint must be a valuetype or string", constraintTypeRef);
  7155. }
  7156. }
  7157. else
  7158. {
  7159. bool checkEquality = false;
  7160. if (constraintType->IsVar())
  7161. {
  7162. // From a `comptype` generic undef resolution. Ignore.
  7163. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_ComptypeExpr);
  7164. genericParamInstance->mComptypeConstraint.Add(constraintTypeRef);
  7165. continue;
  7166. }
  7167. else if (constraintType->IsPrimitiveType())
  7168. {
  7169. checkEquality = true;
  7170. }
  7171. if (constraintType->IsArray())
  7172. {
  7173. if (isUnspecialized)
  7174. {
  7175. 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);
  7176. continue;
  7177. }
  7178. checkEquality = true;
  7179. }
  7180. if (constraintType->IsGenericParam())
  7181. {
  7182. checkEquality = true;
  7183. }
  7184. else if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  7185. {
  7186. checkEquality = true;
  7187. }
  7188. if (checkEquality)
  7189. {
  7190. genericParamInstance->mTypeConstraint = constraintType;
  7191. }
  7192. else if (constraintType->IsInterface())
  7193. {
  7194. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  7195. }
  7196. else
  7197. {
  7198. auto constraintTypeInst = constraintType->ToTypeInstance();
  7199. if (genericParamInstance->mTypeConstraint != NULL)
  7200. {
  7201. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  7202. {
  7203. // Allow more specific type
  7204. genericParamInstance->mTypeConstraint = constraintTypeInst;
  7205. }
  7206. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  7207. {
  7208. // Silently ignore less-specific type
  7209. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  7210. {
  7211. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  7212. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Class);
  7213. }
  7214. }
  7215. else
  7216. {
  7217. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  7218. return;
  7219. }
  7220. }
  7221. else
  7222. genericParamInstance->mTypeConstraint = constraintType;
  7223. }
  7224. }
  7225. }
  7226. }
  7227. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  7228. (genericParamInstance->mTypeConstraint == NULL))
  7229. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  7230. }
  7231. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  7232. {
  7233. if (genericParamSource.mMethodInstance != NULL)
  7234. {
  7235. //auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  7236. //SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  7237. return MethodToString(genericParamSource.mMethodInstance);
  7238. }
  7239. else
  7240. {
  7241. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  7242. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  7243. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  7244. return TypeToString(typeInst);
  7245. }
  7246. }
  7247. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  7248. {
  7249. Array<String> methodParamNameOverrides;
  7250. auto _TypeToString = [&](BfType* type)
  7251. {
  7252. if (genericParamSource.mMethodInstance != NULL)
  7253. {
  7254. if (methodParamNameOverrides.IsEmpty())
  7255. {
  7256. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  7257. methodParamNameOverrides.Add(genericParam->mName);
  7258. }
  7259. return TypeToString(type, &methodParamNameOverrides);
  7260. }
  7261. return TypeToString(type);
  7262. };
  7263. bool ignoreErrors = (errorOut == NULL) ||
  7264. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  7265. BfType* origCheckArgType = checkArgType;
  7266. if (origCheckArgType->IsRef())
  7267. origCheckArgType = origCheckArgType->GetUnderlyingType();
  7268. bool argIsReferenceType = false;
  7269. int checkGenericParamFlags = 0;
  7270. if (checkArgType->IsGenericParam())
  7271. {
  7272. BfGenericParamInstance* checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  7273. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  7274. if (checkGenericParamInst->mTypeConstraint != NULL)
  7275. checkArgType = checkGenericParamInst->mTypeConstraint;
  7276. if (checkGenericParamInst->mGenericParamFlags & BfGenericParamFlag_Var)
  7277. checkArgType = GetPrimitiveType(BfTypeCode_Var);
  7278. // if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  7279. // {
  7280. // argMayBeReferenceType = false;
  7281. // }
  7282. // else
  7283. // {
  7284. // argMayBeReferenceType = true;
  7285. // }
  7286. }
  7287. if (checkArgType->IsObjectOrInterface())
  7288. argIsReferenceType = true;
  7289. BfTypeInstance* typeConstraintInst = NULL;
  7290. if (genericParamInst->mTypeConstraint != NULL)
  7291. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  7292. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  7293. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  7294. {
  7295. if ((!ignoreErrors) && (PreFail()))
  7296. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  7297. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7298. return false;
  7299. }
  7300. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  7301. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  7302. {
  7303. if ((!ignoreErrors) && (PreFail()))
  7304. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  7305. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7306. return false;
  7307. }
  7308. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  7309. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argIsReferenceType))
  7310. {
  7311. if ((!ignoreErrors) && (PreFail()))
  7312. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  7313. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7314. return false;
  7315. }
  7316. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum)
  7317. {
  7318. bool isEnum = checkArgType->IsEnum();
  7319. if ((origCheckArgType->IsGenericParam()) && (checkArgType->IsInstanceOf(mCompiler->mEnumTypeDef)))
  7320. isEnum = true;
  7321. if (((checkGenericParamFlags & (BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!isEnum))
  7322. {
  7323. if ((!ignoreErrors) && (PreFail()))
  7324. *errorOut = Fail(StrFormat("The type '%s' must be an enum type in order to use it as parameter '%s' for '%s'",
  7325. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7326. return false;
  7327. }
  7328. }
  7329. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) &&
  7330. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (checkArgType->IsInterface()))
  7331. {
  7332. if ((!ignoreErrors) && (PreFail()))
  7333. *errorOut = Fail(StrFormat("The type '%s' must be an concrete type in order to use it as parameter '%s' for '%s'",
  7334. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7335. return false;
  7336. }
  7337. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Interface) &&
  7338. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsInterface()))
  7339. {
  7340. if ((!ignoreErrors) && (PreFail()))
  7341. *errorOut = Fail(StrFormat("The type '%s' must be an interface type in order to use it as parameter '%s' for '%s'",
  7342. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7343. return false;
  7344. }
  7345. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7346. {
  7347. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  7348. {
  7349. if ((!ignoreErrors) && (PreFail()))
  7350. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  7351. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7352. return false;
  7353. }
  7354. }
  7355. else
  7356. {
  7357. if (checkArgType->IsConstExprValue())
  7358. {
  7359. if ((!ignoreErrors) && (PreFail()))
  7360. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  7361. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7362. return false;
  7363. }
  7364. }
  7365. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  7366. {
  7367. bool canDelete = false;
  7368. if (checkArgType->IsPointer())
  7369. canDelete = true;
  7370. else if (checkArgType->IsObjectOrInterface())
  7371. canDelete = true;
  7372. else if ((checkGenericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var)) != 0)
  7373. canDelete = true;
  7374. if (!canDelete)
  7375. {
  7376. if ((!ignoreErrors) && (PreFail()))
  7377. {
  7378. if (checkArgType->IsGenericParam())
  7379. *errorOut = Fail(StrFormat("Must add 'where %s : delete' constraint in order to use type as parameter '%s' for '%s'",
  7380. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7381. else
  7382. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  7383. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7384. }
  7385. return false;
  7386. }
  7387. }
  7388. if (checkArgType->IsPointer())
  7389. {
  7390. auto ptrType = (BfPointerType*)checkArgType;
  7391. checkArgType = ptrType->mElementType;
  7392. }
  7393. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  7394. {
  7395. bool canAlloc = false;
  7396. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  7397. {
  7398. if (checkTypeInst->IsObjectOrStruct())
  7399. {
  7400. checkTypeInst->mTypeDef->PopulateMemberSets();
  7401. BfMemberSetEntry* entry = NULL;
  7402. BfMethodDef* checkMethodDef = NULL;
  7403. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  7404. if (entry != NULL)
  7405. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  7406. bool hadProtected = false;
  7407. while (checkMethodDef != NULL)
  7408. {
  7409. if (!checkMethodDef->mParams.IsEmpty())
  7410. {
  7411. auto firstParam = checkMethodDef->mParams[0];
  7412. if (((firstParam->mParamKind == BfParamKind_Params) || (firstParam->mParamKind == BfParamKind_AppendIdx) || (firstParam->mParamKind == BfParamKind_VarArgs)) ||
  7413. ((firstParam->mParamDeclaration != NULL) && (firstParam->mParamDeclaration->mInitializer != NULL)))
  7414. {
  7415. // Allow all-default params
  7416. }
  7417. else
  7418. {
  7419. checkMethodDef = checkMethodDef->mNextWithSameName;
  7420. continue;
  7421. }
  7422. }
  7423. if (checkMethodDef->mProtection == BfProtection_Public)
  7424. {
  7425. canAlloc = true;
  7426. break;
  7427. }
  7428. if ((checkMethodDef->mProtection == BfProtection_Protected) || (checkMethodDef->mProtection == BfProtection_ProtectedInternal))
  7429. hadProtected = true;
  7430. checkMethodDef = checkMethodDef->mNextWithSameName;
  7431. }
  7432. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  7433. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  7434. }
  7435. }
  7436. else if (checkArgType->IsGenericParam())
  7437. {
  7438. canAlloc = (checkGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) != 0;
  7439. }
  7440. else if (checkArgType->IsPrimitiveType())
  7441. {
  7442. // Any primitive types and stuff can be allocated
  7443. canAlloc = true;
  7444. }
  7445. if (!canAlloc)
  7446. {
  7447. if ((!ignoreErrors) && (PreFail()))
  7448. {
  7449. if (checkArgType->IsGenericParam())
  7450. *errorOut = Fail(StrFormat("Must add 'where %s : new' constraint in order to use type as parameter '%s' for '%s'",
  7451. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7452. else
  7453. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  7454. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7455. }
  7456. return false;
  7457. }
  7458. }
  7459. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  7460. return true;
  7461. if (genericParamInst->mTypeConstraint != NULL)
  7462. {
  7463. bool constraintMatched = false;
  7464. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7465. {
  7466. if (checkArgType->IsConstExprValue())
  7467. {
  7468. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  7469. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  7470. {
  7471. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  7472. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  7473. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  7474. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  7475. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  7476. (primType->mTypeDef->mTypeCode != BfTypeCode_Let) &&
  7477. (primType->mTypeDef->mTypeCode != BfTypeCode_Var))
  7478. {
  7479. bool doError = true;
  7480. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  7481. {
  7482. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7483. {
  7484. if (mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue))
  7485. doError = false;
  7486. }
  7487. }
  7488. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_Float) && ((constExprValueType->mValue.mTypeCode == BfTypeCode_Double)))
  7489. {
  7490. doError = false;
  7491. }
  7492. if (doError)
  7493. {
  7494. if ((!ignoreErrors) && (PreFail()))
  7495. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7496. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7497. return false;
  7498. }
  7499. }
  7500. }
  7501. else if (genericParamInst->mTypeConstraint != constExprValueType->mType)
  7502. {
  7503. if ((!ignoreErrors) && (PreFail()))
  7504. *errorOut = Fail(StrFormat("Const generic argument '%s', declared as '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7505. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7506. return false;
  7507. }
  7508. }
  7509. }
  7510. else
  7511. {
  7512. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  7513. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  7514. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7515. if (convCheckConstraint == NULL)
  7516. return false;
  7517. if ((checkArgType->IsMethodRef()) || (checkArgType->IsFunction()))
  7518. {
  7519. if (convCheckConstraint->IsDelegate())
  7520. {
  7521. BfMethodInstance* checkMethodInstance;
  7522. if (checkArgType->IsMethodRef())
  7523. {
  7524. auto methodRefType = (BfMethodRefType*)checkArgType;
  7525. checkMethodInstance = methodRefType->mMethodRef;
  7526. }
  7527. else
  7528. {
  7529. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  7530. }
  7531. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  7532. if (checkMethodInstance->HasExplicitThis() != 0)
  7533. {
  7534. // Don't allow functions with explicit 'this'
  7535. }
  7536. else
  7537. {
  7538. BfExprEvaluator exprEvaluator(this);
  7539. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  7540. constraintMatched = true;
  7541. }
  7542. }
  7543. else if (convCheckConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef))
  7544. constraintMatched = true;
  7545. else if ((checkArgType->IsFunction()) && (convCheckConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))
  7546. constraintMatched = true;
  7547. }
  7548. else if ((checkArgType == convCheckConstraint) || (checkArgType->IsVar()) || (TypeIsSubTypeOf(checkArgType->ToTypeInstance(), convCheckConstraint->ToTypeInstance())))
  7549. {
  7550. constraintMatched = true;
  7551. }
  7552. else if (origCheckArgType->IsWrappableType())
  7553. {
  7554. if (origCheckArgType->IsSizedArray())
  7555. {
  7556. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  7557. if (convCheckConstraint->IsGenericTypeInstance())
  7558. {
  7559. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  7560. if (convCheckConstraintInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  7561. {
  7562. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  7563. {
  7564. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  7565. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  7566. constraintMatched = true;
  7567. }
  7568. }
  7569. }
  7570. }
  7571. if (!constraintMatched)
  7572. {
  7573. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7574. if ((wrappedStructType == convCheckConstraint) || (TypeIsSubTypeOf(wrappedStructType, convCheckConstraint->ToTypeInstance())))
  7575. constraintMatched = true;
  7576. }
  7577. }
  7578. if (!constraintMatched)
  7579. {
  7580. if ((!ignoreErrors) && (PreFail()))
  7581. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  7582. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  7583. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  7584. return false;
  7585. }
  7586. }
  7587. }
  7588. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  7589. {
  7590. BfType* convCheckConstraint = checkConstraint;
  7591. if (convCheckConstraint->IsUnspecializedType())
  7592. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7593. if (convCheckConstraint == NULL)
  7594. return false;
  7595. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  7596. bool implementsInterface = false;
  7597. if (origCheckArgType != checkArgType)
  7598. {
  7599. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  7600. }
  7601. if (!implementsInterface)
  7602. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  7603. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  7604. {
  7605. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7606. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7607. implementsInterface = true;
  7608. }
  7609. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  7610. {
  7611. auto underlyingType = origCheckArgType->GetUnderlyingType();
  7612. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  7613. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7614. implementsInterface = true;
  7615. }
  7616. if (!implementsInterface)
  7617. {
  7618. if ((!ignoreErrors) && (PreFail()))
  7619. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  7620. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  7621. return false;
  7622. }
  7623. }
  7624. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  7625. {
  7626. auto leftType = checkOpConstraint.mLeftType;
  7627. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  7628. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs, mCurTypeInstance);
  7629. if (leftType != NULL)
  7630. leftType = FixIntUnknown(leftType);
  7631. auto rightType = checkOpConstraint.mRightType;
  7632. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  7633. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs, mCurTypeInstance);
  7634. if (rightType != NULL)
  7635. rightType = FixIntUnknown(rightType);
  7636. BfConstraintState constraintSet;
  7637. constraintSet.mPrevState = mContext->mCurConstraintState;
  7638. constraintSet.mGenericParamInstance = genericParamInst;
  7639. constraintSet.mLeftType = leftType;
  7640. constraintSet.mRightType = rightType;
  7641. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  7642. if (!CheckConstraintState(NULL))
  7643. return false;
  7644. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  7645. {
  7646. BfExprEvaluator exprEvaluator(this);
  7647. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  7648. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7649. //
  7650. {
  7651. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7652. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7653. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  7654. }
  7655. if ((!exprEvaluator.mResult) ||
  7656. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  7657. {
  7658. if ((!ignoreErrors) && (PreFail()))
  7659. {
  7660. if (genericParamInst->mExternType != NULL)
  7661. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  7662. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  7663. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7664. ), checkArgTypeRef);
  7665. else
  7666. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  7667. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7668. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7669. ), checkArgTypeRef);
  7670. }
  7671. return false;
  7672. }
  7673. }
  7674. else
  7675. {
  7676. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7677. StringT<128> failedOpName;
  7678. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  7679. {
  7680. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7681. failedOpName = "implicit conversion from '";
  7682. }
  7683. else
  7684. {
  7685. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7686. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7687. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  7688. {
  7689. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7690. failedOpName = "explicit conversion from '";
  7691. }
  7692. else
  7693. {
  7694. BfExprEvaluator exprEvaluator(this);
  7695. exprEvaluator.mResult = rightValue;
  7696. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  7697. if ((!exprEvaluator.mResult) ||
  7698. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  7699. {
  7700. failedOpName += "unary operation '";
  7701. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  7702. }
  7703. }
  7704. }
  7705. if (!failedOpName.IsEmpty())
  7706. {
  7707. if ((!ignoreErrors) && (PreFail()))
  7708. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  7709. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7710. failedOpName.c_str(), TypeToString(rightType).c_str()
  7711. ), checkArgTypeRef);
  7712. return false;
  7713. }
  7714. }
  7715. }
  7716. return true;
  7717. }
  7718. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  7719. {
  7720. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  7721. {
  7722. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  7723. return genericParamType;
  7724. }
  7725. auto genericParamType = new BfGenericParamType();
  7726. genericParamType->mContext = mContext;
  7727. genericParamType->mGenericParamKind = paramKind;
  7728. genericParamType->mGenericParamIdx = paramIdx;
  7729. PopulateType(genericParamType);
  7730. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  7731. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  7732. BfResolvedTypeSet::LookupContext lookupCtx;
  7733. lookupCtx.mModule = this;
  7734. BfResolvedTypeSet::EntryRef typeEntry;
  7735. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  7736. BF_ASSERT(inserted);
  7737. typeEntry->mValue = genericParamType;
  7738. return genericParamType;
  7739. }
  7740. static int sValueFromExprIdx = 0;
  7741. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  7742. {
  7743. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  7744. if ((result) && (!ignoreNullable))
  7745. {
  7746. if (result.mType->IsVar())
  7747. return result;
  7748. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  7749. //TODO: Make this work, needed for 'void' and such
  7750. BfType* nullableType = NULL;
  7751. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  7752. {
  7753. BfTypeVector typeVec;
  7754. typeVec.push_back(result.mType);
  7755. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  7756. BF_ASSERT(nullableType != NULL);
  7757. }
  7758. // Go back to start and do any setup we need
  7759. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7760. BfTypedValue nullableTypedValue;
  7761. if (nullableType != NULL)
  7762. {
  7763. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  7764. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  7765. GetConstValue(nullableType->mSize), nullableType->mAlign);
  7766. }
  7767. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7768. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  7769. mBfIRBuilder->SetInsertPoint(notNullBB);
  7770. result = LoadValue(result);
  7771. if (nullableTypedValue)
  7772. {
  7773. auto elementType = nullableType->GetUnderlyingType();
  7774. if (elementType->IsVar())
  7775. {
  7776. // Do nothing
  7777. }
  7778. else if (elementType->IsValuelessType())
  7779. {
  7780. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  7781. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  7782. }
  7783. else
  7784. {
  7785. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  7786. mBfIRBuilder->CreateAlignedStore(result.mValue, ptrValue, result.mType->mAlign);
  7787. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  7788. mBfIRBuilder->CreateAlignedStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue, 1);
  7789. }
  7790. result = nullableTypedValue;
  7791. }
  7792. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7793. AddBasicBlock(pendingNullCond->mDoneBB);
  7794. if (nullableType == NULL)
  7795. {
  7796. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  7797. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  7798. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  7799. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  7800. {
  7801. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  7802. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  7803. }
  7804. result.mValue = phi;
  7805. }
  7806. }
  7807. else
  7808. {
  7809. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7810. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7811. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7812. AddBasicBlock(pendingNullCond->mDoneBB);
  7813. }
  7814. delete mCurMethodState->mPendingNullConditional;
  7815. mCurMethodState->mPendingNullConditional = NULL;
  7816. return result;
  7817. }
  7818. BF_NOINLINE void BfModule::EvaluateWithNewConditionalScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  7819. {
  7820. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  7821. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData);
  7822. if (mCurMethodState != NULL)
  7823. {
  7824. deferredLocalAssignData.mIsIfCondition = true;
  7825. deferredLocalAssignData.mIfMayBeSkipped = true;
  7826. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  7827. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  7828. mCurMethodState->mDeferredLocalAssignData = &deferredLocalAssignData;
  7829. }
  7830. BfScopeData newScope;
  7831. newScope.mOuterIsConditional = true;
  7832. newScope.mAllowTargeting = false;
  7833. if (mCurMethodState != NULL)
  7834. {
  7835. mCurMethodState->AddScope(&newScope);
  7836. NewScopeState(true, false);
  7837. }
  7838. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7839. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  7840. if (mCurMethodState != NULL)
  7841. RestoreScopeState();
  7842. }
  7843. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7844. {
  7845. //
  7846. {
  7847. BP_ZONE("CreateValueFromExpression:CheckStack");
  7848. StackHelper stackHelper;
  7849. if (!stackHelper.CanStackExpand(128 * 1024))
  7850. {
  7851. BfTypedValue result;
  7852. if (!stackHelper.Execute([&]()
  7853. {
  7854. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7855. }))
  7856. {
  7857. Fail("Expression too complex to compile", expr);
  7858. }
  7859. return result;
  7860. }
  7861. }
  7862. BP_ZONE("BfModule::CreateValueFromExpression");
  7863. if (outOrigType != NULL)
  7864. *outOrigType = NULL;
  7865. exprEvaluator.mExpectingType = wantTypeRef;
  7866. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7867. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  7868. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  7869. {
  7870. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope->mScopeKind != BfScopeKind_StatementTarget_Conditional))
  7871. {
  7872. EvaluateWithNewConditionalScope(exprEvaluator, expr, flags);
  7873. }
  7874. else
  7875. {
  7876. SetAndRestoreValue<bool> prevIsConditional(mCurMethodState->mCurScope->mIsConditional, true);
  7877. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7878. }
  7879. }
  7880. else
  7881. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7882. if (!exprEvaluator.mResult)
  7883. {
  7884. if ((flags & BfEvalExprFlags_InferReturnType) != 0)
  7885. return exprEvaluator.mResult;
  7886. if (!mCompiler->mPassInstance->HasFailed())
  7887. {
  7888. if (PreFail())
  7889. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  7890. }
  7891. return BfTypedValue();
  7892. }
  7893. auto typedVal = exprEvaluator.mResult;
  7894. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  7895. {
  7896. BF_ASSERT(typedVal.mType->IsGenericParam());
  7897. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  7898. bool handled = false;
  7899. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7900. {
  7901. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  7902. if (genericTypeConstraint != NULL)
  7903. {
  7904. auto underlyingConstraint = genericTypeConstraint;
  7905. if ((underlyingConstraint != NULL) && (underlyingConstraint->IsBoxed()))
  7906. underlyingConstraint = underlyingConstraint->GetUnderlyingType();
  7907. if (underlyingConstraint != NULL)
  7908. {
  7909. BfTypedValue result;
  7910. result.mKind = BfTypedValueKind_Value;
  7911. result.mType = genericTypeConstraint;
  7912. result.mValue = mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(underlyingConstraint));
  7913. typedVal = result;
  7914. handled = true;
  7915. }
  7916. }
  7917. }
  7918. if (!handled)
  7919. {
  7920. //Fail("Only const generic parameters can be used as values", expr);
  7921. AssertErrorState();
  7922. return BfTypedValue();
  7923. }
  7924. }
  7925. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  7926. FixIntUnknown(typedVal);
  7927. if (!mBfIRBuilder->mIgnoreWrites)
  7928. FixValueActualization(typedVal);
  7929. exprEvaluator.CheckResultForReading(typedVal);
  7930. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  7931. {
  7932. if ((flags & BfEvalExprFlags_NoCast) == 0)
  7933. {
  7934. // Only allow a 'ref' type if we have an explicit 'ref' operator
  7935. bool allowRef = false;
  7936. BfAstNode* checkExpr = expr;
  7937. while (checkExpr != NULL)
  7938. {
  7939. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  7940. checkExpr = parenExpr->mExpression;
  7941. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  7942. {
  7943. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  7944. allowRef = true;
  7945. break;
  7946. }
  7947. if (auto block = BfNodeDynCast<BfBlock>(checkExpr))
  7948. {
  7949. if (block->mChildArr.mSize == 0)
  7950. break;
  7951. checkExpr = block->mChildArr.back();
  7952. }
  7953. else
  7954. break;
  7955. }
  7956. if (!allowRef)
  7957. typedVal = RemoveRef(typedVal);
  7958. }
  7959. }
  7960. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  7961. {
  7962. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsDataIncomplete()) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  7963. {
  7964. if (typedVal.mValue.IsFake())
  7965. {
  7966. InternalError("Unexpected fakeval in CreateValueFromExpression");
  7967. typedVal = GetDefaultTypedValue(typedVal.mType);
  7968. }
  7969. }
  7970. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7971. }
  7972. if (wantTypeRef != NULL)
  7973. {
  7974. if (outOrigType != NULL)
  7975. *outOrigType = typedVal.mType;
  7976. if (((flags & BfEvalExprFlags_NoCast) == 0) && (!wantTypeRef->IsVar()))
  7977. {
  7978. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  7979. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  7980. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  7981. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  7982. if (!typedVal)
  7983. return typedVal;
  7984. }
  7985. if (exprEvaluator.mIsVolatileReference)
  7986. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7987. }
  7988. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  7989. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7990. return typedVal;
  7991. }
  7992. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7993. {
  7994. BfExprEvaluator exprEvaluator(this);
  7995. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7996. }
  7997. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  7998. {
  7999. BfExprEvaluator exprEvaluator(this);
  8000. exprEvaluator.Evaluate(expr);
  8001. if (!exprEvaluator.mResult)
  8002. {
  8003. Fail("Invalid expression type", expr);
  8004. return BfTypedValue();
  8005. }
  8006. if (!exprEvaluator.mResult.IsAddr())
  8007. {
  8008. Fail("Cannot assign to value", expr);
  8009. return BfTypedValue();
  8010. }
  8011. return exprEvaluator.mResult;
  8012. }
  8013. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  8014. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  8015. {
  8016. auto typeInstance = typedValue.mType->ToTypeInstance();
  8017. if (zeroMemory)
  8018. {
  8019. int zeroAlign = typedValue.mType->mAlign;
  8020. if (typeInstance != NULL)
  8021. zeroAlign = typeInstance->mInstAlign;
  8022. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  8023. }
  8024. if (!typedValue.mType->IsObject())
  8025. {
  8026. return;
  8027. }
  8028. if ((scopeData == NULL) && (mCurMethodState != NULL))
  8029. return; // Handled in heap alloc funcs
  8030. auto typeDef = typeInstance->mTypeDef;
  8031. mBfIRBuilder->PopulateType(typedValue.mType);
  8032. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  8033. bool isAutocomplete = mCompiler->IsAutocomplete();
  8034. BfIRValue vDataRef;
  8035. if (!isAutocomplete)
  8036. {
  8037. vDataRef = GetClassVDataPtr(typeInstance);
  8038. }
  8039. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8040. auto ptrType = CreatePointerType(i8Type);
  8041. auto ptrPtrType = CreatePointerType(ptrType);
  8042. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  8043. PopulateType(ptrType, BfPopulateType_Declaration);
  8044. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  8045. if (!isAutocomplete)
  8046. {
  8047. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8048. {
  8049. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8050. SizedArray<BfIRValue, 4> llvmArgs;
  8051. llvmArgs.push_back(objectPtr);
  8052. llvmArgs.push_back(vDataRef);
  8053. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  8054. if (objectStackInitMethod)
  8055. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  8056. }
  8057. else
  8058. {
  8059. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  8060. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  8061. mBfIRBuilder->CreateStore(srcVal, destAddr);
  8062. }
  8063. }
  8064. }
  8065. bool BfModule::IsAllocatorAligned()
  8066. {
  8067. if (mCompiler->mOptions.mMallocLinkName == "StompAlloc")
  8068. return false;
  8069. return true;
  8070. }
  8071. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  8072. {
  8073. BfIRValue result;
  8074. BfType* ptrType;
  8075. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  8076. ptrType = type;
  8077. else
  8078. ptrType = CreatePointerType(type);
  8079. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  8080. {
  8081. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8082. SizedArray<BfExpression*, 2> argExprs;
  8083. BfTypedValueExpression typedValueExpr;
  8084. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  8085. typedValueExpr.mRefNode = refNode;
  8086. argExprs.push_back(&typedValueExpr);
  8087. BfTypedValueExpression appendSizeValueExpr;
  8088. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  8089. appendSizeValueExpr.mRefNode = refNode;
  8090. argExprs.push_back(&appendSizeValueExpr);
  8091. BfExprEvaluator exprEvaluator(this);
  8092. BfTypedValue allocResult;
  8093. if (allocTarget.mScopedInvocationTarget != NULL)
  8094. {
  8095. SizedArray<BfTypeReference*, 2> genericArgs;
  8096. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, BfMethodGenericArguments());
  8097. allocResult = LoadValue(exprEvaluator.mResult);
  8098. }
  8099. else if (allocTarget.mCustomAllocator)
  8100. {
  8101. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8102. if (customTypeInst == NULL)
  8103. {
  8104. if (allocTarget.mCustomAllocator.mType->IsStructPtr())
  8105. customTypeInst = allocTarget.mCustomAllocator.mType->GetUnderlyingType()->ToTypeInstance();
  8106. }
  8107. if (customTypeInst == NULL)
  8108. {
  8109. Fail(StrFormat("Type '%s' cannot be used as a custom allocator", TypeToString(allocTarget.mCustomAllocator.mType).c_str()), refNode);
  8110. }
  8111. else
  8112. {
  8113. BfTypedValueExpression typeValueExpr;
  8114. String allocMethodName = "Alloc";
  8115. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  8116. {
  8117. allocMethodName = "AllocTyped";
  8118. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  8119. auto typeRefVal = CreateTypeDataRef(type);
  8120. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  8121. typeValueExpr.mRefNode = refNode;
  8122. argExprs.Insert(0, &typeValueExpr);
  8123. }
  8124. if (HasMixin(customTypeInst, allocMethodName, 2))
  8125. {
  8126. BfSizedArray<BfExpression*> argExprArr;
  8127. argExprArr.mSize = (int)argExprs.size();
  8128. argExprArr.mVals = &argExprs[0];
  8129. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  8130. allocResult = exprEvaluator.GetResult();
  8131. }
  8132. else
  8133. {
  8134. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8135. BfResolvedArgs argValues(&sizedArgExprs);
  8136. exprEvaluator.ResolveArgValues(argValues);
  8137. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  8138. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, BfMethodGenericArguments());
  8139. }
  8140. }
  8141. }
  8142. if (allocResult)
  8143. {
  8144. if (allocResult.mType->IsVoidPtr())
  8145. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  8146. else
  8147. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  8148. return result;
  8149. }
  8150. }
  8151. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  8152. return result;
  8153. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8154. {
  8155. BfIRValue allocData = GetDbgRawAllocData(type);
  8156. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  8157. SizedArray<BfIRValue, 2> llvmArgs;
  8158. llvmArgs.push_back(sizeValue);
  8159. llvmArgs.push_back(allocData);
  8160. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  8161. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8162. }
  8163. BfModuleMethodInstance moduleMethodInstance;
  8164. moduleMethodInstance = GetInternalMethod("Malloc");
  8165. SizedArray<BfIRValue, 1> llvmArgs;
  8166. llvmArgs.push_back(sizeValue);
  8167. auto func = moduleMethodInstance.mFunc;
  8168. if ((!func) || (func.IsFake()))
  8169. {
  8170. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  8171. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  8172. }
  8173. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  8174. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  8175. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  8176. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8177. return result;
  8178. }
  8179. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  8180. {
  8181. if (type->IsStruct())
  8182. {
  8183. auto typeInstance = type->ToTypeInstance();
  8184. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  8185. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8186. }
  8187. else if (type->IsObjectOrInterface())
  8188. {
  8189. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8190. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  8191. BF_ASSERT(moduleMethodInst.mFunc);
  8192. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8193. }
  8194. else
  8195. {
  8196. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8197. BfExprEvaluator exprEvaluator(this);
  8198. SizedArray<BfResolvedArg, 1> resolvedArgs;
  8199. BfResolvedArg resolvedArg;
  8200. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  8201. resolvedArgs.Add(resolvedArg);
  8202. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, BfMethodGenericArguments());
  8203. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  8204. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  8205. BF_ASSERT(moduleMethodInst.mFunc);
  8206. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8207. }
  8208. return BfIRValue();
  8209. }
  8210. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  8211. {
  8212. BfIRValue allocDataValue;
  8213. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  8214. return allocDataValue;
  8215. BfIRValue markFuncPtr;
  8216. if (type->WantsGCMarking())
  8217. markFuncPtr = GetMarkFuncPtr(type);
  8218. else
  8219. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8220. BfIRValue typeDataRef = CreateTypeDataRef(type);
  8221. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  8222. BfTypeInstance* typeInstance = type->ToTypeInstance();
  8223. if (typeInstance == NULL)
  8224. {
  8225. typeInstance = GetWrappedStructType(type);
  8226. if (typeInstance != NULL)
  8227. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8228. }
  8229. if (typeInstance != NULL)
  8230. PopulateType(typeInstance);
  8231. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8232. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  8233. {
  8234. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8235. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8236. }
  8237. SizedArray<BfIRValue, 2> dataValues;
  8238. dataValues.Add(mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  8239. dataValues.Add(typeDataRef);
  8240. dataValues.Add(markFuncPtr);
  8241. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  8242. BfIRValue dataStruct = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  8243. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  8244. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  8245. return allocDataValue;
  8246. }
  8247. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  8248. {
  8249. BP_ZONE("AllocFromType");
  8250. BfScopeData* scopeData = allocTarget.mScopeData;
  8251. BF_ASSERT(!type->IsVar());
  8252. auto typeInstance = type->ToTypeInstance();
  8253. if ((typeInstance == NULL) && (type->IsGenericParam()))
  8254. typeInstance = mContext->mBfObjectType;
  8255. bool isHeapAlloc = scopeData == NULL;
  8256. bool isScopeAlloc = scopeData != NULL;
  8257. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  8258. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  8259. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  8260. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  8261. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  8262. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  8263. {
  8264. BfPointerType* ptrType = CreatePointerType(type);
  8265. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  8266. return val;
  8267. }
  8268. if (typeInstance != NULL)
  8269. mBfIRBuilder->PopulateType(typeInstance);
  8270. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  8271. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  8272. {
  8273. return mBfIRBuilder->GetFakeVal();
  8274. }
  8275. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8276. BfIRValue sizeValue;
  8277. BfIRType allocType = mBfIRBuilder->MapType(type);
  8278. int allocSize = type->mSize;
  8279. int allocAlign = type->mAlign;
  8280. if (typeInstance != NULL)
  8281. {
  8282. if ((!mBfIRBuilder->mIgnoreWrites) && (!mIsComptimeModule))
  8283. typeInstance->mHasBeenInstantiated = true;
  8284. allocSize = typeInstance->mInstSize;
  8285. allocAlign = typeInstance->mInstAlign;
  8286. //if (typeInstance->IsEnum())
  8287. //allocType = typeInstance->mIRType;
  8288. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  8289. }
  8290. if (alignOverride != -1)
  8291. allocAlign = alignOverride;
  8292. // The "dynSize" cases:
  8293. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  8294. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  8295. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  8296. // though we'd expect their stack space to be released
  8297. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  8298. {
  8299. MarkDynStack(scopeData);
  8300. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8301. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  8302. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  8303. BfType* voidPtrType = CreatePointerType(voidType);
  8304. if (!mCurMethodState->mDynStackRevIdx)
  8305. {
  8306. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  8307. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8308. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8309. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  8310. mBfIRBuilder->ClearDebugLocation(storeInst);
  8311. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8312. }
  8313. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  8314. auto bytePtrType = CreatePointerType(byteType);
  8315. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  8316. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  8317. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8318. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8319. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  8320. mBfIRBuilder->ClearDebugLocation(storeInst);
  8321. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  8322. mBfIRBuilder->ClearDebugLocation(storeInst);
  8323. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8324. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  8325. if (IsTargetingBeefBackend())
  8326. {
  8327. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  8328. // to ensure there isn't any register collision during looping is just to not allow it to
  8329. // bind to a register at all
  8330. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  8331. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  8332. }
  8333. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  8334. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  8335. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  8336. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  8337. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  8338. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  8339. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  8340. mBfIRBuilder->AddBlock(verCheckBB);
  8341. mBfIRBuilder->SetInsertPoint(verCheckBB);
  8342. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  8343. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  8344. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  8345. mBfIRBuilder->AddBlock(resizeBB);
  8346. mBfIRBuilder->SetInsertPoint(resizeBB);
  8347. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8348. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  8349. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  8350. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  8351. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  8352. mBfIRBuilder->CreateBr(endBB);
  8353. mBfIRBuilder->AddBlock(endBB);
  8354. mBfIRBuilder->SetInsertPoint(endBB);
  8355. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  8356. };
  8357. if (isScopeAlloc)
  8358. {
  8359. if (arraySize)
  8360. {
  8361. bool isConstantArraySize = arraySize.IsConst();
  8362. if (isRawArrayAlloc)
  8363. {
  8364. BfPointerType* ptrType = CreatePointerType(type);
  8365. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8366. {
  8367. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8368. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  8369. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  8370. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  8371. }
  8372. else
  8373. {
  8374. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8375. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  8376. if (!isDynAlloc)
  8377. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8378. else
  8379. {
  8380. MarkDynStack(scopeData);
  8381. SaveStackState(scopeData);
  8382. }
  8383. int typeSize = type->GetStride();
  8384. BfIRValue allocaInst;
  8385. BfIRValue result;
  8386. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  8387. {
  8388. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  8389. result = allocaInst;
  8390. }
  8391. else
  8392. {
  8393. if (typeInstance->IsStruct())
  8394. typeSize = typeInstance->GetInstStride();
  8395. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  8396. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  8397. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8398. auto ptrType = CreatePointerType(typeInstance);
  8399. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  8400. if (!isDynAlloc)
  8401. mBfIRBuilder->ClearDebugLocation(result);
  8402. }
  8403. if (!isDynAlloc)
  8404. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8405. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8406. if (!isDynAlloc)
  8407. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8408. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  8409. if (arraySize.IsConst())
  8410. {
  8411. auto constant = mBfIRBuilder->GetConstant(arraySize);
  8412. if (constant->mInt64 == 0)
  8413. noDtorCall = true;
  8414. }
  8415. if (!noDtorCall)
  8416. {
  8417. bool isConstSize = arraySize.IsConst();
  8418. BfIRBlock clearBlock;
  8419. BfIRBlock contBlock;
  8420. bool wantsDeinit = ((!IsOptimized()) && (!mIsComptimeModule) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly));
  8421. if (wantsDeinit)
  8422. {
  8423. BfIRBlock prevBlock;
  8424. if (!isConstSize)
  8425. {
  8426. clearBlock = mBfIRBuilder->CreateBlock("clear");
  8427. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  8428. prevBlock = mBfIRBuilder->GetInsertBlock();
  8429. mBfIRBuilder->AddBlock(clearBlock);
  8430. mBfIRBuilder->SetInsertPoint(clearBlock);
  8431. }
  8432. auto deferredCall = AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  8433. if (!isConstSize)
  8434. {
  8435. mBfIRBuilder->CreateBr(contBlock);
  8436. mBfIRBuilder->SetInsertPoint(prevBlock);
  8437. if (deferredCall != NULL)
  8438. {
  8439. // Zero out size args
  8440. for (int i = 1; i < deferredCall->mModuleMethodInstance.mMethodInstance->GetParamCount(); i++)
  8441. {
  8442. auto scopedArg = deferredCall->mScopeArgs[i];
  8443. if (scopedArg != deferredCall->mOrigScopeArgs[i])
  8444. mBfIRBuilder->CreateStore(GetDefaultValue(deferredCall->mModuleMethodInstance.mMethodInstance->GetParamType(i)), deferredCall->mScopeArgs[i]);
  8445. }
  8446. }
  8447. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  8448. mBfIRBuilder->AddBlock(contBlock);
  8449. mBfIRBuilder->SetInsertPoint(contBlock);
  8450. }
  8451. }
  8452. }
  8453. return result;
  8454. }
  8455. }
  8456. else
  8457. {
  8458. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8459. {
  8460. // Generate and check new size
  8461. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8462. auto firstElementField = &arrayType->mFieldInstances.back();
  8463. int arrayClassSize = firstElementField->mDataOffset;
  8464. sizeValue = GetConstValue(arrayClassSize);
  8465. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8466. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8467. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  8468. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  8469. if (!noDtorCall)
  8470. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8471. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8472. return typedVal.mValue;
  8473. }
  8474. else
  8475. {
  8476. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8477. auto firstElementField = &arrayType->mFieldInstances.back();
  8478. if (!type->IsValuelessType())
  8479. {
  8480. int arrayClassSize = firstElementField->mDataOffset;
  8481. sizeValue = GetConstValue(arrayClassSize);
  8482. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8483. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8484. }
  8485. else
  8486. sizeValue = GetConstValue(arrayType->mInstSize);
  8487. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8488. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8489. if (!isDynAlloc)
  8490. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8491. else
  8492. {
  8493. MarkDynStack(scopeData);
  8494. SaveStackState(scopeData);
  8495. }
  8496. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  8497. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8498. if (!isDynAlloc)
  8499. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8500. auto allocaBlock = mBfIRBuilder->GetInsertBlock();
  8501. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8502. BfTypedValue typedVal;
  8503. if (!isDynAlloc)
  8504. {
  8505. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8506. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8507. mBfIRBuilder->ClearDebugLocation_Last();
  8508. mBfIRBuilder->SetInsertPoint(prevBlock);
  8509. allocaBlock = mCurMethodState->mIRInitBlock;
  8510. }
  8511. else
  8512. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8513. if (!noDtorCall)
  8514. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true, allocaBlock);
  8515. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8516. return typedVal.mValue;
  8517. }
  8518. }
  8519. }
  8520. else if (appendSizeValue)
  8521. {
  8522. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  8523. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  8524. // use the "dynSize" version conservatively
  8525. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8526. {
  8527. // Generate and check new size
  8528. sizeValue = GetConstValue(typeInstance->mInstSize);
  8529. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8530. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  8531. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  8532. if (!noDtorCall)
  8533. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  8534. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8535. return typedVal.mValue;
  8536. }
  8537. else // stack alloc, unlooped, with append
  8538. {
  8539. sizeValue = GetConstValue(typeInstance->mInstSize);
  8540. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8541. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8542. bool wasDynAlloc = isDynAlloc;
  8543. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8544. if (!isDynAlloc)
  8545. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8546. else
  8547. {
  8548. MarkDynStack(scopeData);
  8549. SaveStackState(scopeData);
  8550. }
  8551. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  8552. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  8553. if (!isDynAlloc)
  8554. {
  8555. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8556. }
  8557. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8558. bool mayBeLarge = false;
  8559. if (sizeValue.IsConst())
  8560. {
  8561. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  8562. if (constantInt->mInt64 >= 4096)
  8563. mayBeLarge = true;
  8564. }
  8565. else
  8566. mayBeLarge = true;
  8567. if (((type->IsObject() && (!mayBeLarge))) ||
  8568. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8569. ((zeroMemory) && (!mayBeLarge)))
  8570. {
  8571. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8572. }
  8573. BfIRValue castedVal;
  8574. if (!isDynAlloc)
  8575. {
  8576. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8577. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8578. mBfIRBuilder->ClearDebugLocation(castedVal);
  8579. mBfIRBuilder->SetInsertPoint(prevBlock);
  8580. if (WantsLifetimes())
  8581. {
  8582. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8583. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8584. }
  8585. }
  8586. else
  8587. {
  8588. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8589. }
  8590. auto typedVal = BfTypedValue(castedVal, typeInstance);
  8591. if (!noDtorCall)
  8592. {
  8593. bool doCondAlloca = false;
  8594. if (!IsTargetingBeefBackend())
  8595. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  8596. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  8597. }
  8598. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8599. return typedVal.mValue;
  8600. }
  8601. }
  8602. else // "Normal" stack alloc
  8603. {
  8604. BF_ASSERT(!sizeValue);
  8605. //TODO: If sizeValue is a constant then do this in the head IR builder
  8606. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8607. if (!isLoopedAlloc)
  8608. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8609. else
  8610. {
  8611. MarkDynStack(scopeData);
  8612. SaveStackState(scopeData);
  8613. }
  8614. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  8615. if (!isLoopedAlloc)
  8616. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8617. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8618. bool mayBeLarge = allocSize >= 4096;
  8619. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  8620. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8621. ((zeroMemory) && (!mayBeLarge)))
  8622. {
  8623. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  8624. // and memset is always safe
  8625. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8626. }
  8627. auto typedVal = BfTypedValue(allocaInst, type);
  8628. if (!isLoopedAlloc)
  8629. {
  8630. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8631. mBfIRBuilder->SetInsertPoint(prevBlock);
  8632. if (WantsLifetimes())
  8633. {
  8634. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8635. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8636. }
  8637. }
  8638. if (!noDtorCall)
  8639. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8640. if (typeInstance != NULL)
  8641. {
  8642. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  8643. }
  8644. else
  8645. {
  8646. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  8647. }
  8648. return allocaInst;
  8649. }
  8650. }
  8651. else if (arraySize)
  8652. {
  8653. if (isRawArrayAlloc)
  8654. {
  8655. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8656. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  8657. }
  8658. else
  8659. {
  8660. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8661. typeInstance = arrayType;
  8662. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8663. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8664. appendSizeValue = elementDataSize;
  8665. if (!type->IsSizeAligned())
  8666. {
  8667. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  8668. }
  8669. }
  8670. }
  8671. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  8672. {
  8673. auto vDataRef = GetClassVDataPtr(typeInstance);
  8674. BfIRValue result;
  8675. bool isResultInitialized = false;
  8676. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8677. if (typeInstance->mTypeOptionsIdx != -1)
  8678. {
  8679. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8680. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8681. }
  8682. if (mIsComptimeModule)
  8683. stackCount = 0;
  8684. if (!sizeValue)
  8685. sizeValue = GetConstValue(typeInstance->mInstSize);
  8686. if (appendSizeValue)
  8687. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8688. BfIRValue origSizeValue = sizeValue;
  8689. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  8690. if (isAllocEx)
  8691. {
  8692. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  8693. if (prepareStackTraceMethod)
  8694. {
  8695. SizedArray<BfIRValue, 2> irArgs;
  8696. irArgs.Add(sizeValue);
  8697. irArgs.Add(GetConstValue(stackCount));
  8698. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  8699. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  8700. }
  8701. }
  8702. if (allocTarget.mCustomAllocator)
  8703. {
  8704. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8705. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  8706. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  8707. {
  8708. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8709. mBfIRBuilder->PopulateType(classVDataType);
  8710. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8711. mBfIRBuilder->PopulateType(typeInstType);
  8712. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  8713. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  8714. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  8715. BfTypedValueExpression typedValueExpr;
  8716. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  8717. typedValueExpr.mRefNode = allocTarget.mRefNode;
  8718. BfExprEvaluator exprEvaluator(this);
  8719. SizedArray<BfExpression*, 2> argExprs;
  8720. argExprs.push_back(&typedValueExpr);
  8721. BfTypedValueExpression sizeValueExpr;
  8722. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  8723. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  8724. argExprs.push_back(&sizeValueExpr);
  8725. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8726. BfResolvedArgs argValues(&sizedArgExprs);
  8727. exprEvaluator.ResolveArgValues(argValues);
  8728. exprEvaluator.mNoBind = true;
  8729. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, BfMethodGenericArguments());
  8730. if (allocResult)
  8731. {
  8732. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  8733. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  8734. else
  8735. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  8736. isResultInitialized = true;
  8737. }
  8738. }
  8739. }
  8740. bool wasAllocated = false;
  8741. if (!result)
  8742. {
  8743. if (hasCustomAllocator)
  8744. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  8745. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8746. {
  8747. SizedArray<BfIRValue, 4> llvmArgs;
  8748. llvmArgs.push_back(sizeValue);
  8749. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8750. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8751. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8752. wasAllocated = true;
  8753. }
  8754. }
  8755. if (result)
  8756. {
  8757. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8758. {
  8759. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  8760. SizedArray<BfIRValue, 4> llvmArgs;
  8761. llvmArgs.push_back(objectPtr);
  8762. llvmArgs.push_back(origSizeValue);
  8763. llvmArgs.push_back(vDataRef);
  8764. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  8765. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  8766. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  8767. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  8768. if (wasAllocated)
  8769. {
  8770. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  8771. auto bytePtrType = CreatePointerType(byteType);
  8772. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  8773. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  8774. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  8775. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  8776. }
  8777. }
  8778. else
  8779. {
  8780. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  8781. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8782. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  8783. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  8784. }
  8785. }
  8786. else
  8787. {
  8788. if ((mBfIRBuilder->mIgnoreWrites) ||
  8789. ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)))
  8790. return GetDefaultValue(typeInstance);
  8791. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8792. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  8793. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8794. {
  8795. SizedArray<BfIRValue, 4> llvmArgs;
  8796. llvmArgs.push_back(vData);
  8797. llvmArgs.push_back(sizeValue);
  8798. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  8799. llvmArgs.push_back(GetConstValue(stackCount));
  8800. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  8801. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  8802. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8803. }
  8804. else
  8805. {
  8806. SizedArray<BfIRValue, 4> llvmArgs;
  8807. llvmArgs.push_back(sizeValue);
  8808. BfIRFunction irFunc;
  8809. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8810. {
  8811. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  8812. irFunc = moduleMethodInstance.mFunc;
  8813. }
  8814. if (!irFunc)
  8815. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8816. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8817. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  8818. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  8819. if (mIsComptimeModule)
  8820. {
  8821. vdataPtr = mBfIRBuilder->CreateBitCast(vdataPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance())));
  8822. }
  8823. mBfIRBuilder->CreateStore(vData, vdataPtr);
  8824. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8825. }
  8826. }
  8827. if ((zeroMemory) && (arraySize))
  8828. {
  8829. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8830. typeInstance = arrayType;
  8831. auto firstElementField = &arrayType->mFieldInstances.back();
  8832. int arrayClassSize = firstElementField->mDataOffset;
  8833. BfIRValue elementDataSize;
  8834. bool skipZero = false;
  8835. if (arraySize.IsConst())
  8836. {
  8837. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8838. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8839. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  8840. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  8841. if (constVal->mInt64 <= 0)
  8842. skipZero = true;
  8843. }
  8844. else
  8845. {
  8846. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  8847. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8848. }
  8849. if (!skipZero)
  8850. {
  8851. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8852. auto ptrType = CreatePointerType(i8Type);
  8853. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  8854. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  8855. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  8856. appendSizeValue = elementDataSize;
  8857. }
  8858. }
  8859. return result;
  8860. }
  8861. else
  8862. {
  8863. if (!sizeValue)
  8864. sizeValue = GetConstValue(allocSize);
  8865. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  8866. }
  8867. }
  8868. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  8869. {
  8870. if ((type == NULL) || (refNode == NULL))
  8871. return;
  8872. auto typeInstance = type->ToTypeInstance();
  8873. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  8874. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  8875. }
  8876. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  8877. {
  8878. if (align <= 1)
  8879. return;
  8880. if (sizeMultiple == 0)
  8881. sizeMultiple = align;
  8882. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  8883. {
  8884. if (!IsAllocatorAligned())
  8885. {
  8886. // Don't align
  8887. }
  8888. else if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  8889. {
  8890. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8891. BF_ASSERT(localVar->mName == "appendIdx");
  8892. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  8893. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8894. if (align > 1)
  8895. {
  8896. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8897. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8898. }
  8899. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  8900. }
  8901. else
  8902. {
  8903. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  8904. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  8905. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  8906. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8907. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8908. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  8909. }
  8910. }
  8911. if (mCurMethodState->mCurAppendAlign == 0)
  8912. mCurMethodState->mCurAppendAlign = sizeMultiple;
  8913. else
  8914. {
  8915. if (sizeMultiple % align == 0)
  8916. mCurMethodState->mCurAppendAlign = align;
  8917. else
  8918. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  8919. }
  8920. }
  8921. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  8922. {
  8923. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8924. BF_ASSERT(localVar->mName == "appendIdx");
  8925. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  8926. BfIRValue retValue;
  8927. BfTypeInstance* retTypeInstance = NULL;
  8928. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  8929. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  8930. if (arraySize)
  8931. {
  8932. if (isRawArrayAlloc)
  8933. {
  8934. EmitAppendAlign(type->mAlign);
  8935. BfPointerType* ptrType = CreatePointerType(type);
  8936. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8937. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8938. if (mSystem->mPtrSize != 4)
  8939. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8940. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8941. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8942. if (zeroMemory)
  8943. {
  8944. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  8945. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  8946. }
  8947. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  8948. }
  8949. else
  8950. {
  8951. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8952. EmitAppendAlign(arrayType->mAlign, type->mSize);
  8953. auto firstElementField = &arrayType->mFieldInstances.back();
  8954. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  8955. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  8956. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8957. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8958. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8959. if (mSystem->mPtrSize != 4)
  8960. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8961. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8962. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8963. if (zeroMemory)
  8964. {
  8965. // Only zero out the actual elements
  8966. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  8967. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  8968. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  8969. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  8970. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  8971. }
  8972. retTypeInstance = arrayType;
  8973. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  8974. }
  8975. }
  8976. else
  8977. {
  8978. auto typeInst = type->ToTypeInstance();
  8979. BfIRValue sizeValue;
  8980. BfIRType toType;
  8981. if (typeInst != NULL)
  8982. {
  8983. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  8984. sizeValue = GetConstValue(typeInst->mInstSize);
  8985. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  8986. }
  8987. else
  8988. {
  8989. EmitAppendAlign(type->mAlign, type->mSize);
  8990. sizeValue = GetConstValue(type->mSize);
  8991. auto toPtrType = CreatePointerType(type);
  8992. toType = mBfIRBuilder->MapType(toPtrType);
  8993. }
  8994. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8995. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8996. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8997. retTypeInstance = typeInst;
  8998. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  8999. }
  9000. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  9001. {
  9002. mBfIRBuilder->PopulateType(retTypeInstance);
  9003. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  9004. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  9005. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  9006. auto curThis = GetThis();
  9007. BfIRValue newFlags;
  9008. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9009. {
  9010. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  9011. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  9012. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  9013. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  9014. }
  9015. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  9016. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  9017. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  9018. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  9019. mBfIRBuilder->CreateStore(srcVal, destAddr);
  9020. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9021. {
  9022. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  9023. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  9024. }
  9025. }
  9026. if (appendSizeValue)
  9027. {
  9028. EmitAppendAlign(appendAllocAlign);
  9029. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9030. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  9031. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9032. }
  9033. return retValue;
  9034. }
  9035. bool BfModule::IsOptimized()
  9036. {
  9037. if (mProject == NULL)
  9038. return false;
  9039. if (mIsComptimeModule)
  9040. return false;
  9041. int optLevel = GetModuleOptions().mOptLevel;
  9042. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  9043. }
  9044. bool BfModule::IsTargetingBeefBackend()
  9045. {
  9046. if (mProject == NULL)
  9047. return true;
  9048. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9049. }
  9050. bool BfModule::WantsLifetimes()
  9051. {
  9052. if (mBfIRBuilder->mIgnoreWrites)
  9053. return false;
  9054. if ((mIsComptimeModule) && (mBfIRBuilder->HasDebugLocation()))
  9055. return true;
  9056. else if (mProject == NULL)
  9057. return false;
  9058. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9059. }
  9060. bool BfModule::HasCompiledOutput()
  9061. {
  9062. return (!mSystem->mIsResolveOnly) && (mGeneratesCode) && (!mIsComptimeModule);
  9063. }
  9064. bool BfModule::HasExecutedOutput()
  9065. {
  9066. return ((!mSystem->mIsResolveOnly) && (mGeneratesCode)) || (mIsComptimeModule);
  9067. }
  9068. // We will skip the object access check for any occurrences of this value
  9069. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  9070. {
  9071. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9072. return;
  9073. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9074. return;
  9075. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  9076. return;
  9077. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  9078. }
  9079. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  9080. {
  9081. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9082. return;
  9083. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9084. return;
  9085. if (typedVal.mValue.IsConst())
  9086. {
  9087. int stringIdx = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  9088. if (stringIdx != -1)
  9089. return;
  9090. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  9091. if (constant->mTypeCode == BfTypeCode_NullPtr)
  9092. return;
  9093. if (constant->mConstType == BfConstType_BitCastNull)
  9094. return;
  9095. }
  9096. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9097. auto typeOptions = GetTypeOptions();
  9098. if (typeOptions != NULL)
  9099. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9100. if (!emitObjectAccessCheck)
  9101. return;
  9102. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  9103. {
  9104. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  9105. return;
  9106. }
  9107. if (typedVal.IsAddr())
  9108. typedVal = LoadValue(typedVal);
  9109. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  9110. }
  9111. bool BfModule::WantsDebugHelpers()
  9112. {
  9113. if (mBfIRBuilder->mIgnoreWrites)
  9114. return false;
  9115. if (mIsComptimeModule)
  9116. {
  9117. // Always add
  9118. }
  9119. else if ((mProject == NULL) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  9120. return false;
  9121. return true;
  9122. }
  9123. void BfModule::EmitEnsureInstructionAt()
  9124. {
  9125. if (!WantsDebugHelpers())
  9126. return;
  9127. mBfIRBuilder->CreateEnsureInstructionAt();
  9128. }
  9129. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  9130. {
  9131. if (mBfIRBuilder->mIgnoreWrites)
  9132. return; // Nothing needed here
  9133. auto irb = mBfIRBuilder;
  9134. auto checkBB = irb->CreateBlock("as.check");
  9135. auto isNull = irb->CreateIsNull(targetValue.mValue);
  9136. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  9137. if (mIsComptimeModule)
  9138. {
  9139. AddBasicBlock(checkBB);
  9140. auto callResult = mBfIRBuilder->Comptime_DynamicCastCheck(targetValue.mValue, targetType->mTypeId, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9141. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult, GetDefaultValue(mContext->mBfObjectType));
  9142. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9143. return;
  9144. }
  9145. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  9146. auto intPtrType = CreatePointerType(intType);
  9147. auto intPtrPtrType = CreatePointerType(intPtrType);
  9148. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  9149. auto int32PtrType = CreatePointerType(int32Type);
  9150. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  9151. if (mCompiler->mOptions.mAllowHotSwapping)
  9152. {
  9153. BfExprEvaluator exprEvaluator(this);
  9154. AddBasicBlock(checkBB);
  9155. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9156. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  9157. SizedArray<BfIRValue, 4> irArgs;
  9158. irArgs.push_back(objectParam);
  9159. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  9160. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  9161. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  9162. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9163. }
  9164. else
  9165. {
  9166. AddBasicBlock(checkBB);
  9167. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  9168. vDataPtr = irb->CreateLoad(vDataPtr);
  9169. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9170. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  9171. if (targetType->IsInterface())
  9172. {
  9173. auto targetTypeInst = targetType->ToTypeInstance();
  9174. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9175. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  9176. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  9177. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9178. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  9179. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  9180. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  9181. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  9182. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  9183. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9184. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  9185. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  9186. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9187. }
  9188. else
  9189. {
  9190. if (!targetType->IsTypeInstance())
  9191. targetType = GetWrappedStructType(targetType);
  9192. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9193. int inheritanceIdOfs = mSystem->mPtrSize * mCompiler->GetVDataPrefixDataCount();
  9194. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9195. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9196. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  9197. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  9198. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  9199. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  9200. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  9201. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9202. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  9203. fieldInst = &typeTypeInstance->mFieldInstances[10];
  9204. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  9205. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9206. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  9207. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  9208. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  9209. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9210. }
  9211. }
  9212. }
  9213. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  9214. {
  9215. if (mBfIRBuilder->mIgnoreWrites)
  9216. return;
  9217. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  9218. auto typeOptions = GetTypeOptions();
  9219. if (typeOptions != NULL)
  9220. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  9221. if (emitDynamicCastCheck)
  9222. {
  9223. int wantTypeId = 0;
  9224. if (!type->IsGenericParam())
  9225. wantTypeId = type->mTypeId;
  9226. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  9227. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  9228. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  9229. AddBasicBlock(failBlock);
  9230. if (mIsComptimeModule)
  9231. {
  9232. mBfIRBuilder->Comptime_Error(CeErrorKind_ObjectDynCheckFailed);
  9233. }
  9234. else
  9235. {
  9236. SizedArray<BfIRValue, 8> llvmArgs;
  9237. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9238. llvmArgs.push_back(bitAddr);
  9239. llvmArgs.push_back(GetConstValue32(wantTypeId));
  9240. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  9241. BF_ASSERT(objDynCheck);
  9242. if (objDynCheck)
  9243. {
  9244. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  9245. }
  9246. }
  9247. mBfIRBuilder->CreateBr(endBlock);
  9248. AddBasicBlock(endBlock);
  9249. }
  9250. }
  9251. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, BfCastFlags castFlags)
  9252. {
  9253. bool callDtor = (castFlags & BfCastFlags_NoBoxDtor) == 0;
  9254. bool wantConst = ((castFlags & BfCastFlags_WantsConst) != 0) && (typedVal.mValue.IsConst());
  9255. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9256. {
  9257. if (toType == mContext->mBfObjectType)
  9258. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9259. if (toType->IsBoxed())
  9260. {
  9261. BfBoxedType* boxedType = (BfBoxedType*)toType;
  9262. if (boxedType->mElementType->IsGenericParam())
  9263. {
  9264. if (typedVal.mType == boxedType->mElementType)
  9265. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9266. else
  9267. return BfTypedValue();
  9268. }
  9269. }
  9270. }
  9271. BP_ZONE("BoxValue");
  9272. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  9273. if (typedVal.mType->IsNullable())
  9274. {
  9275. typedVal = MakeAddressable(typedVal);
  9276. auto innerType = typedVal.mType->GetUnderlyingType();
  9277. if (!innerType->IsValueType())
  9278. {
  9279. if (!mIgnoreErrors)
  9280. Fail("Only value types can be boxed", srcNode);
  9281. return BfTypedValue();
  9282. }
  9283. auto boxedType = CreateBoxedType(innerType);
  9284. auto resultType = toType;
  9285. if (resultType == NULL)
  9286. resultType = boxedType;
  9287. if (mBfIRBuilder->mIgnoreWrites)
  9288. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  9289. auto prevBB = mBfIRBuilder->GetInsertBlock();
  9290. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  9291. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  9292. mBfIRBuilder->PopulateType(typedVal.mType);
  9293. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  9294. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  9295. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  9296. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9297. mBfIRBuilder->AddBlock(boxBB);
  9298. mBfIRBuilder->SetInsertPoint(boxBB);
  9299. BfScopeData newScope;
  9300. newScope.mOuterIsConditional = true;
  9301. mCurMethodState->AddScope(&newScope);
  9302. NewScopeState();
  9303. BfIRValue nullableValueAddr;
  9304. BfIRValue loadedVal;
  9305. if (innerType->IsValuelessType())
  9306. {
  9307. loadedVal = mBfIRBuilder->GetFakeVal();
  9308. }
  9309. else
  9310. {
  9311. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  9312. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  9313. }
  9314. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor ? BfCastFlags_None : BfCastFlags_NoBoxDtor);
  9315. RestoreScopeState();
  9316. if (!boxedVal)
  9317. return BfTypedValue();
  9318. mBfIRBuilder->CreateBr(endBB);
  9319. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  9320. mBfIRBuilder->AddBlock(endBB);
  9321. mBfIRBuilder->SetInsertPoint(endBB);
  9322. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  9323. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  9324. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  9325. return BfTypedValue(phi, resultType);
  9326. }
  9327. bool alreadyCheckedCast = false;
  9328. BfTypeInstance* toTypeInstance = NULL;
  9329. if (toType != NULL)
  9330. toTypeInstance = toType->ToTypeInstance();
  9331. bool isStructPtr = typedVal.mType->IsStructPtr();
  9332. if (fromStructTypeInstance == NULL)
  9333. {
  9334. auto primType = (BfPrimitiveType*)typedVal.mType;
  9335. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  9336. {
  9337. // Can always do IHashable
  9338. alreadyCheckedCast = true;
  9339. }
  9340. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  9341. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9342. else
  9343. {
  9344. auto checkStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9345. if (checkStructTypeInstance == toType->GetUnderlyingType())
  9346. fromStructTypeInstance = checkStructTypeInstance;
  9347. }
  9348. if (isStructPtr)
  9349. {
  9350. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9351. alreadyCheckedCast = true;
  9352. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  9353. }
  9354. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  9355. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9356. }
  9357. if (fromStructTypeInstance == NULL)
  9358. return BfTypedValue();
  9359. // Need to box it
  9360. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  9361. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9362. {
  9363. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9364. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  9365. auto boxedType = CreateBoxedType(typedVal.mType);
  9366. mBfIRBuilder->PopulateType(boxedType);
  9367. if (wantConst)
  9368. return BfTypedValue(mBfIRBuilder->CreateConstBox(typedVal.mValue, mBfIRBuilder->MapType(boxedType)), boxedType);
  9369. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9370. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  9371. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  9372. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  9373. if (boxedType->IsUnspecializedType())
  9374. {
  9375. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  9376. }
  9377. else
  9378. {
  9379. PopulateType(fromStructTypeInstance);
  9380. if (!fromStructTypeInstance->IsValuelessType())
  9381. {
  9382. typedVal = LoadValue(typedVal);
  9383. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  9384. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  9385. {
  9386. auto ptrType = CreatePointerType(typedVal.mType);
  9387. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  9388. }
  9389. if (typedVal.IsSplat())
  9390. {
  9391. AggregateSplatIntoAddr(typedVal, valPtr);
  9392. }
  9393. else
  9394. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr, typedVal.mType->mAlign);
  9395. }
  9396. }
  9397. if (toType == NULL)
  9398. {
  9399. return BfTypedValue(allocaInst, boxedType);
  9400. }
  9401. else
  9402. {
  9403. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  9404. return BfTypedValue(castedValue, toType);
  9405. }
  9406. }
  9407. return BfTypedValue();
  9408. }
  9409. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  9410. {
  9411. BfTypeInstance* checkTypeInst = typeInst;
  9412. while (checkTypeInst != NULL)
  9413. {
  9414. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  9415. {
  9416. if (checkProp->mName == propDef->mName)
  9417. {
  9418. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  9419. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  9420. {
  9421. propDef = checkProp;
  9422. typeInst = checkTypeInst;
  9423. return true;
  9424. }
  9425. }
  9426. }
  9427. checkTypeInst = checkTypeInst->mBaseType;
  9428. }
  9429. return false;
  9430. }
  9431. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  9432. {
  9433. if (!typeInstance->mResolvingVarField)
  9434. {
  9435. if (!typeInstance->DefineStateAllowsStaticMethods())
  9436. PopulateType(typeInstance, BfPopulateType_AllowStaticMethods);
  9437. }
  9438. else
  9439. {
  9440. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  9441. {
  9442. AssertErrorState();
  9443. return NULL;
  9444. }
  9445. }
  9446. if (assertName != NULL)
  9447. {
  9448. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9449. }
  9450. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9451. {
  9452. if (mCompiler->EnsureCeUnpaused(typeInstance))
  9453. {
  9454. BF_FATAL("OOB in GetRawMethodInstanceAtIdx");
  9455. }
  9456. return NULL;
  9457. }
  9458. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  9459. if (methodGroup.mDefault == NULL)
  9460. {
  9461. if (!mCompiler->mIsResolveOnly)
  9462. {
  9463. // Get it from the owning module so we don't create a reference prematurely...
  9464. auto declModule = typeInstance->mModule;
  9465. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  9466. {
  9467. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9468. if (!declModule->mIsScratchModule)
  9469. declModule->mOnDemandMethodCount++;
  9470. }
  9471. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  9472. (typeInstance->mTypeFailed) || (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted));
  9473. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  9474. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9475. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified);
  9476. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9477. }
  9478. else
  9479. {
  9480. auto declModule = typeInstance->mModule;
  9481. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass);
  9482. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9483. }
  9484. }
  9485. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9486. //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
  9487. // be from a call to the NON-raw version
  9488. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  9489. // {
  9490. // methodInstance->mIsReified = mIsReified;
  9491. // if (methodInstance->mMethodProcessRequest == NULL)
  9492. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  9493. // }
  9494. return methodInstance;
  9495. }
  9496. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  9497. {
  9498. if (methodDef->mIsLocalMethod)
  9499. {
  9500. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  9501. }
  9502. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx, NULL);
  9503. }
  9504. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  9505. {
  9506. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9507. while (typeInstance != NULL)
  9508. {
  9509. typeInstance->mTypeDef->PopulateMemberSets();
  9510. BfMemberSetEntry* entry = NULL;
  9511. BfMethodDef* methodDef = NULL;
  9512. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9513. methodDef = (BfMethodDef*)entry->mMemberDef;
  9514. while (methodDef != NULL)
  9515. {
  9516. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  9517. (methodDef->mGenericParams.size() == 0) &&
  9518. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9519. return GetRawMethodInstance(typeInstance, methodDef);
  9520. methodDef = methodDef->mNextWithSameName;
  9521. }
  9522. if (!checkBase)
  9523. break;
  9524. typeInstance = typeInstance->mBaseType;
  9525. }
  9526. return NULL;
  9527. }
  9528. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  9529. {
  9530. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9531. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  9532. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  9533. if (!useUnspecializedType)
  9534. return methodInstance;
  9535. if (!owner->IsGenericTypeInstance())
  9536. return methodInstance;
  9537. if ((owner->IsDelegateFromTypeRef()) ||
  9538. (owner->IsFunctionFromTypeRef()) ||
  9539. (owner->IsTuple()))
  9540. {
  9541. return methodInstance;
  9542. }
  9543. auto genericType = (BfTypeInstance*)owner;
  9544. if ((genericType->IsUnspecializedType()) && (!genericType->IsUnspecializedTypeVariation()))
  9545. return methodInstance;
  9546. if (methodInstance->mMethodDef->mIsLocalMethod)
  9547. return methodInstance;
  9548. if (methodInstance->mMethodDef->mDeclaringType->IsEmitted())
  9549. return methodInstance;
  9550. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef->GetDefinition());
  9551. if (unspecializedType == NULL)
  9552. {
  9553. AssertErrorState();
  9554. return methodInstance;
  9555. }
  9556. if (unspecializedType == NULL)
  9557. return methodInstance;
  9558. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  9559. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  9560. }
  9561. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  9562. {
  9563. int genericCount = 0;
  9564. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  9565. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  9566. {
  9567. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  9568. if (param->IsGenericParam())
  9569. genericCount++;
  9570. }
  9571. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  9572. genericCount++;
  9573. return genericCount;
  9574. }
  9575. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  9576. {
  9577. BF_ASSERT(!mIsScratchModule);
  9578. BF_ASSERT(mIsReified);
  9579. BfModule* mainModule = this;
  9580. if (mParentModule != NULL)
  9581. mainModule = mParentModule;
  9582. BfModule* specModule = NULL;
  9583. BfModule** specModulePtr = NULL;
  9584. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  9585. {
  9586. return *specModulePtr;
  9587. }
  9588. else
  9589. {
  9590. String specModuleName = mModuleName;
  9591. for (auto bfProject : projectList)
  9592. {
  9593. specModuleName += StrFormat("@%s", bfProject->mSafeName.c_str());
  9594. }
  9595. specModule = new BfModule(mContext, specModuleName);
  9596. specModule->mProject = mainModule->mProject;
  9597. specModule->mParentModule = mainModule;
  9598. specModule->mIsSpecializedMethodModuleRoot = true;
  9599. specModule->Init();
  9600. Array<BfProject*> projList;
  9601. for (auto project : projectList)
  9602. projList.Add(project);
  9603. mainModule->mSpecializedMethodModules[projList] = specModule;
  9604. }
  9605. return specModule;
  9606. }
  9607. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  9608. {
  9609. if (IsSkippingExtraResolveChecks())
  9610. return BfIRValue();
  9611. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  9612. {
  9613. //BF_ASSERT(!methodInstance->mIRFunction);
  9614. return BfIRValue();
  9615. }
  9616. auto methodDef = methodInstance->mMethodDef;
  9617. StringT<4096> methodName;
  9618. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  9619. if (isInlined != methodInstance->mAlwaysInline)
  9620. {
  9621. if (isInlined)
  9622. methodName += "__INLINE";
  9623. else
  9624. methodName += "__NOINLINE";
  9625. }
  9626. if (tryExisting)
  9627. {
  9628. auto func = mBfIRBuilder->GetFunction(methodName);
  9629. if (func)
  9630. return func;
  9631. }
  9632. auto intrinsic = GetIntrinsic(methodInstance);
  9633. if (intrinsic)
  9634. return intrinsic;
  9635. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  9636. {
  9637. return CreateDllImportGlobalVar(methodInstance, false);
  9638. }
  9639. BfIRType returnType;
  9640. SizedArray<BfIRType, 8> paramTypes;
  9641. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  9642. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  9643. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  9644. auto callingConv = GetIRCallingConvention(methodInstance);
  9645. if (callingConv != BfIRCallingConv_CDecl)
  9646. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  9647. SetupIRMethod(methodInstance, func, isInlined);
  9648. // auto srcModule = methodInstance->GetOwner()->GetModule();
  9649. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  9650. // {
  9651. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  9652. // {
  9653. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  9654. // }
  9655. // }
  9656. return func;
  9657. }
  9658. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  9659. {
  9660. if (assertName != NULL)
  9661. {
  9662. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9663. }
  9664. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9665. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9666. return BfModuleMethodInstance();
  9667. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9668. BfMethodDef* methodDef = NULL;
  9669. BfTypeInstance* foreignType = NULL;
  9670. if (methodInstance != NULL)
  9671. {
  9672. methodDef = methodInstance->mMethodDef;
  9673. if (methodInstance->mMethodInfoEx != NULL)
  9674. foreignType = methodInstance->mMethodInfoEx->mForeignType;
  9675. }
  9676. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  9677. {
  9678. // Can't use it, not reified
  9679. methodInstance = NULL;
  9680. }
  9681. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  9682. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  9683. {
  9684. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  9685. return BfModuleMethodInstance(methodInstance, func);
  9686. }
  9687. if (foreignType != NULL)
  9688. return GetMethodInstance(typeInstance, methodDef, BfTypeVector(), (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef), foreignType);
  9689. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  9690. }
  9691. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9692. {
  9693. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9694. while (typeInstance != NULL)
  9695. {
  9696. typeInstance->mTypeDef->PopulateMemberSets();
  9697. BfMemberSetEntry* entry = NULL;
  9698. BfMethodDef* methodDef = NULL;
  9699. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9700. methodDef = (BfMethodDef*)entry->mMemberDef;
  9701. while (methodDef != NULL)
  9702. {
  9703. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9704. (methodDef->mGenericParams.size() == 0) &&
  9705. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9706. {
  9707. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9708. if (moduleMethodInstance)
  9709. return moduleMethodInstance;
  9710. }
  9711. methodDef = methodDef->mNextWithSameName;
  9712. }
  9713. if (!checkBase)
  9714. break;
  9715. typeInstance = typeInstance->mBaseType;
  9716. }
  9717. return BfModuleMethodInstance();
  9718. }
  9719. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  9720. {
  9721. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9722. while (typeInstance != NULL)
  9723. {
  9724. typeInstance->mTypeDef->PopulateMemberSets();
  9725. BfMemberSetEntry* entry = NULL;
  9726. BfMethodDef* methodDef = NULL;
  9727. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9728. methodDef = (BfMethodDef*)entry->mMemberDef;
  9729. while (methodDef != NULL)
  9730. {
  9731. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9732. (methodDef->mGenericParams.size() == 0) &&
  9733. (paramTypes.size() == methodDef->mParams.size()))
  9734. {
  9735. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9736. if (moduleMethodInstance.mMethodInstance != NULL)
  9737. {
  9738. bool matches = true;
  9739. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  9740. {
  9741. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  9742. matches = false;
  9743. }
  9744. if (matches)
  9745. return moduleMethodInstance;
  9746. }
  9747. }
  9748. methodDef = methodDef->mNextWithSameName;
  9749. }
  9750. if (!checkBase)
  9751. break;
  9752. typeInstance = typeInstance->mBaseType;
  9753. }
  9754. return BfModuleMethodInstance();
  9755. }
  9756. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  9757. {
  9758. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  9759. PopulateType(internalType);
  9760. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  9761. if (!moduleMethodInstance)
  9762. {
  9763. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  9764. }
  9765. return moduleMethodInstance;
  9766. }
  9767. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  9768. {
  9769. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  9770. typeInstance->mOperatorInfo.Add(NULL);
  9771. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  9772. {
  9773. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  9774. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  9775. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  9776. BfTypeState typeState;
  9777. typeState.mType = typeInstance;
  9778. typeState.mCurTypeDef = operatorDef->mDeclaringType;
  9779. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  9780. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  9781. if (operatorDef->mReturnTypeRef != NULL)
  9782. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  9783. if (operatorDef->mParams.size() >= 1)
  9784. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  9785. if (operatorDef->mParams.size() >= 2)
  9786. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  9787. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  9788. }
  9789. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  9790. }
  9791. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  9792. {
  9793. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  9794. if (operatorInfo == NULL)
  9795. return NULL;
  9796. if (operatorInfo->mReturnType == NULL)
  9797. return NULL;
  9798. auto castFlags = BfCastFlags_IsConstraintCheck;
  9799. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9800. castFlags = (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator);
  9801. if (lhs)
  9802. {
  9803. if (operatorInfo->mLHSType == NULL)
  9804. return NULL;
  9805. if (!CanCast(lhs, operatorInfo->mLHSType, castFlags))
  9806. return NULL;
  9807. }
  9808. if (rhs)
  9809. {
  9810. if (operatorInfo->mRHSType == NULL)
  9811. return NULL;
  9812. if (!CanCast(rhs, operatorInfo->mRHSType, castFlags))
  9813. return NULL;
  9814. }
  9815. return operatorInfo->mReturnType;
  9816. }
  9817. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9818. {
  9819. while (typeInstance != NULL)
  9820. {
  9821. typeInstance->mTypeDef->PopulateMemberSets();
  9822. BfMemberSetEntry* entry = NULL;
  9823. BfMethodDef* methodDef = NULL;
  9824. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9825. methodDef = (BfMethodDef*)entry->mMemberDef;
  9826. while (methodDef != NULL)
  9827. {
  9828. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9829. (methodDef->mGenericParams.size() == 0) &&
  9830. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9831. {
  9832. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  9833. if (!methodInstanceGroup.IsImplemented())
  9834. return false;
  9835. if (methodInstanceGroup.mDefault == NULL)
  9836. return false;
  9837. return methodInstanceGroup.mDefault->mIsReified;
  9838. }
  9839. methodDef = methodDef->mNextWithSameName;
  9840. }
  9841. if (!checkBase)
  9842. break;
  9843. typeInstance = typeInstance->mBaseType;
  9844. }
  9845. return false;
  9846. }
  9847. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9848. {
  9849. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9850. while (typeInstance != NULL)
  9851. {
  9852. typeInstance->mTypeDef->PopulateMemberSets();
  9853. BfMemberSetEntry* entry = NULL;
  9854. BfMethodDef* methodDef = NULL;
  9855. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9856. methodDef = (BfMethodDef*)entry->mMemberDef;
  9857. while (methodDef != NULL)
  9858. {
  9859. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  9860. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9861. return true;
  9862. methodDef = methodDef->mNextWithSameName;
  9863. }
  9864. if (!checkBase)
  9865. break;
  9866. typeInstance = typeInstance->mBaseType;
  9867. }
  9868. return BfModuleMethodInstance();
  9869. }
  9870. String BfModule::FieldToString(BfFieldInstance* fieldInstance)
  9871. {
  9872. auto result = TypeToString(fieldInstance->mOwner);
  9873. result += ".";
  9874. auto fieldDef = fieldInstance->GetFieldDef();
  9875. if (fieldDef != NULL)
  9876. result += fieldDef->mName;
  9877. else
  9878. result += "???";
  9879. return result;
  9880. }
  9881. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* typeGenericArgs, BfTypeVector* methodGenericArgs)
  9882. {
  9883. auto methodDef = methodInst->mMethodDef;
  9884. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  9885. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9886. bool hasGenericArgs = (typeGenericArgs != NULL) || (methodGenericArgs != NULL);
  9887. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  9888. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9889. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  9890. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  9891. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9892. if (allowResolveGenericParamNames)
  9893. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9894. StringT<128> methodName;
  9895. auto _AddTypeName = [&](BfType* type)
  9896. {
  9897. auto typeNameFlags = BfTypeNameFlags_None;
  9898. if (allowResolveGenericParamNames)
  9899. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9900. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9901. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  9902. methodName += TypeToString(type, typeNameFlags);
  9903. };
  9904. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  9905. {
  9906. _AddTypeName(methodInst->mReturnType);
  9907. methodName += " ";
  9908. }
  9909. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  9910. {
  9911. methodName += TypeToString(type, typeNameFlags);
  9912. if (methodName == "$")
  9913. methodName = "";
  9914. else if (!methodName.IsEmpty())
  9915. methodName += ".";
  9916. }
  9917. String accessorString;
  9918. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  9919. if (methodInst->mMethodDef->mIsLocalMethod)
  9920. {
  9921. int atPos = (int)methodDefName.IndexOf('$');
  9922. methodDefName.RemoveToEnd(atPos);
  9923. methodDefName.Replace("@", ".");
  9924. }
  9925. else
  9926. {
  9927. int atPos = (int)methodDefName.IndexOf('$');
  9928. if (atPos != -1)
  9929. {
  9930. accessorString = methodDefName.Substring(0, atPos);
  9931. if ((accessorString == "get") || (accessorString == "set"))
  9932. {
  9933. methodDefName = methodDefName.Substring(atPos + 1);
  9934. }
  9935. else
  9936. accessorString = "";
  9937. }
  9938. }
  9939. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  9940. {
  9941. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9942. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9943. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9944. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  9945. methodName += ".";
  9946. }
  9947. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  9948. {
  9949. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9950. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9951. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9952. methodName += "[";
  9953. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  9954. methodName += "].";
  9955. }
  9956. if (methodDef->mMethodType == BfMethodType_Operator)
  9957. {
  9958. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  9959. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9960. {
  9961. // Don't add explicit/implicit part, since that's not available in GCC mangling
  9962. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  9963. {
  9964. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  9965. methodName += "explicit ";
  9966. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  9967. methodName += "explicit ";
  9968. }*/
  9969. methodName += "operator ";
  9970. if (methodInst->mReturnType != NULL)
  9971. methodName += TypeToString(methodInst->mReturnType);
  9972. }
  9973. else
  9974. {
  9975. methodName += "operator";
  9976. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  9977. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  9978. }
  9979. }
  9980. else if (methodDef->mMethodType == BfMethodType_Ctor)
  9981. {
  9982. if (methodDef->mIsStatic)
  9983. methodName += "__BfStaticCtor";
  9984. else
  9985. methodName += "this";
  9986. accessorString = "";
  9987. }
  9988. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  9989. {
  9990. auto propertyDecl = methodDef->GetPropertyDeclaration();
  9991. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  9992. {
  9993. methodName += "get indexer";
  9994. }
  9995. else
  9996. {
  9997. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  9998. propertyDecl->mNameNode->ToString(methodName);
  9999. methodName += " get accessor";
  10000. return methodName;
  10001. }
  10002. }
  10003. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10004. {
  10005. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10006. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10007. {
  10008. methodName += "set indexer";
  10009. }
  10010. else
  10011. {
  10012. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10013. propertyDecl->mNameNode->ToString(methodName);
  10014. methodName += " set accessor";
  10015. return methodName;
  10016. }
  10017. }
  10018. else
  10019. methodName += methodDefName;
  10020. if (methodDef->mMethodType == BfMethodType_Mixin)
  10021. methodName += "!";
  10022. BfTypeVector newMethodGenericArgs;
  10023. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  10024. {
  10025. methodName += "<";
  10026. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  10027. {
  10028. if (i > 0)
  10029. methodName += ", ";
  10030. BfTypeNameFlags typeNameFlags = BfTypeNameFlag_ShortConst;
  10031. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  10032. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10033. if (allowResolveGenericParamNames)
  10034. typeNameFlags = (BfTypeNameFlags)(typeNameFlags | BfTypeNameFlag_ResolveGenericParamNames);
  10035. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  10036. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  10037. {
  10038. bool hasEmpty = false;
  10039. for (auto arg : *methodGenericArgs)
  10040. {
  10041. if (arg == NULL)
  10042. hasEmpty = true;
  10043. }
  10044. if (hasEmpty)
  10045. {
  10046. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  10047. {
  10048. auto arg = (*methodGenericArgs)[genericIdx];
  10049. if (arg != NULL)
  10050. newMethodGenericArgs.push_back(arg);
  10051. else
  10052. {
  10053. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  10054. if (genericParamInst->mTypeConstraint != NULL)
  10055. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  10056. else
  10057. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  10058. }
  10059. }
  10060. methodGenericArgs = &newMethodGenericArgs;
  10061. }
  10062. if (type->IsUnspecializedType())
  10063. type = ResolveGenericType(type, NULL, methodGenericArgs, mCurTypeInstance);
  10064. }
  10065. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  10066. {
  10067. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  10068. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  10069. methodName += TypeToString(type, typeNameFlags);
  10070. }
  10071. else
  10072. methodName += TypeToString(type, typeNameFlags);
  10073. }
  10074. methodName += ">";
  10075. }
  10076. if (accessorString.length() == 0)
  10077. {
  10078. int dispParamIdx = 0;
  10079. methodName += "(";
  10080. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  10081. {
  10082. int paramKind = methodInst->GetParamKind(paramIdx);
  10083. if ((paramKind == BfParamKind_ImplicitCapture) || (paramKind == BfParamKind_AppendIdx))
  10084. continue;
  10085. if (dispParamIdx > 0)
  10086. methodName += ", ";
  10087. if (paramKind == BfParamKind_Params)
  10088. methodName += "params ";
  10089. BfType* type = methodInst->GetParamType(paramIdx);
  10090. _AddTypeName(type);
  10091. methodName += " ";
  10092. methodName += methodInst->GetParamName(paramIdx);
  10093. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  10094. if ((paramInitializer != NULL) && ((methodNameFlags & BfMethodNameFlag_NoAst) == 0))
  10095. {
  10096. methodName += " = ";
  10097. methodName += paramInitializer->ToString();
  10098. }
  10099. dispParamIdx++;
  10100. }
  10101. methodName += ")";
  10102. }
  10103. if (accessorString.length() != 0)
  10104. {
  10105. methodName += " ";
  10106. methodName += accessorString;
  10107. }
  10108. if ((methodNameFlags & BfMethodNameFlag_IncludeMut) != 0)
  10109. {
  10110. if ((methodDef->mIsMutating) && (methodInst->GetOwner()->IsValueType()))
  10111. methodName += " mut";
  10112. }
  10113. return methodName;
  10114. }
  10115. void BfModule::pt(BfType* type)
  10116. {
  10117. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  10118. }
  10119. void BfModule::pm(BfMethodInstance* type)
  10120. {
  10121. OutputDebugStrF("%s\n", MethodToString(type).c_str());
  10122. }
  10123. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  10124. {
  10125. if ((flagsLeft & checkFlag) == 0)
  10126. return;
  10127. if (!str.empty())
  10128. {
  10129. if (flagsLeft == checkFlag)
  10130. {
  10131. if ((int)str.IndexOf(',') != -1)
  10132. str += ", and ";
  10133. else
  10134. str += " and ";
  10135. }
  10136. else
  10137. str += ", ";
  10138. }
  10139. str += addString;
  10140. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  10141. }
  10142. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  10143. {
  10144. String resultStr;
  10145. auto flagsLeft = attrTarget;
  10146. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  10147. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  10148. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  10149. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  10150. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  10151. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  10152. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  10153. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  10154. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  10155. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  10156. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  10157. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  10158. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  10159. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  10160. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  10161. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  10162. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  10163. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  10164. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  10165. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  10166. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  10167. if (resultStr.IsEmpty())
  10168. return "<nothing>";
  10169. return resultStr;
  10170. }
  10171. BfIRType BfModule::CurrentAddToConstHolder(BfIRType irType)
  10172. {
  10173. if (irType.mKind == BfIRTypeData::TypeKind_SizedArray)
  10174. {
  10175. auto sizedArrayType = (BfConstantSizedArrayType*)mBfIRBuilder->GetConstantById(irType.mId);
  10176. return mCurTypeInstance->GetOrCreateConstHolder()->GetSizedArrayType(CurrentAddToConstHolder(sizedArrayType->mType), (int)sizedArrayType->mLength);
  10177. }
  10178. return irType;
  10179. }
  10180. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  10181. {
  10182. auto constant = mBfIRBuilder->GetConstant(irVal);
  10183. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  10184. if (stringPoolIdx != -1)
  10185. {
  10186. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  10187. return;
  10188. }
  10189. if (constant->mConstType == BfConstType_Agg)
  10190. {
  10191. auto constArray = (BfConstantAgg*)constant;
  10192. SizedArray<BfIRValue, 8> newVals;
  10193. for (auto val : constArray->mValues)
  10194. {
  10195. auto newVal = val;
  10196. CurrentAddToConstHolder(newVal);
  10197. newVals.push_back(newVal);
  10198. }
  10199. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstAgg(CurrentAddToConstHolder(constArray->mType), newVals);
  10200. return;
  10201. }
  10202. auto origConst = irVal;
  10203. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10204. {
  10205. auto bitcast = (BfConstantBitCast*)constant;
  10206. BfIRValue newVal;
  10207. if (constant->mConstType == BfConstType_BitCast)
  10208. {
  10209. newVal = BfIRValue(BfIRValueFlags_Const, bitcast->mTarget);
  10210. CurrentAddToConstHolder(newVal);
  10211. }
  10212. else
  10213. newVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstNull();
  10214. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstBitCast(newVal, CurrentAddToConstHolder(bitcast->mToType));
  10215. return;
  10216. }
  10217. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  10218. }
  10219. void BfModule::ClearConstData()
  10220. {
  10221. mBfIRBuilder->ClearConstData();
  10222. mStringObjectPool.Clear();
  10223. mStringCharPtrPool.Clear();
  10224. mStringPoolRefs.Clear();
  10225. mUnreifiedStringPoolRefs.Clear();
  10226. mStaticFieldRefs.Clear();
  10227. }
  10228. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  10229. {
  10230. switch (constant->mTypeCode)
  10231. {
  10232. case BfTypeCode_StringId:
  10233. case BfTypeCode_Boolean:
  10234. case BfTypeCode_Int8:
  10235. case BfTypeCode_UInt8:
  10236. case BfTypeCode_Int16:
  10237. case BfTypeCode_UInt16:
  10238. case BfTypeCode_Int32:
  10239. case BfTypeCode_UInt32:
  10240. case BfTypeCode_Int64:
  10241. case BfTypeCode_UInt64:
  10242. case BfTypeCode_IntPtr:
  10243. case BfTypeCode_UIntPtr:
  10244. case BfTypeCode_IntUnknown:
  10245. case BfTypeCode_UIntUnknown:
  10246. case BfTypeCode_Char8:
  10247. case BfTypeCode_Char16:
  10248. case BfTypeCode_Char32:
  10249. case BfTypeCode_Float:
  10250. case BfTypeCode_Double:
  10251. {
  10252. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10253. BfTypedValue typedValue;
  10254. bool allowUnactualized = mBfIRBuilder->mIgnoreWrites;
  10255. if (constant->mTypeCode == BfTypeCode_StringId)
  10256. {
  10257. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10258. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10259. {
  10260. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType, allowUnactualized), wantType);
  10261. return typedValue;
  10262. }
  10263. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  10264. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType, allowUnactualized), stringType);
  10265. }
  10266. if (!typedValue)
  10267. {
  10268. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10269. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  10270. }
  10271. if (typedValue.mType == wantType)
  10272. return typedValue;
  10273. if (wantType->IsTypedPrimitive())
  10274. {
  10275. if (typedValue.mType == wantType->GetUnderlyingType())
  10276. {
  10277. typedValue.mType = wantType;
  10278. return typedValue;
  10279. }
  10280. }
  10281. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  10282. if (!castedTypedValue)
  10283. return BfTypedValue();
  10284. return castedTypedValue;
  10285. }
  10286. break;
  10287. default: break;
  10288. }
  10289. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  10290. BF_ASSERT(irValue);
  10291. if (!irValue)
  10292. return BfTypedValue();
  10293. if (constant->mConstType == BfConstType_GlobalVar)
  10294. {
  10295. mBfIRBuilder->PopulateType(wantType);
  10296. auto result = BfTypedValue(irValue, wantType, true);
  10297. if (!wantType->IsComposite())
  10298. result = LoadValue(result);
  10299. return result;
  10300. }
  10301. return BfTypedValue(irValue, wantType, false);
  10302. }
  10303. bool BfModule::HasUnactializedConstant(BfConstant* constant, BfIRConstHolder* constHolder)
  10304. {
  10305. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  10306. return true;
  10307. if (constant->mTypeCode == BfTypeCode_StringId)
  10308. return true;
  10309. if (constant->mConstType == BfConstType_Agg)
  10310. {
  10311. auto constArray = (BfConstantAgg*)constant;
  10312. for (auto val : constArray->mValues)
  10313. {
  10314. if (HasUnactializedConstant(constHolder->GetConstant(val), constHolder))
  10315. return true;
  10316. }
  10317. }
  10318. return false;
  10319. }
  10320. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType, bool allowUnactualized)
  10321. {
  10322. if (constant->mTypeCode == BfTypeCode_NullPtr)
  10323. {
  10324. if ((wantType == NULL) && (constant->mIRType.mKind == BfIRTypeData::TypeKind_TypeId))
  10325. wantType = mContext->mTypes[constant->mIRType.mId];
  10326. if (wantType == NULL)
  10327. return mBfIRBuilder->CreateConstNull();
  10328. return GetDefaultValue(wantType);
  10329. }
  10330. if (constant->mTypeCode == BfTypeCode_StringId)
  10331. {
  10332. if (!allowUnactualized)
  10333. {
  10334. if ((wantType == NULL) ||
  10335. (wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10336. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10337. {
  10338. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  10339. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  10340. if ((wantType != NULL) && (wantType->IsPointer()))
  10341. return GetStringCharPtr(stringObjConst, true);
  10342. return stringObjConst;
  10343. }
  10344. }
  10345. }
  10346. if (constant->mConstType == Beefy::BfConstType_TypeOf)
  10347. {
  10348. auto constTypeOf = (BfTypeOf_Const*)constant;
  10349. if (mCurTypeInstance != NULL)
  10350. AddDependency(constTypeOf->mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10351. return CreateTypeDataRef(constTypeOf->mType);
  10352. }
  10353. if (constant->mConstType == BfConstType_PtrToInt)
  10354. {
  10355. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  10356. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10357. return mBfIRBuilder->CreatePtrToInt(ConstantToCurrent(fromTarget, constHolder, NULL), fromPtrToInt->mToTypeCode);
  10358. }
  10359. if (constant->mConstType == BfConstType_IntToPtr)
  10360. {
  10361. auto fromPtrToInt = (BfConstantIntToPtr*)constant;
  10362. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10363. BfIRType toIRType = fromPtrToInt->mToType;
  10364. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10365. {
  10366. auto toType = mContext->mTypes[toIRType.mId];
  10367. toIRType = mBfIRBuilder->MapType(toType);
  10368. }
  10369. return mBfIRBuilder->CreateIntToPtr(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10370. }
  10371. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10372. {
  10373. auto bitcast = (BfConstantBitCast*)constant;
  10374. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  10375. BfIRType toIRType = bitcast->mToType;
  10376. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10377. {
  10378. auto toType = mContext->mTypes[toIRType.mId];
  10379. toIRType = mBfIRBuilder->MapType(toType);
  10380. }
  10381. return mBfIRBuilder->CreateBitCast(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10382. }
  10383. if (constant->mConstType == BfConstType_Agg)
  10384. {
  10385. auto constArray = (BfConstantAgg*)constant;
  10386. if ((wantType == NULL) && (constArray->mType.mKind == BfIRTypeData::TypeKind_TypeId))
  10387. wantType = mContext->mTypes[constArray->mType.mId];
  10388. if (wantType->IsArray())
  10389. wantType = CreateSizedArrayType(wantType->GetUnderlyingType(), (int)constArray->mValues.mSize);
  10390. bool handleAsArray = false;
  10391. SizedArray<BfIRValue, 8> newVals;
  10392. if (wantType->IsSizedArray())
  10393. {
  10394. handleAsArray = true;
  10395. }
  10396. else if (wantType->IsInstanceOf(mCompiler->mSpanTypeDef))
  10397. {
  10398. auto valueType = ResolveTypeDef(mCompiler->mValueTypeTypeDef);
  10399. handleAsArray = true;
  10400. if (!constArray->mValues.IsEmpty())
  10401. {
  10402. auto firstConstant = constHolder->GetConstant(constArray->mValues[0]);
  10403. if ((firstConstant->mConstType == BfConstType_AggZero) && (firstConstant->mIRType.mKind == BfIRType::TypeKind_TypeId) &&
  10404. (firstConstant->mIRType.mId == valueType->mTypeId))
  10405. handleAsArray = false;
  10406. if (firstConstant->mConstType == BfConstType_Agg)
  10407. {
  10408. auto firstConstArray = (BfConstantAgg*)firstConstant;
  10409. if ((firstConstArray->mType.mKind == BfIRType::TypeKind_TypeId) &&
  10410. (firstConstArray->mType.mId == valueType->mTypeId))
  10411. handleAsArray = false;
  10412. }
  10413. }
  10414. }
  10415. if (handleAsArray)
  10416. {
  10417. auto elementType = wantType->GetUnderlyingType();
  10418. for (auto val : constArray->mValues)
  10419. {
  10420. newVals.Add(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  10421. }
  10422. }
  10423. else
  10424. {
  10425. auto wantTypeInst = wantType->ToTypeInstance();
  10426. if (wantTypeInst == NULL)
  10427. {
  10428. InternalError("BfModule::ConstantToCurrent typeInst error");
  10429. return BfIRValue();
  10430. }
  10431. if (wantTypeInst->mBaseType != NULL)
  10432. {
  10433. auto baseVal = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[0]), constHolder, wantTypeInst->mBaseType);
  10434. newVals.Add(baseVal);
  10435. }
  10436. if (wantType->IsUnion())
  10437. {
  10438. auto innerType = wantType->ToTypeInstance()->GetUnionInnerType();
  10439. if (!innerType->IsValuelessType())
  10440. {
  10441. auto val = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[1]), constHolder, innerType);
  10442. newVals.Add(val);
  10443. }
  10444. }
  10445. if ((!wantType->IsUnion()) || (wantType->IsPayloadEnum()))
  10446. {
  10447. for (auto& fieldInstance : wantTypeInst->mFieldInstances)
  10448. {
  10449. if (fieldInstance.mDataIdx < 0)
  10450. continue;
  10451. if (fieldInstance.mDataIdx >= constArray->mValues.mSize)
  10452. {
  10453. InternalError("BfModule::ConstantToCurrent union error");
  10454. return BfIRValue();
  10455. }
  10456. auto val = constArray->mValues[fieldInstance.mDataIdx];
  10457. BfIRValue memberVal = ConstantToCurrent(constHolder->GetConstant(val), constHolder, fieldInstance.mResolvedType);
  10458. if (fieldInstance.mDataIdx == newVals.mSize)
  10459. newVals.Add(memberVal);
  10460. else
  10461. {
  10462. while (fieldInstance.mDataIdx >= newVals.mSize)
  10463. newVals.Add(BfIRValue());
  10464. newVals[fieldInstance.mDataIdx] = memberVal;
  10465. }
  10466. }
  10467. }
  10468. for (auto& val : newVals)
  10469. {
  10470. if (!val)
  10471. val = mBfIRBuilder->CreateConstArrayZero(0);
  10472. }
  10473. }
  10474. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(wantType, BfIRPopulateType_Identity), newVals);
  10475. }
  10476. return mBfIRBuilder->CreateConst(constant, constHolder);
  10477. }
  10478. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  10479. {
  10480. if (attrTarget == BfAttributeTargets_SkipValidate)
  10481. return;
  10482. for (auto& customAttribute : customAttributes->mAttributes)
  10483. {
  10484. if (!customAttribute.mAwaitingValidation)
  10485. continue;
  10486. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  10487. {
  10488. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  10489. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  10490. }
  10491. customAttribute.mAwaitingValidation = false;
  10492. }
  10493. }
  10494. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10495. {
  10496. bool allowNonConstArgs = (flags & BfGetCustomAttributesFlags_AllowNonConstArgs) != 0;
  10497. bool keepConstsInModule = (flags & BfGetCustomAttributesFlags_KeepConstsInModule) != 0;
  10498. if (!mCompiler->mHasRequiredTypes)
  10499. return;
  10500. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  10501. {
  10502. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  10503. sourceClassifier->VisitChild(attributesDirective);
  10504. }
  10505. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  10506. if (mCompiler->IsAutocomplete())
  10507. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  10508. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  10509. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  10510. BfTypeDef* activeTypeDef = GetActiveTypeDef();
  10511. BfAutoComplete* autoComplete = NULL;
  10512. if (mCompiler->mResolvePassData != NULL)
  10513. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  10514. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  10515. {
  10516. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  10517. {
  10518. if (captureInfo == NULL)
  10519. {
  10520. Fail("Capture specifiers can only be used in lambda allocations", tokenNode);
  10521. continue;
  10522. }
  10523. BfCaptureInfo::Entry captureEntry;
  10524. captureEntry.mRefNode = tokenNode;
  10525. captureEntry.mCaptureType = BfCaptureType_Copy;
  10526. if (tokenNode->mToken == BfToken_Ampersand)
  10527. captureEntry.mCaptureType = BfCaptureType_Reference;
  10528. if (tokenNode->mToken == BfToken_Question)
  10529. captureEntry.mCaptureType = BfCaptureType_Auto;
  10530. if (!attributesDirective->mArguments.IsEmpty())
  10531. {
  10532. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]))
  10533. captureEntry.mNameNode = identifierNode;
  10534. else if (auto thisExpr = BfNodeDynCast<BfThisExpression>(attributesDirective->mArguments[0]))
  10535. {
  10536. captureEntry.mNameNode = thisExpr;
  10537. }
  10538. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  10539. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  10540. }
  10541. captureInfo->mCaptures.Add(captureEntry);
  10542. continue;
  10543. }
  10544. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  10545. BfCustomAttribute customAttribute;
  10546. customAttribute.mAwaitingValidation = true;
  10547. customAttribute.mDeclaringType = activeTypeDef;
  10548. customAttribute.mRef = attributesDirective;
  10549. if (attributesDirective->mAttrOpenToken != NULL)
  10550. targetOverride = (BfAttributeTargets)0;
  10551. if (attributesDirective->mAttributeTypeRef == NULL)
  10552. {
  10553. AssertErrorState();
  10554. continue;
  10555. }
  10556. BfType* attrType;
  10557. if (mContext->mCurTypeState != NULL)
  10558. {
  10559. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10560. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10561. }
  10562. else
  10563. {
  10564. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10565. }
  10566. BfTypeDef* attrTypeDef = NULL;
  10567. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  10568. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  10569. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10570. {
  10571. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  10572. if (attrTypeDef != NULL)
  10573. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  10574. }
  10575. bool isBypassedAttr = false;
  10576. if (attrTypeDef != NULL)
  10577. {
  10578. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  10579. // We solve it by having a 'bypass' for known attributes that Object depends on
  10580. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  10581. {
  10582. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  10583. {
  10584. for (auto methodDef : attrTypeDef->mMethods)
  10585. {
  10586. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  10587. {
  10588. customAttribute.mType = attrType->ToTypeInstance();
  10589. customAttribute.mCtor = methodDef;
  10590. isBypassedAttr = true;
  10591. break;
  10592. }
  10593. }
  10594. }
  10595. }
  10596. if (isBypassedAttr)
  10597. {
  10598. customAttribute.mAwaitingValidation = false;
  10599. customAttributes->mAttributes.push_back(customAttribute);
  10600. continue;
  10601. }
  10602. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInst(mContext->mUnreifiedModule->mCurTypeInstance, mCurTypeInstance);
  10603. SetAndRestoreValue<BfMethodInstance*> prevCurMethodInst(mContext->mUnreifiedModule->mCurMethodInstance, mCurMethodInstance);
  10604. if (mContext->mCurTypeState != NULL)
  10605. {
  10606. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10607. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10608. }
  10609. else
  10610. {
  10611. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10612. }
  10613. }
  10614. BfTypeInstance* attrTypeInst = NULL;
  10615. if (attrType == NULL)
  10616. continue;
  10617. attrTypeInst = attrType->ToTypeInstance();
  10618. if ((attrTypeInst != NULL) && (attrTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting))
  10619. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  10620. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  10621. {
  10622. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  10623. continue;
  10624. }
  10625. if ((mIsReified) && (attrTypeInst->mAttributeData != NULL) && ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_ReflectAttribute) != 0))
  10626. {
  10627. // Reify attribute
  10628. PopulateType(attrTypeInst);
  10629. }
  10630. if (mCurTypeInstance != NULL)
  10631. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10632. customAttribute.mType = attrTypeInst;
  10633. bool allocatedMethodState = NULL;
  10634. defer(
  10635. {
  10636. if (allocatedMethodState)
  10637. {
  10638. delete mCurMethodState;
  10639. mCurMethodState = NULL;
  10640. }
  10641. });
  10642. if (mCurMethodState == NULL)
  10643. {
  10644. allocatedMethodState = true;
  10645. mCurMethodState = new BfMethodState();
  10646. mCurMethodState->mTempKind = BfMethodState::TempKind_Static;
  10647. }
  10648. BfConstResolver constResolver(this);
  10649. if (allowNonConstArgs)
  10650. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  10651. bool inPropSet = false;
  10652. SizedArray<BfResolvedArg, 2> argValues;
  10653. for (BfExpression* arg : attributesDirective->mArguments)
  10654. {
  10655. if (arg == NULL)
  10656. {
  10657. continue;
  10658. }
  10659. if (autoComplete != NULL)
  10660. autoComplete->mShowAttributeProperties = attrTypeInst;
  10661. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  10662. {
  10663. inPropSet = true;
  10664. if (autoComplete != NULL)
  10665. autoComplete->CheckNode(assignExpr->mLeft, true);
  10666. String findName = assignExpr->mLeft->ToString();
  10667. BfPropertyDef* bestProp = NULL;
  10668. BfTypeInstance* bestPropTypeInst = NULL;
  10669. BfFieldDef* bestField = NULL;
  10670. BfTypeInstance* bestFieldTypeInst = NULL;
  10671. auto checkTypeInst = attrTypeInst;
  10672. while (checkTypeInst != NULL)
  10673. {
  10674. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  10675. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  10676. {
  10677. if (prop->mName == findName)
  10678. {
  10679. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  10680. {
  10681. bestProp = prop;
  10682. bestPropTypeInst = checkTypeInst;
  10683. }
  10684. }
  10685. }
  10686. for (auto field : checkTypeInst->mTypeDef->mFields)
  10687. {
  10688. if (field->mName == findName)
  10689. {
  10690. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  10691. {
  10692. bestField = field;
  10693. bestFieldTypeInst = checkTypeInst;
  10694. }
  10695. }
  10696. }
  10697. if ((bestProp != NULL) || (bestField != NULL))
  10698. break;
  10699. checkTypeInst = checkTypeInst->mBaseType;
  10700. }
  10701. bool handledExpr = false;
  10702. if (bestField != NULL)
  10703. {
  10704. handledExpr = true;
  10705. if (mCompiler->mResolvePassData != NULL)
  10706. {
  10707. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  10708. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10709. {
  10710. autoComplete->mDefField = bestField;
  10711. autoComplete->mDefType = attrTypeDef;
  10712. }
  10713. }
  10714. if (bestField->mProtection != BfProtection_Public)
  10715. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10716. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10717. BfCustomAttributeSetField setField;
  10718. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  10719. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  10720. if (assignExpr->mRight != NULL)
  10721. {
  10722. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType, BfConstResolveFlag_NoActualizeValues);
  10723. if (result)
  10724. {
  10725. if (!keepConstsInModule)
  10726. CurrentAddToConstHolder(result.mValue);
  10727. setField.mParam = result;
  10728. customAttribute.mSetField.push_back(setField);
  10729. }
  10730. }
  10731. }
  10732. else if (bestProp == NULL)
  10733. {
  10734. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  10735. }
  10736. else
  10737. {
  10738. BfMethodDef* setMethod = NULL;
  10739. for (auto methodDef : bestProp->mMethods)
  10740. {
  10741. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10742. {
  10743. setMethod = methodDef;
  10744. break;
  10745. }
  10746. }
  10747. if (setMethod == NULL)
  10748. {
  10749. Fail("Property has no setter", assignExpr->mLeft);
  10750. }
  10751. else
  10752. {
  10753. if (mCompiler->mResolvePassData != NULL)
  10754. {
  10755. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  10756. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10757. {
  10758. autoComplete->mDefProp = bestProp;
  10759. autoComplete->mDefType = attrTypeDef;
  10760. }
  10761. }
  10762. handledExpr = true;
  10763. if (bestProp->mProtection != BfProtection_Public)
  10764. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10765. BfResolvedArg resolvedArg;
  10766. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10767. BfCustomAttributeSetProperty setProperty;
  10768. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  10769. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  10770. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  10771. if (methodInstance.mMethodInstance != NULL)
  10772. {
  10773. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  10774. if (assignExpr->mRight != NULL)
  10775. {
  10776. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType, BfConstResolveFlag_NoActualizeValues);
  10777. if ((result) && (!result.mType->IsVar()))
  10778. {
  10779. if (!result.mValue.IsConst())
  10780. result = GetDefaultTypedValue(result.mType);
  10781. BF_ASSERT(result.mType == propType);
  10782. if (!keepConstsInModule)
  10783. CurrentAddToConstHolder(result.mValue);
  10784. setProperty.mParam = result;
  10785. customAttribute.mSetProperties.push_back(setProperty);
  10786. }
  10787. }
  10788. }
  10789. }
  10790. }
  10791. if ((!handledExpr) && (assignExpr->mRight != NULL))
  10792. constResolver.Resolve(assignExpr->mRight, NULL, BfConstResolveFlag_NoActualizeValues);
  10793. }
  10794. else
  10795. {
  10796. if (inPropSet)
  10797. {
  10798. Fail("Named attribute argument expected", arg); // CS1016
  10799. }
  10800. BfDeferEvalChecker deferEvalChecker;
  10801. arg->Accept(&deferEvalChecker);
  10802. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  10803. BfResolvedArg resolvedArg;
  10804. resolvedArg.mExpression = arg;
  10805. if (deferParamEval)
  10806. {
  10807. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  10808. }
  10809. else
  10810. resolvedArg.mTypedValue = constResolver.Resolve(arg, NULL, BfConstResolveFlag_NoActualizeValues);
  10811. if (!inPropSet)
  10812. {
  10813. argValues.push_back(resolvedArg);
  10814. }
  10815. }
  10816. if (autoComplete != NULL)
  10817. autoComplete->mShowAttributeProperties = NULL;
  10818. }
  10819. auto wasCapturingMethodInfo = false;
  10820. if (autoComplete != NULL)
  10821. {
  10822. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  10823. if (attributesDirective->mCtorOpenParen != NULL)
  10824. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  10825. }
  10826. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, BfMethodGenericArguments());
  10827. methodMatcher.mBfEvalExprFlags = constResolver.mBfEvalExprFlags;
  10828. attrTypeDef = attrTypeInst->mTypeDef;
  10829. bool success = true;
  10830. bool isFailurePass = false;
  10831. for (int pass = 0; pass < 2; pass++)
  10832. {
  10833. bool isFailurePass = pass == 1;
  10834. for (auto checkMethod : attrTypeDef->mMethods)
  10835. {
  10836. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  10837. continue; // Don't match private default ctor if there's a user-defined one
  10838. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  10839. continue;
  10840. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  10841. continue;
  10842. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  10843. }
  10844. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  10845. break;
  10846. }
  10847. if (autoComplete != NULL)
  10848. {
  10849. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  10850. {
  10851. autoComplete->mIsCapturingMethodMatchInfo = true;
  10852. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  10853. }
  10854. else
  10855. autoComplete->mIsCapturingMethodMatchInfo = false;
  10856. }
  10857. if (methodMatcher.mBestMethodDef == NULL)
  10858. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  10859. if (methodMatcher.mBestMethodDef == NULL)
  10860. {
  10861. AssertErrorState();
  10862. continue;
  10863. }
  10864. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  10865. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  10866. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  10867. {
  10868. Fail("Custom attribute circular reference", attributesDirective);
  10869. }
  10870. if (mCurTypeInstance != NULL)
  10871. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10872. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  10873. success = false;
  10874. for (auto& arg : argValues)
  10875. {
  10876. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  10877. {
  10878. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  10879. constResolver.Resolve(expr, NULL, BfConstResolveFlag_NoActualizeValues);
  10880. }
  10881. }
  10882. // Move all those to the constHolder
  10883. if (!keepConstsInModule)
  10884. {
  10885. for (auto& ctorArg : customAttribute.mCtorArgs)
  10886. {
  10887. if (ctorArg.IsConst())
  10888. CurrentAddToConstHolder(ctorArg);
  10889. }
  10890. }
  10891. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  10892. {
  10893. targetOverride = BfAttributeTargets_ReturnValue;
  10894. if (attrTarget != BfAttributeTargets_Method)
  10895. {
  10896. 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.",
  10897. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  10898. success = false;
  10899. }
  10900. }
  10901. if ((success) && (targetOverride != (BfAttributeTargets)0))
  10902. {
  10903. if ((mCurMethodInstance != NULL) && (targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  10904. {
  10905. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  10906. if (methodInfoEx->mMethodCustomAttributes == NULL)
  10907. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  10908. if (success)
  10909. {
  10910. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  10911. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  10912. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  10913. }
  10914. }
  10915. // Mark as failed since we don't actually want to add this to the custom attributes set
  10916. success = false;
  10917. }
  10918. if (success)
  10919. {
  10920. if ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_DisallowAllowMultiple) != 0)
  10921. {
  10922. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  10923. {
  10924. if (prevCustomAttribute.mType == attrTypeInst)
  10925. {
  10926. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToCleanAttributeString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  10927. }
  10928. }
  10929. }
  10930. }
  10931. if (success)
  10932. {
  10933. customAttributes->mAttributes.push_back(customAttribute);
  10934. }
  10935. }
  10936. ValidateCustomAttributes(customAttributes, attrTarget);
  10937. }
  10938. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10939. {
  10940. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  10941. GetCustomAttributes(customAttributes, attributesDirective, attrType, flags, captureInfo);
  10942. return customAttributes;
  10943. }
  10944. BfCustomAttributes* BfModule::GetCustomAttributes(BfTypeDef* typeDef)
  10945. {
  10946. BF_ASSERT(mCompiler->IsAutocomplete());
  10947. BfAttributeTargets attrTarget;
  10948. if (typeDef->mIsDelegate)
  10949. attrTarget = BfAttributeTargets_Delegate;
  10950. else if (typeDef->mIsFunction)
  10951. attrTarget = BfAttributeTargets_Function;
  10952. else if (typeDef->mTypeCode == BfTypeCode_Enum)
  10953. attrTarget = BfAttributeTargets_Enum;
  10954. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  10955. attrTarget = BfAttributeTargets_Interface;
  10956. else if (typeDef->mTypeCode == BfTypeCode_Struct)
  10957. attrTarget = BfAttributeTargets_Struct;
  10958. else if (typeDef->mTypeCode == BfTypeCode_Extension)
  10959. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Struct | BfAttributeTargets_Class | BfAttributeTargets_Interface | BfAttributeTargets_Enum);
  10960. else
  10961. attrTarget = BfAttributeTargets_Class;
  10962. return GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  10963. }
  10964. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  10965. {
  10966. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  10967. Warn(0, "Unused attributes", attributeState->mSrc);
  10968. }
  10969. void BfModule::ProcessTypeInstCustomAttributes(int& packing, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  10970. {
  10971. if (mCurTypeInstance->mTypeDef->mIsAlwaysInclude)
  10972. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  10973. if (mCurTypeInstance->mCustomAttributes != NULL)
  10974. {
  10975. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  10976. {
  10977. String typeName = TypeToString(customAttribute.mType);
  10978. if (typeName == "System.PackedAttribute")
  10979. {
  10980. packing = 1;
  10981. if (customAttribute.mCtorArgs.size() >= 1)
  10982. {
  10983. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10984. int checkPacking = alignConstant->mInt32;
  10985. if (((checkPacking & (checkPacking - 1)) == 0) && (packing > 0) && (packing < 256))
  10986. packing = checkPacking;
  10987. else
  10988. Fail("Packing must be a power of 2", customAttribute.GetRefNode());
  10989. }
  10990. }
  10991. else if (typeName == "System.UnionAttribute")
  10992. {
  10993. isUnion = true;
  10994. }
  10995. else if (typeName == "System.CReprAttribute")
  10996. {
  10997. isCRepr = true;
  10998. isOrdered = true;
  10999. }
  11000. else if (typeName == "System.OrderedAttribute")
  11001. {
  11002. isOrdered = true;
  11003. }
  11004. else if (typeName == "System.AlwaysIncludeAttribute")
  11005. {
  11006. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11007. for (auto setProp : customAttribute.mSetProperties)
  11008. {
  11009. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  11010. if (propertyDef->mName == "AssumeInstantiated")
  11011. {
  11012. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11013. if ((constant != NULL) && (constant->mBool))
  11014. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_AssumeInstantiated);
  11015. }
  11016. else if (propertyDef->mName == "IncludeAllMethods")
  11017. {
  11018. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11019. if ((constant != NULL) && (constant->mBool))
  11020. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_IncludeAllMethods);
  11021. }
  11022. }
  11023. }
  11024. else if (typeName == "System.AlignAttribute")
  11025. {
  11026. if (customAttribute.mCtorArgs.size() >= 1)
  11027. {
  11028. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11029. int checkAlign = alignConstant->mInt32;
  11030. if ((checkAlign & (checkAlign - 1)) == 0)
  11031. alignOverride = checkAlign;
  11032. else
  11033. Fail("Alignment must be a power of 2", customAttribute.GetRefNode());
  11034. }
  11035. }
  11036. else if (typeName == "System.UnderlyingArrayAttribute")
  11037. {
  11038. if (customAttribute.mCtorArgs.size() >= 2)
  11039. {
  11040. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11041. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  11042. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  11043. {
  11044. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  11045. underlyingArraySize = sizeConstant->mInt32;
  11046. }
  11047. }
  11048. }
  11049. if (customAttribute.mType->mAttributeData == NULL)
  11050. PopulateType(customAttribute.mType);
  11051. BF_ASSERT(customAttribute.mType->mAttributeData != NULL);
  11052. if ((customAttribute.mType->mAttributeData != NULL) && ((customAttribute.mType->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0))
  11053. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | customAttribute.mType->mAttributeData->mAlwaysIncludeUser);
  11054. }
  11055. }
  11056. }
  11057. // Checking to see if we're an attribute or not
  11058. void BfModule::ProcessCustomAttributeData()
  11059. {
  11060. if (mCurTypeInstance->mAttributeData != NULL)
  11061. return;
  11062. bool isAttribute = false;
  11063. auto checkTypeInst = mCurTypeInstance->mBaseType;
  11064. while (checkTypeInst != NULL)
  11065. {
  11066. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  11067. isAttribute = true;
  11068. checkTypeInst = checkTypeInst->mBaseType;
  11069. }
  11070. if (!isAttribute)
  11071. return;
  11072. auto attributeData = new BfAttributeData();
  11073. bool hasCustomAttribute = false;
  11074. if (mCurTypeInstance->mCustomAttributes != NULL)
  11075. {
  11076. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11077. {
  11078. if (customAttribute.mType->IsInstanceOf(mCompiler->mAttributeUsageAttributeTypeDef))
  11079. {
  11080. if (customAttribute.mCtorArgs.size() > 0)
  11081. {
  11082. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11083. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11084. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11085. }
  11086. if (customAttribute.mCtorArgs.size() == 2)
  11087. {
  11088. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11089. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11090. {
  11091. attributeData->mFlags = (BfAttributeFlags)constant->mInt32;
  11092. }
  11093. }
  11094. for (auto& setProp : customAttribute.mSetProperties)
  11095. {
  11096. BfPropertyDef* propDef = setProp.mPropertyRef;
  11097. if (propDef->mName == "AllowMultiple")
  11098. {
  11099. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11100. if ((constant != NULL) && (constant->mBool))
  11101. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_DisallowAllowMultiple);
  11102. else
  11103. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_DisallowAllowMultiple);
  11104. }
  11105. else if (propDef->mName == "Inherited")
  11106. {
  11107. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11108. if ((constant != NULL) && (constant->mBool))
  11109. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_NotInherited);
  11110. else
  11111. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_NotInherited);
  11112. }
  11113. else if (propDef->mName == "ValidOn")
  11114. {
  11115. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11116. if (constant != NULL)
  11117. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11118. }
  11119. else if (propDef->mName == "AlwaysIncludeUser")
  11120. {
  11121. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11122. if (constant != NULL)
  11123. attributeData->mAlwaysIncludeUser = (BfAlwaysIncludeFlags)constant->mInt32;
  11124. }
  11125. }
  11126. hasCustomAttribute = true;
  11127. }
  11128. }
  11129. }
  11130. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  11131. {
  11132. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  11133. attributeData->mFlags = mCurTypeInstance->mBaseType->mAttributeData->mFlags;
  11134. attributeData->mAlwaysIncludeUser = mCurTypeInstance->mBaseType->mAttributeData->mAlwaysIncludeUser;
  11135. }
  11136. mCurTypeInstance->mAttributeData = attributeData;
  11137. }
  11138. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  11139. {
  11140. auto constant = constHolder->GetConstant(irValue);
  11141. if (constant == NULL)
  11142. return false;
  11143. if (constant->mTypeCode != BfTypeCode_StringId)
  11144. return false;
  11145. int stringId = constant->mInt32;
  11146. BfStringPoolEntry* entry = NULL;
  11147. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  11148. {
  11149. str += entry->mString;
  11150. }
  11151. else
  11152. {
  11153. BF_DBG_FATAL("Failed to find string by id");
  11154. }
  11155. return true;
  11156. }
  11157. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  11158. {
  11159. BfVariant variant;
  11160. variant.mTypeCode = BfTypeCode_None;
  11161. BfType* primType = NULL;
  11162. if (value.mType->IsPrimitiveType())
  11163. primType = (BfPrimitiveType*)value.mType;
  11164. else if (value.mType->IsTypedPrimitive())
  11165. primType = value.mType->GetUnderlyingType();
  11166. else if (value.mType->IsInstanceOf(mCompiler->mStringTypeDef))
  11167. primType = value.mType;
  11168. if (primType)
  11169. {
  11170. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  11171. if (constant != NULL)
  11172. {
  11173. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  11174. {
  11175. variant.mUInt64 = 0;
  11176. variant.mTypeCode = BfTypeCode_Let;
  11177. return variant;
  11178. }
  11179. if (constant->mConstType == BfConstType_GlobalVar)
  11180. {
  11181. int stringIdx = GetStringPoolIdx(value.mValue, mBfIRBuilder);
  11182. if (stringIdx != -1)
  11183. {
  11184. variant.mTypeCode = BfTypeCode_StringId;
  11185. variant.mInt64 = stringIdx;
  11186. return variant;
  11187. }
  11188. }
  11189. switch (constant->mTypeCode)
  11190. {
  11191. case BfTypeCode_Boolean:
  11192. case BfTypeCode_Int8:
  11193. case BfTypeCode_UInt8:
  11194. case BfTypeCode_Int16:
  11195. case BfTypeCode_UInt16:
  11196. case BfTypeCode_Int32:
  11197. case BfTypeCode_UInt32:
  11198. case BfTypeCode_Int64:
  11199. case BfTypeCode_UInt64:
  11200. case BfTypeCode_IntPtr:
  11201. case BfTypeCode_UIntPtr:
  11202. case BfTypeCode_IntUnknown:
  11203. case BfTypeCode_UIntUnknown:
  11204. case BfTypeCode_Double:
  11205. case BfTypeCode_Char8:
  11206. case BfTypeCode_Char16:
  11207. case BfTypeCode_Char32:
  11208. case BfTypeCode_StringId:
  11209. variant.mTypeCode = constant->mTypeCode;
  11210. if (((variant.mTypeCode == BfTypeCode_Int64) || (variant.mTypeCode == BfTypeCode_UInt64)) &&
  11211. (primType->mSize > 0) && (primType->mSize < 8) &&
  11212. (mBfIRBuilder->IsIntable(primType->GetTypeCode())))
  11213. {
  11214. // We may have an 'int unknown' that we need to downsize
  11215. variant.mTypeCode = primType->GetTypeCode();
  11216. }
  11217. variant.mInt64 = constant->mInt64;
  11218. break;
  11219. case BfTypeCode_Float:
  11220. variant.mTypeCode = constant->mTypeCode;
  11221. variant.mSingle = (float)constant->mDouble;
  11222. break;
  11223. default:
  11224. if (refNode != NULL)
  11225. Fail("Invalid const expression type", refNode);
  11226. break;
  11227. }
  11228. }
  11229. }
  11230. else
  11231. {
  11232. BfVariant::StructData* structData = (BfVariant::StructData*)(new uint8[value.mType->mSize + 4]);
  11233. structData->mSize = value.mType->mSize;
  11234. mBfIRBuilder->WriteConstant(value.mValue, structData->mData, value.mType);
  11235. variant.mTypeCode = BfTypeCode_Struct;
  11236. variant.mPtr = structData;
  11237. }
  11238. return variant;
  11239. }
  11240. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  11241. {
  11242. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  11243. {
  11244. auto refType = (BfRefType*)typedValue.mType;
  11245. auto elementType = typedValue.mType->GetUnderlyingType();
  11246. if (typedValue.IsAddr())
  11247. {
  11248. if (elementType->IsValuelessType())
  11249. {
  11250. BF_ASSERT(!typedValue.mValue);
  11251. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11252. }
  11253. else
  11254. typedValue = BfTypedValue(mBfIRBuilder->CreateAlignedLoad(typedValue.mValue, elementType->mAlign), elementType, true);
  11255. }
  11256. else
  11257. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11258. if (typedValue.mType->IsValuelessType())
  11259. {
  11260. BF_ASSERT(typedValue.mValue.IsFake());
  11261. }
  11262. if (refType->mRefKind == BfRefType::RefKind_In)
  11263. {
  11264. if (typedValue.mKind == BfTypedValueKind_Addr)
  11265. typedValue.mKind = BfTypedValueKind_ReadOnlyAddr;
  11266. }
  11267. }
  11268. return typedValue;
  11269. }
  11270. BfTypedValue BfModule::SanitizeAddr(BfTypedValue typedValue)
  11271. {
  11272. if (!typedValue)
  11273. return typedValue;
  11274. if (typedValue.mType->IsRef())
  11275. {
  11276. typedValue = LoadValue(typedValue);
  11277. auto copiedVal = BfTypedValue(CreateAlloca(typedValue.mType), typedValue.mType, true);
  11278. mBfIRBuilder->CreateStore(typedValue.mValue, copiedVal.mValue);
  11279. return copiedVal;
  11280. }
  11281. return typedValue;
  11282. }
  11283. BfTypedValue BfModule::ToRef(BfTypedValue typedValue, BfRefType* refType)
  11284. {
  11285. if (refType == NULL)
  11286. refType = CreateRefType(typedValue.mType);
  11287. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (typedValue.mType->IsObjectOrInterface()))
  11288. {
  11289. return LoadValue(typedValue);
  11290. }
  11291. if (refType->mRefKind == BfRefType::RefKind_Mut)
  11292. refType = CreateRefType(typedValue.mType);
  11293. if (!typedValue.mType->IsValuelessType())
  11294. typedValue = MakeAddressable(typedValue, false, true);
  11295. return BfTypedValue(typedValue.mValue, refType);
  11296. }
  11297. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  11298. {
  11299. if (!typedValue.IsAddr())
  11300. return typedValue;
  11301. PopulateType(typedValue.mType);
  11302. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  11303. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  11304. if (typedValue.mValue.IsConst())
  11305. {
  11306. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  11307. if (constantValue != NULL)
  11308. {
  11309. if (constantValue->mConstType == BfConstType_GlobalVar)
  11310. {
  11311. auto globalVar = (BfGlobalVar*)constantValue;
  11312. if (globalVar->mName[0] == '#')
  11313. {
  11314. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  11315. if (result)
  11316. {
  11317. // We want to avoid 'unreachable code' issues from values that
  11318. // are technically constant but change depending on compilation context
  11319. if (mCurMethodState != NULL)
  11320. {
  11321. auto checkScope = mCurMethodState->mCurScope;
  11322. while (checkScope != NULL)
  11323. {
  11324. checkScope->mSupressNextUnreachable = true;
  11325. checkScope = checkScope->mPrevScope;
  11326. }
  11327. }
  11328. return result;
  11329. }
  11330. if (!mIsComptimeModule)
  11331. return GetDefaultTypedValue(typedValue.mType);
  11332. }
  11333. }
  11334. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  11335. {
  11336. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  11337. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  11338. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  11339. auto ceTypedValue = ceDebugger->GetAddr(constantValue);
  11340. if (ceTypedValue)
  11341. {
  11342. if ((typedValue.mType->IsObjectOrInterface()) || (typedValue.mType->IsPointer()) || (typedValue.mType->IsRef()))
  11343. {
  11344. void* data = ceContext->GetMemoryPtr((addr_ce)ceTypedValue.mAddr, sizeof(addr_ce));
  11345. if (data == NULL)
  11346. {
  11347. Fail("Invalid address", refNode);
  11348. return GetDefaultTypedValue(typedValue.mType);
  11349. }
  11350. uint64 dataAddr;
  11351. if (mSystem->mPtrSize == 4)
  11352. dataAddr = *(uint32*)data;
  11353. else
  11354. dataAddr = *(uint64*)data;
  11355. return BfTypedValue(mBfIRBuilder->CreateIntToPtr(
  11356. mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataAddr), mBfIRBuilder->MapType(typedValue.mType)), typedValue.mType);
  11357. }
  11358. auto constVal = ceContext->CreateConstant(this, ceContext->mMemory.mVals + ceTypedValue.mAddr, typedValue.mType);
  11359. if (!constVal)
  11360. {
  11361. Fail("Failed to create const", refNode);
  11362. return GetDefaultTypedValue(typedValue.mType);
  11363. }
  11364. return BfTypedValue(constVal, typedValue.mType);
  11365. }
  11366. }
  11367. }
  11368. }
  11369. BfIRValue loadedVal = typedValue.mValue;
  11370. if (loadedVal)
  11371. {
  11372. if (typedValue.mType->IsVar())
  11373. {
  11374. return BfTypedValue(loadedVal, typedValue.mType, false);
  11375. }
  11376. PopulateType(typedValue.mType, BfPopulateType_Data);
  11377. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile || typedValue.IsVolatile());
  11378. }
  11379. return BfTypedValue(loadedVal, typedValue.mType, false);
  11380. }
  11381. BfTypedValue BfModule::PrepareConst(BfTypedValue& typedValue)
  11382. {
  11383. if (!typedValue.mValue.IsConst())
  11384. return typedValue;
  11385. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  11386. if (constant->mTypeCode == BfTypeCode_StringId)
  11387. return GetTypedValueFromConstant(constant, mBfIRBuilder, typedValue.mType);
  11388. return typedValue;
  11389. }
  11390. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  11391. {
  11392. if (typedValue.IsSplat())
  11393. return AggregateSplat(typedValue);
  11394. if (typedValue.IsAddr())
  11395. return LoadValue(typedValue);
  11396. return typedValue;
  11397. }
  11398. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  11399. {
  11400. if (!typedValue.IsSplat())
  11401. return typedValue;
  11402. BF_ASSERT(!mIsComptimeModule);
  11403. if (typedValue.mType->IsValuelessType())
  11404. return typedValue;
  11405. int elementIdx = 0;
  11406. auto _ExtractValue = [&](BfType* checkType)
  11407. {
  11408. if (valueArrPtr != NULL)
  11409. return valueArrPtr[elementIdx++];
  11410. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  11411. };
  11412. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11413. {
  11414. if (checkType->IsStruct())
  11415. {
  11416. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11417. auto checkTypeInstance = checkType->ToTypeInstance();
  11418. if (checkTypeInstance->mBaseType != NULL)
  11419. {
  11420. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  11421. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  11422. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  11423. }
  11424. if (checkTypeInstance->mIsUnion)
  11425. {
  11426. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11427. if (!unionInnerType->IsValuelessType())
  11428. {
  11429. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  11430. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  11431. }
  11432. if (checkTypeInstance->IsEnum())
  11433. {
  11434. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11435. BfIRValue fieldValue = checkTypeLambda(dscrType);
  11436. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  11437. }
  11438. }
  11439. else
  11440. {
  11441. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11442. {
  11443. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11444. if (fieldInstance->mDataIdx >= 0)
  11445. {
  11446. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  11447. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  11448. }
  11449. }
  11450. }
  11451. return curValue;
  11452. }
  11453. else if (checkType->IsMethodRef())
  11454. {
  11455. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11456. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11457. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11458. {
  11459. BfIRValue fieldValue;
  11460. auto checkType = methodRefType->GetCaptureType(dataIdx);
  11461. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11462. {
  11463. fieldValue = checkTypeLambda(checkType);
  11464. }
  11465. else
  11466. {
  11467. fieldValue = _ExtractValue(checkType);
  11468. }
  11469. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  11470. }
  11471. return curValue;
  11472. }
  11473. else if (!checkType->IsValuelessType())
  11474. {
  11475. return _ExtractValue(checkType);
  11476. }
  11477. return BfIRValue();
  11478. };
  11479. BfIRValue value = checkTypeLambda(typedValue.mType);
  11480. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  11481. }
  11482. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  11483. {
  11484. if (!typedValue.IsSplat())
  11485. return;
  11486. if (typedValue.mType->IsValuelessType())
  11487. return;
  11488. BF_ASSERT(!mIsComptimeModule);
  11489. /*static int sCallIdx = 0;
  11490. if (!mCompiler->mIsResolveOnly)
  11491. sCallIdx++;
  11492. int callIdx = sCallIdx;*/
  11493. int elementIdx = 0;
  11494. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  11495. {
  11496. if (checkType->IsStruct())
  11497. {
  11498. auto checkTypeInstance = checkType->ToTypeInstance();
  11499. if (checkTypeInstance->mBaseType != NULL)
  11500. {
  11501. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  11502. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  11503. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  11504. }
  11505. if (checkTypeInstance->mIsUnion)
  11506. {
  11507. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11508. if (!unionInnerType->IsValuelessType())
  11509. {
  11510. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  11511. checkTypeLambda(unionInnerType, fieldAddrVal);
  11512. }
  11513. if (checkTypeInstance->IsEnum())
  11514. {
  11515. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11516. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  11517. checkTypeLambda(dscrType, fieldAddrVal);
  11518. }
  11519. }
  11520. else
  11521. {
  11522. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11523. {
  11524. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11525. if (fieldInstance->mDataIdx >= 0)
  11526. {
  11527. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  11528. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  11529. }
  11530. }
  11531. }
  11532. }
  11533. else if (checkType->IsMethodRef())
  11534. {
  11535. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11536. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11537. {
  11538. auto dataType = methodRefType->GetCaptureType(dataIdx);
  11539. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  11540. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11541. {
  11542. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  11543. }
  11544. else
  11545. {
  11546. // static int sItrCount = 0;
  11547. // sItrCount++;
  11548. // int curItr = sItrCount;
  11549. // if (curItr == 1)
  11550. // {
  11551. // NOP;
  11552. // }
  11553. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  11554. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  11555. }
  11556. }
  11557. }
  11558. else if (!checkType->IsValuelessType())
  11559. {
  11560. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  11561. mBfIRBuilder->CreateStore(val, curAddrVal);
  11562. }
  11563. };
  11564. checkTypeLambda(typedValue.mType, addrVal);
  11565. }
  11566. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal, bool forceMutable, bool forceAddressable)
  11567. {
  11568. bool wasReadOnly = typedVal.IsReadOnly();
  11569. if ((forceAddressable) ||
  11570. ((typedVal.mType->IsValueType()) &&
  11571. (!typedVal.mType->IsValuelessType())))
  11572. {
  11573. wasReadOnly = true; // Any non-addr is implicitly read-only
  11574. //static int gCallIdx = 0;
  11575. FixValueActualization(typedVal);
  11576. if (typedVal.IsAddr())
  11577. return typedVal;
  11578. BfType* type = typedVal.mType;
  11579. PopulateType(type);
  11580. BfIRValue tempVar;
  11581. if (typedVal.mValue.IsFake())
  11582. tempVar = mBfIRBuilder->GetFakeVal();
  11583. else
  11584. {
  11585. tempVar = CreateAlloca(type);
  11586. if (typedVal.IsSplat())
  11587. AggregateSplatIntoAddr(typedVal, tempVar);
  11588. else
  11589. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  11590. }
  11591. if (forceMutable)
  11592. wasReadOnly = false;
  11593. return BfTypedValue(tempVar, type,
  11594. typedVal.IsThis() ?
  11595. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  11596. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  11597. }
  11598. return LoadValue(typedVal);
  11599. }
  11600. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  11601. {
  11602. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  11603. typedValue.mKind = BfTypedValueKind_Addr;
  11604. return typedValue;
  11605. }
  11606. BfTypedValue BfModule::CopyValue(const BfTypedValue& typedValue)
  11607. {
  11608. return MakeAddressable(LoadValue(typedValue), true);
  11609. }
  11610. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  11611. {
  11612. BF_ASSERT(!mIsComptimeModule);
  11613. BfIRValue val;
  11614. if (typedValue.mValue.IsArg())
  11615. {
  11616. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  11617. if (isAddr != NULL)
  11618. {
  11619. if (wantType != NULL)
  11620. *isAddr = wantType->IsComposite();
  11621. else
  11622. *isAddr = false;
  11623. }
  11624. else if (wantType->IsComposite())
  11625. val = mBfIRBuilder->CreateLoad(val);
  11626. }
  11627. if (!val)
  11628. {
  11629. auto checkMethodState = mCurMethodState;
  11630. while (checkMethodState != NULL)
  11631. {
  11632. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  11633. {
  11634. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  11635. if (decompAddr == typedValue.mValue)
  11636. {
  11637. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  11638. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  11639. {
  11640. // This is really backing for a POINTER to a composite inside a methodRef
  11641. val = mBfIRBuilder->CreateLoad(val);
  11642. }
  11643. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  11644. {
  11645. *isAddr = true;
  11646. return val;
  11647. }
  11648. else
  11649. {
  11650. val = mBfIRBuilder->CreateAlignedLoad(val, wantType->mAlign);
  11651. break;
  11652. }
  11653. }
  11654. }
  11655. if (val)
  11656. break;
  11657. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  11658. {
  11659. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  11660. return mBfIRBuilder->GetFakeVal();
  11661. }
  11662. checkMethodState = checkMethodState->mPrevMethodState;
  11663. }
  11664. }
  11665. if (val)
  11666. {
  11667. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  11668. {
  11669. BF_ASSERT(wantType != NULL);
  11670. if (wantType != NULL)
  11671. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  11672. }
  11673. return val;
  11674. }
  11675. BFMODULE_FATAL(this, "Splat not found");
  11676. return BfIRValue();
  11677. }
  11678. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  11679. {
  11680. int useFieldIdx = fieldIdx;
  11681. BfType* fieldType = NULL;
  11682. if (fieldInstance != NULL)
  11683. {
  11684. fieldType = fieldInstance->mResolvedType;
  11685. if (typedValue.mType->IsUnion())
  11686. {
  11687. if (fieldIdx == 1)
  11688. {
  11689. if (typedValue.IsSplat())
  11690. {
  11691. bool isAddr = false;
  11692. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  11693. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  11694. }
  11695. }
  11696. }
  11697. }
  11698. else
  11699. {
  11700. if (typedValue.mType->IsPayloadEnum())
  11701. {
  11702. auto typeInst = typedValue.mType->ToTypeInstance();
  11703. if (fieldIdx == 1)
  11704. fieldType = typeInst->GetUnionInnerType();
  11705. else if (fieldIdx == 2)
  11706. {
  11707. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  11708. }
  11709. }
  11710. else if (typedValue.mType->IsUnion())
  11711. {
  11712. if (fieldIdx == 1)
  11713. {
  11714. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  11715. if (typedValue.IsSplat())
  11716. {
  11717. bool isAddr = false;
  11718. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  11719. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  11720. }
  11721. }
  11722. }
  11723. }
  11724. BF_ASSERT(typedValue.mType->IsStruct());
  11725. if (typedValue.IsSplat())
  11726. {
  11727. if (typedValue.mType->IsPayloadEnum())
  11728. {
  11729. if (fieldIdx == 1)
  11730. {
  11731. // Payload
  11732. auto typeInst = typedValue.mType->ToTypeInstance();
  11733. auto unionInnerType = typeInst->GetUnionInnerType();
  11734. bool isAddr = false;
  11735. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  11736. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  11737. }
  11738. if (fieldIdx == 2)
  11739. {
  11740. // Discriminator
  11741. auto typeInst = typedValue.mType->ToTypeInstance();
  11742. auto unionInnerType = typeInst->GetUnionInnerType();
  11743. auto dscrType = typeInst->GetDiscriminatorType();
  11744. int argIdx = typedValue.mValue.mId;
  11745. int componentIdx = 0;
  11746. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  11747. bool isAddr;
  11748. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  11749. return BfTypedValue(irVal, dscrType, isAddr);
  11750. }
  11751. }
  11752. int componentIdx = 0;
  11753. BfTypedValue retVal;
  11754. BfFieldInstance* wantFieldInstance = fieldInstance;
  11755. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11756. {
  11757. if (checkType->IsStruct())
  11758. {
  11759. auto checkTypeInstance = checkType->ToTypeInstance();
  11760. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  11761. {
  11762. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  11763. fieldType = checkTypeInstance->GetUnionInnerType();
  11764. checkTypeLambda(fieldType);
  11765. if (checkType->IsEnum())
  11766. {
  11767. // Past discriminator...
  11768. componentIdx++;
  11769. }
  11770. return;
  11771. }
  11772. if (checkTypeInstance->mBaseType != NULL)
  11773. checkTypeLambda(checkTypeInstance->mBaseType);
  11774. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11775. {
  11776. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11777. if (fieldInstance == wantFieldInstance)
  11778. {
  11779. if (fieldInstance->mResolvedType->IsValuelessType())
  11780. {
  11781. retVal = GetDefaultTypedValue(fieldInstance->mResolvedType);
  11782. break;
  11783. }
  11784. bool isAddr = false;
  11785. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  11786. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  11787. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  11788. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  11789. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  11790. {
  11791. retVal = LoadValue(retVal);
  11792. }
  11793. break;
  11794. }
  11795. if (fieldInstance->mDataIdx >= 0)
  11796. checkTypeLambda(fieldInstance->GetResolvedType());
  11797. }
  11798. }
  11799. else if (!checkType->IsValuelessType())
  11800. {
  11801. componentIdx++;
  11802. //argIdx++;
  11803. }
  11804. };
  11805. checkTypeLambda(typedValue.mType);
  11806. BF_ASSERT(retVal);
  11807. return retVal;
  11808. }
  11809. if (typedValue.IsAddr())
  11810. {
  11811. BF_ASSERT(fieldType != NULL);
  11812. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  11813. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  11814. }
  11815. else
  11816. {
  11817. BF_ASSERT(fieldType != NULL);
  11818. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  11819. }
  11820. }
  11821. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  11822. {
  11823. if (typedValue.IsAddr())
  11824. {
  11825. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  11826. return mBfIRBuilder->CreateAlignedLoad(addrVal, typedValue.mType->mAlign);
  11827. }
  11828. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  11829. }
  11830. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  11831. {
  11832. if (isElementIndex)
  11833. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11834. else
  11835. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11836. // if (elementType->IsSizeAligned())
  11837. // {
  11838. // if (isElementIndex)
  11839. // return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11840. // else
  11841. // return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11842. // }
  11843. //
  11844. // auto ptrType = CreatePointerType(elementType);
  11845. // auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  11846. // auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  11847. // auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  11848. // BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  11849. // BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  11850. // return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  11851. }
  11852. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  11853. {
  11854. if (elementType->IsSizeAligned())
  11855. {
  11856. if (isElementIndex)
  11857. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  11858. else
  11859. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11860. }
  11861. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  11862. }
  11863. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  11864. {
  11865. if (modifyType == NULL)
  11866. modifyType = "modify";
  11867. if (typedValue.mType->IsVar())
  11868. return true;
  11869. if (typedValue.IsReadOnly())
  11870. {
  11871. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  11872. return false;
  11873. }
  11874. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  11875. {
  11876. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  11877. return false;
  11878. }
  11879. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  11880. {
  11881. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  11882. return false;
  11883. }
  11884. return true;
  11885. }
  11886. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  11887. {
  11888. // If one is an interface and the other is an impl, B is the impl
  11889. auto implOwner = methodB->GetOwner();
  11890. if (methodA->mMethodDef->mIsLocalMethod)
  11891. {
  11892. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  11893. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  11894. if (sepPosA != sepPosB)
  11895. return false;
  11896. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  11897. return false;
  11898. }
  11899. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  11900. return false;
  11901. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  11902. return false;
  11903. if (methodA->mMethodDef->mHasComptime != methodB->mMethodDef->mHasComptime)
  11904. return false;
  11905. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  11906. return false;
  11907. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  11908. {
  11909. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  11910. return false;
  11911. }
  11912. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  11913. {
  11914. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  11915. return false;
  11916. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  11917. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  11918. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  11919. return false;
  11920. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  11921. return false;
  11922. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  11923. return false;
  11924. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  11925. {
  11926. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  11927. return false;
  11928. }
  11929. }
  11930. int implicitParamCountA = methodA->GetImplicitParamCount();
  11931. int implicitParamCountB = methodB->GetImplicitParamCount();
  11932. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  11933. return false;
  11934. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  11935. return false;
  11936. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  11937. {
  11938. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  11939. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  11940. return false;
  11941. }
  11942. // Compare generic params. Generic params are part of the method signature here
  11943. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  11944. return false;
  11945. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  11946. {
  11947. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  11948. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  11949. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  11950. return false;
  11951. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  11952. return false;
  11953. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  11954. return false;
  11955. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  11956. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  11957. return false;
  11958. }
  11959. return true;
  11960. }
  11961. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  11962. {
  11963. if (!CompareMethodSignatures(methodA, methodB))
  11964. return false;
  11965. if (methodA->mReturnType != methodB->mReturnType)
  11966. return false;
  11967. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  11968. return false;
  11969. return true;
  11970. }
  11971. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  11972. {
  11973. if ((iMethodInst->GetNumGenericParams() != 0) || (methodInstance->GetNumGenericParams() != 0))
  11974. return false;
  11975. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  11976. return false;
  11977. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  11978. return false;
  11979. if (iMethodInst->mMethodDef->mIsOperator)
  11980. {
  11981. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  11982. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  11983. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  11984. return false;
  11985. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  11986. return false;
  11987. }
  11988. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  11989. return false;
  11990. auto selfType = methodInstance->GetOwner();
  11991. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  11992. {
  11993. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  11994. return false;
  11995. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  11996. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  11997. iParamType = ResolveSelfType(iParamType, selfType);
  11998. methodParamType = ResolveSelfType(methodParamType, selfType);
  11999. if (!iParamType->IsGenericParam())
  12000. {
  12001. if (methodParamType != iParamType)
  12002. return false;
  12003. }
  12004. else
  12005. {
  12006. if (!methodParamType->IsGenericParam())
  12007. return false;
  12008. auto genericParamType = (BfGenericParamType*)methodParamType;
  12009. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  12010. return false;
  12011. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12012. bool hadInterface = false;
  12013. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  12014. if (interfaceConstraint == iParamType)
  12015. hadInterface = true;
  12016. if (!hadInterface)
  12017. return false;
  12018. }
  12019. }
  12020. return true;
  12021. }
  12022. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  12023. {
  12024. BfMethodInstance* methodInstance = methodRef;
  12025. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  12026. {
  12027. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  12028. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  12029. {
  12030. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  12031. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  12032. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12033. BfMethodRef methodRef = methodInstance;
  12034. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  12035. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  12036. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  12037. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  12038. (mIsReified))
  12039. {
  12040. specializedMethodRefInfo->mHasReifiedRef = true;
  12041. }
  12042. }
  12043. }
  12044. }
  12045. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  12046. {
  12047. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  12048. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12049. if (mBfIRBuilder == NULL)
  12050. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12051. if (methodInstance->GetOwner()->IsFunction())
  12052. {
  12053. // No actual ref needed- not an actual generated function
  12054. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12055. }
  12056. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  12057. if (!isGenFunction)
  12058. AddMethodReference(methodInstance, flags);
  12059. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  12060. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  12061. if (IsSkippingExtraResolveChecks())
  12062. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12063. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  12064. {
  12065. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12066. }
  12067. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12068. if ((methodInstance->mIsIntrinsic) || (methodInstance->mMethodDef->mIsExtern))
  12069. isInlined = false;
  12070. BfMethodRef methodRef = methodInstance;
  12071. if (isInlined)
  12072. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  12073. else
  12074. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  12075. if (!isGenFunction)
  12076. {
  12077. BfIRValue* irFuncPtr = NULL;
  12078. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  12079. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  12080. }
  12081. if (mAwaitingInitFinish)
  12082. FinishInit();
  12083. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  12084. if (!isGenFunction)
  12085. {
  12086. BF_ASSERT(func || methodInstance->mMethodInstanceGroup->mOwner->IsInterface());
  12087. mFuncReferences[methodRef] = func;
  12088. }
  12089. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  12090. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12091. {
  12092. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  12093. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  12094. // type instance
  12095. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  12096. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  12097. for (auto ownedTypeInst : mOwnedTypeInstances)
  12098. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  12099. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  12100. {
  12101. mIncompleteMethodCount++;
  12102. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12103. inlineMethodRequest->mType = methodInstance->GetOwner();
  12104. inlineMethodRequest->mFromModule = this;
  12105. inlineMethodRequest->mFunc = func;
  12106. inlineMethodRequest->mFromModuleRevision = mRevision;
  12107. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  12108. inlineMethodRequest->mMethodInstance = methodInstance;
  12109. BF_ASSERT(mIsModuleMutable);
  12110. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12111. }
  12112. }
  12113. return BfModuleMethodInstance(methodInstance, func);
  12114. }
  12115. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  12116. {
  12117. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  12118. if (mBfIRBuilder == NULL)
  12119. {
  12120. // To allow for custom attribute data
  12121. PrepareForIRWriting(typeInst);
  12122. }
  12123. BfModule* declareModule = this;
  12124. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  12125. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  12126. declareModule = declareModule->mParentModule;
  12127. // Check for attributes
  12128. if (typeInst == mContext->mBfObjectType)
  12129. {
  12130. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  12131. if (methodDecl != NULL)
  12132. {
  12133. auto attributesDirective = methodDecl->mAttributes;
  12134. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  12135. {
  12136. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  12137. sourceClassifier->VisitChild(attributesDirective);
  12138. }
  12139. }
  12140. }
  12141. else
  12142. {
  12143. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  12144. GetMethodCustomAttributes(methodInstance);
  12145. }
  12146. BF_ASSERT(mModuleOptions == NULL);
  12147. if (methodInstance->GetCustomAttributes() != NULL)
  12148. {
  12149. auto project = typeInst->mTypeDef->mProject;
  12150. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  12151. BfModuleOptions wantOptions = moduleOptions;
  12152. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  12153. if (typeOptions != NULL)
  12154. {
  12155. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  12156. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  12157. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  12158. }
  12159. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  12160. {
  12161. StringT<128> attrName;
  12162. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  12163. {
  12164. attrName.Clear();
  12165. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  12166. Array<int>* arrPtr;
  12167. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  12168. {
  12169. for (auto optionsIdx : *arrPtr)
  12170. {
  12171. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  12172. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  12173. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  12174. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  12175. }
  12176. }
  12177. }
  12178. }
  12179. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  12180. {
  12181. auto lastCheckModule = this;
  12182. auto checkModule = this->mNextAltModule;
  12183. while (checkModule != NULL)
  12184. {
  12185. if (*checkModule->mModuleOptions == wantOptions)
  12186. {
  12187. declareModule = checkModule;
  12188. break;
  12189. }
  12190. lastCheckModule = checkModule;
  12191. checkModule = checkModule->mNextAltModule;
  12192. }
  12193. // Not found?
  12194. if (declareModule == this)
  12195. {
  12196. String specModuleName = mModuleName + "@@";
  12197. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  12198. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  12199. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  12200. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  12201. declareModule = new BfModule(mContext, specModuleName);
  12202. declareModule->mProject = project;
  12203. declareModule->mModuleOptions = new BfModuleOptions();
  12204. *declareModule->mModuleOptions = wantOptions;
  12205. declareModule->mParentModule = lastCheckModule;
  12206. declareModule->Init();
  12207. lastCheckModule->mNextAltModule = declareModule;
  12208. }
  12209. }
  12210. }
  12211. declareModule->PrepareForIRWriting(typeInst);
  12212. return declareModule;
  12213. }
  12214. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType, BfModule* referencingModule)
  12215. {
  12216. if (methodDef->mMethodType == BfMethodType_Init)
  12217. return BfModuleMethodInstance();
  12218. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  12219. {
  12220. // Don't bother inlining for resolve-only
  12221. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12222. }
  12223. if (methodDef->mIsExtern)
  12224. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12225. bool processNow = false;
  12226. bool keepInCurrentModule = false;
  12227. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  12228. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  12229. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  12230. {
  12231. return BfModuleMethodInstance();
  12232. }
  12233. if (methodDef->mIsLocalMethod)
  12234. {
  12235. auto rootMethodState = mCurMethodState->GetRootMethodState();
  12236. BfLocalMethod* localMethod;
  12237. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  12238. {
  12239. // Handle the def in the correct method state
  12240. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  12241. }
  12242. BFMODULE_FATAL(this, "Cannot find local method");
  12243. return BfModuleMethodInstance();
  12244. }
  12245. #ifdef _DEBUG
  12246. for (auto arg : methodGenericArguments)
  12247. BF_ASSERT(!arg->IsVar());
  12248. #endif
  12249. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  12250. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  12251. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  12252. // a FinishInit
  12253. if ((typeInst->IsIncomplete()) &&
  12254. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  12255. {
  12256. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  12257. // for resolve-only because we don't differentiate between reified/unreified there
  12258. if ((methodDef->mIsStatic) /*&& (mIsComptimeModule)*/)
  12259. {
  12260. if (!typeInst->DefineStateAllowsStaticMethods())
  12261. PopulateType(typeInst, BfPopulateType_AllowStaticMethods);
  12262. }
  12263. else
  12264. PopulateType(typeInst, BfPopulateType_Full);
  12265. if (typeInst->mDefineState < BfTypeDefineState_Defined)
  12266. {
  12267. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12268. {
  12269. BfLogSysM("GetMethodInstance (DefineState < BfTypeDefineState_Defined)) bailing due to IsCePaused\n");
  12270. return BfModuleMethodInstance();
  12271. }
  12272. }
  12273. }
  12274. bool tryModuleMethodLookup = false;
  12275. BfModuleMethodInstance moduleMethodInst;
  12276. BfModule* instModule = typeInst->mModule;
  12277. if (keepInCurrentModule)
  12278. {
  12279. // Stay here
  12280. instModule = this;
  12281. }
  12282. if (this == mContext->mUnreifiedModule)
  12283. {
  12284. // Stay in this 'resolve only' module here
  12285. }
  12286. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  12287. {
  12288. BF_ASSERT(this == mContext->mUnreifiedModule);
  12289. }
  12290. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  12291. {
  12292. BF_ASSERT(instModule == mParentModule);
  12293. }
  12294. else if (instModule != this)
  12295. {
  12296. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12297. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  12298. if ((!mIsComptimeModule) && (!mIsReified) && (instModule->mIsReified))
  12299. {
  12300. BF_ASSERT(!mCompiler->mIsResolveOnly);
  12301. // A resolve-only module is specializing a method from a type in a reified module,
  12302. // we need to take care that this doesn't cause anything new to become reified
  12303. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  12304. if (!moduleMethodInstance)
  12305. return moduleMethodInstance;
  12306. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  12307. return moduleMethodInstance;
  12308. }
  12309. else
  12310. {
  12311. if ((!mIsComptimeModule) && (mIsReified) && (!instModule->mIsReified))
  12312. {
  12313. if (!typeInst->IsUnspecializedType())
  12314. {
  12315. if (!instModule->mReifyQueued)
  12316. {
  12317. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  12318. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  12319. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  12320. mContext->mReifyModuleWorkList.Add(instModule);
  12321. instModule->mReifyQueued = true;
  12322. }
  12323. 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);
  12324. // This ensures that the method will actually be created when it gets reified
  12325. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  12326. specializationRequest->mFromModule = typeInst->mModule;
  12327. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  12328. specializationRequest->Init(typeInst, foreignType, methodDef);
  12329. //specializationRequest->mMethodDef = methodDef;
  12330. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  12331. specializationRequest->mType = typeInst;
  12332. specializationRequest->mFlags = flags;
  12333. }
  12334. }
  12335. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12336. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoReference);
  12337. if (mIsComptimeModule)
  12338. {
  12339. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12340. if (!mCompiler->mIsResolveOnly)
  12341. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification | BfGetMethodInstanceFlag_Unreified | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12342. }
  12343. // Not extern
  12344. // Create the instance in the proper module and then create a reference in this one
  12345. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType, this);
  12346. if (!moduleMethodInst)
  12347. return moduleMethodInst;
  12348. tryModuleMethodLookup = true;
  12349. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  12350. {
  12351. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  12352. }
  12353. }
  12354. }
  12355. if (tryModuleMethodLookup)
  12356. {
  12357. SetMethodDependency(moduleMethodInst.mMethodInstance);
  12358. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  12359. }
  12360. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  12361. {
  12362. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  12363. if (moduleMethodInstance)
  12364. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  12365. return moduleMethodInst;
  12366. }
  12367. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  12368. bool hadConcreteInterfaceGenericArgument = false;
  12369. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  12370. isReified = false;
  12371. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  12372. {
  12373. isReified = false;
  12374. }
  12375. BfTypeVector sanitizedMethodGenericArguments;
  12376. SizedArray<BfProject*, 4> projectList;
  12377. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  12378. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  12379. isUnspecializedPass = false;
  12380. // 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
  12381. bool isExternalExtensionMethod = false;
  12382. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  12383. {
  12384. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) &&
  12385. (methodDef->mDeclaringType != NULL) &&
  12386. (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  12387. {
  12388. auto specProject = methodDef->mDeclaringType->mProject;
  12389. isExternalExtensionMethod = true;
  12390. if (typeInst->IsGenericTypeInstance())
  12391. {
  12392. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12393. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12394. genericTypeInst->GenerateProjectsReferenced();
  12395. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  12396. {
  12397. // This is a generic type where a generic param is already confined to the project in question
  12398. isExternalExtensionMethod = false;
  12399. }
  12400. }
  12401. if (isExternalExtensionMethod)
  12402. {
  12403. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  12404. projectList.push_back(methodDef->mDeclaringType->mProject);
  12405. }
  12406. }
  12407. }
  12408. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  12409. {
  12410. int typeProjectsCounts = 0;
  12411. if (typeInst->IsGenericTypeInstance())
  12412. {
  12413. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12414. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12415. genericTypeInst->GenerateProjectsReferenced();
  12416. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  12417. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  12418. }
  12419. else
  12420. {
  12421. typeProjectsCounts = 1;
  12422. projectList.Insert(0, typeInst->mTypeDef->mProject);
  12423. }
  12424. isUnspecializedPass = true;
  12425. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  12426. {
  12427. auto genericArgType = methodGenericArguments[genericArgIdx];
  12428. //BF_ASSERT(!genericArgType->IsRef());
  12429. if (genericArgType->IsConcreteInterfaceType())
  12430. {
  12431. hadConcreteInterfaceGenericArgument = true;
  12432. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  12433. genericArgType = concreteInterfaceType->mInterface;
  12434. }
  12435. if (genericArgType->IsGenericParam())
  12436. {
  12437. auto genericParam = (BfGenericParamType*) genericArgType;
  12438. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  12439. isUnspecializedPass = false;
  12440. }
  12441. else
  12442. {
  12443. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  12444. isUnspecializedPass = false;
  12445. }
  12446. sanitizedMethodGenericArguments.push_back(genericArgType);
  12447. }
  12448. if ((int)projectList.size() > typeProjectsCounts)
  12449. {
  12450. // Just leave the new items
  12451. projectList.RemoveRange(0, typeProjectsCounts);
  12452. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  12453. {
  12454. return lhs->mName < rhs->mName;
  12455. });
  12456. }
  12457. else
  12458. {
  12459. projectList.Clear();
  12460. }
  12461. }
  12462. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  12463. BfMethodInstanceGroup* methodInstGroup = NULL;
  12464. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12465. {
  12466. BF_ASSERT(!typeInst->IsInterface());
  12467. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  12468. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  12469. {
  12470. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  12471. // if (checkGroup.mDefault == NULL)
  12472. // {
  12473. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  12474. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  12475. // methodInstGroup = &checkGroup;
  12476. // break;
  12477. // }
  12478. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  12479. {
  12480. methodInstGroup = &checkGroup;
  12481. break;
  12482. }
  12483. }
  12484. if (methodInstGroup == NULL)
  12485. {
  12486. if (lookupMethodGenericArguments.size() != 0)
  12487. {
  12488. BF_ASSERT((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0);
  12489. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12490. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12491. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12492. }
  12493. else
  12494. {
  12495. // Allocate a new entry
  12496. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  12497. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  12498. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  12499. methodInstGroup->mOwner = typeInst;
  12500. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12501. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12502. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  12503. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12504. else
  12505. {
  12506. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  12507. if (!mIsScratchModule)
  12508. mOnDemandMethodCount++;
  12509. }
  12510. }
  12511. }
  12512. }
  12513. else
  12514. {
  12515. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  12516. }
  12517. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12518. {
  12519. if (typeInst->mDefineState > BfTypeDefineState_DefinedAndMethodsSlotted)
  12520. {
  12521. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  12522. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12523. }
  12524. }
  12525. BfIRFunction prevIRFunc;
  12526. bool doingRedeclare = false;
  12527. BfMethodInstance* methodInstance = NULL;
  12528. auto _SetReified = [&]()
  12529. {
  12530. if (!mCompiler->mIsResolveOnly)
  12531. BF_ASSERT(mCompiler->mCompileState <= BfCompiler::CompileState_Normal);
  12532. methodInstance->mIsReified = true;
  12533. };
  12534. if (lookupMethodGenericArguments.size() == 0)
  12535. {
  12536. methodInstance = methodInstGroup->mDefault;
  12537. if ((methodInstance != NULL) && ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0))
  12538. return methodInstance;
  12539. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  12540. {
  12541. MarkDerivedDirty(typeInst);
  12542. if (!HasCompiledOutput())
  12543. {
  12544. BfLogSysM("Marking non-compiled-output module method instance as reified: %p\n", methodInstance);
  12545. _SetReified();
  12546. CheckHotMethod(methodInstance, "");
  12547. }
  12548. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  12549. {
  12550. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  12551. // the specializations to handle that for us
  12552. return BfModuleMethodInstance(methodInstance);
  12553. }
  12554. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  12555. {
  12556. if (methodDef->mIsAbstract)
  12557. {
  12558. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12559. _SetReified();
  12560. }
  12561. else
  12562. {
  12563. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12564. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  12565. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  12566. doingRedeclare = true;
  12567. mOnDemandMethodCount++;
  12568. VerifyOnDemandMethods();
  12569. }
  12570. }
  12571. else
  12572. {
  12573. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  12574. // We haven't processed it yet
  12575. _SetReified();
  12576. CheckHotMethod(methodInstance, "");
  12577. if (methodInstance->mDeclModule == this)
  12578. {
  12579. if (methodInstance->mMethodProcessRequest != NULL)
  12580. {
  12581. // Disconnect method process request
  12582. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  12583. }
  12584. }
  12585. else
  12586. {
  12587. if (methodInstance->mMethodProcessRequest != NULL)
  12588. {
  12589. // Disconnect method process request
  12590. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  12591. methodInstance->mMethodProcessRequest = NULL;
  12592. }
  12593. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  12594. {
  12595. // Add new request in proper module
  12596. methodInstance->mDeclModule = this;
  12597. }
  12598. else
  12599. {
  12600. if (methodInstance->mDeclModule == NULL)
  12601. {
  12602. //
  12603. }
  12604. else if (methodInstance->mDeclModule != this)
  12605. {
  12606. // Is from specialized module?
  12607. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  12608. }
  12609. }
  12610. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12611. {
  12612. methodInstance->mIRFunction = BfIRFunction();
  12613. if (!mIsModuleMutable)
  12614. StartExtension();
  12615. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  12616. {
  12617. StringT<512> mangledName;
  12618. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  12619. bool isIntrinsic = false;
  12620. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  12621. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  12622. }
  12623. }
  12624. AddMethodToWorkList(methodInstance);
  12625. }
  12626. }
  12627. }
  12628. }
  12629. else
  12630. {
  12631. if (methodInstGroup->mDefault == NULL)
  12632. {
  12633. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12634. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12635. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12636. }
  12637. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  12638. if (methodInstGroup->mMethodSpecializationMap == NULL)
  12639. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  12640. BfMethodInstance** methodInstancePtr = NULL;
  12641. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  12642. {
  12643. methodInstance = *methodInstancePtr;
  12644. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  12645. return methodInstance;
  12646. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  12647. {
  12648. BfLogSysM("Setting mRequestedByAutocomplete=false for method instance %p\n", methodInstance);
  12649. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  12650. if (methodInstance->mMethodProcessRequest == NULL)
  12651. AddMethodToWorkList(methodInstance);
  12652. methodInstance->mRequestedByAutocomplete = false;
  12653. }
  12654. if ((isReified) && (!methodInstance->mIsReified))
  12655. {
  12656. MarkDerivedDirty(typeInst);
  12657. if (methodInstance->mHasBeenProcessed)
  12658. {
  12659. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  12660. delete methodInstance;
  12661. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12662. methodInstance = NULL;
  12663. }
  12664. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12665. {
  12666. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  12667. delete methodInstance;
  12668. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12669. methodInstance = NULL;
  12670. }
  12671. else
  12672. {
  12673. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  12674. // We haven't processed it yet
  12675. _SetReified();
  12676. CheckHotMethod(methodInstance, "");
  12677. if (methodInstance->mMethodProcessRequest == NULL)
  12678. AddMethodToWorkList(methodInstance);
  12679. }
  12680. }
  12681. }
  12682. }
  12683. if ((methodInstance != NULL) && (!doingRedeclare))
  12684. {
  12685. SetMethodDependency(methodInstance);
  12686. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  12687. {
  12688. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  12689. BF_ASSERT(!methodInstance->mIsReified);*/
  12690. if ((!mCompiler->mIsResolveOnly) && (isReified))
  12691. {
  12692. auto refModule = referencingModule;
  12693. if (refModule == NULL)
  12694. refModule = this;
  12695. 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);
  12696. }
  12697. if (methodInstance->mIsReified != isReified)
  12698. {
  12699. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  12700. }
  12701. if ((!isReified) &&
  12702. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  12703. {
  12704. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  12705. methodInstance->mIRFunction = BfIRFunction();
  12706. }
  12707. methodInstance->mIsReified = isReified;
  12708. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  12709. {
  12710. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  12711. }
  12712. if (!methodInstance->mMethodDef->mIsAbstract)
  12713. {
  12714. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  12715. {
  12716. // Wait until unreified
  12717. }
  12718. else
  12719. AddMethodToWorkList(methodInstance);
  12720. }
  12721. else
  12722. {
  12723. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  12724. auto owningModule = methodInstance->GetOwner()->mModule;
  12725. if (!owningModule->mIsScratchModule)
  12726. {
  12727. owningModule->mOnDemandMethodCount--;
  12728. owningModule->VerifyOnDemandMethods();
  12729. }
  12730. }
  12731. }
  12732. if (mExtensionCount > 0)
  12733. {
  12734. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  12735. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  12736. {
  12737. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  12738. if (mAwaitingInitFinish)
  12739. FinishInit();
  12740. // We need to refer to a function that was defined in a prior module
  12741. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12742. if (methodInstance->mIsIntrinsic)
  12743. isInlined = false;
  12744. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  12745. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  12746. methodInstance->mDeclModule = this;
  12747. // Add this inlined def to ourselves
  12748. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12749. {
  12750. mIncompleteMethodCount++;
  12751. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12752. inlineMethodRequest->mType = typeInst;
  12753. inlineMethodRequest->mFromModule = this;
  12754. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  12755. inlineMethodRequest->mFromModuleRevision = mRevision;
  12756. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  12757. inlineMethodRequest->mMethodInstance = methodInstance;
  12758. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12759. BF_ASSERT(mIsModuleMutable);
  12760. }
  12761. }
  12762. }
  12763. if (IsSkippingExtraResolveChecks())
  12764. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12765. else
  12766. {
  12767. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12768. return methodInstance;
  12769. if (methodInstance->mDeclModule != this)
  12770. return ReferenceExternalMethodInstance(methodInstance, flags);
  12771. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  12772. {
  12773. auto importKind = methodInstance->GetImportCallKind();
  12774. if (importKind != BfImportCallKind_None)
  12775. {
  12776. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  12777. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  12778. auto func = CreateDllImportGlobalVar(methodInstance, true);
  12779. BF_ASSERT(func);
  12780. mFuncReferences[methodInstance] = func;
  12781. }
  12782. }
  12783. return BfModuleMethodInstance(methodInstance);
  12784. }
  12785. }
  12786. if (!doingRedeclare)
  12787. {
  12788. BfModule* specModule = NULL;
  12789. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  12790. {
  12791. specModule = GetSpecializedMethodModule(projectList);
  12792. }
  12793. if ((specModule != NULL) && (specModule != this))
  12794. {
  12795. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  12796. if (mAwaitingInitFinish)
  12797. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  12798. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12799. return specMethodInstance.mMethodInstance;
  12800. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  12801. }
  12802. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  12803. {
  12804. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  12805. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  12806. }
  12807. }
  12808. if (methodInstance == NULL)
  12809. {
  12810. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12811. {
  12812. BfLogSysM("GetMethodInstance (methodInstance == NULL) bailing due to IsCePaused\n");
  12813. return BfModuleMethodInstance();
  12814. }
  12815. if (lookupMethodGenericArguments.size() == 0)
  12816. {
  12817. BF_ASSERT(methodInstGroup->mDefault == NULL);
  12818. methodInstance = new BfMethodInstance();
  12819. methodInstGroup->mDefault = methodInstance;
  12820. BF_ASSERT(typeInst->mDefineState > BfTypeDefineState_Declared);
  12821. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  12822. }
  12823. else
  12824. {
  12825. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  12826. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12827. depthExceeded = true;
  12828. if (depthExceeded)
  12829. {
  12830. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  12831. return BfModuleMethodInstance();
  12832. }
  12833. BfMethodInstance** methodInstancePtr = NULL;
  12834. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  12835. BF_ASSERT(added);
  12836. methodInstance = new BfMethodInstance();
  12837. *methodInstancePtr = methodInstance;
  12838. if (mCompiler->IsAutocomplete())
  12839. methodInstance->mRequestedByAutocomplete = true;
  12840. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  12841. }
  12842. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  12843. methodInstance->mIRFunction = prevIRFunc; // Take it over
  12844. }
  12845. methodInstance->mMethodDef = methodDef;
  12846. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  12847. methodInstance->mMethodInstanceGroup = methodInstGroup;
  12848. methodInstance->mIsReified = isReified;
  12849. SetupMethodIdHash(methodInstance);
  12850. if (hadConcreteInterfaceGenericArgument)
  12851. methodInstance->mIgnoreBody = true;
  12852. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12853. {
  12854. methodInstance->mIsForeignMethodDef = true;
  12855. BF_ASSERT(foreignType != NULL);
  12856. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  12857. }
  12858. if ((typeInst->IsInstanceOf(mCompiler->mValueTypeTypeDef)) && (methodDef->mName == BF_METHODNAME_EQUALS))
  12859. {
  12860. if (!lookupMethodGenericArguments.empty())
  12861. {
  12862. auto compareType = lookupMethodGenericArguments[0];
  12863. PopulateType(compareType, BfPopulateType_Data);
  12864. if (compareType->IsSplattable())
  12865. methodInstance->mAlwaysInline = true;
  12866. }
  12867. }
  12868. if (methodDef->mMethodType == BfMethodType_Init)
  12869. {
  12870. methodInstance->mMangleWithIdx = true;
  12871. }
  12872. BF_ASSERT(typeInst == methodInstance->GetOwner());
  12873. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12874. if (isUnspecializedPass)
  12875. {
  12876. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  12877. {
  12878. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  12879. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  12880. }
  12881. }
  12882. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  12883. {
  12884. if (!sanitizedMethodGenericArguments.IsEmpty())
  12885. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  12886. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  12887. {
  12888. Fail("Internal error");
  12889. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  12890. return NULL;
  12891. }
  12892. for (auto genericArg : sanitizedMethodGenericArguments)
  12893. {
  12894. if (genericArg->IsPrimitiveType())
  12895. genericArg = GetWrappedStructType(genericArg);
  12896. if (genericArg != NULL)
  12897. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  12898. }
  12899. }
  12900. // Generic constraints
  12901. if (!methodDef->mGenericParams.IsEmpty())
  12902. {
  12903. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  12904. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  12905. {
  12906. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  12907. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12908. }
  12909. }
  12910. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  12911. {
  12912. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  12913. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12914. }
  12915. bool addToWorkList = !processNow;
  12916. if (mCompiler->GetAutoComplete() != NULL)
  12917. {
  12918. if (typeInst->IsSpecializedByAutoCompleteMethod())
  12919. addToWorkList = false;
  12920. if (methodInstance->mRequestedByAutocomplete)
  12921. addToWorkList = false;
  12922. }
  12923. BfModule* declareModule;
  12924. //
  12925. {
  12926. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  12927. declareModule = GetOrCreateMethodModule(methodInstance);
  12928. }
  12929. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  12930. declareModule = methodInstance->mDeclModule;
  12931. BF_ASSERT(declareModule != NULL);
  12932. methodInstance->mDeclModule = declareModule;
  12933. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  12934. {
  12935. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  12936. // of a reified module -
  12937. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  12938. // BUT if we don't reify it then we have to remove the body after processing.
  12939. // 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
  12940. // the proper reified module.
  12941. declareModule = mContext->mUnreifiedModule;
  12942. }
  12943. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  12944. {
  12945. if (!methodInstance->mIsReified)
  12946. {
  12947. declareModule = mContext->mUnreifiedModule;
  12948. }
  12949. else
  12950. {
  12951. declareModule->PrepareForIRWriting(methodInstance->GetOwner());
  12952. }
  12953. }
  12954. SetMethodDependency(methodInstance);
  12955. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  12956. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  12957. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  12958. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  12959. {
  12960. // For mixins we only process the unspecialized version
  12961. addToWorkList = false;
  12962. }
  12963. if (((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0) && (methodInstGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  12964. {
  12965. addToWorkList = false;
  12966. }
  12967. // if ((flags & BfGetMethodInstanceFlag_NoReference) != 0)
  12968. // addToWorkList = false;
  12969. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  12970. if (processNow)
  12971. {
  12972. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  12973. ProcessMethod(methodInstance);
  12974. }
  12975. if (IsSkippingExtraResolveChecks())
  12976. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12977. if (methodInstance->mDeclModule != this)
  12978. return ReferenceExternalMethodInstance(methodInstance, flags);
  12979. return BfModuleMethodInstance(methodInstance);
  12980. }
  12981. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  12982. {
  12983. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  12984. if (methodInstance->mIsForeignMethodDef)
  12985. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  12986. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  12987. }
  12988. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  12989. {
  12990. if (!methodInstance->mMethodDef->mIsLocalMethod)
  12991. return NULL;
  12992. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  12993. if (outerLocal == NULL)
  12994. return NULL;
  12995. BfTypeVector genericArgs;
  12996. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  12997. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  12998. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  12999. }
  13000. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  13001. {
  13002. HashContext hashCtx;
  13003. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  13004. {
  13005. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  13006. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  13007. if (methodInstance->GetNumGenericArguments() != 0)
  13008. {
  13009. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  13010. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13011. hashCtx.Mixin(methodGenericArg->mTypeId);
  13012. }
  13013. };
  13014. _MixinMethodInstance(methodInstance);
  13015. if (methodInstance->mMethodDef->mIsLocalMethod)
  13016. {
  13017. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  13018. if (outmostMethodInstance != NULL)
  13019. {
  13020. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  13021. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  13022. }
  13023. }
  13024. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  13025. }
  13026. bool BfModule::CheckUseMethodInstance(BfMethodInstance* methodInstance, BfAstNode* refNode)
  13027. {
  13028. if (methodInstance->mHasBeenDeclared)
  13029. return true;
  13030. Fail(StrFormat("Circular reference in method instance '%s'", MethodToString(methodInstance).c_str()), refNode);
  13031. return false;
  13032. }
  13033. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  13034. {
  13035. BfIRValue globalValue;
  13036. BfIRValue* globalValuePtr = NULL;
  13037. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  13038. {
  13039. globalValue = *globalValuePtr;
  13040. }
  13041. if (!globalValue)
  13042. {
  13043. // This is necessary to reify the interface type
  13044. PopulateType(ifaceType);
  13045. StringT<512> slotVarName;
  13046. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  13047. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  13048. BfIRValue value;
  13049. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  13050. {
  13051. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  13052. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  13053. int virtSlotIdx = ifaceType->mSlotNum + 1;
  13054. value = GetConstValue32(virtSlotIdx);*/
  13055. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  13056. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  13057. }
  13058. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  13059. mInterfaceSlotRefs[ifaceType] = globalValue;
  13060. // Make sure we reify
  13061. PopulateType(ifaceType, BfPopulateType_Declaration);
  13062. AddDependency(ifaceType, mCurTypeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  13063. }
  13064. return mBfIRBuilder->CreateAlignedLoad(globalValue/*, "slotOfs"*/, 4);
  13065. }
  13066. void BfModule::HadSlotCountDependency()
  13067. {
  13068. if (mCompiler->mIsResolveOnly)
  13069. return;
  13070. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  13071. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  13072. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  13073. }
  13074. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  13075. {
  13076. if (str == "#IsComptime")
  13077. {
  13078. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsComptimeModule ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13079. }
  13080. if (str == "#IsBuilding")
  13081. {
  13082. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (!mCompiler->mIsResolveOnly) ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13083. }
  13084. if (str == "#IsReified")
  13085. {
  13086. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsReified ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13087. }
  13088. if (str == "#CompileRev")
  13089. {
  13090. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mRevision), GetPrimitiveType(BfTypeCode_Int32));
  13091. }
  13092. if (str == "#NextId")
  13093. {
  13094. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)++mCompiler->mUniqueId), GetPrimitiveType(BfTypeCode_Int32));
  13095. }
  13096. if (str == "#ModuleName")
  13097. {
  13098. return BfTypedValue(GetStringObjectValue(mModuleName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13099. }
  13100. if (str == "#ProjectName")
  13101. {
  13102. if (mProject != NULL)
  13103. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13104. }
  13105. if (str == "#AllocStackCount")
  13106. {
  13107. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mOptions.mAllocStackCount), GetPrimitiveType(BfTypeCode_Int32));
  13108. }
  13109. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  13110. {
  13111. if (str == "#CallerLineNum")
  13112. {
  13113. return BfTypedValue(GetConstValue(mCurMethodState->mMixinState->mInjectFilePosition.mCurLine + 1), GetPrimitiveType(BfTypeCode_Int32));
  13114. }
  13115. else if (str == "#CallerFilePath")
  13116. {
  13117. String filePath = "";
  13118. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13119. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13120. return BfTypedValue(GetStringObjectValue(filePath), ResolveTypeDef(mCompiler->mStringTypeDef));
  13121. }
  13122. else if (str == "#CallerFileName")
  13123. {
  13124. String filePath = "";
  13125. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13126. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13127. return BfTypedValue(GetStringObjectValue(GetFileName(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13128. }
  13129. else if (str == "#CallerFileDir")
  13130. {
  13131. String filePath = "";
  13132. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13133. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13134. return BfTypedValue(GetStringObjectValue(GetFileDir(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13135. }
  13136. else if (str == "#CallerTypeName")
  13137. {
  13138. String typeName = "";
  13139. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13140. typeName = TypeToString(mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner());
  13141. return BfTypedValue(GetStringObjectValue(typeName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13142. }
  13143. else if (str == "#CallerType")
  13144. {
  13145. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  13146. BfType* type = NULL;
  13147. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13148. type = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  13149. if (type != NULL)
  13150. {
  13151. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  13152. return BfTypedValue(CreateTypeDataRef(type), typeType);
  13153. }
  13154. }
  13155. else if (str == "#CallerMemberName")
  13156. {
  13157. String memberName = "";
  13158. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13159. memberName = MethodToString(mCurMethodState->mMixinState->mMixinMethodInstance);
  13160. return BfTypedValue(GetStringObjectValue(memberName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13161. }
  13162. else if (str == "#CallerProject")
  13163. {
  13164. BfProject* project = NULL;
  13165. project = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mProject;
  13166. if (project != NULL)
  13167. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13168. }
  13169. }
  13170. if (str == "#TimeLocal")
  13171. {
  13172. time_t rawtime;
  13173. time(&rawtime);
  13174. tm* timeinfo = localtime(&rawtime);
  13175. char result[32];
  13176. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  13177. 1900 + timeinfo->tm_year,
  13178. timeinfo->tm_mon + 1,
  13179. timeinfo->tm_mday,
  13180. timeinfo->tm_hour,
  13181. timeinfo->tm_min,
  13182. timeinfo->tm_sec);
  13183. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  13184. }
  13185. return BfTypedValue();
  13186. }
  13187. BfTypedValue BfModule::GetCompilerFieldValue(BfTypedValue typedValue)
  13188. {
  13189. if (!typedValue.IsAddr())
  13190. return BfTypedValue();
  13191. if (typedValue.mValue.IsConst())
  13192. {
  13193. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  13194. if (constantValue != NULL)
  13195. {
  13196. if (constantValue->mConstType == BfConstType_GlobalVar)
  13197. {
  13198. auto globalVar = (BfGlobalVar*)constantValue;
  13199. if (globalVar->mName[0] == '#')
  13200. {
  13201. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  13202. return result;
  13203. }
  13204. }
  13205. }
  13206. }
  13207. return BfTypedValue();
  13208. }
  13209. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  13210. {
  13211. BfIRValue globalValue;
  13212. auto fieldDef = fieldInstance->GetFieldDef();
  13213. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  13214. {
  13215. if (fieldInstance->mConstIdx != -1)
  13216. {
  13217. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  13218. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  13219. }
  13220. else
  13221. {
  13222. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  13223. }
  13224. }
  13225. if ((mIsScratchModule) && (mCompiler->mIsResolveOnly) && (!fieldInstance->mOwner->IsInstanceOf(mCompiler->mCompilerTypeDef)))
  13226. {
  13227. // Just fake it for the extern and unspecialized modules
  13228. // We can't do this for compilation because unreified methods with default params need to get actual global variable refs
  13229. return BfTypedValue(mBfIRBuilder->CreateConstNull(), fieldInstance->GetResolvedType(), true);
  13230. }
  13231. BfIRValue* globalValuePtr = NULL;
  13232. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  13233. {
  13234. globalValue = *globalValuePtr;
  13235. BF_ASSERT(globalValue);
  13236. auto globalVar = (BfGlobalVar*)mBfIRBuilder->GetConstant(globalValue);
  13237. if ((globalVar->mStreamId == -1) && (!mBfIRBuilder->mIgnoreWrites))
  13238. {
  13239. mBfIRBuilder->MapType(fieldInstance->mResolvedType);
  13240. mBfIRBuilder->CreateGlobalVariable(globalValue);
  13241. }
  13242. }
  13243. else
  13244. {
  13245. StringT<512> staticVarName;
  13246. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  13247. auto typeType = fieldInstance->GetResolvedType();
  13248. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  13249. {
  13250. typeType = typeType->GetUnderlyingType();
  13251. }
  13252. if (mIsComptimeModule)
  13253. {
  13254. mCompiler->mCeMachine->QueueStaticField(fieldInstance, staticVarName);
  13255. }
  13256. PopulateType(typeType);
  13257. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  13258. {
  13259. BfIRType irType = mBfIRBuilder->MapType(typeType);
  13260. if (fieldInstance->IsAppendedObject())
  13261. irType = mBfIRBuilder->MapTypeInst(typeType->ToTypeInstance());
  13262. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  13263. globalValue = mBfIRBuilder->CreateGlobalVariable(
  13264. irType,
  13265. false,
  13266. BfIRLinkageType_External,
  13267. BfIRValue(),
  13268. staticVarName,
  13269. IsThreadLocal(fieldInstance));
  13270. BF_ASSERT(globalValue);
  13271. mStaticFieldRefs[fieldInstance] = globalValue;
  13272. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  13273. }
  13274. }
  13275. auto type = fieldInstance->GetResolvedType();
  13276. if (type->IsValuelessType())
  13277. return BfTypedValue(globalValue, type);
  13278. if (fieldDef->mIsVolatile)
  13279. return BfTypedValue(globalValue, type, BfTypedValueKind_VolatileAddr);
  13280. return BfTypedValue(globalValue, type, !fieldDef->mIsConst && !fieldInstance->IsAppendedObject());
  13281. }
  13282. BfFieldInstance* BfModule::GetFieldInstance(BfTypeInstance* typeInst, int fieldIdx, const char* fieldName)
  13283. {
  13284. if (typeInst->IsDataIncomplete())
  13285. PopulateType(typeInst);
  13286. if (fieldIdx >= typeInst->mFieldInstances.mSize)
  13287. {
  13288. Fail(StrFormat("Invalid field data in type '%s'", TypeToString(typeInst).c_str()));
  13289. return 0;
  13290. }
  13291. return &typeInst->mFieldInstances[fieldIdx];
  13292. }
  13293. void BfModule::MarkUsingThis()
  13294. {
  13295. auto useMethodState = mCurMethodState;
  13296. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13297. {
  13298. useMethodState = useMethodState->mPrevMethodState;
  13299. }
  13300. if ((useMethodState != NULL) && (!useMethodState->mLocals.IsEmpty()))
  13301. {
  13302. auto localVar = useMethodState->mLocals[0];
  13303. if (localVar->mIsThis)
  13304. localVar->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13305. }
  13306. }
  13307. BfTypedValue BfModule::GetThis(bool markUsing)
  13308. {
  13309. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  13310. {
  13311. if (mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis)
  13312. return mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis;
  13313. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  13314. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  13315. if ((activeFrame != NULL) && (activeFrame->mFunction->mDbgInfo != NULL))
  13316. {
  13317. for (auto& dbgVar : activeFrame->mFunction->mDbgInfo->mVariables)
  13318. {
  13319. if (dbgVar.mName == "this")
  13320. return BfTypedValue(mBfIRBuilder->CreateConstAggCE(mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs), dbgVar.mType,
  13321. dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  13322. }
  13323. }
  13324. return BfTypedValue();
  13325. }
  13326. auto useMethodState = mCurMethodState;
  13327. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13328. {
  13329. useMethodState = useMethodState->mPrevMethodState;
  13330. }
  13331. if (useMethodState != NULL)
  13332. {
  13333. // Fake a 'this' for var field resolution
  13334. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  13335. {
  13336. auto thisType = mCurTypeInstance;
  13337. if (thisType->IsValueType())
  13338. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  13339. else
  13340. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  13341. }
  13342. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  13343. {
  13344. return BfTypedValue();
  13345. }
  13346. }
  13347. else
  13348. {
  13349. //TODO: Do we allow useMethodState to be NULL anymore?
  13350. return BfTypedValue();
  13351. }
  13352. // Check mixin state for 'this'
  13353. {
  13354. auto checkMethodState = mCurMethodState;
  13355. while (checkMethodState != NULL)
  13356. {
  13357. if (checkMethodState->mMixinState != NULL)
  13358. {
  13359. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  13360. if (thisValue.HasType())
  13361. {
  13362. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13363. if (!thisValue.mType->IsValueType())
  13364. thisValue = LoadValue(thisValue);
  13365. return thisValue;
  13366. }
  13367. }
  13368. checkMethodState = checkMethodState->mPrevMethodState;
  13369. }
  13370. }
  13371. auto curMethodInstance = mCurMethodInstance;
  13372. if (useMethodState->mMethodInstance != NULL)
  13373. curMethodInstance = useMethodState->mMethodInstance;
  13374. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  13375. {
  13376. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  13377. {
  13378. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  13379. if (constLocal.mIsThis)
  13380. {
  13381. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  13382. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  13383. }
  13384. }
  13385. return BfTypedValue();
  13386. }
  13387. if (useMethodState->mLocals.IsEmpty())
  13388. {
  13389. // 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
  13390. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  13391. return BfTypedValue();
  13392. }
  13393. auto thisLocal = useMethodState->mLocals[0];
  13394. BF_ASSERT(thisLocal->mIsThis);
  13395. bool preferValue = !IsTargetingBeefBackend();
  13396. if (!thisLocal->mAddr)
  13397. preferValue = true;
  13398. bool usedVal = false;
  13399. BfIRValue thisValue;
  13400. if ((preferValue) && (!thisLocal->mIsLowered))
  13401. {
  13402. thisValue = thisLocal->mValue;
  13403. usedVal = true;
  13404. }
  13405. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  13406. thisValue = thisLocal->mAddr;
  13407. else
  13408. thisValue = mBfIRBuilder->CreateAlignedLoad(thisLocal->mAddr, thisLocal->mResolvedType->mAlign);
  13409. if (markUsing)
  13410. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13411. if (useMethodState->mClosureState != NULL)
  13412. {
  13413. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  13414. if (closureTypeInst != NULL)
  13415. {
  13416. if (closureTypeInst->mFieldInstances.size() > 0)
  13417. {
  13418. auto& field = closureTypeInst->mFieldInstances[0];
  13419. auto fieldDef = field.GetFieldDef();
  13420. if (fieldDef->mName == "__this")
  13421. {
  13422. if (mCurMethodState->mClosureState->mCapturing)
  13423. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  13424. // This is a captured 'this'
  13425. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  13426. if (field.mResolvedType->IsRef())
  13427. {
  13428. auto refType = (BfRefType*)field.mResolvedType;
  13429. auto underlyingType = refType->GetUnderlyingType();
  13430. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  13431. }
  13432. if (field.mResolvedType->IsObject())
  13433. {
  13434. result = LoadValue(result);
  13435. result.mKind = BfTypedValueKind_ThisValue;
  13436. }
  13437. else
  13438. {
  13439. if (fieldDef->mIsReadOnly)
  13440. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  13441. else
  13442. result.mKind = BfTypedValueKind_ThisAddr;
  13443. }
  13444. return result;
  13445. }
  13446. }
  13447. return BfTypedValue();
  13448. }
  13449. if (useMethodState->mClosureState->mCapturing)
  13450. {
  13451. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  13452. if (thisType->IsValueType())
  13453. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  13454. else
  13455. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  13456. }
  13457. }
  13458. if (mCurMethodInstance == NULL)
  13459. return BfTypedValue();
  13460. auto localDef = useMethodState->mLocals[0];
  13461. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  13462. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  13463. {
  13464. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  13465. {
  13466. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  13467. }
  13468. if (localDef->mIsSplat)
  13469. {
  13470. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  13471. }
  13472. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  13473. }
  13474. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  13475. }
  13476. BfLocalVariable* BfModule::GetThisVariable()
  13477. {
  13478. if (mCurMethodState == NULL)
  13479. return NULL;
  13480. auto methodState = mCurMethodState->GetNonCaptureState();
  13481. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  13482. return methodState->mLocals[0];
  13483. return NULL;
  13484. }
  13485. bool BfModule::IsInGeneric()
  13486. {
  13487. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  13488. }
  13489. bool BfModule::InDefinitionSection()
  13490. {
  13491. if (mCurTypeInstance != NULL)
  13492. {
  13493. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  13494. return false;
  13495. }
  13496. return !IsInSpecializedSection();
  13497. }
  13498. bool BfModule::IsInSpecializedGeneric()
  13499. {
  13500. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  13501. return true;
  13502. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  13503. return false;
  13504. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  13505. }
  13506. bool BfModule::IsInSpecializedSection()
  13507. {
  13508. return IsInSpecializedGeneric() ||
  13509. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  13510. }
  13511. bool BfModule::IsInUnspecializedGeneric()
  13512. {
  13513. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  13514. return true;
  13515. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedType()))
  13516. return true;
  13517. return false;
  13518. }
  13519. //////////////////////////////////////////////////////////////////////////
  13520. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  13521. {
  13522. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  13523. if (type->IsValuelessType())
  13524. return mBfIRBuilder->GetFakeVal();
  13525. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  13526. if ((!doLifetimeEnd) && (WantsLifetimes()))
  13527. {
  13528. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  13529. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  13530. }
  13531. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  13532. auto typeOptions = GetTypeOptions();
  13533. if (typeOptions != NULL)
  13534. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  13535. // Local variable inits are implicitly handled in the Beef Backend
  13536. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  13537. {
  13538. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13539. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13540. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  13541. mBfIRBuilder->ClearDebugLocation(storeInst);
  13542. mBfIRBuilder->SetInsertPoint(prevBlock);
  13543. }
  13544. return allocaInst;
  13545. }
  13546. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  13547. {
  13548. while (localVar->mName.StartsWith('@'))
  13549. {
  13550. localVar->mNamePrefixCount++;
  13551. localVar->mName.Remove(0);
  13552. }
  13553. if (mCurMethodState->mLocals.mAllocSize == 0)
  13554. {
  13555. mCurMethodState->mLocals.Reserve(16);
  13556. mCurMethodState->mLocalVarSet.Reserve(16);
  13557. }
  13558. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  13559. mCurMethodState->mLocals.push_back(localVar);
  13560. BfLocalVarEntry* localVarEntryPtr;
  13561. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  13562. {
  13563. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  13564. localVarEntryPtr->mLocalVar = localVar;
  13565. }
  13566. }
  13567. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13568. {
  13569. if (localVarDef->mResolvedType->IsVar())
  13570. return;
  13571. if ((mBfIRBuilder->DbgHasInfo()) &&
  13572. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  13573. (mHasFullDebugInfo) &&
  13574. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  13575. {
  13576. auto varType = localVarDef->mResolvedType;
  13577. if (localVarDef->mResolvedType->IsValuelessType())
  13578. {
  13579. }
  13580. else
  13581. {
  13582. bool isByAddr = false;
  13583. auto diValue = localVarDef->mValue;
  13584. if (localVarDef->mConstValue)
  13585. diValue = localVarDef->mConstValue;
  13586. else if (localVarDef->mAddr)
  13587. {
  13588. diValue = localVarDef->mAddr;
  13589. isByAddr = true;
  13590. }
  13591. if (diValue.IsConst())
  13592. {
  13593. auto constant = mBfIRBuilder->GetConstant(diValue);
  13594. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  13595. {
  13596. // Ignore for now
  13597. return;
  13598. }
  13599. }
  13600. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  13601. bool didConstToMem = false;
  13602. bool isConstant = false;
  13603. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  13604. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13605. else if (localVarDef->mConstValue)
  13606. {
  13607. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  13608. isConstant =
  13609. (constant->mConstType < BfConstType_GlobalVar) ||
  13610. (constant->mConstType == BfConstType_AggZero) ||
  13611. (constant->mConstType == BfConstType_Agg);
  13612. if (isConstant)
  13613. {
  13614. if (localVarDef->mResolvedType->IsComposite())
  13615. {
  13616. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  13617. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  13618. // if (IsTargetingBeefBackend())
  13619. // {
  13620. // diValue = mBfIRBuilder->CreateAliasValue(constMem);
  13621. // didConstToMem = true;
  13622. //
  13623. // diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13624. // }
  13625. //else
  13626. {
  13627. isByAddr = true;
  13628. mBfIRBuilder->SaveDebugLocation();
  13629. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13630. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13631. mBfIRBuilder->ClearDebugLocation();
  13632. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  13633. auto addrVal = CreateAlloca(ptrType);
  13634. mBfIRBuilder->CreateStore(constMem, addrVal);
  13635. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13636. diValue = addrVal;
  13637. didConstToMem = true;
  13638. mBfIRBuilder->SetInsertPoint(prevBlock);
  13639. mBfIRBuilder->RestoreDebugLocation();
  13640. }
  13641. }
  13642. if (mCompiler->mOptions.IsCodeView())
  13643. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13644. }
  13645. }
  13646. if (!mBfIRBuilder->mIgnoreWrites)
  13647. {
  13648. if ((localVarDef->mIsStatic) && (localVarDef->mAddr) && (!localVarDef->mResolvedType->IsValuelessType()))
  13649. {
  13650. auto refType = CreateRefType(localVarDef->mResolvedType);
  13651. diType = mBfIRBuilder->DbgGetType(refType);
  13652. auto refAlloca = CreateAlloca(refType);
  13653. mBfIRBuilder->CreateStore(localVarDef->mAddr, refAlloca);
  13654. diValue = refAlloca;
  13655. }
  13656. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13657. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  13658. localVarDef->mDbgVarInst = diVariable;
  13659. if (mBfIRBuilder->HasDebugLocation())
  13660. {
  13661. if ((isConstant) && (!didConstToMem))
  13662. {
  13663. BfTypedValue result(localVarDef->mConstValue, localVarDef->mResolvedType);
  13664. FixValueActualization(result);
  13665. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(result.mValue, diVariable);
  13666. }
  13667. else
  13668. {
  13669. if ((IsTargetingBeefBackend()) && (doAliasValue) && (!mIsComptimeModule))
  13670. {
  13671. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  13672. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  13673. }
  13674. if (isByAddr)
  13675. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  13676. else if (diValue)
  13677. {
  13678. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  13679. }
  13680. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  13681. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  13682. }
  13683. }
  13684. }
  13685. }
  13686. }
  13687. }
  13688. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13689. {
  13690. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  13691. {
  13692. if ((!localVarDef->mValue.IsConst()) &&
  13693. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  13694. {
  13695. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  13696. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  13697. }
  13698. }
  13699. if (addDebugInfo)
  13700. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  13701. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  13702. DoAddLocalVariable(localVarDef);
  13703. auto rootMethodState = mCurMethodState->GetRootMethodState();
  13704. if (localVarDef->mLocalVarId == -1)
  13705. {
  13706. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  13707. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  13708. }
  13709. bool checkLocal = true;
  13710. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  13711. {
  13712. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(mCurMethodInstance->mMethodDef->mMethodDeclaration))
  13713. checkLocal = false;
  13714. }
  13715. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!mIsComptimeModule) && (checkLocal))
  13716. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  13717. if (((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL)) && (checkLocal))
  13718. {
  13719. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  13720. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL) && (rootMethodState->mMethodInstance != NULL) && (!mIsComptimeModule))
  13721. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  13722. }
  13723. return localVarDef;
  13724. }
  13725. void BfModule::CreateDIRetVal()
  13726. {
  13727. if (!WantsDebugInfo())
  13728. return;
  13729. /*if (!mCurMethodState->mRetVal)
  13730. {
  13731. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  13732. return;
  13733. }*/
  13734. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  13735. {
  13736. BfType* dbgType = mCurMethodInstance->mReturnType;
  13737. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  13738. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13739. {
  13740. BF_ASSERT(mCurMethodState->mRetValAddr);
  13741. dbgType = CreatePointerType(dbgType);
  13742. dbgValue = mCurMethodState->mRetValAddr;
  13743. }
  13744. else
  13745. {
  13746. BF_ASSERT(!mCurMethodState->mRetValAddr);
  13747. }
  13748. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13749. "@return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  13750. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  13751. }
  13752. }
  13753. BfTypedValue BfModule::CreateTuple(const Array<BfTypedValue>& values, const Array<String>& fieldNames)
  13754. {
  13755. BfTypeVector fieldTypes;
  13756. for (auto arg : values)
  13757. fieldTypes.Add(arg.mType);
  13758. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  13759. auto tupleTypedValue = BfTypedValue(CreateAlloca(tupleType), tupleType, true);
  13760. for (int fieldIdx = 0; fieldIdx < tupleType->mFieldInstances.size(); fieldIdx++)
  13761. {
  13762. auto& fieldInstance = tupleType->mFieldInstances[fieldIdx];
  13763. if (fieldInstance.mDataIdx <= 0)
  13764. continue;
  13765. auto typedVal = values[fieldIdx];
  13766. typedVal = LoadOrAggregateValue(typedVal);
  13767. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, mBfIRBuilder->CreateInBoundsGEP(tupleTypedValue.mValue, 0, fieldInstance.mDataIdx), typedVal.mType->mAlign);
  13768. }
  13769. return tupleTypedValue;
  13770. }
  13771. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  13772. {
  13773. if (variableDef->mName.IsEmpty())
  13774. return;
  13775. BfLocalVarEntry* localVarEntryPtr = NULL;
  13776. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  13777. {
  13778. auto checkLocal = localVarEntryPtr->mLocalVar;
  13779. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  13780. {
  13781. BfError* error;
  13782. if (checkLocal->mIsImplicitParam)
  13783. return; // Ignore 'redefinition'
  13784. if (checkLocal->IsParam())
  13785. {
  13786. if (variableDef->IsParam())
  13787. error = Fail(StrFormat("A parameter named '%s' has already been declared", variableDef->mName.c_str()), variableDef->mNameNode);
  13788. else
  13789. 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);
  13790. }
  13791. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  13792. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13793. else
  13794. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13795. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  13796. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  13797. return;
  13798. }
  13799. }
  13800. }
  13801. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  13802. {
  13803. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  13804. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  13805. {
  13806. if (tokenNode->GetToken() == BfToken_Colon)
  13807. {
  13808. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  13809. {
  13810. Fail("Cannot access method scope across deferred block boundary", scopeName);
  13811. return NULL;
  13812. }
  13813. return &mCurMethodState->mHeadScope;
  13814. }
  13815. else if (tokenNode->GetToken() == BfToken_Mixin)
  13816. {
  13817. if (fromMixinState == NULL)
  13818. {
  13819. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  13820. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  13821. return mCurMethodState->mCurScope;
  13822. }
  13823. fromMixinState->mUsedInvocationScope = true;
  13824. return fromMixinState->mTargetScope;
  13825. }
  13826. else if (tokenNode->GetToken() == BfToken_New)
  13827. return NULL;
  13828. }
  13829. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  13830. {
  13831. auto findLabel = scopeName->ToString();
  13832. bool crossedDeferredBlock = false;
  13833. auto checkScope = mCurMethodState->mCurScope;
  13834. while (checkScope != NULL)
  13835. {
  13836. if (checkScope->mIsDeferredBlock)
  13837. crossedDeferredBlock = true;
  13838. if (checkScope->mLabel == findLabel)
  13839. {
  13840. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  13841. {
  13842. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  13843. return NULL;
  13844. }
  13845. return checkScope;
  13846. }
  13847. checkScope = checkScope->mPrevScope;
  13848. }
  13849. if (!inMixinDecl)
  13850. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  13851. }
  13852. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  13853. {
  13854. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  13855. }
  13856. return mCurMethodState->mCurScope;
  13857. }
  13858. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  13859. {
  13860. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  13861. }
  13862. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  13863. {
  13864. auto scopeData = FindScope(scopeName, false);
  13865. if (scopeData == NULL)
  13866. return NULL;
  13867. int scopeDepth = scopeData->GetDepth();
  13868. // Find the first break data that is at or below the depth of our requested scope
  13869. auto breakData = mCurMethodState->mBreakData;
  13870. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  13871. {
  13872. if (breakData->mScope->mIsConditional)
  13873. return NULL;
  13874. breakData = breakData->mPrevBreakData;
  13875. }
  13876. return breakData;
  13877. }
  13878. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  13879. {
  13880. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  13881. if (!IsTargetingBeefBackend())
  13882. return;
  13883. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  13884. {
  13885. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13886. }
  13887. }
  13888. void BfModule::ClearLifetimeEnds()
  13889. {
  13890. auto scopeData = mCurMethodState->mCurScope;
  13891. while (scopeData != NULL)
  13892. {
  13893. scopeData->mDeferredLifetimeEnds.Clear();
  13894. scopeData = scopeData->mPrevScope;
  13895. }
  13896. }
  13897. bool BfModule::WantsDebugInfo()
  13898. {
  13899. if ((mCurMethodInstance != NULL) &&
  13900. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  13901. return false;
  13902. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  13903. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  13904. }
  13905. BfTypeOptions* BfModule::GetTypeOptions()
  13906. {
  13907. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  13908. return mCurMethodState->mMethodTypeOptions;
  13909. if (mCurMethodInstance == NULL)
  13910. return NULL;
  13911. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  13912. }
  13913. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  13914. {
  13915. BfReflectKind reflectKind = BfReflectKind_None;
  13916. if (attrType->mCustomAttributes != NULL)
  13917. {
  13918. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  13919. {
  13920. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  13921. {
  13922. for (auto& prop : customAttr.mSetProperties)
  13923. {
  13924. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  13925. if (propDef->mName == "ReflectUser")
  13926. {
  13927. if (prop.mParam.mValue.IsConst())
  13928. {
  13929. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  13930. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  13931. }
  13932. }
  13933. }
  13934. // Check for Flags arg
  13935. if (customAttr.mCtorArgs.size() < 2)
  13936. continue;
  13937. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  13938. if (constant == NULL)
  13939. continue;
  13940. if (constant->mTypeCode == BfTypeCode_Boolean)
  13941. continue;
  13942. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  13943. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  13944. }
  13945. }
  13946. }
  13947. return reflectKind;
  13948. }
  13949. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  13950. {
  13951. auto checkTypeInstance = typeInstance;
  13952. while (checkTypeInstance != NULL)
  13953. {
  13954. if (checkTypeInstance->mCustomAttributes != NULL)
  13955. {
  13956. auto checkReflectKind = BfReflectKind_None;
  13957. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  13958. {
  13959. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  13960. {
  13961. if (customAttr.mCtorArgs.size() > 0)
  13962. {
  13963. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  13964. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  13965. }
  13966. else
  13967. {
  13968. checkReflectKind = BfReflectKind_All;
  13969. }
  13970. }
  13971. else
  13972. {
  13973. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  13974. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  13975. }
  13976. }
  13977. if ((checkTypeInstance == typeInstance) ||
  13978. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  13979. {
  13980. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  13981. }
  13982. }
  13983. for (auto ifaceEntry : typeInstance->mInterfaces)
  13984. {
  13985. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  13986. {
  13987. auto iface = ifaceEntry.mInterfaceType;
  13988. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  13989. if (customAttr != NULL)
  13990. {
  13991. for (auto& prop : customAttr->mSetProperties)
  13992. {
  13993. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  13994. if (propDef->mName == "ReflectImplementer")
  13995. {
  13996. if (prop.mParam.mValue.IsConst())
  13997. {
  13998. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  13999. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  14000. }
  14001. }
  14002. }
  14003. }
  14004. }
  14005. }
  14006. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  14007. }
  14008. return reflectKind;
  14009. }
  14010. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  14011. {
  14012. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14013. while (checkScope != NULL)
  14014. {
  14015. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  14016. return true;
  14017. if (checkScope == scope)
  14018. break;
  14019. checkScope = checkScope->mPrevScope;
  14020. }
  14021. return false;
  14022. }
  14023. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  14024. {
  14025. // Is there anything we need to do here?
  14026. if (mBfIRBuilder->mIgnoreWrites)
  14027. {
  14028. // Just visit deferred blocks
  14029. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14030. while (checkScope != NULL)
  14031. {
  14032. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14033. while (deferredCallEntry != NULL)
  14034. {
  14035. if (deferredCallEntry->mDeferredBlock != NULL)
  14036. {
  14037. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14038. if (checkScope == &mCurMethodState->mHeadScope)
  14039. CreateRetValLocal();
  14040. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry->mEmitRefNode);
  14041. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  14042. }
  14043. deferredCallEntry = deferredCallEntry->mNext;
  14044. }
  14045. if (checkScope == scopeData)
  14046. break;
  14047. checkScope = checkScope->mPrevScope;
  14048. }
  14049. return;
  14050. }
  14051. // Why did we want to do SetIllegalSrcPos here?
  14052. // Don't we always want to step onto these instances?
  14053. // Find a case where we don't and perhaps only do it there.
  14054. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  14055. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  14056. //SetIllegalSrcPos();
  14057. bool setSrcPos = false;
  14058. bool wantsNop = true;
  14059. BfAstNode* deferCloseNode = NULL;
  14060. if (mCurMethodState->mInPostReturn)
  14061. {
  14062. // These won't get used, they are post-return
  14063. return;
  14064. }
  14065. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  14066. BfScopeData* scopeJumpBlock = NULL;
  14067. bool hadExtraDeferredLifetimeEnds = false;
  14068. auto _FlushLifetimeEnds = [&]()
  14069. {
  14070. for (auto lifetimeEnd : deferredLifetimeEnds)
  14071. {
  14072. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14073. mBfIRBuilder->ClearDebugLocation_Last();
  14074. }
  14075. deferredLifetimeEnds.clear();
  14076. };
  14077. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14078. while (checkScope != NULL)
  14079. {
  14080. if (checkScope->mCloseNode != NULL)
  14081. deferCloseNode = checkScope->mCloseNode;
  14082. if (doneBlock)
  14083. {
  14084. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  14085. for (auto& checkHandler : checkScope->mDeferredHandlers)
  14086. {
  14087. if (checkHandler.mDoneBlock == doneBlock)
  14088. {
  14089. scopeJumpBlock = checkScope;
  14090. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  14091. mBfIRBuilder->ClearDebugLocation_Last();
  14092. _FlushLifetimeEnds();
  14093. break;
  14094. }
  14095. }
  14096. if (scopeJumpBlock != NULL)
  14097. break;
  14098. }
  14099. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  14100. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  14101. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  14102. if (hasWork)
  14103. {
  14104. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  14105. if (deferCloseNode != NULL)
  14106. {
  14107. UpdateSrcPos(deferCloseNode);
  14108. }
  14109. if (checkScope == &mCurMethodState->mHeadScope)
  14110. CreateRetValLocal();
  14111. if (doneBlock)
  14112. {
  14113. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  14114. String blockName = "deferredCalls";
  14115. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  14116. BfDeferredHandler deferredHandler;
  14117. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  14118. {
  14119. mBfIRBuilder->SaveDebugLocation();
  14120. mBfIRBuilder->ClearDebugLocation();
  14121. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  14122. mBfIRBuilder->RestoreDebugLocation();
  14123. }
  14124. else
  14125. {
  14126. // Definitely chain
  14127. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  14128. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  14129. mBfIRBuilder->ClearDebugLocation_Last();
  14130. _FlushLifetimeEnds();
  14131. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  14132. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  14133. }
  14134. deferredHandler.mDoneBlock = doneBlock;
  14135. if (!mBfIRBuilder->mIgnoreWrites)
  14136. checkScope->mDeferredHandlers.push_back(deferredHandler);
  14137. if (checkScope == &mCurMethodState->mHeadScope)
  14138. {
  14139. if (!mCurMethodState->mDIRetVal)
  14140. {
  14141. // 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
  14142. // be scoped to the physical method
  14143. /*if (deferCloseNode != NULL)
  14144. {
  14145. UpdateSrcPos(deferCloseNode);
  14146. }*/
  14147. CreateDIRetVal();
  14148. }
  14149. }
  14150. if (checkScope != mCurMethodState->mTailScope)
  14151. {
  14152. if (deferredHandler.mHandlerBlock.IsFake())
  14153. {
  14154. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14155. }
  14156. if (!mBfIRBuilder->mIgnoreWrites)
  14157. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  14158. }
  14159. }
  14160. HashSet<BfDeferredCallEntry*> handledSet;
  14161. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14162. while (deferredCallEntry != NULL)
  14163. {
  14164. BfDeferredCallEmitState deferredCallEmitState;
  14165. deferredCallEmitState.mCloseNode = deferCloseNode;
  14166. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  14167. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  14168. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14169. if (deferCloseNode != NULL)
  14170. {
  14171. UpdateSrcPos(deferCloseNode);
  14172. }
  14173. if (wantsNop)
  14174. EmitEnsureInstructionAt();
  14175. wantsNop = false;
  14176. if (deferredCallEntry->mDeferredBlock != NULL)
  14177. {
  14178. BfDeferredCallEntry** entryPtr = NULL;
  14179. if (!handledSet.TryAdd(deferredCallEntry, &entryPtr))
  14180. {
  14181. // Already handled, can happen if we defer again within the block
  14182. deferredCallEntry = deferredCallEntry->mNext;
  14183. continue;
  14184. }
  14185. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  14186. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14187. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  14188. {
  14189. // The list changed, start over and ignore anything we've already handled
  14190. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14191. }
  14192. else
  14193. deferredCallEntry = deferredCallEntry->mNext;
  14194. }
  14195. else
  14196. {
  14197. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14198. deferredCallEntry = deferredCallEntry->mNext;
  14199. }
  14200. }
  14201. if (checkScope->mSavedStack)
  14202. {
  14203. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  14204. if (mCurMethodState->mDynStackRevIdx)
  14205. {
  14206. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  14207. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  14208. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  14209. }
  14210. }
  14211. }
  14212. if (!checkScope->mIsScopeHead)
  14213. {
  14214. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  14215. if (!IsTargetingBeefBackend())
  14216. {
  14217. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14218. {
  14219. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14220. }
  14221. }
  14222. else
  14223. {
  14224. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14225. {
  14226. deferredLifetimeEnds.Add(lifetimeEnd);
  14227. }
  14228. }
  14229. }
  14230. if (checkScope == scopeData)
  14231. break;
  14232. checkScope = checkScope->mPrevScope;
  14233. }
  14234. if ((doneBlock) && (scopeJumpBlock == NULL))
  14235. {
  14236. mBfIRBuilder->CreateBr(doneBlock);
  14237. mBfIRBuilder->ClearDebugLocation_Last();
  14238. }
  14239. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  14240. // may have been created when other scope lifetimes were available
  14241. _FlushLifetimeEnds();
  14242. // Emit lifetimeEnds after the branch for Beef
  14243. /*if (IsTargetingBeefBackend())
  14244. {
  14245. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  14246. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14247. while (checkScope != NULL)
  14248. {
  14249. if (checkScope == scopeJumpBlock)
  14250. break;
  14251. if (!checkScope->mIsScopeHead)
  14252. {
  14253. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14254. {
  14255. if (needsEnsureInst)
  14256. {
  14257. needsEnsureInst = false;
  14258. }
  14259. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14260. }
  14261. }
  14262. if (checkScope == scopeData)
  14263. break;
  14264. checkScope = checkScope->mPrevScope;
  14265. }
  14266. }*/
  14267. }
  14268. void BfModule::MarkScopeLeft(BfScopeData* scopeData, bool isNoReturn)
  14269. {
  14270. if ((mCurMethodState->mDeferredLocalAssignData != NULL) && (!isNoReturn))
  14271. {
  14272. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  14273. while (deferredLocalAssignData != NULL)
  14274. {
  14275. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  14276. break;
  14277. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  14278. deferredLocalAssignData->mIsUnconditional = false;
  14279. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  14280. }
  14281. }
  14282. // When we leave a scope, mark those as assigned for deferred assignment purposes
  14283. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  14284. {
  14285. auto localDef = mCurMethodState->mLocals[localIdx];
  14286. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  14287. {
  14288. bool hadAssignment = false;
  14289. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  14290. {
  14291. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  14292. if (entry.mLocalVar == localDef)
  14293. hadAssignment = true;
  14294. }
  14295. if (!hadAssignment)
  14296. {
  14297. if (!isNoReturn)
  14298. localDef->mHadExitBeforeAssign = true;
  14299. mCurMethodState->LocalDefined(localDef);
  14300. }
  14301. }
  14302. }
  14303. }
  14304. void BfModule::CreateReturn(BfIRValue val)
  14305. {
  14306. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14307. {
  14308. // Store to sret
  14309. BF_ASSERT(val);
  14310. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14311. mBfIRBuilder->CreateRetVoid();
  14312. return;
  14313. }
  14314. if (mCurMethodInstance->mReturnType->IsVar())
  14315. return;
  14316. if (mCurMethodInstance->mReturnType->IsValuelessType())
  14317. {
  14318. mBfIRBuilder->CreateRetVoid();
  14319. return;
  14320. }
  14321. if (mCurMethodInstance->mReturnType->IsStruct())
  14322. {
  14323. BfTypeCode loweredReturnType = BfTypeCode_None;
  14324. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  14325. if (!mIsComptimeModule)
  14326. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  14327. if (loweredReturnType != BfTypeCode_None)
  14328. {
  14329. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  14330. mBfIRBuilder->CreateStore(val, retVal);
  14331. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  14332. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  14333. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  14334. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  14335. mBfIRBuilder->CreateRet(loadedReturnValue);
  14336. return;
  14337. }
  14338. }
  14339. BF_ASSERT(val);
  14340. mBfIRBuilder->CreateRet(val);
  14341. }
  14342. void BfModule::EmitReturn(const BfTypedValue& val)
  14343. {
  14344. if (mCurMethodState->mIRExitBlock)
  14345. {
  14346. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  14347. {
  14348. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  14349. {
  14350. if ((mCurMethodState->mRetValAddr) || (mCurMethodState->mRetVal))
  14351. {
  14352. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  14353. if (!mCurMethodState->mRetVal)
  14354. retVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetValAddr, mCurMethodInstance->mReturnType->mAlign);
  14355. mBfIRBuilder->CreateAlignedStore(val.mValue, retVal, mCurMethodInstance->mReturnType->mAlign);
  14356. }
  14357. else if (mIsComptimeModule)
  14358. {
  14359. if (!val.mType->IsValuelessType())
  14360. mBfIRBuilder->CreateSetRet(val.mValue, val.mType->mTypeId);
  14361. else
  14362. mBfIRBuilder->CreateSetRet(BfIRValue(), val.mType->mTypeId);
  14363. }
  14364. else
  14365. {
  14366. // Just ignore
  14367. BF_ASSERT(mCurMethodInstance->mReturnType->IsVar());
  14368. }
  14369. }
  14370. }
  14371. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14372. }
  14373. else
  14374. {
  14375. EmitDeferredScopeCalls(false, NULL);
  14376. if (val)
  14377. {
  14378. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14379. }
  14380. }
  14381. mCurMethodState->SetHadReturn(true);
  14382. mCurMethodState->mLeftBlockUncond = true;
  14383. }
  14384. void BfModule::EmitDefaultReturn()
  14385. {
  14386. if (mCurMethodState->mInDeferredBlock)
  14387. return;
  14388. if (mCurMethodState->mIRExitBlock)
  14389. {
  14390. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14391. }
  14392. else
  14393. {
  14394. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mReturnType->IsVar()))
  14395. {
  14396. // Ignore
  14397. }
  14398. else if (mCurMethodInstance->mReturnType->IsVoid())
  14399. mBfIRBuilder->CreateRetVoid();
  14400. else if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == -1))
  14401. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  14402. }
  14403. mCurMethodState->SetHadReturn(true);
  14404. mCurMethodState->mLeftBlockUncond = true;
  14405. }
  14406. void BfModule::AssertErrorState()
  14407. {
  14408. if (mIgnoreErrors)
  14409. return;
  14410. if (mHadBuildError)
  14411. return;
  14412. if (mCurTypeInstance != NULL)
  14413. {
  14414. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  14415. return;
  14416. }
  14417. if (mCurMethodInstance != NULL)
  14418. {
  14419. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  14420. return;
  14421. if (mCurMethodInstance->mHasFailed)
  14422. return;
  14423. }
  14424. // We want the module to be marked as failed even if it's just an error in the parser
  14425. if (mCurMethodInstance != NULL)
  14426. mCurMethodInstance->mHasFailed = true;
  14427. mHadBuildError = true;
  14428. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  14429. if (mCurTypeInstance != NULL)
  14430. {
  14431. if (mCurTypeInstance->mTypeFailed)
  14432. return;
  14433. if ((mCurTypeInstance->mTypeDef->GetDefinition()->mSource != NULL) && (mCurTypeInstance->mTypeDef->GetDefinition()->mSource->mParsingFailed))
  14434. return;
  14435. }
  14436. if (mCurMethodInstance != NULL)
  14437. {
  14438. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) &&
  14439. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14440. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14441. return;
  14442. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) &&
  14443. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14444. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14445. return;
  14446. }
  14447. if (mCompiler->IsAutocomplete())
  14448. return;
  14449. if (mCompiler->mPassInstance->HasFailed())
  14450. return;
  14451. InternalError("Compiler in invalid state but AssertErrorState failed to prior error");
  14452. }
  14453. void BfModule::AssertParseErrorState()
  14454. {
  14455. if (mCompiler->mRevision == 1)
  14456. AssertErrorState();
  14457. }
  14458. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  14459. {
  14460. BF_ASSERT(delegateType->IsDelegateOrFunction());
  14461. auto typeInst = delegateType->ToTypeInstance();
  14462. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  14463. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  14464. if (invokeMethodInstance == NULL)
  14465. return GetPrimitiveType(BfTypeCode_Var);
  14466. return invokeMethodInstance->mReturnType;
  14467. }
  14468. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  14469. {
  14470. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  14471. }
  14472. void BfModule::CreateDelegateInvokeMethod()
  14473. {
  14474. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  14475. //mBfIRBuilder->ClearDebugLocation();
  14476. SetIllegalSrcPos();
  14477. auto typeInstance = mCurTypeInstance;
  14478. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  14479. SizedArray<BfIRType, 4> staticParamTypes;
  14480. SizedArray<BfIRValue, 4> staticFuncArgs;
  14481. SizedArray<BfIRValue, 4> memberFuncArgs;
  14482. auto multicastDelegateType = typeInstance->mBaseType;
  14483. if (multicastDelegateType->mFieldInstances.size() != 2)
  14484. {
  14485. AssertErrorState();
  14486. return;
  14487. }
  14488. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  14489. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  14490. auto fieldVal = mBfIRBuilder->CreateAlignedLoad(fieldPtr, mSystem->mPtrSize);
  14491. BfExprEvaluator exprEvaluator(this);
  14492. SizedArray<BfIRType, 8> origParamTypes;
  14493. BfIRType origReturnType;
  14494. BfIRType staticReturnType;
  14495. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  14496. if (mCurMethodInstance->mReturnType->IsValueType())
  14497. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  14498. if ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() != 0))
  14499. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14500. int thisIdx = 0;
  14501. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14502. {
  14503. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  14504. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14505. }
  14506. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14507. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14508. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == 0))
  14509. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14510. mCurMethodInstance->GetIRFunctionInfo(this, staticReturnType, staticParamTypes, true);
  14511. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14512. {
  14513. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  14514. exprEvaluator.PushArg(localVal, staticFuncArgs);
  14515. exprEvaluator.PushArg(localVal, memberFuncArgs);
  14516. }
  14517. auto staticFunc = mBfIRBuilder->CreateFunctionType(staticReturnType, staticParamTypes, false);
  14518. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  14519. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  14520. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  14521. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  14522. auto doneBB = mBfIRBuilder->CreateBlock("done");
  14523. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  14524. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  14525. BfIRValue nonStaticResult;
  14526. BfIRValue staticResult;
  14527. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  14528. /// Non-static invocation
  14529. {
  14530. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  14531. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  14532. mBfIRBuilder->SetInsertPoint(trueBB);
  14533. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  14534. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14535. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  14536. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14537. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  14538. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14539. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  14540. if (callingConv != BfIRCallingConv_CDecl)
  14541. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  14542. mCurMethodState->SetHadReturn(false);
  14543. mCurMethodState->mLeftBlockUncond = false;
  14544. mCurMethodState->mLeftBlockCond = false;
  14545. mBfIRBuilder->CreateBr(doneBB);
  14546. }
  14547. // Static invocation
  14548. {
  14549. mBfIRBuilder->AddBlock(falseBB);
  14550. mBfIRBuilder->SetInsertPoint(falseBB);
  14551. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14552. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  14553. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14554. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  14555. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14556. {
  14557. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  14558. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  14559. }
  14560. // We had a sret for the non-static but no sret for the static (because we have a lowered return type there)
  14561. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1) && (mCurMethodInstance->GetStructRetIdx(true) == -1))
  14562. {
  14563. auto sretToType = mBfIRBuilder->GetPointerTo(staticReturnType);
  14564. auto sretCastedPtr = mBfIRBuilder->CreateBitCast(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), sretToType);
  14565. mBfIRBuilder->CreateStore(staticResult, sretCastedPtr);
  14566. }
  14567. if (callingConv == BfIRCallingConv_ThisCall)
  14568. callingConv = BfIRCallingConv_CDecl;
  14569. if (callingConv != BfIRCallingConv_CDecl)
  14570. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  14571. mCurMethodState->SetHadReturn(false);
  14572. mCurMethodState->mLeftBlockUncond = false;
  14573. mCurMethodState->mLeftBlockCond = false;
  14574. mBfIRBuilder->CreateBr(doneBB);
  14575. }
  14576. mBfIRBuilder->AddBlock(doneBB);
  14577. mBfIRBuilder->SetInsertPoint(doneBB);
  14578. if (mCurMethodInstance->mReturnType->IsVar())
  14579. {
  14580. // Do nothing
  14581. }
  14582. else if ((mCurMethodInstance->mReturnType->IsValuelessType()) ||
  14583. ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1)))
  14584. {
  14585. mBfIRBuilder->CreateRetVoid();
  14586. }
  14587. else
  14588. {
  14589. BfIRType loweredIRReturnType;
  14590. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14591. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14592. if ((!mIsComptimeModule) && (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2)))
  14593. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  14594. else
  14595. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  14596. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  14597. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  14598. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  14599. mBfIRBuilder->CreateRet(phi);
  14600. }
  14601. }
  14602. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  14603. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  14604. {
  14605. auto typeDef = typeInstance->mTypeDef;
  14606. auto methodDeclaration = methodDef->mMethodDeclaration;
  14607. if (!mCompiler->mIsResolveOnly)
  14608. return true;
  14609. if (typeInstance->IsGenericTypeInstance())
  14610. {
  14611. // We only really want to process the unspecialized type for autocompletion
  14612. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  14613. return false;
  14614. }
  14615. BfAstNode* checkNode = methodDeclaration;
  14616. if (methodDeclaration == NULL)
  14617. checkNode = methodDef->mBody;
  14618. if ((!mCompiler->mResolvePassData->mParsers.IsEmpty()) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParsers[0])))
  14619. {
  14620. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  14621. return true;
  14622. }
  14623. return false;
  14624. }
  14625. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  14626. {
  14627. methodInst->mAppendAllocAlign = 1;
  14628. }
  14629. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args, bool force)
  14630. {
  14631. BP_ZONE("BfModule::TryConstCalcAppend");
  14632. BF_ASSERT(methodInst->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  14633. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (!force))
  14634. return BfTypedValue();
  14635. // We want to regenerate all ctor calls when the method internals change
  14636. {
  14637. auto checkTypeInst = methodInst->GetOwner();
  14638. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  14639. {
  14640. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  14641. checkTypeInst = GetBaseType(checkTypeInst);
  14642. }
  14643. }
  14644. if (!methodInst->mMayBeConst)
  14645. return BfTypedValue();
  14646. // Do we need to iterate in order to resolve mAppendAllocAlign?
  14647. bool isFirstRun = methodInst->mEndingAppendAllocAlign < 0;
  14648. bool wasAllConst = true;
  14649. int argIdx = 0;
  14650. int paramIdx = 0;
  14651. while (true)
  14652. {
  14653. if (argIdx >= (int)args.size())
  14654. break;
  14655. auto paramType = methodInst->GetParamType(paramIdx);
  14656. PopulateType(paramType);
  14657. int argCount = 0;
  14658. if (!paramType->IsValuelessType())
  14659. {
  14660. if ((!mIsComptimeModule) && (methodInst->GetParamIsSplat(paramIdx)))
  14661. argCount = paramType->GetSplatCount();
  14662. else
  14663. argCount = 1;
  14664. for (int argOfs = 0; argOfs < argCount; argOfs++)
  14665. {
  14666. auto arg = args[argIdx + argOfs];
  14667. if (!arg.IsConst())
  14668. {
  14669. wasAllConst = false;
  14670. if (!isFirstRun)
  14671. {
  14672. auto& param = methodInst->mParams[argIdx];
  14673. if (param.mReferencedInConstPass)
  14674. {
  14675. // If this param is required as part of the const calculation then
  14676. // we require that it be const...
  14677. return BfTypedValue();
  14678. }
  14679. }
  14680. }
  14681. }
  14682. }
  14683. paramIdx++;
  14684. argIdx += argCount;
  14685. }
  14686. auto methodDef = methodInst->mMethodDef;
  14687. auto methodDecl = methodDef->GetMethodDeclaration();
  14688. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14689. if (methodDeclBlock == NULL)
  14690. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  14691. BfTypedValue constValue;
  14692. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  14693. auto checkState = mCurMethodState->mConstResolveState;
  14694. while (checkState != NULL)
  14695. {
  14696. if (checkState->mMethodInstance == methodInst)
  14697. {
  14698. return BfTypedValue();
  14699. }
  14700. checkState = checkState->mPrevConstResolveState;
  14701. }
  14702. //auto accumValue = GetConstValue(0);
  14703. bool failed = false;
  14704. //
  14705. {
  14706. BfConstResolveState constResolveState;
  14707. constResolveState.mMethodInstance = methodInst;
  14708. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  14709. constResolveState.mInCalcAppend = true;
  14710. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14711. BfMethodState methodState;
  14712. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  14713. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  14714. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  14715. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  14716. methodState.mConstResolveState = &constResolveState;
  14717. int argIdx = 0;
  14718. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14719. {
  14720. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  14721. continue;
  14722. auto paramType = methodInst->GetParamType(paramIdx);
  14723. // Fix this after we allow structs to be consts
  14724. //BF_ASSERT(!paramType->IsSplattable());
  14725. BfLocalVariable* localVar = new BfLocalVariable();
  14726. localVar->mName = methodInst->GetParamName(paramIdx);
  14727. localVar->mResolvedType = paramType;
  14728. localVar->mConstValue = args[argIdx];
  14729. localVar->mParamIdx = paramIdx;
  14730. AddLocalVariableDef(localVar);
  14731. argIdx++;
  14732. }
  14733. AppendAllocVisitor appendAllocVisitor;
  14734. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  14735. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  14736. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  14737. if (baseCtorAppendValue)
  14738. {
  14739. if (baseCtorAppendValue.mValue.IsFake())
  14740. appendAllocVisitor.mFailed = true;
  14741. else
  14742. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  14743. }
  14744. appendAllocVisitor.mModule = this;
  14745. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14746. if (constResolveState.mFailed)
  14747. appendAllocVisitor.mFailed = true;
  14748. if (!appendAllocVisitor.mFailed)
  14749. constValue = appendAllocVisitor.mConstAccum;
  14750. if (isFirstRun)
  14751. {
  14752. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  14753. if (mCurMethodInstance->mAppendAllocAlign <= 0)
  14754. mCurMethodInstance->mAppendAllocAlign = 1;
  14755. }
  14756. if (isFirstRun)
  14757. {
  14758. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14759. {
  14760. auto localVar = mCurMethodState->mLocals[paramIdx];
  14761. if (localVar->mReadFromId != -1)
  14762. {
  14763. auto& param = methodInst->mParams[paramIdx];
  14764. param.mReferencedInConstPass = true;
  14765. }
  14766. }
  14767. }
  14768. }
  14769. mBfIRBuilder->SetInsertPoint(prevBlock);
  14770. if (!constValue)
  14771. {
  14772. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  14773. // all-const args
  14774. if (wasAllConst)
  14775. {
  14776. methodInst->mMayBeConst = false;
  14777. }
  14778. }
  14779. return constValue;
  14780. }
  14781. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  14782. {
  14783. // Any errors should only be shown in the actual CTOR call
  14784. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  14785. auto methodDef = mCurMethodInstance->mMethodDef;
  14786. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  14787. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  14788. BfCustomAttributes* customAttributes = NULL;
  14789. defer(delete customAttributes);
  14790. BfInvocationExpression* ctorInvocation = NULL;
  14791. if (ctorDeclaration != NULL)
  14792. {
  14793. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  14794. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  14795. {
  14796. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  14797. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  14798. }
  14799. }
  14800. BfTypeInstance* targetType = NULL;
  14801. if (ctorInvocation != NULL)
  14802. {
  14803. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  14804. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  14805. }
  14806. else
  14807. targetType = mCurTypeInstance->mBaseType;
  14808. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  14809. return NULL;
  14810. auto targetRefNode = methodDef->GetRefNode();
  14811. BfType* targetThisType = targetType;
  14812. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  14813. BfExprEvaluator exprEvaluator(this);
  14814. BfResolvedArgs argValues;
  14815. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  14816. {
  14817. argValues.Init(&ctorInvocation->mArguments);
  14818. }
  14819. //
  14820. {
  14821. }
  14822. BfFunctionBindResult bindResult;
  14823. bindResult.mSkipThis = true;
  14824. bindResult.mWantsArgs = true;
  14825. {
  14826. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14827. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14828. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14829. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  14830. }
  14831. if (bindResult.mMethodInstance == NULL)
  14832. {
  14833. AssertErrorState();
  14834. return BfTypedValue();
  14835. }
  14836. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  14837. {
  14838. return BfTypedValue();
  14839. }
  14840. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14841. bindResult.mIRArgs.RemoveAt(0);
  14842. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  14843. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs, true);
  14844. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  14845. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  14846. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  14847. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  14848. if (appendSizeTypedValue)
  14849. return appendSizeTypedValue;
  14850. if (constOnly)
  14851. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  14852. bool needsRecalc = false;
  14853. for (auto irArg : bindResult.mIRArgs)
  14854. {
  14855. if (irArg.IsFake())
  14856. needsRecalc = true;
  14857. }
  14858. auto calcAppendArgs = bindResult.mIRArgs;
  14859. if (needsRecalc)
  14860. {
  14861. // Do it again, but without mIgnoreWrites set
  14862. BfResolvedArgs argValues;
  14863. argValues.Init(&ctorInvocation->mArguments);
  14864. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14865. BfFunctionBindResult bindResult;
  14866. bindResult.mSkipThis = true;
  14867. bindResult.mWantsArgs = true;
  14868. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14869. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  14870. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14871. bindResult.mIRArgs.RemoveAt(0);
  14872. calcAppendArgs = bindResult.mIRArgs;
  14873. }
  14874. if (mBfIRBuilder->mIgnoreWrites)
  14875. {
  14876. appendSizeTypedValue = GetFakeTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  14877. }
  14878. else
  14879. {
  14880. BF_ASSERT(calcAppendMethodModule.mFunc);
  14881. appendSizeTypedValue = exprEvaluator.CreateCall(NULL, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  14882. }
  14883. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  14884. return appendSizeTypedValue;
  14885. }
  14886. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  14887. void BfModule::EmitCtorCalcAppend()
  14888. {
  14889. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  14890. return;
  14891. auto methodDef = mCurMethodInstance->mMethodDef;
  14892. auto methodDecl = methodDef->GetMethodDeclaration();
  14893. Array<BfAstNode*> deferredNodeList;
  14894. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14895. if (methodDeclBlock == NULL)
  14896. return;
  14897. AppendAllocVisitor appendAllocVisitor;
  14898. auto baseCalcAppend = CallBaseCtorCalc(false);
  14899. if (baseCalcAppend)
  14900. {
  14901. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  14902. }
  14903. appendAllocVisitor.mModule = this;
  14904. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14905. }
  14906. void BfModule::CreateStaticCtor()
  14907. {
  14908. auto typeDef = mCurTypeInstance->mTypeDef;
  14909. auto methodDef = mCurMethodInstance->mMethodDef;
  14910. BfIRBlock exitBB;
  14911. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  14912. {
  14913. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  14914. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  14915. mBfIRBuilder->MapType(boolType),
  14916. false,
  14917. BfIRLinkageType_Internal,
  14918. GetDefaultValue(boolType),
  14919. "didStaticInit");
  14920. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  14921. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14922. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  14923. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  14924. mBfIRBuilder->SetInsertPoint(initBB);
  14925. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  14926. }
  14927. // Do DLL imports
  14928. if (!mDllImportEntries.empty())
  14929. {
  14930. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  14931. PopulateType(internalType);
  14932. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  14933. if (!getSharedProcAddressInstance)
  14934. {
  14935. if (!mCompiler->mPassInstance->HasFailed())
  14936. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  14937. }
  14938. }
  14939. // Fill in initializer values
  14940. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  14941. {
  14942. for (auto fieldDef : typeDef->mFields)
  14943. {
  14944. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic))
  14945. {
  14946. // For extensions, only handle these fields in the appropriate extension
  14947. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14948. continue;
  14949. auto initializer = fieldDef->GetInitializer();
  14950. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  14951. if (!fieldInst->mFieldIncluded)
  14952. continue;
  14953. if (fieldInst->mResolvedType->IsVar())
  14954. {
  14955. continue;
  14956. }
  14957. if (fieldInst->IsAppendedObject())
  14958. {
  14959. AppendedObjectInit(fieldInst);
  14960. }
  14961. else if (initializer != NULL)
  14962. {
  14963. UpdateSrcPos(initializer);
  14964. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  14965. }
  14966. }
  14967. }
  14968. auto _CheckInitBlock = [&](BfAstNode* node)
  14969. {
  14970. };
  14971. EmitInitBlocks(_CheckInitBlock);
  14972. }
  14973. else
  14974. {
  14975. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  14976. {
  14977. if (tempTypeDef->mFullName == typeDef->mFullName)
  14978. {
  14979. for (auto fieldDef : tempTypeDef->mFields)
  14980. {
  14981. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  14982. {
  14983. if (fieldDef->GetInitializer() != NULL)
  14984. {
  14985. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDef->GetInitializer()))
  14986. {
  14987. sourceClassifier->SetElementType(fieldDef->GetInitializer(), BfSourceElementType_Normal);
  14988. sourceClassifier->VisitChildNoRef(fieldDef->GetInitializer());
  14989. }
  14990. BfType* wantType = NULL;
  14991. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  14992. {
  14993. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  14994. }
  14995. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  14996. if (fieldDef->mIsAppend)
  14997. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  14998. CreateValueFromExpression(fieldDef->GetInitializer(), wantType, exprFlags);
  14999. }
  15000. }
  15001. }
  15002. }
  15003. }
  15004. }
  15005. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15006. CallChainedMethods(mCurMethodInstance, false);
  15007. }
  15008. void BfModule::EmitDtorBody()
  15009. {
  15010. if (!mCurMethodState->mIRExitBlock)
  15011. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15012. if (mCurTypeInstance->IsClosure())
  15013. {
  15014. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  15015. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  15016. auto thisVal = GetThis();
  15017. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  15018. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  15019. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  15020. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  15021. SizedArray<BfIRValue, 1> args;
  15022. args.push_back(thisVal.mValue);
  15023. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  15024. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15025. // Fall through to Object::~this call
  15026. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  15027. if (mIsComptimeModule)
  15028. mCompiler->mCeMachine->QueueMethod(dtorFunc.mMethodInstance, dtorFunc.mFunc);
  15029. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  15030. SizedArray<BfIRValue, 1> vals = { basePtr };
  15031. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  15032. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  15033. mBfIRBuilder->SetTailCall(result);
  15034. return;
  15035. }
  15036. auto typeDef = mCurTypeInstance->mTypeDef;
  15037. auto methodDef = mCurMethodInstance->mMethodDef;
  15038. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15039. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15040. CallChainedMethods(mCurMethodInstance, true);
  15041. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15042. {
  15043. VisitEmbeddedStatement(bodyBlock);
  15044. if (bodyBlock->mCloseBrace != NULL)
  15045. {
  15046. UpdateSrcPos(bodyBlock->mCloseBrace);
  15047. }
  15048. }
  15049. else
  15050. {
  15051. if (methodDeclaration != NULL)
  15052. UpdateSrcPos(methodDeclaration);
  15053. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15054. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  15055. else if (typeDef->mTypeDeclaration != NULL)
  15056. UpdateSrcPos(typeDef->mTypeDeclaration);
  15057. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  15058. {
  15059. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  15060. }
  15061. }
  15062. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15063. {
  15064. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  15065. {
  15066. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  15067. auto fieldDef = fieldInst->GetFieldDef();
  15068. BfFieldDeclaration* fieldDecl = NULL;
  15069. if (fieldDef != NULL)
  15070. fieldDecl = fieldDef->GetFieldDeclaration();
  15071. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDecl != NULL) && (fieldDecl->mFieldDtor != NULL))
  15072. {
  15073. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15074. {
  15075. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15076. continue;
  15077. }
  15078. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  15079. {
  15080. Fail("Structs cannot have field destructors", fieldDecl->mFieldDtor->mTildeToken, true);
  15081. }
  15082. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  15083. auto fieldDtor = fieldDecl->mFieldDtor;
  15084. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  15085. continue;
  15086. UpdateSrcPos(fieldDtor);
  15087. BfScopeData scopeData;
  15088. mCurMethodState->AddScope(&scopeData);
  15089. NewScopeState();
  15090. UpdateSrcPos(fieldDtor);
  15091. bool hasDbgInfo = (!fieldDef->mIsConst);
  15092. if (hasDbgInfo)
  15093. {
  15094. mBfIRBuilder->SaveDebugLocation();
  15095. mBfIRBuilder->ClearDebugLocation();
  15096. }
  15097. BfIRValue value;
  15098. if (fieldDef->mIsStatic)
  15099. {
  15100. value = ReferenceStaticField(fieldInst).mValue;
  15101. }
  15102. else
  15103. {
  15104. PopulateType(fieldInst->mResolvedType);
  15105. if (fieldInst->mResolvedType->IsValuelessType())
  15106. {
  15107. value = mBfIRBuilder->GetFakeVal();
  15108. }
  15109. else if (!mCurTypeInstance->IsValueType())
  15110. {
  15111. auto thisValue = GetThis();
  15112. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  15113. }
  15114. else
  15115. {
  15116. AssertErrorState();
  15117. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15118. }
  15119. }
  15120. BfIRValue staticVal;
  15121. if (hasDbgInfo)
  15122. {
  15123. BfIRValue dbgShowValue = value;
  15124. BfLocalVariable* localDef = new BfLocalVariable();
  15125. localDef->mName = "_";
  15126. localDef->mResolvedType = fieldInst->mResolvedType;
  15127. if (fieldInst->IsAppendedObject())
  15128. {
  15129. localDef->mValue = mBfIRBuilder->CreateBitCast(value, mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15130. }
  15131. else
  15132. {
  15133. localDef->mAddr = value;
  15134. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  15135. {
  15136. // Create another pointer indirection, a ref to the gep
  15137. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  15138. auto allocaInst = CreateAlloca(refFieldType);
  15139. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  15140. localDef->mResolvedType = refFieldType;
  15141. localDef->mAddr = allocaInst;
  15142. }
  15143. }
  15144. mBfIRBuilder->RestoreDebugLocation();
  15145. auto defLocalVar = AddLocalVariableDef(localDef, true);
  15146. if (!fieldInst->IsAppendedObject())
  15147. {
  15148. // Put back so we actually modify the correct value*/
  15149. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  15150. defLocalVar->mAddr = value;
  15151. }
  15152. }
  15153. while (fieldDtor != NULL)
  15154. {
  15155. if (mCompiler->mResolvePassData != NULL)
  15156. {
  15157. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15158. {
  15159. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15160. sourceClassifier->VisitChild(fieldDtor);
  15161. }
  15162. }
  15163. UpdateSrcPos(fieldDtor);
  15164. VisitEmbeddedStatement(fieldDtor->mBody);
  15165. fieldDtor = fieldDtor->mNextFieldDtor;
  15166. }
  15167. RestoreScopeState();
  15168. }
  15169. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldInst->IsAppendedObject()))
  15170. {
  15171. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15172. {
  15173. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15174. continue;
  15175. }
  15176. auto refNode = fieldDef->GetRefNode();
  15177. UpdateSrcPos(refNode);
  15178. auto objectType = mContext->mBfObjectType;
  15179. BfTypeInstance* checkTypeInst = mCurTypeInstance->ToTypeInstance();
  15180. BfTypedValue val;
  15181. if (fieldDef->mIsStatic)
  15182. val = ReferenceStaticField(fieldInst);
  15183. else
  15184. {
  15185. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  15186. val = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  15187. }
  15188. bool allowPrivate = checkTypeInst == mCurTypeInstance;
  15189. bool allowProtected = allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst);
  15190. while (checkTypeInst != NULL)
  15191. {
  15192. auto dtorMethodDef = checkTypeInst->mTypeDef->GetMethodByName("~this");
  15193. if (dtorMethodDef)
  15194. {
  15195. if (!CheckProtection(dtorMethodDef->mProtection, checkTypeInst->mTypeDef, allowProtected, allowPrivate))
  15196. {
  15197. auto error = Fail(StrFormat("'%s.~this()' is inaccessible due to its protection level", TypeToString(checkTypeInst).c_str()), refNode); // CS0122
  15198. }
  15199. }
  15200. checkTypeInst = checkTypeInst->mBaseType;
  15201. allowPrivate = false;
  15202. }
  15203. // call dtor
  15204. BfExprEvaluator expressionEvaluator(this);
  15205. PopulateType(val.mType);
  15206. PopulateType(objectType, BfPopulateType_DataAndMethods);
  15207. if (objectType->mVirtualMethodTable.size() == 0)
  15208. {
  15209. if (!mCompiler->IsAutocomplete())
  15210. AssertErrorState();
  15211. }
  15212. else if (!IsSkippingExtraResolveChecks())
  15213. {
  15214. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  15215. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  15216. SizedArray<BfIRValue, 4> llvmArgs;
  15217. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  15218. expressionEvaluator.CreateCall(refNode, methodInstance, mBfIRBuilder->GetFakeVal(), false, llvmArgs);
  15219. }
  15220. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  15221. {
  15222. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  15223. auto int8PtrVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(int8PtrType));
  15224. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  15225. }
  15226. }
  15227. }
  15228. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15229. {
  15230. auto checkBaseType = mCurTypeInstance->mBaseType;
  15231. while (checkBaseType != NULL)
  15232. {
  15233. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15234. {
  15235. if (bodyBlock->mCloseBrace != NULL)
  15236. UpdateSrcPos(bodyBlock->mCloseBrace);
  15237. }
  15238. else
  15239. {
  15240. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  15241. }
  15242. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  15243. if (dtorMethodDef != NULL)
  15244. {
  15245. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  15246. if (IsSkippingExtraResolveChecks())
  15247. {
  15248. // Nothing
  15249. }
  15250. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  15251. {
  15252. if ((!IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  15253. {
  15254. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  15255. SizedArray<BfIRValue, 1> vals = { basePtr };
  15256. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  15257. if (mIsComptimeModule)
  15258. mCompiler->mCeMachine->QueueMethod(dtorMethodInstance.mMethodInstance, dtorMethodInstance.mFunc);
  15259. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  15260. }
  15261. }
  15262. else
  15263. {
  15264. // Invalid base dtor declaration
  15265. AssertErrorState();
  15266. }
  15267. break;
  15268. }
  15269. checkBaseType = checkBaseType->mBaseType;
  15270. }
  15271. }
  15272. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15273. }
  15274. else
  15275. {
  15276. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15277. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15278. // resolve pass, NOT the autocomplete expression
  15279. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15280. {
  15281. if (tempTypeDef->mFullName == typeDef->mFullName)
  15282. {
  15283. for (auto fieldDef : tempTypeDef->mFields)
  15284. {
  15285. auto fieldDecl = fieldDef->GetFieldDeclaration();
  15286. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  15287. (fieldDecl->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  15288. {
  15289. BfType* fieldType = NULL;
  15290. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  15291. {
  15292. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  15293. auto curFieldDef = curFieldInstance->GetFieldDef();
  15294. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  15295. fieldType = curFieldInstance->GetResolvedType();
  15296. }
  15297. if (fieldType == NULL)
  15298. fieldType = GetPrimitiveType(BfTypeCode_Var);
  15299. auto fieldDtor = fieldDecl->mFieldDtor;
  15300. BfScopeData scopeData;
  15301. mCurMethodState->AddScope(&scopeData);
  15302. NewScopeState();
  15303. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  15304. if (fieldType != NULL)
  15305. {
  15306. BfLocalVariable* localDef = new BfLocalVariable();
  15307. localDef->mName = "_";
  15308. localDef->mResolvedType = fieldType;
  15309. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  15310. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15311. AddLocalVariableDef(localDef);
  15312. }
  15313. while (fieldDtor != NULL)
  15314. {
  15315. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15316. {
  15317. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15318. sourceClassifier->VisitChild(fieldDtor);
  15319. }
  15320. UpdateSrcPos(fieldDtor);
  15321. VisitEmbeddedStatement(fieldDtor->mBody);
  15322. fieldDtor = fieldDtor->mNextFieldDtor;
  15323. }
  15324. RestoreScopeState();
  15325. }
  15326. }
  15327. }
  15328. }
  15329. }
  15330. }
  15331. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  15332. {
  15333. BF_ASSERT(methodInstance->mIsReified);
  15334. auto typeInstance = methodInstance->GetOwner();
  15335. bool foundDllImportAttr = false;
  15336. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  15337. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  15338. {
  15339. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  15340. {
  15341. foundDllImportAttr = true;
  15342. }
  15343. }
  15344. if (!foundDllImportAttr)
  15345. {
  15346. AssertErrorState();
  15347. return BfIRValue();
  15348. }
  15349. StringT<512> name = "bf_hs_preserve@";
  15350. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  15351. name += "__imp";
  15352. BfIRType returnType;
  15353. SizedArray<BfIRType, 8> paramTypes;
  15354. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  15355. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  15356. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  15357. BfIRValue initVal;
  15358. if (define)
  15359. {
  15360. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  15361. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  15362. }
  15363. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  15364. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  15365. {
  15366. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15367. auto ptrType = CreatePointerType(voidType);
  15368. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  15369. }
  15370. return globalVar;
  15371. }
  15372. void BfModule::CreateDllImportMethod()
  15373. {
  15374. if (mBfIRBuilder->mIgnoreWrites)
  15375. return;
  15376. auto globalVar = mFuncReferences[mCurMethodInstance];
  15377. if (!globalVar)
  15378. return;
  15379. bool allowTailCall = true;
  15380. mBfIRBuilder->ClearDebugLocation();
  15381. bool isHotCompile = mCompiler->IsHotCompile();
  15382. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  15383. if (isHotCompile)
  15384. {
  15385. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  15386. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  15387. }
  15388. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  15389. BfIRType returnType;
  15390. SizedArray<BfIRType, 8> paramTypes;
  15391. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15392. SizedArray<BfIRValue, 8> args;
  15393. for (int i = 0; i < (int)paramTypes.size(); i++)
  15394. args.push_back(mBfIRBuilder->GetArgument(i));
  15395. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15396. if (isHotCompile)
  15397. {
  15398. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  15399. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  15400. if (callingConvention == BfIRCallingConv_StdCall)
  15401. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  15402. else if (callingConvention == BfIRCallingConv_FastCall)
  15403. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  15404. else
  15405. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15406. if (allowTailCall)
  15407. mBfIRBuilder->SetTailCall(result);
  15408. CreateReturn(result);
  15409. mCurMethodState->mHadReturn = true;
  15410. }
  15411. if (HasCompiledOutput())
  15412. {
  15413. BfDllImportEntry dllImportEntry;
  15414. dllImportEntry.mFuncVar = globalVar;
  15415. dllImportEntry.mMethodInstance = mCurMethodInstance;
  15416. mDllImportEntries.push_back(dllImportEntry);
  15417. }
  15418. }
  15419. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  15420. {
  15421. auto methodDef = methodInstance->mMethodDef;
  15422. BfTypeInstance* owner = NULL;
  15423. if (!methodDef->mIsStatic)
  15424. owner = methodInstance->GetThisType()->ToTypeInstance();
  15425. if (owner == NULL)
  15426. owner = methodInstance->GetOwner();
  15427. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  15428. return BfIRCallingConv_CDecl;
  15429. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  15430. return BfIRCallingConv_StdCall;
  15431. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  15432. return BfIRCallingConv_FastCall;
  15433. if (!methodDef->mIsStatic)
  15434. {
  15435. if (owner->mIsCRepr)
  15436. return BfIRCallingConv_ThisCall;
  15437. if ((!owner->IsValuelessType()) &&
  15438. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  15439. return BfIRCallingConv_ThisCall;
  15440. }
  15441. return BfIRCallingConv_CDecl;
  15442. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  15443. }
  15444. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  15445. {
  15446. BfMethodDef* methodDef = NULL;
  15447. if (methodInstance != NULL)
  15448. methodDef = methodInstance->mMethodDef;
  15449. if (!func)
  15450. return;
  15451. if (mCompiler->mOptions.mNoFramePointerElim)
  15452. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  15453. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  15454. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  15455. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  15456. if (methodInstance == NULL)
  15457. return;
  15458. if (methodInstance->mReturnType->IsVar())
  15459. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_VarRet);
  15460. if (methodDef->mImportKind == BfImportKind_Export)
  15461. {
  15462. if (methodDef->mDeclaringType->mProject->mTargetType != BfTargetType_BeefLib_StaticLib)
  15463. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  15464. }
  15465. if (methodDef->mIsNoReturn)
  15466. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  15467. auto callingConv = GetIRCallingConvention(methodInstance);
  15468. if (callingConv != BfIRCallingConv_CDecl)
  15469. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  15470. if (isInlined)
  15471. {
  15472. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15473. }
  15474. int argIdx = 0;
  15475. int paramIdx = 0;
  15476. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  15477. paramIdx = -1;
  15478. int argCount = methodInstance->GetIRFunctionParamCount(this);
  15479. while (argIdx < argCount)
  15480. {
  15481. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  15482. {
  15483. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  15484. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  15485. argIdx++;
  15486. continue;
  15487. }
  15488. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  15489. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  15490. paramIdx++;
  15491. BfType* resolvedTypeRef = NULL;
  15492. BfType* resolvedTypeRef2 = NULL;
  15493. String paramName;
  15494. bool isSplattable = false;
  15495. bool tryLowering = !mIsComptimeModule;
  15496. if (isThis)
  15497. {
  15498. paramName = "this";
  15499. if (methodInstance->mIsClosure)
  15500. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  15501. else
  15502. resolvedTypeRef = methodInstance->GetThisType();
  15503. isSplattable = (!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(-1));
  15504. tryLowering = (!mIsComptimeModule) && (methodInstance->AllowsSplatting(-1));
  15505. }
  15506. else
  15507. {
  15508. paramName = methodInstance->GetParamName(paramIdx);
  15509. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  15510. if (resolvedTypeRef->IsMethodRef())
  15511. isSplattable = true;
  15512. else if ((!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(paramIdx)))
  15513. {
  15514. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15515. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15516. {
  15517. // crepr splat is always splattable
  15518. isSplattable = true;
  15519. }
  15520. else
  15521. {
  15522. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15523. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15524. isSplattable = true;
  15525. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  15526. isSplattable = true;
  15527. }
  15528. }
  15529. }
  15530. if (tryLowering)
  15531. {
  15532. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15533. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15534. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  15535. {
  15536. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  15537. argIdx++;
  15538. if (loweredTypeCode2 != BfTypeCode_None)
  15539. {
  15540. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  15541. argIdx++;
  15542. }
  15543. paramIdx++;
  15544. continue;
  15545. }
  15546. }
  15547. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  15548. {
  15549. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  15550. int addDeref = -1;
  15551. if (resolvedTypeRef->IsRef())
  15552. {
  15553. auto refType = (BfRefType*)resolvedTypeRef;
  15554. auto elementType = refType->mElementType;
  15555. PopulateType(elementType, BfPopulateType_Data);
  15556. addDeref = elementType->mSize;
  15557. if ((addDeref <= 0) && (!elementType->IsValuelessType()) && (!elementType->IsOpaque()))
  15558. AssertErrorState();
  15559. }
  15560. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  15561. {
  15562. if (isThis)
  15563. {
  15564. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  15565. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  15566. addDeref = resolvedTypeRef->mSize;
  15567. }
  15568. else if (methodInstance->WantsStructsAttribByVal(resolvedTypeRef))
  15569. {
  15570. mBfIRBuilder->PopulateType(resolvedTypeRef, BfIRPopulateType_Full);
  15571. BF_ASSERT(resolvedTypeRef->mAlign > 0);
  15572. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  15573. }
  15574. }
  15575. else if (resolvedTypeRef->IsPrimitiveType())
  15576. {
  15577. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  15578. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  15579. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  15580. }
  15581. if (addDeref >= 0)
  15582. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  15583. argIdx++;
  15584. };
  15585. if (isSplattable)
  15586. {
  15587. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  15588. {
  15589. if (checkType->IsStruct())
  15590. {
  15591. auto checkTypeInstance = checkType->ToTypeInstance();
  15592. if (checkTypeInstance->mBaseType != NULL)
  15593. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  15594. if (checkTypeInstance->mIsUnion)
  15595. {
  15596. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  15597. checkTypeLambda(unionInnerType, curName + "_data");
  15598. }
  15599. else
  15600. {
  15601. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  15602. {
  15603. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  15604. auto fieldDef = fieldInstance->GetFieldDef();
  15605. if (fieldInstance->mDataIdx >= 0)
  15606. {
  15607. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  15608. }
  15609. }
  15610. }
  15611. if (checkTypeInstance->IsEnum())
  15612. {
  15613. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  15614. argIdx++;
  15615. }
  15616. }
  15617. else if (checkType->IsMethodRef())
  15618. {
  15619. auto methodRefType = (BfMethodRefType*)checkType;
  15620. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  15621. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  15622. {
  15623. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  15624. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  15625. {
  15626. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  15627. }
  15628. else
  15629. {
  15630. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  15631. }
  15632. }
  15633. }
  15634. else if (!checkType->IsValuelessType())
  15635. {
  15636. _SetupParam(curName, checkType);
  15637. }
  15638. };
  15639. checkTypeLambda(resolvedTypeRef, paramName);
  15640. paramIdx++;
  15641. continue;
  15642. }
  15643. _SetupParam(paramName, resolvedTypeRef);
  15644. if (resolvedTypeRef2 != NULL)
  15645. _SetupParam(paramName, resolvedTypeRef2);
  15646. paramIdx++;
  15647. }
  15648. }
  15649. void BfModule::EmitInitBlocks(const std::function<void(BfAstNode*)>& initBlockCallback)
  15650. {
  15651. auto methodDef = mCurMethodInstance->mMethodDef;
  15652. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  15653. BfMemberSetEntry* entry = NULL;
  15654. BfMethodDef* initMethodDef = NULL;
  15655. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  15656. if (entry != NULL)
  15657. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  15658. SizedArray<BfAstNode*, 8> initBodies;
  15659. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  15660. {
  15661. if (initMethodDef->mDeclaringType->GetDefinition() != methodDef->mDeclaringType->GetDefinition())
  15662. continue;
  15663. if (initMethodDef->mMethodType != BfMethodType_Init)
  15664. continue;
  15665. if (initMethodDef->mIsStatic != methodDef->mIsStatic)
  15666. continue;
  15667. initBodies.Insert(0, initMethodDef->mBody);
  15668. }
  15669. for (auto body : initBodies)
  15670. {
  15671. initBlockCallback(body);
  15672. VisitEmbeddedStatement(body);
  15673. }
  15674. }
  15675. void BfModule::EmitCtorBody(bool& skipBody)
  15676. {
  15677. auto methodInstance = mCurMethodInstance;
  15678. auto methodDef = methodInstance->mMethodDef;
  15679. auto methodDeclaration = methodDef->mMethodDeclaration;
  15680. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  15681. auto typeDef = mCurTypeInstance->mTypeDef;
  15682. BfCustomAttributes* customAttributes = NULL;
  15683. defer(delete customAttributes);
  15684. BfInvocationExpression* ctorInvocation = NULL;
  15685. BfAttributeState attributeState;
  15686. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  15687. if (ctorDeclaration != NULL)
  15688. {
  15689. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  15690. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  15691. {
  15692. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  15693. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  15694. }
  15695. }
  15696. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  15697. // Prologue
  15698. mBfIRBuilder->ClearDebugLocation();
  15699. bool hadThisInitializer = false;
  15700. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15701. {
  15702. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15703. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15704. if (targetToken->GetToken() == BfToken_This)
  15705. {
  15706. hadThisInitializer = true;
  15707. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  15708. mCurMethodState->LocalDefined(GetThisVariable());
  15709. }
  15710. }
  15711. // Zero out memory for default ctor
  15712. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()) && (methodInstance->mChainType != BfMethodChainType_ChainMember) &&
  15713. (!mCurMethodState->mLocals.IsEmpty()))
  15714. {
  15715. if (mCurTypeInstance->IsTypedPrimitive())
  15716. {
  15717. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15718. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  15719. }
  15720. else if (mCurTypeInstance->mInstSize > 0)
  15721. {
  15722. BfIRValue fillValue = GetConstValue8(0);
  15723. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  15724. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15725. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  15726. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  15727. }
  15728. }
  15729. BfAstNode* baseCtorNode = NULL;
  15730. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  15731. baseCtorNode = ctorInvocation->mTarget;
  15732. else if (methodDef->mBody != NULL)
  15733. baseCtorNode = methodDef->mBody;
  15734. else if (ctorDeclaration != NULL)
  15735. baseCtorNode = ctorDeclaration;
  15736. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15737. baseCtorNode = methodDef->mDeclaringType->GetRefNode();
  15738. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15739. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  15740. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  15741. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  15742. else
  15743. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  15744. bool calledCtorNoBody = false;
  15745. if ((mCurTypeInstance->IsTypedPrimitive()) && (!mCurTypeInstance->IsValuelessType()))
  15746. {
  15747. // Zero out typed primitives in ctor
  15748. mBfIRBuilder->CreateAlignedStore(GetDefaultValue(mCurTypeInstance->GetUnderlyingType()), mBfIRBuilder->GetArgument(0), mCurTypeInstance->mAlign);
  15749. }
  15750. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  15751. {
  15752. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  15753. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  15754. {
  15755. BfMethodDef* defaultCtor = NULL;
  15756. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  15757. {
  15758. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  15759. {
  15760. defaultCtor = methodDef;
  15761. }
  15762. }
  15763. if (defaultCtor != NULL)
  15764. {
  15765. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  15766. SetIllegalSrcPos();
  15767. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  15768. BfExprEvaluator exprEvaluator(this);
  15769. SizedArray<BfIRValue, 1> irArgs;
  15770. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  15771. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  15772. if (mIsComptimeModule)
  15773. mCompiler->mCeMachine->QueueMethod(moduleMethodInstance);
  15774. calledCtorNoBody = true;
  15775. }
  15776. }
  15777. }
  15778. // Initialize fields (if applicable)
  15779. if (mCurTypeInstance->IsBoxed())
  15780. {
  15781. skipBody = true;
  15782. }
  15783. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  15784. {
  15785. // Field initializers occur in CtorNoBody methods for extensions
  15786. }
  15787. else if (!hadThisInitializer)
  15788. {
  15789. // If we had a 'this' initializer, that other ctor will have initialized our fields
  15790. //auto
  15791. if ((!mCompiler->mIsResolveOnly) ||
  15792. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  15793. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  15794. {
  15795. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  15796. // to properly set the assigned flags
  15797. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  15798. bool hadInlineInitBlock = false;
  15799. BfScopeData scopeData;
  15800. scopeData.mInInitBlock = true;
  15801. auto _CheckInitBlock = [&](BfAstNode* node)
  15802. {
  15803. if (!hadInlineInitBlock)
  15804. {
  15805. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  15806. {
  15807. UpdateSrcPos(baseCtorNode);
  15808. if (methodDef->mBody == NULL)
  15809. SetIllegalSrcPos();
  15810. // 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
  15811. EmitEnsureInstructionAt();
  15812. BfType* thisType = mCurTypeInstance;
  15813. if (thisType->IsValueType())
  15814. thisType = CreateRefType(thisType);
  15815. SizedArray<BfIRMDNode, 1> diParamTypes;
  15816. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  15817. mCurMethodState->AddScope(&scopeData);
  15818. NewScopeState();
  15819. int flags = 0;
  15820. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  15821. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  15822. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  15823. String linkageName;
  15824. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mCurBuilder != NULL))
  15825. linkageName = StrFormat("%d", mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(mCurMethodInstance, "$initFields"));
  15826. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", linkageName, mCurFilePosition.mFileInstance->mDIFile,
  15827. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  15828. UpdateSrcPos(node);
  15829. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  15830. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  15831. //
  15832. {
  15833. auto loadedThis = GetThis();
  15834. // LLVM can't handle two variables pointing to the same value
  15835. BfIRValue copiedThisPtr;
  15836. copiedThisPtr = CreateAlloca(thisType);
  15837. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  15838. mBfIRBuilder->ClearDebugLocation(storeInst);
  15839. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  15840. }
  15841. hadInlineInitBlock = true;
  15842. }
  15843. else
  15844. {
  15845. // Just do a simple one
  15846. mCurMethodState->AddScope(&scopeData);
  15847. NewScopeState();
  15848. hadInlineInitBlock = true;
  15849. }
  15850. }
  15851. UpdateSrcPos(node);
  15852. };
  15853. for (auto fieldDef : typeDef->mFields)
  15854. {
  15855. // For extensions, only handle these fields in the appropriate extension
  15856. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15857. continue;
  15858. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  15859. {
  15860. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15861. if (!fieldInst->mFieldIncluded)
  15862. continue;
  15863. if (fieldInst->mDataIdx < 0)
  15864. continue;
  15865. auto initializer = fieldDef->GetInitializer();
  15866. if (fieldInst->IsAppendedObject())
  15867. {
  15868. UpdateSrcPos(fieldDef->GetNameNode());
  15869. AppendedObjectInit(fieldInst);
  15870. continue;
  15871. }
  15872. if (initializer == NULL)
  15873. {
  15874. continue;
  15875. // if (fieldDef->mProtection != BfProtection_Hidden)
  15876. // continue;
  15877. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  15878. // continue;
  15879. }
  15880. if (fieldInst->mResolvedType == NULL)
  15881. {
  15882. BF_ASSERT(mHadBuildError);
  15883. continue;
  15884. }
  15885. if (initializer != NULL)
  15886. {
  15887. _CheckInitBlock(initializer);
  15888. }
  15889. BfIRValue fieldAddr;
  15890. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  15891. {
  15892. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  15893. }
  15894. else
  15895. {
  15896. // Failed
  15897. }
  15898. auto assignValue = GetFieldInitializerValue(fieldInst);
  15899. if (mCurTypeInstance->IsUnion())
  15900. {
  15901. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  15902. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  15903. }
  15904. if ((fieldAddr) && (assignValue))
  15905. mBfIRBuilder->CreateAlignedStore(assignValue.mValue, fieldAddr, fieldInst->mResolvedType->mAlign);
  15906. }
  15907. }
  15908. EmitInitBlocks(_CheckInitBlock);
  15909. if (hadInlineInitBlock)
  15910. {
  15911. RestoreScopeState();
  15912. // This gets set to false because of AddScope but we actually are still in the head block
  15913. mCurMethodState->mInHeadScope = true;
  15914. // Make sure we emit a return even if we had a NoReturn call or return inside ourselves
  15915. mCurMethodState->mHadReturn = false;
  15916. mCurMethodState->mLeftBlockUncond = false;
  15917. }
  15918. }
  15919. else // Autocomplete case
  15920. {
  15921. BfScopeData scopeData;
  15922. scopeData.mInInitBlock = true;
  15923. mCurMethodState->AddScope(&scopeData);
  15924. NewScopeState();
  15925. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15926. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15927. // resolve pass, NOT the autocomplete expression
  15928. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15929. {
  15930. if (tempTypeDef->mFullName == typeDef->mFullName)
  15931. {
  15932. for (auto fieldDef : tempTypeDef->mFields)
  15933. {
  15934. auto initializer = fieldDef->GetInitializer();
  15935. if ((!fieldDef->mIsStatic) && (initializer != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  15936. {
  15937. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  15938. {
  15939. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  15940. sourceClassifier->VisitChild(initializer);
  15941. }
  15942. BfType* wantType = NULL;
  15943. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) &&
  15944. (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  15945. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowInferredSizedArray);
  15946. if ((wantType != NULL) &&
  15947. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  15948. wantType = NULL;
  15949. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  15950. if (fieldDef->mIsAppend)
  15951. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  15952. CreateValueFromExpression(initializer, wantType, exprFlags);
  15953. }
  15954. }
  15955. tempTypeDef->PopulateMemberSets();
  15956. BfMemberSetEntry* entry = NULL;
  15957. BfMethodDef* initMethodDef = NULL;
  15958. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  15959. if (entry != NULL)
  15960. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  15961. SizedArray<BfAstNode*, 8> initBodies;
  15962. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  15963. {
  15964. if (initMethodDef->mMethodType != BfMethodType_Init)
  15965. continue;
  15966. initBodies.Insert(0, initMethodDef->mBody);
  15967. }
  15968. for (auto body : initBodies)
  15969. VisitEmbeddedStatement(body);
  15970. }
  15971. }
  15972. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  15973. for (auto fieldDef : typeDef->mFields)
  15974. {
  15975. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->GetInitializer() != NULL))
  15976. {
  15977. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15978. if (fieldDef->GetInitializer() != NULL)
  15979. MarkFieldInitialized(fieldInst);
  15980. }
  15981. }
  15982. RestoreScopeState();
  15983. }
  15984. }
  15985. if (!methodInstance->mIsAutocompleteMethod)
  15986. {
  15987. if (auto autoDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  15988. {
  15989. BfExprEvaluator exprEvaluator(this);
  15990. for (int paramIdx = 0; paramIdx < methodDef->mParams.mSize; paramIdx++)
  15991. {
  15992. auto paramDef = methodDef->mParams[paramIdx];
  15993. auto& fieldInstance = mCurTypeInstance->mFieldInstances[paramIdx];
  15994. BF_ASSERT(paramDef->mName == fieldInstance.GetFieldDef()->mName);
  15995. if (fieldInstance.mDataIdx < 0)
  15996. continue;
  15997. if (paramDef->mParamKind != BfParamKind_Normal)
  15998. continue;
  15999. auto localVar = mCurMethodState->mLocals[paramIdx + 1];
  16000. BF_ASSERT(localVar->mName == paramDef->mName);
  16001. auto localVal = exprEvaluator.LoadLocal(localVar);
  16002. localVal = LoadOrAggregateValue(localVal);
  16003. if (!localVal.mType->IsVar())
  16004. {
  16005. auto thisVal = GetThis();
  16006. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance.mDataIdx);
  16007. if (mCurTypeInstance->IsUnion())
  16008. fieldPtr = mBfIRBuilder->CreateBitCast(fieldPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInstance.mResolvedType)));
  16009. mBfIRBuilder->CreateAlignedStore(localVal.mValue, fieldPtr, localVar->mResolvedType->mAlign);
  16010. }
  16011. MarkFieldInitialized(&fieldInstance);
  16012. }
  16013. }
  16014. }
  16015. // Call base ctor (if applicable)
  16016. BfTypeInstance* targetType = NULL;
  16017. BfAstNode* targetRefNode = NULL;
  16018. if (ctorDeclaration != NULL)
  16019. targetRefNode = ctorDeclaration->mInitializer;
  16020. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  16021. targetRefNode = invocationExpr->mTarget;
  16022. if (baseCtorNode != NULL)
  16023. {
  16024. UpdateSrcPos(baseCtorNode);
  16025. if (methodDef->mBody == NULL)
  16026. SetIllegalSrcPos();
  16027. }
  16028. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16029. {
  16030. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  16031. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  16032. }
  16033. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()) && (methodDef->mMethodType != BfMethodType_CtorNoBody))
  16034. {
  16035. auto baseType = mCurTypeInstance->mBaseType;
  16036. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  16037. ((baseType->mTypeDef != mCompiler->mValueTypeTypeDef) || (!mContext->mCanSkipValueTypeCtor)) &&
  16038. ((baseType->mTypeDef != mCompiler->mBfObjectTypeDef) || (!mContext->mCanSkipObjectCtor)))
  16039. {
  16040. // Try to find a ctor without any params first
  16041. BfMethodDef* matchedMethod = NULL;
  16042. bool hadCtorWithAllDefaults = false;
  16043. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  16044. for (int pass = 0; pass < 2; pass++)
  16045. {
  16046. baseType->mTypeDef->PopulateMemberSets();
  16047. BfMemberSetEntry* entry = NULL;
  16048. BfMethodDef* checkMethodDef = NULL;
  16049. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  16050. if (entry != NULL)
  16051. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  16052. while (checkMethodDef != NULL)
  16053. {
  16054. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  16055. if (isHiddenGenerated)
  16056. {
  16057. // Allow calling of the default base ctor if it is implicitly defined
  16058. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  16059. allowMethod = true;
  16060. }
  16061. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  16062. {
  16063. if (checkMethodDef->mParams.size() == 0)
  16064. {
  16065. if (matchedMethod != NULL)
  16066. {
  16067. // Has multiple matched methods - can happen from extensions
  16068. matchedMethod = NULL;
  16069. break;
  16070. }
  16071. matchedMethod = checkMethodDef;
  16072. }
  16073. else if (isHiddenGenerated)
  16074. {
  16075. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  16076. hadCtorWithAllDefaults = true;
  16077. }
  16078. }
  16079. checkMethodDef = checkMethodDef->mNextWithSameName;
  16080. }
  16081. if (matchedMethod != NULL)
  16082. break;
  16083. }
  16084. if ((HasExecutedOutput()) && (matchedMethod != NULL))
  16085. {
  16086. SizedArray<BfIRValue, 1> args;
  16087. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  16088. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  16089. {
  16090. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  16091. args.push_back(basePtr);
  16092. }
  16093. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  16094. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  16095. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  16096. if (callingConv != BfIRCallingConv_CDecl)
  16097. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  16098. if (mIsComptimeModule)
  16099. mCompiler->mCeMachine->QueueMethod(ctorBodyMethodInstance);
  16100. }
  16101. if (matchedMethod == NULL)
  16102. {
  16103. targetType = mCurTypeInstance->mBaseType;
  16104. if (ctorDeclaration != NULL)
  16105. targetRefNode = ctorDeclaration->mThisToken;
  16106. else if (typeDef->mTypeDeclaration != NULL)
  16107. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  16108. }
  16109. }
  16110. }
  16111. if (methodDef->mHasAppend)
  16112. {
  16113. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  16114. }
  16115. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  16116. {
  16117. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  16118. {
  16119. if (targetType == mCurTypeInstance)
  16120. {
  16121. auto thisVariable = GetThisVariable();
  16122. if (thisVariable != NULL)
  16123. {
  16124. thisVariable->mUnassignedFieldFlags = 0;
  16125. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16126. }
  16127. }
  16128. targetType = NULL;
  16129. }
  16130. }
  16131. auto autoComplete = mCompiler->GetAutoComplete();
  16132. if (targetType != NULL)
  16133. {
  16134. BfAstNode* refNode = methodDeclaration;
  16135. if (refNode == NULL)
  16136. refNode = typeDef->mTypeDeclaration;
  16137. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  16138. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  16139. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16140. {
  16141. auto invocationExpr = ctorInvocation;
  16142. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  16143. }
  16144. BfType* targetThisType = targetType;
  16145. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  16146. BfExprEvaluator exprEvaluator(this);
  16147. BfResolvedArgs argValues;
  16148. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16149. {
  16150. argValues.Init(&ctorInvocation->mArguments);
  16151. if (gDebugStuff)
  16152. {
  16153. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  16154. }
  16155. }
  16156. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  16157. BfTypedValue appendIdxVal;
  16158. if (methodDef->mHasAppend)
  16159. {
  16160. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  16161. BF_ASSERT(localVar->mName == "appendIdx");
  16162. auto intRefType = localVar->mResolvedType;
  16163. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  16164. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  16165. }
  16166. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  16167. if (autoComplete != NULL)
  16168. {
  16169. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  16170. {
  16171. if (autoComplete->mMethodMatchInfo != NULL)
  16172. autoComplete->mIsCapturingMethodMatchInfo = true;
  16173. else
  16174. autoComplete->mIsCapturingMethodMatchInfo = false;
  16175. }
  16176. else
  16177. autoComplete->mIsCapturingMethodMatchInfo = false;
  16178. }
  16179. }
  16180. auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration);
  16181. if ((autoComplete != NULL) && (autoComplete->CheckFixit(methodDeclaration)) && (methodDeclaration != NULL) && (autoCtorDecl != NULL))
  16182. {
  16183. auto typeDecl = methodDef->mDeclaringType->mTypeDeclaration;
  16184. BfParserData* parser = typeDecl->GetSourceData()->ToParserData();
  16185. if (parser != NULL)
  16186. {
  16187. String fixitStr = "Expand auto constructor\t";
  16188. int insertPos = typeDecl->mSrcStart;
  16189. bool needsBlock = false;
  16190. if (auto defBlock = BfNodeDynCast<BfBlock>(typeDecl->mDefineNode))
  16191. {
  16192. insertPos = defBlock->mOpenBrace->mSrcStart + 1;
  16193. }
  16194. else if (auto tokenNode = BfNodeDynCast<BfTokenNode>(typeDecl->mDefineNode))
  16195. {
  16196. insertPos = tokenNode->mSrcStart;
  16197. fixitStr += StrFormat("delete|%s-%d|\x01",
  16198. autoComplete->FixitGetLocation(parser, tokenNode->mSrcStart).c_str(), tokenNode->mSrcEnd - tokenNode->mSrcStart);
  16199. needsBlock = true;
  16200. }
  16201. int srcStart = methodDeclaration->mSrcStart;
  16202. if ((autoCtorDecl->mPrefix == NULL) && (typeDecl->mColonToken != NULL))
  16203. srcStart = typeDecl->mColonToken->mSrcStart;
  16204. while ((srcStart > 0) && (::isspace((uint8)parser->mSrc[srcStart - 1])))
  16205. srcStart--;
  16206. fixitStr += StrFormat("expand|%s|%d|",
  16207. parser->mFileName.c_str(), insertPos);
  16208. if (needsBlock)
  16209. fixitStr += "\t";
  16210. else
  16211. fixitStr += "\f";
  16212. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16213. {
  16214. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16215. paramStr.Replace('\n', '\r');
  16216. fixitStr += "public ";
  16217. fixitStr += paramStr;
  16218. fixitStr += ";\r";
  16219. }
  16220. fixitStr += "\rpublic this(";
  16221. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16222. {
  16223. if (paramIdx > 0)
  16224. fixitStr += ", ";
  16225. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16226. paramStr.Replace('\n', '\r');
  16227. fixitStr += paramStr;
  16228. }
  16229. fixitStr += ")\t";
  16230. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16231. {
  16232. if (paramIdx > 0)
  16233. fixitStr += "\r";
  16234. auto nameNode = autoCtorDecl->mParams[paramIdx]->mNameNode;
  16235. if (nameNode == NULL)
  16236. continue;
  16237. String nameStr = nameNode->ToString();
  16238. fixitStr += "this.";
  16239. fixitStr += nameStr;
  16240. fixitStr += " = ";
  16241. fixitStr += nameStr;
  16242. fixitStr += ";";
  16243. }
  16244. fixitStr += "\b";
  16245. if (needsBlock)
  16246. fixitStr += "\b";
  16247. fixitStr += StrFormat("\x01""delete|%s-%d|",
  16248. autoComplete->FixitGetLocation(parser, srcStart).c_str(), autoCtorDecl->mSrcEnd - srcStart);
  16249. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", fixitStr.c_str()));
  16250. }
  16251. }
  16252. }
  16253. void BfModule::EmitEnumToStringBody()
  16254. {
  16255. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16256. auto strVal = CreateAlloca(stringType);
  16257. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  16258. BfExprEvaluator exprEvaluator(this);
  16259. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16260. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  16261. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  16262. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  16263. BfType* discriminatorType = NULL;
  16264. BfTypedValue rawPayload;
  16265. BfIRValue enumVal;
  16266. if (mCurTypeInstance->IsPayloadEnum())
  16267. {
  16268. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  16269. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  16270. enumTypedValue = LoadValue(enumTypedValue);
  16271. enumVal = enumTypedValue.mValue;
  16272. rawPayload = ExtractValue(GetThis(), NULL, 1);
  16273. }
  16274. else
  16275. enumVal = mBfIRBuilder->GetArgument(0);
  16276. Array<BfType*> paramTypes;
  16277. paramTypes.Add(stringType);
  16278. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16279. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  16280. HashSet<int64> handledCases;
  16281. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16282. {
  16283. if (fieldInstance.mIsEnumPayloadCase)
  16284. {
  16285. int tagId = -fieldInstance.mDataIdx - 1;
  16286. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16287. mBfIRBuilder->AddBlock(caseBlock);
  16288. mBfIRBuilder->SetInsertPoint(caseBlock);
  16289. BF_ASSERT(discriminatorType->IsPrimitiveType());
  16290. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  16291. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16292. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16293. auto stringDestVal = LoadValue(stringDestAddr);
  16294. SizedArray<BfIRValue, 2> args;
  16295. args.Add(stringDestVal.mValue);
  16296. args.Add(caseStr);
  16297. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16298. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  16299. BF_ASSERT(payloadType->IsTuple());
  16300. if (payloadType->mFieldInstances.size() != 0)
  16301. {
  16302. auto payload = rawPayload;
  16303. if (payload.mType != payloadType)
  16304. {
  16305. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  16306. }
  16307. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  16308. SizedArray<BfIRValue, 2> irArgs;
  16309. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  16310. stringDestVal = LoadValue(stringDestAddr);
  16311. irArgs.Add(stringDestVal.mValue);
  16312. exprEvaluator.CreateCall(NULL, toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  16313. }
  16314. mBfIRBuilder->CreateBr(endBlock);
  16315. continue;
  16316. }
  16317. if (fieldInstance.mConstIdx == -1)
  16318. continue;
  16319. // Only allow compact 'ValA, ValB' enum declaration fields through
  16320. auto fieldDef = fieldInstance.GetFieldDef();
  16321. auto fieldDecl = fieldDef->mFieldDeclaration;
  16322. if ((fieldDecl == NULL) || (fieldDef->mTypeRef != NULL))
  16323. continue;
  16324. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  16325. if (!handledCases.TryAdd(constant->mInt64, NULL))
  16326. {
  16327. // Duplicate
  16328. continue;
  16329. }
  16330. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16331. mBfIRBuilder->AddBlock(caseBlock);
  16332. mBfIRBuilder->SetInsertPoint(caseBlock);
  16333. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  16334. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16335. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16336. mBfIRBuilder->CreateStore(caseStr, strVal);
  16337. mBfIRBuilder->CreateBr(appendBlock);
  16338. }
  16339. mBfIRBuilder->AddBlock(appendBlock);
  16340. mBfIRBuilder->SetInsertPoint(appendBlock);
  16341. SizedArray<BfIRValue, 2> args;
  16342. auto stringDestVal = LoadValue(stringDestAddr);
  16343. args.Add(stringDestVal.mValue);
  16344. args.Add(mBfIRBuilder->CreateLoad(strVal));
  16345. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16346. mBfIRBuilder->CreateBr(endBlock);
  16347. mBfIRBuilder->AddBlock(noMatchBlock);
  16348. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  16349. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  16350. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  16351. args.clear();
  16352. args.Add(int64Val);
  16353. stringDestVal = LoadValue(stringDestAddr);
  16354. args.Add(stringDestVal.mValue);
  16355. exprEvaluator.CreateCall(NULL, toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  16356. mBfIRBuilder->CreateBr(endBlock);
  16357. mBfIRBuilder->AddBlock(endBlock);
  16358. mBfIRBuilder->SetInsertPoint(endBlock);
  16359. }
  16360. void BfModule::EmitTupleToStringBody()
  16361. {
  16362. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16363. BfExprEvaluator exprEvaluator(this);
  16364. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16365. Array<BfType*> paramTypes;
  16366. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  16367. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16368. paramTypes.Clear();
  16369. paramTypes.Add(stringType);
  16370. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16371. auto _AppendChar = [&](char c)
  16372. {
  16373. SizedArray<BfIRValue, 2> args;
  16374. auto stringDestVal = LoadValue(stringDestRef);
  16375. args.Add(stringDestVal.mValue);
  16376. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  16377. exprEvaluator.CreateCall(NULL, appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  16378. };
  16379. int fieldIdx = 0;
  16380. auto thisValue = GetThis();
  16381. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  16382. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  16383. BfIRValue commaStr;
  16384. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  16385. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  16386. _AppendChar('(');
  16387. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16388. {
  16389. if (fieldInstance.mDataIdx == -1)
  16390. continue;
  16391. if (fieldIdx > 0)
  16392. {
  16393. if (!commaStr)
  16394. commaStr = GetStringObjectValue(", ");
  16395. SizedArray<BfIRValue, 2> args;
  16396. auto stringDestVal = LoadValue(stringDestRef);
  16397. args.Add(stringDestVal.mValue);
  16398. args.Add(commaStr);
  16399. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16400. }
  16401. fieldIdx++;
  16402. if (fieldInstance.mResolvedType->IsValuelessType())
  16403. continue;
  16404. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  16405. if (fieldValue.mType->IsWrappableType())
  16406. {
  16407. auto wrappedType = GetWrappedStructType(fieldValue.mType);
  16408. if ((wrappedType->IsTypedPrimitive()) || (wrappedType->IsValuelessType()))
  16409. {
  16410. fieldValue.mType = wrappedType;
  16411. }
  16412. else
  16413. {
  16414. fieldValue = MakeAddressable(fieldValue);
  16415. fieldValue.mType = wrappedType;
  16416. fieldValue.mValue = mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapTypeInstPtr(fieldValue.mType->ToTypeInstance()));
  16417. }
  16418. }
  16419. auto typeInstance = fieldValue.mType->ToTypeInstance();
  16420. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  16421. {
  16422. BfExprEvaluator exprEvaluator(this);
  16423. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16424. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16425. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  16426. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  16427. methodMatcher.TryDevirtualizeCall(fieldValue);
  16428. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16429. BfResolvedArg resolvedArg;
  16430. auto stringDestVal = LoadValue(stringDestRef);
  16431. resolvedArg.mTypedValue = stringDestVal;
  16432. resolvedArg.mResolvedType = stringDestVal.mType;
  16433. resolvedArgs.Add(resolvedArg);
  16434. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16435. continue;
  16436. }
  16437. if (fieldValue.mType->IsObjectOrInterface())
  16438. {
  16439. fieldValue = LoadValue(fieldValue);
  16440. BF_ASSERT(!fieldValue.IsAddr());
  16441. SizedArray<BfIRValue, 2> args;
  16442. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16443. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16444. stringDestVal = LoadValue(stringDestVal);
  16445. args.Add(stringDestVal.mValue);
  16446. exprEvaluator.CreateCall(NULL, toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  16447. continue;
  16448. }
  16449. BfExprEvaluator exprEvaluator(this);
  16450. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16451. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16452. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  16453. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  16454. methodMatcher.TryDevirtualizeCall(fieldValue);
  16455. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  16456. {
  16457. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  16458. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  16459. // Just append the type name
  16460. String typeName = TypeToString(fieldInstance.mResolvedType);
  16461. auto strVal = GetStringObjectValue(typeName);
  16462. SizedArray<BfIRValue, 2> args;
  16463. auto stringDestVal = LoadValue(stringDestRef);
  16464. args.Add(stringDestVal.mValue);
  16465. args.Add(strVal);
  16466. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16467. continue;
  16468. }
  16469. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16470. BfResolvedArg resolvedArg;
  16471. auto stringDestVal = LoadValue(stringDestRef);
  16472. resolvedArg.mTypedValue = stringDestVal;
  16473. resolvedArg.mResolvedType = stringDestVal.mType;
  16474. resolvedArgs.Add(resolvedArg);
  16475. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16476. }
  16477. _AppendChar(')');
  16478. }
  16479. void BfModule::EmitIteratorBlock(bool& skipBody)
  16480. {
  16481. auto methodInstance = mCurMethodInstance;
  16482. auto methodDef = methodInstance->mMethodDef;
  16483. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16484. auto typeDef = mCurTypeInstance->mTypeDef;
  16485. BfType* innerRetType = NULL;
  16486. BfTypeInstance* usingInterface = NULL;
  16487. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  16488. if (retTypeInst != NULL)
  16489. {
  16490. if ((retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef)) ||
  16491. (retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumeratorTypeDef)))
  16492. {
  16493. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  16494. }
  16495. }
  16496. if (innerRetType == NULL)
  16497. {
  16498. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  16499. return;
  16500. }
  16501. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  16502. if (blockBody == NULL)
  16503. return;
  16504. }
  16505. void BfModule::EmitGCMarkAppended(BfTypedValue markVal)
  16506. {
  16507. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  16508. if (gcType == NULL)
  16509. return;
  16510. BfModuleMethodInstance markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "MarkAppendedObject", 1);
  16511. if (!markFromGCThreadMethodInstance)
  16512. return;
  16513. SizedArray<BfIRValue, 1> args;
  16514. args.push_back(mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16515. BfExprEvaluator exprEvaluator(this);
  16516. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16517. }
  16518. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  16519. {
  16520. auto fieldType = markVal.mType;
  16521. auto fieldTypeInst = fieldType->ToTypeInstance();
  16522. if (fieldType == NULL)
  16523. return;
  16524. if (!markVal.mType->IsComposite())
  16525. markVal = LoadValue(markVal);
  16526. BfExprEvaluator exprEvaluator(this);
  16527. PopulateType(markVal.mType, BfPopulateType_Data);
  16528. if (markVal.mType->IsObjectOrInterface())
  16529. {
  16530. BfIRValue val = markVal.mValue;
  16531. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  16532. SizedArray<BfIRValue, 1> args;
  16533. args.push_back(val);
  16534. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16535. }
  16536. else if (fieldType->IsSizedArray())
  16537. {
  16538. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)fieldType;
  16539. if (sizedArrayType->mElementType->WantsGCMarking())
  16540. {
  16541. BfTypedValue arrayValue = markVal;
  16542. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  16543. auto itr = CreateAlloca(intPtrType);
  16544. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  16545. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  16546. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  16547. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  16548. mBfIRBuilder->CreateBr(loopBB);
  16549. mBfIRBuilder->SetInsertPoint(loopBB);
  16550. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  16551. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  16552. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  16553. mBfIRBuilder->SetInsertPoint(bodyBB);
  16554. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16555. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16556. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  16557. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16558. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16559. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  16560. mBfIRBuilder->CreateStore(incValue, itr);
  16561. mBfIRBuilder->CreateBr(loopBB);
  16562. mBfIRBuilder->SetInsertPoint(doneBB);
  16563. }
  16564. }
  16565. else if ((fieldType->IsComposite()) && (!fieldType->IsTypedPrimitive()) && (fieldTypeInst != NULL))
  16566. {
  16567. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  16568. if (markMemberMethodInstance)
  16569. {
  16570. SizedArray<BfIRValue, 1> args;
  16571. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  16572. if (markVal.mType != methodOwner)
  16573. markVal = Cast(NULL, markVal, methodOwner);
  16574. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  16575. exprEvaluator.CreateCall(NULL, markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  16576. }
  16577. }
  16578. }
  16579. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  16580. {
  16581. Array<BfMethodInstance*> methodInstances;
  16582. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  16583. {
  16584. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  16585. auto chainedMethodInst = methodInstGroup.mDefault;
  16586. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  16587. {
  16588. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  16589. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  16590. {
  16591. methodInstances.push_back(chainedMethodInst);
  16592. }
  16593. }
  16594. }
  16595. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  16596. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  16597. {
  16598. bool isBetter;
  16599. bool isWorse;
  16600. CompareDeclTypes(mCurTypeInstance, lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  16601. if (isBetter == isWorse)
  16602. {
  16603. return false;
  16604. }
  16605. return isWorse;
  16606. });
  16607. if (reverse)
  16608. std::reverse(methodInstances.begin(), methodInstances.end());
  16609. for (auto chainedMethodInst : methodInstances)
  16610. {
  16611. auto declModule = this;
  16612. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  16613. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  16614. BfExprEvaluator exprEvaluator(this);
  16615. SizedArray<BfIRValue, 1> args;
  16616. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  16617. exprEvaluator.CreateCall(NULL, moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  16618. }
  16619. }
  16620. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  16621. {
  16622. BF_ASSERT(mCurMethodInstance->mIsReified);
  16623. if (mCurTypeInstance->mHotTypeData == NULL)
  16624. {
  16625. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  16626. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  16627. }
  16628. auto hotMethod = mCurMethodInstance->mHotMethod;
  16629. for (auto depData : hotMethod->mReferences)
  16630. {
  16631. // Only virtual decls are allowed to already be there
  16632. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  16633. }
  16634. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  16635. int prevSize = (int)hotMethod->mReferences.size();
  16636. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  16637. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  16638. refCount++;
  16639. hotMethod->mReferences.Reserve(refCount);
  16640. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  16641. {
  16642. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  16643. hotThis->mRefCount++;
  16644. hotMethod->mReferences.Insert(0, hotThis);
  16645. prevSize++;
  16646. }
  16647. for (auto val : builder->mAllocatedData)
  16648. {
  16649. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  16650. hotMethod->mReferences.Add(hotAllocation);
  16651. }
  16652. for (auto val : builder->mUsedData)
  16653. hotMethod->mReferences.Add(val);
  16654. for (auto val : builder->mCalledMethods)
  16655. hotMethod->mReferences.Add(val);
  16656. for (auto val : builder->mDevirtualizedCalledMethods)
  16657. {
  16658. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  16659. hotMethod->mReferences.Add(devirtualizedMethod);
  16660. }
  16661. for (auto val : builder->mFunctionPtrs)
  16662. {
  16663. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  16664. hotMethod->mReferences.Add(funcRef);
  16665. }
  16666. for (auto val : builder->mInnerMethods)
  16667. {
  16668. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  16669. hotMethod->mReferences.Add(innerMethod);
  16670. }
  16671. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  16672. {
  16673. auto depData = hotMethod->mReferences[refIdx];
  16674. BF_ASSERT(depData != NULL);
  16675. depData->mRefCount++;
  16676. }
  16677. }
  16678. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  16679. {
  16680. auto methodDef = methodInstance->mMethodDef;
  16681. auto methodDeclaration = methodDef->mMethodDeclaration;
  16682. bool isThisStruct = false;
  16683. if (thisType != NULL)
  16684. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  16685. int argIdx = 0;
  16686. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16687. argIdx++;
  16688. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16689. if (!methodDef->mIsStatic)
  16690. {
  16691. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16692. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16693. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  16694. paramVar->mIsBumpAlloc = true;
  16695. paramVar->mResolvedType = thisType;
  16696. paramVar->mName.Reference("this");
  16697. if (!thisType->IsValuelessType())
  16698. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16699. else
  16700. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  16701. if ((!mIsComptimeModule) && (thisType->IsSplattable()) && (methodInstance->AllowsSplatting(-1)))
  16702. {
  16703. if (!thisType->IsTypedPrimitive())
  16704. paramVar->mIsSplat = true;
  16705. }
  16706. else if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  16707. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  16708. auto thisTypeInst = thisType->ToTypeInstance();
  16709. paramVar->mIsStruct = isThisStruct;
  16710. paramVar->mAddr = BfIRValue();
  16711. paramVar->mIsThis = true;
  16712. paramVar->mParamIdx = -1;
  16713. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  16714. {
  16715. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  16716. }
  16717. else
  16718. {
  16719. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16720. }
  16721. paramVar->mReadFromId = -1;
  16722. paramVar->Init();
  16723. if (methodDeclaration == NULL)
  16724. UseDefaultSrcPos();
  16725. AddLocalVariableDef(paramVar);
  16726. if (!thisType->IsValuelessType())
  16727. {
  16728. if (wantsDIData)
  16729. {
  16730. BfType* thisPtrType = thisType;
  16731. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  16732. if (!thisType->IsValueType())
  16733. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  16734. else if (!paramVar->mIsSplat)
  16735. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  16736. diParams->push_back(diType);
  16737. }
  16738. if (paramVar->mIsSplat)
  16739. {
  16740. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16741. }
  16742. else
  16743. {
  16744. argIdx++;
  16745. if (loweredTypeCode2 != BfTypeCode_None)
  16746. argIdx++;
  16747. }
  16748. }
  16749. }
  16750. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16751. argIdx++;
  16752. bool hadParams = false;
  16753. bool hasDefault = false;
  16754. int compositeVariableIdx = -1;
  16755. int paramIdx = 0;
  16756. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16757. {
  16758. // We already issues a type error for this param if we had one in declaration processing
  16759. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  16760. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  16761. paramVar->mIsBumpAlloc = true;
  16762. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16763. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16764. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  16765. auto resolvedType = methodInstance->GetParamType(paramIdx);
  16766. if (resolvedType == NULL)
  16767. {
  16768. AssertErrorState();
  16769. paramVar->mParamFailed = true;
  16770. }
  16771. prevIgnoreErrors.Restore();
  16772. PopulateType(resolvedType, BfPopulateType_Declaration);
  16773. paramVar->mResolvedType = resolvedType;
  16774. int namePrefixCount = 0;
  16775. methodInstance->GetParamName(paramIdx, paramVar->mName, namePrefixCount);
  16776. paramVar->mNamePrefixCount = (uint8)namePrefixCount;
  16777. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  16778. if (!isParamSkipped)
  16779. {
  16780. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16781. if (resolvedType->IsMethodRef())
  16782. {
  16783. paramVar->mIsSplat = true;
  16784. }
  16785. else if ((!mIsComptimeModule) && (resolvedType->IsComposite()) && (resolvedType->IsSplattable()))
  16786. {
  16787. if (methodInstance->AllowsSplatting(paramIdx))
  16788. {
  16789. auto resolveTypeInst = resolvedType->ToTypeInstance();
  16790. if ((resolveTypeInst != NULL) && (resolveTypeInst->mIsCRepr))
  16791. paramVar->mIsSplat = true;
  16792. else
  16793. {
  16794. int splatCount = resolvedType->GetSplatCount();
  16795. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16796. paramVar->mIsSplat = true;
  16797. }
  16798. }
  16799. }
  16800. }
  16801. else
  16802. {
  16803. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  16804. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  16805. }
  16806. paramVar->mIsLowered = (!mIsComptimeModule) && resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  16807. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  16808. paramVar->mParamIdx = paramIdx;
  16809. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  16810. paramVar->mReadFromId = 0;
  16811. if (resolvedType->IsRef())
  16812. {
  16813. auto refType = (BfRefType*)resolvedType;
  16814. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  16815. if (refType->mRefKind == BfRefType::RefKind_In)
  16816. {
  16817. paramVar->mIsReadOnly = true;
  16818. }
  16819. }
  16820. else
  16821. {
  16822. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16823. if (methodDef->mMethodType != BfMethodType_Mixin)
  16824. paramVar->mIsReadOnly = true;
  16825. }
  16826. if (paramVar->mResolvedType->IsGenericParam())
  16827. {
  16828. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  16829. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  16830. {
  16831. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  16832. paramVar->mResolvedType = typedVal.mType;
  16833. paramVar->mConstValue = typedVal.mValue;
  16834. }
  16835. }
  16836. if (paramVar->mResolvedType->IsConstExprValue())
  16837. {
  16838. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  16839. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  16840. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  16841. BF_ASSERT(unspecParamType->IsGenericParam());
  16842. if (unspecParamType->IsGenericParam())
  16843. {
  16844. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  16845. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  16846. {
  16847. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  16848. if (genericParamInst->mTypeConstraint != NULL)
  16849. {
  16850. BfExprEvaluator exprEvaluator(this);
  16851. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  16852. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  16853. auto checkType = genericParamInst->mTypeConstraint;
  16854. if (checkType->IsTypedPrimitive())
  16855. checkType = checkType->GetUnderlyingType();
  16856. auto typedVal = exprEvaluator.mResult;
  16857. if ((typedVal) && (typedVal.mType != checkType))
  16858. typedVal = Cast(NULL, typedVal, checkType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  16859. if ((typedVal.mType == checkType) && (typedVal.mValue.IsConst()))
  16860. {
  16861. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  16862. paramVar->mConstValue = typedVal.mValue;
  16863. BF_ASSERT(paramVar->mConstValue.IsConst());
  16864. paramVar->mIsConst = true;
  16865. }
  16866. else
  16867. {
  16868. AssertErrorState();
  16869. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  16870. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  16871. paramVar->mIsConst = true;
  16872. }
  16873. if (paramVar->mResolvedType->IsObject())
  16874. {
  16875. BfTypedValue typedVal(paramVar->mConstValue, paramVar->mResolvedType);
  16876. FixValueActualization(typedVal);
  16877. if (typedVal.mValue.IsConst())
  16878. paramVar->mConstValue = typedVal.mValue;
  16879. }
  16880. }
  16881. }
  16882. }
  16883. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  16884. if (paramVar->mResolvedType->IsConstExprValue())
  16885. {
  16886. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  16887. //AssertErrorState();
  16888. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  16889. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  16890. paramVar->mIsConst = true;
  16891. }
  16892. }
  16893. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  16894. {
  16895. if (compositeVariableIdx == -1)
  16896. {
  16897. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  16898. BfLocalVariable* localVar = new BfLocalVariable();
  16899. auto paramInst = &methodInstance->mParams[paramIdx];
  16900. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  16901. localVar->mName = paramDef->mName;
  16902. localVar->mNamePrefixCount = paramDef->mNamePrefixCount;
  16903. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  16904. localVar->mCompositeCount = 0;
  16905. DoAddLocalVariable(localVar);
  16906. }
  16907. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  16908. paramVar->mIsImplicitParam = true;
  16909. }
  16910. if (!mCurTypeInstance->IsDelegateOrFunction())
  16911. CheckVariableDef(paramVar);
  16912. paramVar->Init();
  16913. AddLocalVariableDef(paramVar);
  16914. if (!isParamSkipped)
  16915. {
  16916. if (wantsDIData)
  16917. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  16918. if (paramVar->mIsSplat)
  16919. {
  16920. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16921. }
  16922. else
  16923. {
  16924. argIdx++;
  16925. }
  16926. if (loweredTypeCode2 != BfTypeCode_None)
  16927. argIdx++;
  16928. }
  16929. }
  16930. // Try to find an ending delegate params composite
  16931. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  16932. {
  16933. auto paramDef = methodDef->mParams.back();
  16934. if (paramDef->mParamKind == BfParamKind_Params)
  16935. {
  16936. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  16937. if (paramsType == NULL)
  16938. {
  16939. // Had error or 'var'
  16940. }
  16941. else if (paramsType->IsGenericParam())
  16942. {
  16943. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  16944. if (genericParamInstance->mTypeConstraint != NULL)
  16945. {
  16946. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16947. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16948. ((typeInstConstraint != NULL) &&
  16949. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  16950. {
  16951. BfLocalVariable* localVar = new BfLocalVariable();
  16952. localVar->mName = paramDef->mName;
  16953. localVar->mResolvedType = paramsType;
  16954. localVar->mCompositeCount = 0;
  16955. DoAddLocalVariable(localVar);
  16956. }
  16957. }
  16958. }
  16959. else if (paramsType->IsDelegate())
  16960. {
  16961. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  16962. if (invokeMethodInstance != NULL)
  16963. {
  16964. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  16965. // and wasn't cleared by the preceding loop
  16966. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  16967. BfLocalVariable* localVar = new BfLocalVariable();
  16968. localVar->mName = paramDef->mName;
  16969. localVar->mResolvedType = paramsType;
  16970. localVar->mCompositeCount = 0;
  16971. DoAddLocalVariable(localVar);
  16972. }
  16973. }
  16974. }
  16975. }
  16976. }
  16977. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  16978. {
  16979. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  16980. // return;
  16981. auto startMethodState = mCurMethodState;
  16982. auto _ClearState = [&]()
  16983. {
  16984. mCurMethodState->mLocalMethods.Clear();
  16985. for (auto& local : mCurMethodState->mLocals)
  16986. {
  16987. if (local->mIsBumpAlloc)
  16988. local->~BfLocalVariable();
  16989. else
  16990. delete local;
  16991. }
  16992. mCurMethodState->mLocals.Clear();
  16993. mCurMethodState->mLocalVarSet.Clear();
  16994. };
  16995. while (true)
  16996. {
  16997. bool didWork = false;
  16998. // 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
  16999. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  17000. // however (compiler bug), so this is the safest way
  17001. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  17002. {
  17003. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  17004. {
  17005. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  17006. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  17007. if (!mHadBuildError)
  17008. {
  17009. // Process as a closure - that allows us to look back and see the const locals and stuff
  17010. BfClosureState closureState;
  17011. mCurMethodState->mClosureState = &closureState;
  17012. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17013. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  17014. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  17015. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  17016. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  17017. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17018. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  17019. _ClearState();
  17020. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  17021. {
  17022. auto localVar = new BfLocalVariable();
  17023. *localVar = constLocal;
  17024. DoAddLocalVariable(localVar);
  17025. }
  17026. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  17027. bool doProcess = !mCompiler->mCanceling;
  17028. if (doProcess)
  17029. {
  17030. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  17031. ProcessMethod(deferredLocalMethod->mMethodInstance);
  17032. }
  17033. }
  17034. delete deferredLocalMethod;
  17035. mContext->CheckLockYield();
  17036. didWork = true;
  17037. }
  17038. mCurMethodState->mDeferredLocalMethods.Clear();
  17039. }
  17040. for (auto& kv : mCurMethodState->mLocalMethodCache)
  17041. {
  17042. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  17043. }
  17044. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  17045. {
  17046. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  17047. {
  17048. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  17049. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  17050. BfClosureState closureState;
  17051. mCurMethodState->mClosureState = &closureState;
  17052. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17053. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  17054. if (lambdaInstance->mClosureTypeInstance != NULL)
  17055. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  17056. else
  17057. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  17058. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17059. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  17060. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  17061. _ClearState();
  17062. for (auto& constLocal : lambdaInstance->mConstLocals)
  17063. {
  17064. //if (constLocal.mIsThis)
  17065. {
  17066. // Valueless 'this'
  17067. closureState.mConstLocals.Add(constLocal);
  17068. }
  17069. /*else
  17070. {
  17071. auto localVar = new BfLocalVariable();
  17072. *localVar = constLocal;
  17073. DoAddLocalVariable(localVar);
  17074. }*/
  17075. }
  17076. BfMethodInstanceGroup methodInstanceGroup;
  17077. methodInstanceGroup.mOwner = mCurTypeInstance;
  17078. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  17079. bool doProcess = !mCompiler->mCanceling;
  17080. if (doProcess)
  17081. {
  17082. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  17083. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17084. ProcessMethod(lambdaInstance->mMethodInstance);
  17085. lambdaInstance->mMethodInstance->mMethodInstanceGroup = NULL;
  17086. if (lambdaInstance->mDtorMethodInstance != NULL)
  17087. {
  17088. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17089. auto startMethodState2 = mCurMethodState;
  17090. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  17091. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = NULL;
  17092. }
  17093. }
  17094. didWork = true;
  17095. }
  17096. mContext->CheckLockYield();
  17097. mCurMethodState->mDeferredLambdaInstances.Clear();
  17098. }
  17099. if (!didWork)
  17100. break;
  17101. }
  17102. }
  17103. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance, bool isAppendObject)
  17104. {
  17105. if (checkType->IsComposite())
  17106. PopulateType(checkType, BfPopulateType_Data);
  17107. if (!checkType->WantsGCMarking())
  17108. return;
  17109. auto typeInstance = checkType->ToTypeInstance();
  17110. bool callMarkMethod = false;
  17111. // Call the actual marking method
  17112. if (memberDepth == 0)
  17113. {
  17114. // Don't call marking method on self
  17115. }
  17116. else if (checkType->IsObjectOrInterface())
  17117. {
  17118. if (!objectOffsets.Add(curOffset))
  17119. {
  17120. return;
  17121. }
  17122. callMarkMethod = true;
  17123. }
  17124. else if (checkType->IsSizedArray())
  17125. {
  17126. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  17127. if (sizedArrayType->mElementType->WantsGCMarking())
  17128. {
  17129. BfTypedValue arrayValue = thisValue;
  17130. if (thisValue.mType != checkType)
  17131. {
  17132. BfIRValue srcValue = thisValue.mValue;
  17133. if (curOffset != 0)
  17134. {
  17135. if (!thisValue.mType->IsPointer())
  17136. {
  17137. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17138. auto int8PtrType = CreatePointerType(int8Type);
  17139. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  17140. }
  17141. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  17142. }
  17143. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  17144. }
  17145. if (sizedArrayType->mElementCount > 6)
  17146. {
  17147. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  17148. auto itr = CreateAlloca(intPtrType);
  17149. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  17150. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  17151. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  17152. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  17153. mBfIRBuilder->CreateBr(loopBB);
  17154. mBfIRBuilder->SetInsertPoint(loopBB);
  17155. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  17156. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  17157. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  17158. mBfIRBuilder->SetInsertPoint(bodyBB);
  17159. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17160. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17161. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  17162. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17163. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17164. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  17165. mBfIRBuilder->CreateStore(incValue, itr);
  17166. mBfIRBuilder->CreateBr(loopBB);
  17167. mBfIRBuilder->SetInsertPoint(doneBB);
  17168. }
  17169. else
  17170. {
  17171. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  17172. {
  17173. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17174. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17175. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  17176. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17177. HashSet<int> objectOffsets;
  17178. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17179. }
  17180. }
  17181. }
  17182. }
  17183. else if (typeInstance != NULL)
  17184. {
  17185. typeInstance->mTypeDef->PopulateMemberSets();
  17186. BfMemberSetEntry* entry = NULL;
  17187. BfMethodDef* methodDef = NULL;
  17188. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  17189. {
  17190. methodDef = (BfMethodDef*)entry->mMemberDef;
  17191. if (methodDef->HasBody())
  17192. {
  17193. callMarkMethod = true;
  17194. }
  17195. }
  17196. }
  17197. if (callMarkMethod)
  17198. {
  17199. BfTypedValue markValue;
  17200. auto memberType = checkType;
  17201. if (memberType->IsObjectOrInterface())
  17202. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  17203. auto memberPtrType = CreatePointerType(memberType);
  17204. if (curOffset == 0)
  17205. {
  17206. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17207. }
  17208. else
  17209. {
  17210. if (!thisValue.mType->IsPointer())
  17211. {
  17212. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17213. auto int8PtrType = CreatePointerType(int8Type);
  17214. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  17215. }
  17216. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  17217. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17218. }
  17219. if (isAppendObject)
  17220. EmitGCMarkAppended(markValue);
  17221. else
  17222. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17223. return;
  17224. }
  17225. auto methodDef = mCurMethodInstance->mMethodDef;
  17226. if (checkType->IsPayloadEnum())
  17227. {
  17228. for (auto& fieldInst : typeInstance->mFieldInstances)
  17229. {
  17230. if (!fieldInst.mIsEnumPayloadCase)
  17231. continue;
  17232. auto fieldDef = fieldInst.GetFieldDef();
  17233. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17234. }
  17235. return;
  17236. }
  17237. if (typeInstance == NULL)
  17238. return;
  17239. for (auto& fieldInst : typeInstance->mFieldInstances)
  17240. {
  17241. auto fieldDef = fieldInst.GetFieldDef();
  17242. if (fieldDef == NULL)
  17243. continue;
  17244. if (fieldDef->mIsStatic)
  17245. continue;
  17246. if (typeInstance == mCurTypeInstance)
  17247. {
  17248. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  17249. // we may be marking member values that can never contain a value anyway, but this is benign
  17250. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17251. continue;
  17252. }
  17253. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance, fieldInst.IsAppendedObject());
  17254. }
  17255. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  17256. {
  17257. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17258. }
  17259. }
  17260. void BfModule::EmitGCMarkMembers()
  17261. {
  17262. auto methodDef = mCurMethodInstance->mMethodDef;
  17263. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  17264. BfModuleMethodInstance markFromGCThreadMethodInstance;
  17265. if (gcType != NULL)
  17266. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  17267. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  17268. {
  17269. if (mCurTypeInstance->IsBoxed())
  17270. {
  17271. // This already gets filled in by the normal boxed forwarding
  17272. }
  17273. else
  17274. {
  17275. auto thisValue = GetThis();
  17276. if (thisValue.IsSplat())
  17277. {
  17278. BfIRFunction func = mCurMethodInstance->mIRFunction;
  17279. int argIdx = 0;
  17280. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  17281. {
  17282. if (checkType->IsStruct())
  17283. {
  17284. auto checkTypeInstance = checkType->ToTypeInstance();
  17285. if (checkTypeInstance->mBaseType != NULL)
  17286. checkTypeLambda(checkTypeInstance->mBaseType);
  17287. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  17288. {
  17289. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  17290. if (fieldInstance->mDataIdx >= 0)
  17291. checkTypeLambda(fieldInstance->GetResolvedType());
  17292. }
  17293. }
  17294. else if (checkType->IsMethodRef())
  17295. {
  17296. BFMODULE_FATAL(this, "Not handled");
  17297. }
  17298. else if (checkType->WantsGCMarking())
  17299. {
  17300. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  17301. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17302. argIdx++;
  17303. }
  17304. };
  17305. checkTypeLambda(thisValue.mType);
  17306. }
  17307. else if (!methodDef->mIsStatic)
  17308. {
  17309. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  17310. {
  17311. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  17312. if (moduleMethodInst)
  17313. {
  17314. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  17315. bool wantsBaseMarking = true;
  17316. if (methodBaseType == mContext->mBfObjectType)
  17317. {
  17318. wantsBaseMarking = false;
  17319. PopulateType(methodBaseType);
  17320. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  17321. {
  17322. if ((fieldInstance.GetFieldDef()->mDeclaringType->IsExtension()) &&
  17323. (fieldInstance.mResolvedType->WantsGCMarking()))
  17324. wantsBaseMarking = true;
  17325. }
  17326. }
  17327. if (wantsBaseMarking)
  17328. {
  17329. auto thisValue = GetThis();
  17330. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  17331. SizedArray<BfIRValue, 1> args;
  17332. if ((!mIsComptimeModule) && (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1)))
  17333. {
  17334. BfExprEvaluator exprEvaluator(this);
  17335. exprEvaluator.SplatArgs(baseValue, args);
  17336. }
  17337. else
  17338. {
  17339. args.push_back(baseValue.mValue);
  17340. }
  17341. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  17342. }
  17343. }
  17344. }
  17345. }
  17346. if (!methodDef->mIsStatic)
  17347. {
  17348. HashSet<int> objectOffsets;
  17349. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  17350. }
  17351. else
  17352. {
  17353. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17354. {
  17355. if (thisValue.IsSplat())
  17356. break;
  17357. auto fieldDef = fieldInst.GetFieldDef();
  17358. if (fieldDef == NULL)
  17359. continue;
  17360. if (IsThreadLocal(&fieldInst))
  17361. continue;
  17362. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  17363. {
  17364. // For extensions, only handle these fields in the appropriate extension
  17365. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17366. continue;
  17367. if (!fieldInst.mFieldIncluded)
  17368. continue;
  17369. auto fieldType = fieldInst.mResolvedType;
  17370. auto fieldDef = fieldInst.GetFieldDef();
  17371. BfTypedValue markVal;
  17372. if (fieldDef->mIsConst)
  17373. continue;
  17374. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17375. continue;
  17376. mBfIRBuilder->PopulateType(fieldType);
  17377. if (fieldType->IsValuelessType())
  17378. continue;
  17379. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  17380. {
  17381. StringT<512> staticVarName;
  17382. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  17383. if (staticVarName.StartsWith('#'))
  17384. continue;
  17385. markVal = ReferenceStaticField(&fieldInst);
  17386. }
  17387. else if (!fieldDef->mIsStatic)
  17388. {
  17389. if (fieldInst.IsAppendedObject())
  17390. {
  17391. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst.mDataIdx);
  17392. auto val = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  17393. markVal = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst.mResolvedType)), fieldInst.mResolvedType);
  17394. }
  17395. else
  17396. {
  17397. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  17398. }
  17399. }
  17400. if (markVal)
  17401. {
  17402. if (fieldInst.IsAppendedObject())
  17403. EmitGCMarkAppended(markVal);
  17404. else
  17405. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  17406. }
  17407. }
  17408. }
  17409. }
  17410. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17411. CallChainedMethods(mCurMethodInstance, false);
  17412. }
  17413. }
  17414. }
  17415. void BfModule::EmitGCFindTLSMembers()
  17416. {
  17417. auto methodDef = mCurMethodInstance->mMethodDef;
  17418. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  17419. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  17420. BF_ASSERT(reportTLSMark);
  17421. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17422. {
  17423. auto fieldDef = fieldInst.GetFieldDef();
  17424. if (fieldDef == NULL)
  17425. continue;
  17426. if (!IsThreadLocal(&fieldInst))
  17427. continue;
  17428. // For extensions, only handle these fields in the appropriate extension
  17429. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17430. continue;
  17431. if (!fieldInst.mFieldIncluded)
  17432. continue;
  17433. if (fieldDef->mIsConst)
  17434. continue;
  17435. auto fieldType = fieldInst.mResolvedType;
  17436. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17437. continue;
  17438. if (fieldType->IsValuelessType())
  17439. continue;
  17440. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  17441. if (markVal)
  17442. {
  17443. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  17444. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  17445. SizedArray<BfIRValue, 2> llvmArgs;
  17446. llvmArgs.push_back(fieldRefPtr);
  17447. llvmArgs.push_back(markFuncPtr);
  17448. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  17449. }
  17450. }
  17451. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17452. CallChainedMethods(mCurMethodInstance, false);
  17453. }
  17454. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup, bool forceIRWrites)
  17455. {
  17456. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  17457. if (mIsComptimeModule)
  17458. {
  17459. BF_ASSERT(!mCompiler->IsAutocomplete());
  17460. }
  17461. if (mAwaitingInitFinish)
  17462. FinishInit();
  17463. if ((methodInstance->mIsReified) && (!mCompiler->mIsResolveOnly))
  17464. {
  17465. BfLogSysM("REIFIED(ProcessMethod): %s %p Module: %s\n", methodInstance->mMethodDef->mName.c_str(), methodInstance, mModuleName.c_str());
  17466. }
  17467. // Reify types that are actually used - they don't get reified during method declaration
  17468. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  17469. {
  17470. auto _CheckType = [&](BfType* type)
  17471. {
  17472. if (!type->IsReified())
  17473. PopulateType(type, BfPopulateType_Declaration);
  17474. };
  17475. _CheckType(methodInstance->mReturnType);
  17476. for (auto& param : methodInstance->mParams)
  17477. {
  17478. _CheckType(param.mResolvedType);
  17479. }
  17480. }
  17481. if (!methodInstance->mIsReified)
  17482. BF_ASSERT(!mIsReified);
  17483. BF_ASSERT((!methodInstance->GetOwner()->IsUnspecializedTypeVariation()) || (mIsComptimeModule));
  17484. if (methodInstance->mMethodInfoEx != NULL)
  17485. {
  17486. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  17487. {
  17488. if (methodGenericArg->IsMethodRef())
  17489. {
  17490. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  17491. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  17492. }
  17493. }
  17494. }
  17495. if (mBfIRBuilder == NULL)
  17496. {
  17497. BfLogSysM("ProcessMethod %p calling EnsureIRBuilder\n", methodInstance);
  17498. EnsureIRBuilder();
  17499. }
  17500. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, (mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized) && (!forceIRWrites));
  17501. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  17502. {
  17503. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  17504. }
  17505. SetAndRestoreValue<bool> prevIsClassifying;
  17506. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  17507. (mCompiler->mResolvePassData != NULL))
  17508. {
  17509. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  17510. prevIsClassifying.Init(mCompiler->mResolvePassData->mIsClassifying, false);
  17511. }
  17512. if (methodInstance->mHasBeenProcessed)
  17513. {
  17514. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  17515. return;
  17516. }
  17517. if (methodInstance->mFailedConstraints)
  17518. {
  17519. // The only way this should be able to happen is if we fail our generic param check
  17520. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  17521. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  17522. methodInstance->mHasBeenProcessed = true;
  17523. return;
  17524. }
  17525. if (HasExecutedOutput())
  17526. {
  17527. BF_ASSERT(mIsModuleMutable);
  17528. }
  17529. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  17530. if (!mIsComptimeModule)
  17531. {
  17532. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  17533. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  17534. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  17535. {
  17536. auto owningModule = methodInstance->GetOwner()->mModule;
  17537. if (owningModule->mIsScratchModule)
  17538. {
  17539. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  17540. }
  17541. else
  17542. {
  17543. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  17544. if (owningModule->mOnDemandMethodCount > 0)
  17545. owningModule->mOnDemandMethodCount--;
  17546. }
  17547. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  17548. VerifyOnDemandMethods();
  17549. }
  17550. }
  17551. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  17552. // self-referencing append allocations in ctor@calcAppend
  17553. methodInstance->mHasBeenProcessed = true;
  17554. mIncompleteMethodCount--;
  17555. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  17556. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  17557. auto methodDef = methodInstance->mMethodDef;
  17558. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17559. if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  17560. mBfIRBuilder->mIgnoreWrites = true;
  17561. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  17562. {
  17563. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  17564. // so we get the new vdata for it
  17565. methodInstance->GetOwner()->mDirty = true;
  17566. }
  17567. int dependentGenericStartIdx = 0;
  17568. if ((methodDef->mIsLocalMethod) && (mCurMethodState != NULL)) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  17569. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  17570. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  17571. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  17572. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  17573. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  17574. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  17575. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors);
  17576. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, mIsComptimeModule);
  17577. if ((!mIsComptimeModule) && (methodInstance->mIsReified) &&
  17578. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  17579. {
  17580. mCurTypeInstance->mHasBeenInstantiated = true;
  17581. }
  17582. // Warnings are shown in the capture phase
  17583. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  17584. mIgnoreWarnings = true;
  17585. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  17586. UseDefaultSrcPos();
  17587. if ((mIsComptimeModule) && (methodDef->mIsStatic))
  17588. {
  17589. PopulateType(mCurTypeInstance, BfPopulateType_AllowStaticMethods);
  17590. }
  17591. else
  17592. {
  17593. // We may not actually be populated in relatively rare autocompelte cases
  17594. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  17595. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  17596. }
  17597. BfAstNode* nameNode = NULL;
  17598. if (methodDeclaration != NULL)
  17599. {
  17600. nameNode = methodDeclaration->mNameNode;
  17601. if (nameNode == NULL)
  17602. {
  17603. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  17604. nameNode = ctorDeclaration->mThisToken;
  17605. }
  17606. }
  17607. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  17608. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) &&
  17609. (methodDef->mIdx >= 0) && (!methodInstance->mIsForeignMethodDef))
  17610. {
  17611. if (methodInstance->GetExplicitInterface() == NULL)
  17612. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  17613. else
  17614. {
  17615. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  17616. {
  17617. auto ifaceInst = ifaceEntry.mInterfaceType;
  17618. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  17619. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17620. if (methodInstance->GetExplicitInterface() != ifaceInst)
  17621. continue;
  17622. ifaceInst->mTypeDef->PopulateMemberSets();
  17623. BfMethodDef* nextMethod = NULL;
  17624. BfMemberSetEntry* entry = NULL;
  17625. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17626. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17627. while (nextMethod != NULL)
  17628. {
  17629. auto checkMethod = nextMethod;
  17630. nextMethod = nextMethod->mNextWithSameName;
  17631. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  17632. if (implMethodInst == methodInstance)
  17633. {
  17634. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  17635. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  17636. }
  17637. }
  17638. }
  17639. }
  17640. if (methodDef->mIsOverride)
  17641. {
  17642. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  17643. {
  17644. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  17645. if (ventry.mDeclaringMethod.mMethodNum == -1)
  17646. continue;
  17647. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  17648. if (virtMethod != NULL)
  17649. {
  17650. if (virtMethod == methodInstance)
  17651. {
  17652. // Is matching method
  17653. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  17654. {
  17655. auto baseType = mCurTypeInstance->mBaseType;
  17656. if (baseType != NULL)
  17657. {
  17658. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  17659. baseType = baseType->mBaseType;
  17660. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  17661. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  17662. }
  17663. }
  17664. break;
  17665. }
  17666. }
  17667. }
  17668. }
  17669. }
  17670. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d Incomplete:%d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified, mIncompleteMethodCount);
  17671. int importStrNum = -1;
  17672. auto importKind = methodInstance->GetImportKind();
  17673. if ((!mCompiler->mIsResolveOnly) &&
  17674. ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic)))
  17675. {
  17676. if (auto customAttr = methodInstance->GetCustomAttributes()->Get(mCompiler->mImportAttributeTypeDef))
  17677. {
  17678. if (customAttr->mCtorArgs.size() == 1)
  17679. {
  17680. auto fileNameArg = customAttr->mCtorArgs[0];
  17681. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  17682. if (constant != NULL)
  17683. {
  17684. if (!constant->IsNull())
  17685. importStrNum = constant->mInt32;
  17686. }
  17687. else
  17688. {
  17689. importStrNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  17690. }
  17691. if (importStrNum != -1)
  17692. {
  17693. if (!mStringPoolRefs.Contains(importStrNum))
  17694. mStringPoolRefs.Add(importStrNum);
  17695. }
  17696. }
  17697. }
  17698. }
  17699. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  17700. {
  17701. if (mBfIRBuilder->mIgnoreWrites)
  17702. return;
  17703. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  17704. if (!methodInstance->mIRFunction)
  17705. {
  17706. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  17707. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  17708. BF_ASSERT(dllImportGlobalVar || methodInstance->mHasFailed);
  17709. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  17710. }
  17711. if (HasCompiledOutput())
  17712. {
  17713. BfDllImportEntry dllImportEntry;
  17714. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  17715. dllImportEntry.mMethodInstance = mCurMethodInstance;
  17716. mDllImportEntries.push_back(dllImportEntry);
  17717. }
  17718. return;
  17719. }
  17720. StringT<512> mangledName;
  17721. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  17722. if (!methodInstance->mIRFunction)
  17723. {
  17724. bool isIntrinsic = false;
  17725. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  17726. }
  17727. if (methodInstance->mIsIntrinsic)
  17728. return;
  17729. if (mCurTypeInstance->IsFunction())
  17730. return;
  17731. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  17732. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  17733. if (methodDef->mBody != NULL)
  17734. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17735. else if (methodDeclaration != NULL)
  17736. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17737. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17738. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  17739. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17740. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17741. if ((mCurMethodState == NULL) && (!IsInSpecializedSection())) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  17742. {
  17743. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()))
  17744. {
  17745. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(methodDef->mBody))
  17746. sourceClassifier->VisitChildNoRef(methodDef->mBody);
  17747. }
  17748. }
  17749. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  17750. BfMethodState methodState;
  17751. if (mCurMethodState != NULL)
  17752. methodState.mClosureState = mCurMethodState->mClosureState;
  17753. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  17754. {
  17755. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  17756. if (methodInstance->mHotMethod == NULL)
  17757. CheckHotMethod(methodInstance, mangledName);
  17758. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  17759. }
  17760. methodState.mPrevMethodState = mCurMethodState;
  17761. methodState.mMethodInstance = methodInstance;
  17762. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17763. if (methodInstance->GetCustomAttributes() != NULL)
  17764. {
  17765. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  17766. if (typeOptionsIdx != -1)
  17767. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  17768. }
  17769. BfTypeState typeState(mCurTypeInstance);
  17770. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  17771. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  17772. BfMethodInstance* unspecializedMethodInstance = NULL;
  17773. if ((prevMethodState.mPrevVal != NULL) &&
  17774. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  17775. {
  17776. // This is 'inner' (probably a closure) - use binding from outer function
  17777. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  17778. }
  17779. else if ((methodInstance->mIsUnspecialized) ||
  17780. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  17781. {
  17782. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17783. }
  17784. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  17785. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation || mIsComptimeModule) && (!methodInstance->mMethodDef->mIsLocalMethod) && (!methodInstance->mMethodDef->mDeclaringType->IsEmitted()))))
  17786. {
  17787. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  17788. if ((mIsComptimeModule) && (!unspecializedMethodInstance->mHasBeenProcessed))
  17789. {
  17790. // This will have already been populated by CeMachine
  17791. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17792. }
  17793. else
  17794. {
  17795. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  17796. if (!unspecializedMethodInstance->mHasBeenProcessed)
  17797. {
  17798. // Make sure the unspecialized method is processed so we can take its bindings
  17799. // Clear mCurMethodState so we don't think we're in a local method
  17800. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  17801. if (unspecializedMethodInstance->mMethodProcessRequest == NULL)
  17802. unspecializedMethodInstance->mDeclModule->mIncompleteMethodCount++;
  17803. mContext->ProcessMethod(unspecializedMethodInstance);
  17804. }
  17805. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17806. }
  17807. }
  17808. if (methodDef->mMethodType == BfMethodType_Operator)
  17809. {
  17810. auto operatorDef = (BfOperatorDef*) methodDef;
  17811. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  17812. auto paramErrorRefNode = refNode;
  17813. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  17814. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  17815. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  17816. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  17817. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  17818. {
  17819. if (methodDef->mParams.size() != 2)
  17820. {
  17821. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  17822. }
  17823. else
  17824. {
  17825. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17826. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17827. checkParam0 = checkParam0->GetUnderlyingType();
  17828. auto checkParam1 = mCurMethodInstance->GetParamType(1);
  17829. if ((checkParam1->IsRef()) && (!checkParam1->IsOut()))
  17830. checkParam1 = checkParam1->GetUnderlyingType();
  17831. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  17832. (checkParam1 != mCurTypeInstance) && (!checkParam1->IsSelf()))
  17833. {
  17834. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  17835. }
  17836. }
  17837. BfType* wantType = NULL;
  17838. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  17839. {
  17840. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  17841. }
  17842. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  17843. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  17844. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  17845. }
  17846. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  17847. {
  17848. if (methodDef->mIsStatic)
  17849. {
  17850. if (methodDef->mParams.size() != 1)
  17851. {
  17852. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  17853. }
  17854. else
  17855. {
  17856. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17857. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17858. checkParam0 = checkParam0->GetUnderlyingType();
  17859. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()))
  17860. {
  17861. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  17862. }
  17863. }
  17864. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  17865. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  17866. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  17867. {
  17868. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  17869. }
  17870. }
  17871. else
  17872. {
  17873. if (methodDef->mParams.size() != 0)
  17874. {
  17875. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  17876. }
  17877. if (!mCurMethodInstance->mReturnType->IsVoid())
  17878. {
  17879. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  17880. }
  17881. }
  17882. }
  17883. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  17884. {
  17885. if (methodDef->mParams.size() != 1)
  17886. {
  17887. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  17888. }
  17889. if (!mCurMethodInstance->mReturnType->IsVoid())
  17890. {
  17891. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  17892. }
  17893. }
  17894. else // Conversion
  17895. {
  17896. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  17897. {
  17898. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  17899. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  17900. }
  17901. if (methodDef->mParams.size() != 1)
  17902. {
  17903. auto refNode = paramErrorRefNode;
  17904. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  17905. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  17906. Fail("Conversion operators must declare one parameter", refNode);
  17907. }
  17908. else if ((methodInstance->mMethodInfoEx == NULL) ||
  17909. (methodInstance->mMethodInfoEx->mMethodGenericArguments.IsEmpty()) ||
  17910. ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation)))
  17911. {
  17912. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17913. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17914. checkParam0 = checkParam0->GetUnderlyingType();
  17915. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  17916. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  17917. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  17918. if (checkParam0 == mCurMethodInstance->mReturnType)
  17919. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  17920. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  17921. // happened here
  17922. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (checkParam0 != mContext->mBfObjectType)))
  17923. {
  17924. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  17925. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, checkParam0->ToTypeInstance());
  17926. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  17927. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  17928. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  17929. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  17930. }
  17931. }
  17932. }
  17933. }
  17934. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mBfIRBuilder->mIgnoreWrites) && (mHasFullDebugInfo);
  17935. if (methodDef->mMethodType == BfMethodType_Mixin)
  17936. wantsDIData = false;
  17937. if (mCurTypeInstance->IsUnspecializedType())
  17938. wantsDIData = false;
  17939. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  17940. wantsDIData = false;
  17941. bool wantsDIVariables = wantsDIData;
  17942. if (methodDef->mIsExtern)
  17943. wantsDIVariables = false;
  17944. SizedArray<BfIRMDNode, 8> diParams;
  17945. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  17946. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  17947. BfType* thisType = NULL;
  17948. if (!methodDef->mIsStatic)
  17949. {
  17950. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  17951. thisType = methodState.mClosureState->mClosureType;
  17952. else
  17953. thisType = mCurTypeInstance;
  17954. }
  17955. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  17956. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  17957. //////////////////////////////////////////////////////////////////////////
  17958. //
  17959. {
  17960. if (methodDeclaration != NULL)
  17961. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17962. else if (methodDef->mBody != NULL)
  17963. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17964. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17965. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  17966. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17967. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17968. }
  17969. BfIRMDNode diFunction;
  17970. if (wantsDIData)
  17971. {
  17972. BP_ZONE("BfModule::DoMethodDeclaration.DISetup");
  17973. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  17974. int defLine = mCurFilePosition.mCurLine;
  17975. if (mDICompileUnit)
  17976. {
  17977. int flags = 0;
  17978. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  17979. if (methodDef->mProtection == BfProtection_Public)
  17980. flags = llvm::DINode::FlagPublic;
  17981. else if (methodDef->mProtection == BfProtection_Protected)
  17982. flags = llvm::DINode::FlagProtected;
  17983. else
  17984. flags = llvm::DINode::FlagPrivate;
  17985. if (methodDef->mIsOverride)
  17986. {
  17987. //flags |= llvm::DINode::FlagVirtual;
  17988. }
  17989. else if (methodDef->mIsVirtual)
  17990. flags |= llvm::DINode::FlagIntroducedVirtual;
  17991. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  17992. flags |= llvm::DINode::FlagStaticMember;
  17993. else
  17994. {
  17995. if ((mCurTypeInstance->IsValuelessType()) ||
  17996. ((!mIsComptimeModule) && (mCurTypeInstance->IsSplattable())))
  17997. flags |= llvm::DINode::FlagStaticMember;
  17998. }
  17999. flags |= llvm::DINode::FlagPrototyped;
  18000. if (methodDef->mMethodType == BfMethodType_Ctor)
  18001. {
  18002. flags |= llvm::DINode::FlagArtificial;
  18003. }
  18004. auto llvmFunction = methodInstance->mIRFunction;
  18005. SizedArray<BfIRMDNode, 1> genericArgs;
  18006. SizedArray<BfIRValue, 1> genericConstValueArgs;
  18007. String methodName;
  18008. if (methodInstance->GetForeignType() != NULL)
  18009. {
  18010. methodName += TypeToString(methodInstance->GetForeignType());
  18011. methodName += ".";
  18012. }
  18013. if (methodInstance->GetExplicitInterface() != NULL)
  18014. {
  18015. methodName += TypeToString(methodInstance->GetExplicitInterface());
  18016. methodName += ".";
  18017. }
  18018. methodName += methodDef->mName;
  18019. if (methodInstance->GetNumGenericArguments() != 0)
  18020. {
  18021. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  18022. {
  18023. if (genericArg->IsConstExprValue())
  18024. {
  18025. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  18026. while (genericConstValueArgs.size() < genericArgs.size())
  18027. genericConstValueArgs.push_back(BfIRValue());
  18028. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  18029. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  18030. }
  18031. else
  18032. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  18033. }
  18034. methodName += "<";
  18035. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  18036. {
  18037. if (i > 0)
  18038. methodName += ", ";
  18039. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  18040. methodName += TypeToString(type);
  18041. }
  18042. methodName += ">";
  18043. }
  18044. if ((methodName.empty()) && (methodDeclaration != NULL))
  18045. {
  18046. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18047. {
  18048. methodName += "operator";
  18049. if (operatorDecl->mIsConvOperator)
  18050. {
  18051. methodName += " ";
  18052. methodName += TypeToString(methodInstance->mReturnType);
  18053. }
  18054. else if (operatorDecl->mOpTypeToken != NULL)
  18055. methodName += operatorDecl->mOpTypeToken->ToString();
  18056. }
  18057. }
  18058. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  18059. methodName += "$CHK";
  18060. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  18061. methodName += "$UCHK";
  18062. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18063. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18064. // defLine + 1, diFuncType, false, true,
  18065. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  18066. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  18067. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18068. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18069. defLine + 1, diFuncType, false, true,
  18070. llvm::dwarf::DW_VIRTUALITY_none,
  18071. 0,
  18072. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18073. }
  18074. else
  18075. {
  18076. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18077. }
  18078. }
  18079. //////////////////////////////////////////////////////////////////////////
  18080. // Head and Init get rolled into Entry afterwards.
  18081. methodState.mIRFunction = methodInstance->mIRFunction;
  18082. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  18083. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  18084. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  18085. methodState.mCurScope->mDIScope = diFunction;
  18086. auto llvmEntryBlock = methodState.mIREntryBlock;
  18087. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  18088. if (methodDef->mName == "__MALFORMED")
  18089. {
  18090. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  18091. mBfIRBuilder->SetInsertPoint(newBlock);
  18092. }
  18093. if (methodDef->mBody != NULL)
  18094. {
  18095. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18096. }
  18097. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  18098. {
  18099. // We want to be able to step into delegate invokes -- we actually step over them
  18100. if (methodDef->mName != "Invoke")
  18101. {
  18102. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18103. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  18104. }
  18105. }
  18106. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18107. mBfIRBuilder->ClearDebugLocation();
  18108. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  18109. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  18110. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  18111. {
  18112. int localIdx = 0;
  18113. int argIdx = 0;
  18114. Array<BfIRValue> splatAddrValues;
  18115. for ( ; argIdx < irParamCount; localIdx++)
  18116. {
  18117. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18118. if ((isThis) && (thisType->IsValuelessType()))
  18119. isThis = false;
  18120. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() == argIdx))
  18121. {
  18122. argIdx++;
  18123. if (argIdx == irParamCount)
  18124. break;
  18125. }
  18126. BfLocalVariable* paramVar = NULL;
  18127. while (true)
  18128. {
  18129. BF_ASSERT(localIdx < methodState.mLocals.size());
  18130. paramVar = methodState.mLocals[localIdx];
  18131. if ((paramVar->mCompositeCount == -1) &&
  18132. (!paramVar->mIsConst) &&
  18133. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  18134. break;
  18135. localIdx++;
  18136. }
  18137. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  18138. {
  18139. paramVar->mIsReadOnly = true;
  18140. }
  18141. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) ||
  18142. ((!mIsComptimeModule) && (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter)));
  18143. if (paramVar->mResolvedType->IsMethodRef())
  18144. wantsAddr = false;
  18145. // if ((methodDef->mHasAppend) && (argIdx == 1))
  18146. // {
  18147. // BF_ASSERT(paramVar->mName == "appendIdx");
  18148. // wantsAddr = true;
  18149. // }
  18150. if (paramVar->mIsSplat)
  18151. {
  18152. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18153. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18154. BfTypeUtils::SplatIterate([&](BfType* checkType)
  18155. {
  18156. BfIRType splatIRType;
  18157. if (checkType->IsComposite())
  18158. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  18159. else
  18160. splatIRType = mBfIRBuilder->MapType(checkType);
  18161. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  18162. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  18163. if (!paramVar->mAddr)
  18164. paramVar->mAddr = allocaInst;
  18165. if (WantsLifetimes())
  18166. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18167. splatAddrValues.push_back(allocaInst);
  18168. }, paramVar->mResolvedType);
  18169. mBfIRBuilder->SetInsertPoint(prevInsert);
  18170. }
  18171. else if (isThis)
  18172. {
  18173. if (wantsAddr)
  18174. {
  18175. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18176. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18177. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  18178. if (paramVar->mIsSplat)
  18179. {
  18180. //
  18181. }
  18182. else
  18183. {
  18184. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  18185. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  18186. wantPtr = true;
  18187. if (wantPtr)
  18188. {
  18189. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  18190. }
  18191. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  18192. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18193. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  18194. paramVar->mAddr = allocaInst;
  18195. if (WantsLifetimes())
  18196. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18197. }
  18198. mBfIRBuilder->SetInsertPoint(prevInsert);
  18199. }
  18200. }
  18201. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  18202. {
  18203. // Address doesn't change so we don't have to alloca it
  18204. BfIRType allocType;
  18205. int alignSize = mSystem->mPtrSize;
  18206. if (paramVar->mResolvedType->IsRef())
  18207. {
  18208. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18209. }
  18210. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  18211. {
  18212. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18213. alignSize = paramVar->mResolvedType->mAlign;
  18214. }
  18215. else
  18216. {
  18217. paramVar->mHasLocalStructBacking = true;
  18218. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  18219. if (typeInst != NULL)
  18220. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  18221. else
  18222. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  18223. }
  18224. if (wantsAddr)
  18225. {
  18226. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18227. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18228. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18229. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  18230. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18231. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  18232. paramVar->mAddr = allocaInst;
  18233. mBfIRBuilder->SetInsertPoint(prevInsert);
  18234. if (WantsLifetimes())
  18235. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18236. }
  18237. }
  18238. else if (wantsAddr)
  18239. {
  18240. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  18241. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18242. paramVar->mAddr = allocaInst;
  18243. }
  18244. if (paramVar->mIsSplat)
  18245. {
  18246. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18247. }
  18248. else if (paramVar->mIsLowered)
  18249. {
  18250. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18251. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18252. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18253. argIdx++;
  18254. if (loweredTypeCode2 != BfTypeCode_None)
  18255. argIdx++;
  18256. }
  18257. else
  18258. {
  18259. argIdx++;
  18260. }
  18261. }
  18262. if (methodDef->mBody != NULL)
  18263. UpdateSrcPos(methodDef->mBody);
  18264. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18265. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18266. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18267. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  18268. localIdx = 0;
  18269. argIdx = 0;
  18270. int splatAddrIdx = 0;
  18271. while (localIdx < (int)methodState.mLocals.size())
  18272. {
  18273. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  18274. argIdx++;
  18275. int curLocalIdx = localIdx++;
  18276. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  18277. if (paramVar->mIsConst)
  18278. continue;
  18279. if (!paramVar->IsParam())
  18280. continue;
  18281. if (paramVar->mCompositeCount != -1)
  18282. continue;
  18283. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18284. if ((isThis) && (thisType->IsValuelessType()))
  18285. isThis = false;
  18286. if (paramVar->mValue.IsArg())
  18287. BF_ASSERT(paramVar->mValue.mId == argIdx);
  18288. BfIRMDNode diVariable;
  18289. if (wantsDIData)
  18290. {
  18291. String paramName = paramVar->mName;
  18292. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18293. if (isThis)
  18294. {
  18295. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  18296. paramName = "__closure";
  18297. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18298. {
  18299. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18300. bool wantRef = paramVar->mResolvedType->IsComposite();
  18301. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  18302. wantRef = true;
  18303. if (wantRef)
  18304. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18305. }
  18306. else if (!paramVar->mResolvedType->IsValueType())
  18307. {
  18308. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  18309. }
  18310. }
  18311. else
  18312. {
  18313. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18314. {
  18315. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18316. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18317. diType = mBfIRBuilder->DbgCreateConstType(diType);
  18318. }
  18319. }
  18320. if (!paramVar->mIsSplat)
  18321. {
  18322. if ((paramVar->mParamIdx >= 0) && (paramVar->mParamIdx < methodInstance->mDefaultValues.mSize))
  18323. {
  18324. auto defaultValue = methodInstance->mDefaultValues[paramVar->mParamIdx];
  18325. auto constant = mCurTypeInstance->mConstHolder->GetConstant(defaultValue.mValue);
  18326. if ((constant != NULL) &&
  18327. ((BfIRConstHolder::IsIntable(constant->mTypeCode)) || (BfIRConstHolder::IsFloat(constant->mTypeCode))))
  18328. {
  18329. int64 writeVal = constant->mInt64;
  18330. if (constant->mTypeCode == BfTypeCode_Float)
  18331. {
  18332. // We need to do this because Singles are stored in mDouble, so we need to reduce here
  18333. float floatVal = (float)constant->mDouble;
  18334. writeVal = *(uint32*)&floatVal;
  18335. }
  18336. if (writeVal < 0)
  18337. paramName += StrFormat("$_%llu", -writeVal);
  18338. else
  18339. paramName += StrFormat("$%llu", writeVal);
  18340. }
  18341. }
  18342. if (paramVar->mResolvedType->IsValuelessType())
  18343. {
  18344. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  18345. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18346. }
  18347. else if (paramVar->mIsImplicitParam)
  18348. {
  18349. // Annotate this specially?
  18350. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18351. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18352. }
  18353. else
  18354. {
  18355. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18356. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18357. }
  18358. paramVar->mDbgVarInst = diVariable;
  18359. }
  18360. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  18361. {
  18362. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  18363. // {
  18364. // // Only add this placeholder if we don't have any values
  18365. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  18366. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18367. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  18368. // }
  18369. }
  18370. }
  18371. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  18372. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  18373. {
  18374. // Write our argument value into the .addr
  18375. mBfIRBuilder->ClearDebugLocation();
  18376. if (paramVar->mIsSplat)
  18377. {
  18378. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18379. //
  18380. }
  18381. else
  18382. {
  18383. bool handled = false;
  18384. if (paramVar->mIsLowered)
  18385. {
  18386. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18387. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18388. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  18389. {
  18390. BfIRValue targetAddr = paramVar->mAddr;
  18391. bool isTempTarget = false;
  18392. int loweredSize = mBfIRBuilder->GetSize(loweredTypeCode) + mBfIRBuilder->GetSize(loweredTypeCode2);
  18393. if (paramVar->mResolvedType->mSize < loweredSize)
  18394. {
  18395. isTempTarget = true;
  18396. targetAddr = CreateAlloca(GetPrimitiveType(BfTypeCode_Int8), true, NULL, GetConstValue(loweredSize));
  18397. mBfIRBuilder->SetAllocaAlignment(targetAddr,
  18398. BF_MAX(paramVar->mResolvedType->mAlign,
  18399. BF_MAX(mBfIRBuilder->GetSize(loweredTypeCode), mBfIRBuilder->GetSize(loweredTypeCode2))));
  18400. }
  18401. // We have a lowered type coming in, so we have to cast the .addr before storing
  18402. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  18403. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  18404. auto primPtrVal = mBfIRBuilder->CreateBitCast(targetAddr, primPtrType);
  18405. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, mCurTypeInstance->mAlign);
  18406. if (loweredTypeCode2 != BfTypeCode_None)
  18407. {
  18408. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  18409. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  18410. BfIRValue primPtrVal2;
  18411. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  18412. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  18413. else
  18414. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  18415. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  18416. }
  18417. if (isTempTarget)
  18418. {
  18419. auto castedTempPtr = mBfIRBuilder->CreateBitCast(targetAddr, mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType)));
  18420. auto tempVal = mBfIRBuilder->CreateAlignedLoad(castedTempPtr, paramVar->mResolvedType->mAlign);
  18421. mBfIRBuilder->CreateAlignedStore(tempVal, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  18422. }
  18423. // We don't want to allow directly using value
  18424. paramVar->mValue = BfIRValue();
  18425. handled = true;
  18426. }
  18427. else
  18428. {
  18429. BF_ASSERT("Expected lowered");
  18430. }
  18431. }
  18432. if (!handled)
  18433. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  18434. }
  18435. }
  18436. if (methodDef->mBody != NULL)
  18437. UpdateSrcPos(methodDef->mBody);
  18438. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  18439. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  18440. else if (methodDeclaration == NULL)
  18441. UseDefaultSrcPos();
  18442. // Write our argument value into the .addr
  18443. if (paramVar->mIsSplat)
  18444. {
  18445. int splatComponentIdx = 0;
  18446. auto curArgIdx = argIdx;
  18447. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  18448. {
  18449. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  18450. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  18451. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  18452. mBfIRBuilder->ClearDebugLocation(storeInst);
  18453. if (wantsDIData)
  18454. {
  18455. BfIRMDNode diType;
  18456. if (checkType->IsComposite())
  18457. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  18458. else
  18459. diType = mBfIRBuilder->DbgGetType(checkType);
  18460. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18461. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18462. if (wantsDIVariables)
  18463. {
  18464. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  18465. }
  18466. }
  18467. curArgIdx++;
  18468. splatComponentIdx++;
  18469. };
  18470. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  18471. {
  18472. if (checkType->IsStruct())
  18473. {
  18474. auto checkTypeInstance = checkType->ToTypeInstance();
  18475. if (checkTypeInstance->mBaseType != NULL)
  18476. {
  18477. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  18478. }
  18479. if (checkTypeInstance->mIsUnion)
  18480. {
  18481. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  18482. if (!unionInnerType->IsValuelessType())
  18483. {
  18484. _FinishSplatsIterate(unionInnerType, name + "$u");
  18485. }
  18486. if (checkTypeInstance->IsEnum())
  18487. {
  18488. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  18489. _FinishSplatsIterate(dscrType, name + "$d");
  18490. }
  18491. }
  18492. else
  18493. {
  18494. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  18495. {
  18496. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  18497. auto fieldDef = fieldInstance->GetFieldDef();
  18498. if (fieldInstance->mDataIdx >= 0)
  18499. {
  18500. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  18501. }
  18502. }
  18503. }
  18504. }
  18505. else if (checkType->IsMethodRef())
  18506. {
  18507. auto methodRefType = (BfMethodRefType*)checkType;
  18508. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  18509. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  18510. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  18511. // {
  18512. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  18513. // if (!paramType->IsValuelessType())
  18514. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  18515. // }
  18516. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  18517. {
  18518. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  18519. String paramName = methodInstance->GetParamName(paramIdx);
  18520. if (paramName == "this")
  18521. paramName = "__this";
  18522. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  18523. {
  18524. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  18525. }
  18526. else
  18527. {
  18528. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  18529. }
  18530. }
  18531. }
  18532. else if (!checkType->IsValuelessType())
  18533. {
  18534. _FinishSplats(checkType, name);
  18535. }
  18536. };
  18537. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18538. if (!paramVar->mConstValue)
  18539. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  18540. }
  18541. BfIRValue declareCall;
  18542. if (diVariable)
  18543. {
  18544. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  18545. {
  18546. if (!paramVar->mAddr)
  18547. {
  18548. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  18549. {
  18550. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  18551. {
  18552. // We don't need to set the location for this
  18553. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  18554. }
  18555. }
  18556. else
  18557. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  18558. }
  18559. else
  18560. {
  18561. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  18562. }
  18563. }
  18564. }
  18565. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  18566. {
  18567. // We don't allow actually assignment to "this", so we just do a single load
  18568. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  18569. // we need to store it in the stack frame for debugging purposes
  18570. auto loadedThis = mBfIRBuilder->CreateAlignedLoad(paramVar->mAddr/*, "this"*/, paramVar->mResolvedType->mAlign);
  18571. mBfIRBuilder->ClearDebugLocation(loadedThis);
  18572. paramVar->mValue = loadedThis;
  18573. }
  18574. if ((wantsDIData) && (declareCall))
  18575. mBfIRBuilder->UpdateDebugLocation(declareCall);
  18576. if (paramVar->mIsSplat)
  18577. {
  18578. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18579. }
  18580. else if (paramVar->mIsLowered)
  18581. {
  18582. argIdx++;
  18583. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18584. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18585. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18586. if (loweredTypeCode2 != BfTypeCode_None)
  18587. argIdx++;
  18588. }
  18589. else if (!paramVar->mResolvedType->IsValuelessType())
  18590. {
  18591. argIdx++;
  18592. }
  18593. }
  18594. if (wantsDIData)
  18595. {
  18596. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  18597. }
  18598. }
  18599. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  18600. {
  18601. auto paramVar = mCurMethodState->mLocals[varIdx];
  18602. // 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
  18603. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  18604. // if (paramVar->mIsSplat)
  18605. // {
  18606. // if (wantsDIVariables)
  18607. // {
  18608. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  18609. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  18610. // }
  18611. // }
  18612. if (paramVar->mResolvedType->IsValuelessType())
  18613. {
  18614. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  18615. {
  18616. // Only add this placeholder if we don't have any values
  18617. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18618. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  18619. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18620. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  18621. }
  18622. }
  18623. }
  18624. if (IsTargetingBeefBackend())
  18625. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  18626. if (methodState.mClosureState != NULL)
  18627. {
  18628. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  18629. {
  18630. BfLocalVariable* localVar = new BfLocalVariable();
  18631. *localVar = constLocal;
  18632. localVar->mIsBumpAlloc = false;
  18633. AddLocalVariableDef(localVar, true);
  18634. }
  18635. }
  18636. bool wantsRemoveBody = false;
  18637. bool skipBody = false;
  18638. bool skipUpdateSrcPos = false;
  18639. bool skipEndChecks = false;
  18640. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  18641. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18642. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  18643. hasExternSpecifier = true;
  18644. // Allocate, clear, set classVData
  18645. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  18646. {
  18647. CreateStaticCtor();
  18648. }
  18649. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  18650. {
  18651. skipBody = true;
  18652. skipEndChecks = true;
  18653. if (HasExecutedOutput())
  18654. {
  18655. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18656. mBfIRBuilder->ClearDebugLocation();
  18657. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  18658. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  18659. PopulateType(innerType, BfPopulateType_DataAndMethods);
  18660. mBfIRBuilder->PopulateType(mCurTypeInstance);
  18661. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  18662. if (methodInstance->mIsForeignMethodDef)
  18663. {
  18664. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  18665. }
  18666. BfTypeVector methodGenericArguments;
  18667. if (methodInstance->mMethodInfoEx != NULL)
  18668. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  18669. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  18670. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  18671. {
  18672. if (!methodInstance->mReturnType->IsValuelessType())
  18673. {
  18674. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  18675. CreateReturn(retVal);
  18676. }
  18677. else
  18678. mBfIRBuilder->CreateRetVoid();
  18679. }
  18680. else
  18681. {
  18682. auto innerMethodDef = innerMethodInstance.mMethodInstance->mMethodDef;
  18683. BF_ASSERT(innerMethodDef == methodDef);
  18684. SizedArray<BfIRValue, 8> innerParams;
  18685. BfExprEvaluator exprEvaluator(this);
  18686. if (!innerType->IsValuelessType())
  18687. {
  18688. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  18689. BfTypedValue innerVal(thisValue, innerType, true);
  18690. if (boxedType->IsBoxedStructPtr())
  18691. {
  18692. innerVal = LoadValue(innerVal);
  18693. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  18694. }
  18695. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  18696. }
  18697. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  18698. {
  18699. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  18700. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  18701. exprEvaluator.PushArg(localVal, innerParams);
  18702. }
  18703. if (!innerMethodInstance.mFunc)
  18704. {
  18705. BF_ASSERT(innerType->IsUnspecializedType());
  18706. }
  18707. else if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  18708. {
  18709. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  18710. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  18711. exprEvaluator.mReceivingValue = &returnType;
  18712. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  18713. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  18714. mBfIRBuilder->CreateRetVoid();
  18715. }
  18716. else
  18717. {
  18718. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  18719. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  18720. if (mCurMethodInstance->mReturnType->IsValueType())
  18721. retVal = LoadValue(retVal);
  18722. CreateReturn(retVal.mValue);
  18723. }
  18724. }
  18725. }
  18726. mCurMethodState->SetHadReturn(true);
  18727. mCurMethodState->mLeftBlockUncond = true;
  18728. }
  18729. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  18730. {
  18731. SetIllegalSrcPos();
  18732. mBfIRBuilder->ClearDebugLocation();
  18733. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  18734. auto thisVal = GetThis();
  18735. int prevSize = 0;
  18736. if (mContext->mBfObjectType != NULL)
  18737. {
  18738. prevSize = mContext->mBfObjectType->mInstSize;
  18739. PopulateType(mContext->mBfObjectType);
  18740. // If we have object extensions, clear out starting at the extension
  18741. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  18742. {
  18743. if (fieldInstance.GetFieldDef()->mDeclaringType->IsExtension())
  18744. {
  18745. prevSize = fieldInstance.mDataOffset;
  18746. break;
  18747. }
  18748. }
  18749. }
  18750. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  18751. int curSize = mCurTypeInstance->mInstSize;
  18752. if (curSize > prevSize)
  18753. {
  18754. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  18755. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  18756. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  18757. }
  18758. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  18759. {
  18760. auto useThis = mCurMethodState->mLocals[0]->mValue;
  18761. auto useThisType = mCurTypeInstance;
  18762. auto checkTypeInst = mCurTypeInstance;
  18763. while (checkTypeInst != NULL)
  18764. {
  18765. for (auto& fieldInstance : checkTypeInst->mFieldInstances)
  18766. {
  18767. auto fieldDef = fieldInstance.GetFieldDef();
  18768. if ((fieldDef == NULL) || (fieldDef->mIsStatic))
  18769. continue;
  18770. if (fieldInstance.IsAppendedObject())
  18771. {
  18772. if (checkTypeInst != useThisType)
  18773. {
  18774. useThis = mBfIRBuilder->CreateBitCast(useThis, mBfIRBuilder->MapType(checkTypeInst));
  18775. useThisType = checkTypeInst;
  18776. }
  18777. BfIRValue fieldAddr = mBfIRBuilder->CreateInBoundsGEP(useThis, 0, fieldInstance.mDataIdx);
  18778. auto int8PtrVal = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(int8PtrType));
  18779. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  18780. }
  18781. }
  18782. checkTypeInst = checkTypeInst->mBaseType;
  18783. }
  18784. }
  18785. skipUpdateSrcPos = true;
  18786. }
  18787. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  18788. {
  18789. EmitCtorBody(skipBody);
  18790. }
  18791. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  18792. {
  18793. EmitDtorBody();
  18794. skipBody = true;
  18795. }
  18796. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  18797. {
  18798. EmitIteratorBlock(skipBody);
  18799. }
  18800. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  18801. {
  18802. // We need to be able to mark deleted objects
  18803. mCurMethodState->mIgnoreObjectAccessCheck = true;
  18804. }
  18805. auto customAttributes = methodInstance->GetCustomAttributes();
  18806. if (customAttributes != NULL)
  18807. {
  18808. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  18809. mCurMethodState->mIgnoreObjectAccessCheck = true;
  18810. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  18811. mCurMethodState->mDisableChecks = true;
  18812. }
  18813. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  18814. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  18815. {
  18816. // We chain even non-default ctors to the default ctors
  18817. auto defaultCtor = methodInstance;
  18818. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  18819. CallChainedMethods(defaultCtor, false);
  18820. }
  18821. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  18822. if (!mCompiler->mHasRequiredTypes)
  18823. {
  18824. // Skip processing to avoid errors
  18825. }
  18826. else if (methodDef->mBody == NULL)
  18827. {
  18828. if (methodDeclaration != NULL)
  18829. {
  18830. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18831. {
  18832. if (operatorDeclaration->mIsConvOperator)
  18833. wantsRemoveBody = true;
  18834. }
  18835. }
  18836. bool isDllImport = false;
  18837. if ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic))
  18838. {
  18839. if (importStrNum != -1)
  18840. {
  18841. if (importKind == BfImportKind_Import_Static)
  18842. {
  18843. if (!mImportFileNames.Contains(importStrNum))
  18844. {
  18845. mImportFileNames.Add(importStrNum);
  18846. }
  18847. }
  18848. }
  18849. }
  18850. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  18851. {
  18852. CreateDllImportMethod();
  18853. }
  18854. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  18855. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  18856. {
  18857. if (mCurTypeInstance->mTypeDef->mIsFunction)
  18858. {
  18859. // Emit nothing
  18860. }
  18861. else
  18862. {
  18863. CreateDelegateInvokeMethod();
  18864. mCurMethodState->SetHadReturn(true);
  18865. mCurMethodState->mLeftBlockUncond = true;
  18866. }
  18867. }
  18868. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  18869. {
  18870. if (mCurTypeInstance->IsObject())
  18871. {
  18872. CreateDynamicCastMethod();
  18873. }
  18874. else
  18875. {
  18876. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  18877. mCurMethodState->mHadReturn = true;
  18878. }
  18879. }
  18880. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  18881. {
  18882. BfIRValue ret;
  18883. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  18884. {
  18885. // This can happen if we provide an invalid name
  18886. AssertErrorState();
  18887. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  18888. }
  18889. else
  18890. {
  18891. // Unfortunate DebugLoc shenanigans-
  18892. // 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,
  18893. // so we only set the loc on the CreateRet which gets inlined out
  18894. mBfIRBuilder->SaveDebugLocation();
  18895. mBfIRBuilder->ClearDebugLocation();
  18896. BfIRValue fromBool;
  18897. if (!mCurTypeInstance->IsTypedPrimitive())
  18898. {
  18899. fromBool = GetDefaultValue(methodInstance->mReturnType);
  18900. }
  18901. else
  18902. {
  18903. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  18904. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  18905. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  18906. }
  18907. mBfIRBuilder->RestoreDebugLocation();
  18908. ret = mBfIRBuilder->CreateRet(fromBool);
  18909. //ExtendLocalLifetimes(0);
  18910. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18911. }
  18912. mCurMethodState->SetHadReturn(true);
  18913. mCurMethodState->mLeftBlockUncond = true;
  18914. }
  18915. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  18916. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  18917. {
  18918. BfIRValue ret;
  18919. // Unfortunate DebugLoc shenanigans-
  18920. // 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,
  18921. // so we only set the loc on the CreateRet which gets inlined out
  18922. mBfIRBuilder->SaveDebugLocation();
  18923. mBfIRBuilder->ClearDebugLocation();
  18924. BfIRValue fromBool;
  18925. mBfIRBuilder->RestoreDebugLocation();
  18926. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  18927. //ExtendLocalLifetimes(0);
  18928. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18929. mCurMethodState->SetHadReturn(true);
  18930. mCurMethodState->mLeftBlockUncond = true;
  18931. }
  18932. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  18933. {
  18934. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  18935. if (HasExecutedOutput())
  18936. {
  18937. EmitEnumToStringBody();
  18938. }
  18939. mBfIRBuilder->CreateRetVoid();
  18940. mCurMethodState->SetHadReturn(true);
  18941. mCurMethodState->mLeftBlockUncond = true;
  18942. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18943. }
  18944. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  18945. {
  18946. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  18947. if (HasExecutedOutput())
  18948. {
  18949. EmitTupleToStringBody();
  18950. }
  18951. mBfIRBuilder->CreateRetVoid();
  18952. mCurMethodState->SetHadReturn(true);
  18953. mCurMethodState->mLeftBlockUncond = true;
  18954. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18955. }
  18956. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  18957. {
  18958. CreateValueTypeEqualsMethod(false);
  18959. skipBody = true;
  18960. skipEndChecks = true;
  18961. }
  18962. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  18963. {
  18964. CreateValueTypeEqualsMethod(true);
  18965. skipBody = true;
  18966. skipEndChecks = true;
  18967. }
  18968. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef->GetDefinition() == mCompiler->mValueTypeTypeDef))
  18969. {
  18970. CreateValueTypeEqualsMethod(false);
  18971. skipBody = true;
  18972. skipEndChecks = true;
  18973. }
  18974. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (mCurTypeInstance->IsDelegate()))
  18975. {
  18976. CreateDelegateEqualsMethod();
  18977. skipBody = true;
  18978. skipEndChecks = true;
  18979. }
  18980. else
  18981. {
  18982. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18983. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  18984. {
  18985. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  18986. Fail("Body expected", methodDef->mBody);
  18987. }
  18988. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  18989. {
  18990. if ((methodInstance->mReturnType->IsRef()) && (!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  18991. Fail("Auto-implemented ref property getters must declare 'mut'", methodInstance->mMethodDef->GetRefNode());
  18992. if (methodInstance->mReturnType->IsValuelessType())
  18993. {
  18994. mBfIRBuilder->CreateRetVoid();
  18995. }
  18996. else if (HasExecutedOutput())
  18997. {
  18998. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  18999. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19000. BfFieldDef* fieldDef = NULL;
  19001. if (fieldInstance != NULL)
  19002. fieldDef = fieldInstance->GetFieldDef();
  19003. BfType* retType = methodInstance->mReturnType;
  19004. if (retType->IsRef())
  19005. retType = retType->GetUnderlyingType();
  19006. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  19007. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19008. {
  19009. BfTypedValue lookupValue;
  19010. if (fieldDef->IsNonConstStatic())
  19011. lookupValue = ReferenceStaticField(fieldInstance);
  19012. else if (mCurTypeInstance->IsObject())
  19013. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  19014. else
  19015. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  19016. if (methodInstance->mReturnType->IsRef())
  19017. {
  19018. if ((!lookupValue.IsAddr()) && (!lookupValue.mType->IsValuelessType()))
  19019. lookupValue = MakeAddressable(lookupValue);
  19020. }
  19021. else
  19022. lookupValue = LoadOrAggregateValue(lookupValue);
  19023. CreateReturn(lookupValue.mValue);
  19024. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19025. }
  19026. else
  19027. {
  19028. // This can happen if we have two properties with the same name but different types
  19029. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19030. EmitDefaultReturn();
  19031. }
  19032. }
  19033. else
  19034. {
  19035. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19036. EmitDefaultReturn();
  19037. }
  19038. mCurMethodState->SetHadReturn(true);
  19039. }
  19040. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  19041. {
  19042. if ((!methodDef->mIsMutating) && (!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  19043. {
  19044. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  19045. }
  19046. else if (!mCompiler->IsAutocomplete())
  19047. {
  19048. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19049. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19050. auto fieldDef = fieldInstance->GetFieldDef();
  19051. auto& lastParam = mCurMethodState->mLocals.back();
  19052. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  19053. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19054. {
  19055. BfIRValue lookupAddr;
  19056. if (fieldDef->IsNonConstStatic())
  19057. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  19058. else
  19059. {
  19060. auto thisValue = GetThis();
  19061. if (thisValue.IsSplat())
  19062. {
  19063. BFMODULE_FATAL(this, "Should not happen");
  19064. }
  19065. if (mCurTypeInstance->IsObject())
  19066. thisValue = LoadValue(thisValue);
  19067. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  19068. }
  19069. BfExprEvaluator exprEvaluator(this);
  19070. auto localVal = exprEvaluator.LoadLocal(lastParam);
  19071. localVal = LoadOrAggregateValue(localVal);
  19072. if (!localVal.mType->IsValuelessType())
  19073. mBfIRBuilder->CreateAlignedStore(localVal.mValue, lookupAddr, localVal.mType->mAlign);
  19074. }
  19075. else if (!fieldInstance->mResolvedType->IsValuelessType())
  19076. {
  19077. // This can happen if we have two properties with the same name but different types
  19078. AssertErrorState();
  19079. }
  19080. }
  19081. }
  19082. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  19083. {
  19084. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19085. {
  19086. if (HasCompiledOutput())
  19087. EmitGCMarkMembers();
  19088. }
  19089. else if (!mCurTypeInstance->IsObject())
  19090. {
  19091. }
  19092. }
  19093. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  19094. {
  19095. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19096. {
  19097. if (HasCompiledOutput())
  19098. EmitGCFindTLSMembers();
  19099. }
  19100. }
  19101. }
  19102. }
  19103. else if (!skipBody)
  19104. {
  19105. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  19106. bool wantsRetVal = true;
  19107. if ((mIsComptimeModule) && (methodDef->mMethodType != BfMethodType_CtorCalcAppend))
  19108. wantsRetVal = false;
  19109. else if (mCurMethodInstance->mReturnType->IsVar())
  19110. wantsRetVal = false;
  19111. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  19112. {
  19113. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  19114. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  19115. {
  19116. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  19117. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  19118. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst, mCurMethodInstance->mReturnType->mAlign);
  19119. mBfIRBuilder->ClearDebugLocation(storeInst);
  19120. mCurMethodState->mRetValAddr = allocaInst;
  19121. }
  19122. else if (wantsRetVal)
  19123. {
  19124. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  19125. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  19126. }
  19127. }
  19128. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19129. {
  19130. mBfIRBuilder->CreateAlignedStore(GetConstValue(0), mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19131. BfGetSymbolReferenceKind prevSymbolKind;
  19132. BfAutoComplete* prevAutoComplete;
  19133. if (mCompiler->mResolvePassData != NULL)
  19134. {
  19135. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  19136. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19137. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  19138. }
  19139. EmitCtorCalcAppend();
  19140. if (mCompiler->mResolvePassData != NULL)
  19141. {
  19142. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  19143. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  19144. }
  19145. }
  19146. else if (!isEmptyBodied)
  19147. {
  19148. if (!mCurMethodState->mIRExitBlock)
  19149. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  19150. bool isExpressionBody = false;
  19151. if (methodDeclaration != NULL)
  19152. {
  19153. if (methodDeclaration->mFatArrowToken != NULL)
  19154. isExpressionBody = true;
  19155. }
  19156. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  19157. {
  19158. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  19159. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  19160. isExpressionBody = true;
  19161. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  19162. {
  19163. isExpressionBody = true;
  19164. }
  19165. }
  19166. else
  19167. {
  19168. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  19169. {
  19170. if (!block->mChildArr.IsEmpty())
  19171. {
  19172. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  19173. {
  19174. if (exprStmt->mTrailingSemicolon == NULL)
  19175. isExpressionBody = true;
  19176. }
  19177. }
  19178. }
  19179. else
  19180. isExpressionBody = true;
  19181. }
  19182. DoCEEmit(methodInstance);
  19183. if (methodInstance->mCeCancelled)
  19184. mIgnoreErrors = true;
  19185. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  19186. {
  19187. while (fieldDtorBody != NULL)
  19188. {
  19189. VisitEmbeddedStatement(fieldDtorBody->mBody);
  19190. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  19191. }
  19192. }
  19193. else if (!isExpressionBody)
  19194. {
  19195. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  19196. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  19197. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  19198. VisitCodeBlock(bodyBlock);
  19199. }
  19200. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  19201. {
  19202. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  19203. // {
  19204. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  19205. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  19206. // }
  19207. auto expectingType = mCurMethodInstance->mReturnType;
  19208. // What was this error for?
  19209. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  19210. // {
  19211. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  19212. // }
  19213. BfEvalExprFlags exprEvalFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_IsExpressionBody);
  19214. if (expectingType->IsVoid())
  19215. {
  19216. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  19217. bool wasReturnGenericParam = false;
  19218. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  19219. {
  19220. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  19221. }
  19222. else
  19223. {
  19224. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  19225. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  19226. wasReturnGenericParam = true;
  19227. }
  19228. // If we the void return was from a generic specialization, allow us to return a void result,
  19229. // otherwise treat expression as though it must be a statement
  19230. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  19231. if (isStatement)
  19232. expectingType = NULL;
  19233. }
  19234. BfExprEvaluator exprEvaluator(this);
  19235. if (mCurMethodInstance->mMethodDef->mIsReadOnly)
  19236. exprEvaluator.mAllowReadOnlyReference = true;
  19237. UpdateSrcPos(expressionBody);
  19238. auto retVal = CreateValueFromExpression(exprEvaluator, expressionBody, expectingType, exprEvalFlags);
  19239. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  19240. {
  19241. mCurMethodState->mHadReturn = true;
  19242. if (!mCurMethodState->mLeftBlockUncond)
  19243. {
  19244. retVal = LoadOrAggregateValue(retVal);
  19245. EmitReturn(retVal);
  19246. }
  19247. }
  19248. }
  19249. }
  19250. }
  19251. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  19252. if (skipUpdateSrcPos)
  19253. {
  19254. // Skip
  19255. }
  19256. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19257. UpdateSrcPos(bodyBlock->mCloseBrace);
  19258. else if (methodDef->mBody != NULL)
  19259. UpdateSrcPos(methodDef->mBody);
  19260. else if (methodDeclaration != NULL)
  19261. UpdateSrcPos(methodDeclaration);
  19262. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  19263. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  19264. else
  19265. UseDefaultSrcPos();
  19266. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19267. {
  19268. if (mCurMethodState->mRetVal)
  19269. {
  19270. mCurMethodState->SetHadReturn(true);
  19271. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  19272. mBfIRBuilder->CreateRet(retVal);
  19273. }
  19274. else
  19275. AssertErrorState();
  19276. }
  19277. mCurMethodState->mHeadScope.mDone = true;
  19278. if (!mCurMethodState->mHadReturn)
  19279. {
  19280. // Clear off the stackallocs that have occurred after a scopeData break
  19281. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  19282. }
  19283. EmitDeferredCallProcessorInstances(&mCurMethodState->mHeadScope);
  19284. if (mCurMethodState->mIRExitBlock)
  19285. {
  19286. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  19287. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  19288. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  19289. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  19290. if ((!mCurMethodState->mDIRetVal) && (wantsDIData))
  19291. CreateDIRetVal();
  19292. }
  19293. for (auto localVar : mCurMethodState->mLocals)
  19294. {
  19295. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  19296. {
  19297. //
  19298. }
  19299. else if ((skipEndChecks) || (methodDef->mBody == NULL))
  19300. break;
  19301. LocalVariableDone(localVar, true);
  19302. }
  19303. if (mCurMethodState->mIRExitBlock)
  19304. {
  19305. if ((mCurMethodState->mRetVal) &&
  19306. ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() == -1)))
  19307. {
  19308. auto loadedVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19309. CreateReturn(loadedVal);
  19310. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19311. if (mCurMethodState->mDIRetVal)
  19312. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19313. }
  19314. else
  19315. {
  19316. // Have something on the last line to step onto
  19317. if (mHasFullDebugInfo)
  19318. {
  19319. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19320. UpdateSrcPos(bodyBlock->mCloseBrace);
  19321. EmitEnsureInstructionAt();
  19322. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19323. {
  19324. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19325. mBfIRBuilder->EnsureFunctionPatchable();
  19326. }
  19327. }
  19328. mBfIRBuilder->CreateRetVoid();
  19329. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19330. if (mCurMethodState->mDIRetVal)
  19331. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19332. }
  19333. }
  19334. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  19335. {
  19336. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  19337. {
  19338. if ((!mIsComptimeModule) && (irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19339. {
  19340. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19341. mBfIRBuilder->EnsureFunctionPatchable();
  19342. }
  19343. mBfIRBuilder->CreateRetVoid();
  19344. }
  19345. }
  19346. else
  19347. {
  19348. if (!mCurMethodState->mHadReturn)
  19349. {
  19350. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  19351. if (bodyBlock != NULL)
  19352. {
  19353. if (bodyBlock->mCloseBrace != NULL)
  19354. {
  19355. BfAstNode* target = bodyBlock->mCloseBrace;
  19356. if (!mCompiler->mHasRequiredTypes)
  19357. {
  19358. AddFailType(mCurTypeInstance);
  19359. mHadBuildError = true;
  19360. }
  19361. else
  19362. Fail("Method must return value", target);
  19363. }
  19364. else
  19365. {
  19366. // It's possible to not have a closing brace if the method ends in an EOF
  19367. AssertErrorState();
  19368. }
  19369. }
  19370. }
  19371. }
  19372. // Move 'init' into 'entry'
  19373. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  19374. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  19375. if (((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType())) &&
  19376. (!mIsComptimeModule))
  19377. {
  19378. // Don't keep instructions for unspecialized types
  19379. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19380. }
  19381. // Avoid linking any internal funcs that were just supposed to be comptime-accessible
  19382. /*if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  19383. wantsRemoveBody = true;*/
  19384. if ((hasExternSpecifier) && (!skipBody))
  19385. {
  19386. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  19387. // incase it gets called later by some hot-loaded coded
  19388. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()) && (mCurTypeInstance != mContext->mBfObjectType))
  19389. {
  19390. if (!mCurMethodInstance->mMethodDef->mName.StartsWith("Comptime_"))
  19391. CreateFakeCallerMethod(mangledName);
  19392. }
  19393. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19394. }
  19395. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  19396. {
  19397. // We only need the DLL stub when we may be hot swapping
  19398. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19399. }
  19400. else if (wantsRemoveBody)
  19401. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  19402. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  19403. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  19404. // unspecialized types
  19405. if (((mCurTypeInstance->IsUnspecializedType()) && (!mIsComptimeModule)) ||
  19406. (mCurTypeInstance->IsInterface()))
  19407. {
  19408. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  19409. methodInstance->mIRFunction = BfIRFunction();
  19410. }
  19411. CheckAddFailType();
  19412. if (mHadBuildError)
  19413. prevHadBuildError.CancelRestore();
  19414. if (mHadBuildWarning)
  19415. prevHadWarning.CancelRestore();
  19416. if (!methodDef->mIsLocalMethod)
  19417. ProcessMethod_ProcessDeferredLocals();
  19418. prevIgnoreWrites.Restore();
  19419. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  19420. if (methodState.mHotDataReferenceBuilder != NULL)
  19421. {
  19422. AddHotDataReferences(&hotDataReferenceBuilder);
  19423. }
  19424. else
  19425. {
  19426. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  19427. {
  19428. // Remove the hot method data
  19429. auto hotMethod = methodInstance->mHotMethod;
  19430. auto prevMethod = hotMethod->mPrevVersion;
  19431. if (prevMethod != NULL)
  19432. {
  19433. // If there's a prev method then pull its data into the main HotMethod.
  19434. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  19435. // over to the main HotMethod definition to keep the HotMethod address
  19436. // invariant
  19437. for (auto ref : hotMethod->mReferences)
  19438. ref->Deref();
  19439. hotMethod->mReferences.Clear();
  19440. BF_ASSERT(prevMethod->mRefCount == 1);
  19441. hotMethod->mReferences = prevMethod->mReferences;
  19442. if (hotMethod->mSrcTypeVersion != NULL)
  19443. hotMethod->mSrcTypeVersion->Deref();
  19444. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  19445. prevMethod->mSrcTypeVersion = NULL;
  19446. prevMethod->mReferences.Clear();
  19447. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  19448. prevMethod->mPrevVersion = NULL;
  19449. prevMethod->Deref();
  19450. }
  19451. hotMethod->Deref();
  19452. methodInstance->mHotMethod = NULL;
  19453. }
  19454. }
  19455. }
  19456. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  19457. {
  19458. String name;
  19459. bool found = false;
  19460. auto checkMethodState = mCurMethodState;
  19461. while (checkMethodState != NULL)
  19462. {
  19463. if (checkMethodState->mClosureState == NULL)
  19464. break;
  19465. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  19466. {
  19467. found = true;
  19468. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  19469. break;
  19470. }
  19471. checkMethodState = checkMethodState->mPrevMethodState;
  19472. }
  19473. if (!found)
  19474. name += mCurMethodInstance->mMethodDef->mName;
  19475. int prevSepPos = (int)name.LastIndexOf('$');
  19476. if (prevSepPos != -1)
  19477. {
  19478. name.RemoveToEnd(prevSepPos);
  19479. }
  19480. name += "@";
  19481. name += baseName;
  19482. HashContext hashCtx;
  19483. if (anchorNode != NULL)
  19484. {
  19485. hashCtx.Mixin(anchorNode->GetStartCharId());
  19486. }
  19487. //
  19488. {
  19489. auto checkMethodState = declMethodState;
  19490. auto checkMixinState = declMixinState;
  19491. while (checkMethodState != NULL)
  19492. {
  19493. if (checkMixinState != NULL)
  19494. {
  19495. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  19496. }
  19497. checkMethodState = checkMethodState->mPrevMethodState;
  19498. if (checkMethodState != NULL)
  19499. checkMixinState = checkMethodState->mMixinState;
  19500. }
  19501. }
  19502. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19503. if ((rootMethodState != NULL) && (rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19504. {
  19505. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  19506. {
  19507. StringT<512> genericTypeName;
  19508. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  19509. hashCtx.MixinStr(genericTypeName);
  19510. }
  19511. }
  19512. uint64 hashVal = hashCtx.Finish64();
  19513. name += "$";
  19514. name += BfTypeUtils::HashEncode64(hashVal);
  19515. return name;
  19516. }
  19517. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  19518. {
  19519. if (localMethod->mMethodDef != NULL)
  19520. return localMethod->mMethodDef;
  19521. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19522. auto declMethodState = localMethod->mDeclMethodState;
  19523. auto declMixinState = localMethod->mDeclMixinState;
  19524. auto typeInst = mCurTypeInstance;
  19525. BfAstNode* body = NULL;
  19526. BfAstNode* anchorNode = NULL;
  19527. auto _AllocDirectTypeRef = [&](BfType* type)
  19528. {
  19529. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  19530. directTypeRef->Init(type);
  19531. return directTypeRef;
  19532. };
  19533. auto methodDeclaration = localMethod->mMethodDeclaration;
  19534. if (methodDeclaration != NULL)
  19535. {
  19536. body = methodDeclaration->mBody;
  19537. anchorNode = methodDeclaration->mOpenParen;
  19538. }
  19539. else
  19540. {
  19541. body = localMethod->mLambdaBindExpr->mBody;
  19542. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  19543. }
  19544. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  19545. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  19546. BfMethodDef* methodDef;
  19547. BfMethodDef* outerMethodDef = NULL;
  19548. if (localMethod->mOuterLocalMethod != NULL)
  19549. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  19550. else if (rootMethodState->mMethodInstance != NULL)
  19551. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  19552. if (methodDeclaration != NULL)
  19553. {
  19554. BfDefBuilder defBuilder(mCompiler->mSystem);
  19555. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  19556. defBuilder.mPassInstance = mCompiler->mPassInstance;
  19557. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  19558. defBuilder.mCurDeclaringTypeDef = defBuilder.mCurTypeDef;
  19559. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  19560. }
  19561. else
  19562. {
  19563. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  19564. methodDef = new BfMethodDef();
  19565. methodDef->mName = localMethod->mMethodName;
  19566. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  19567. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  19568. methodDef->mBody = body;
  19569. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  19570. {
  19571. auto paramType = invokeMethod->GetParamType(paramIdx);
  19572. String paramName;
  19573. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  19574. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  19575. else
  19576. paramName = invokeMethod->GetParamName(paramIdx);
  19577. auto paramDef = new BfParameterDef();
  19578. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  19579. paramDef->mName = paramName;
  19580. methodDef->mParams.Add(paramDef);
  19581. }
  19582. if (outerMethodDef != NULL)
  19583. {
  19584. for (auto genericParam : outerMethodDef->mGenericParams)
  19585. {
  19586. auto* copiedGenericParamDef = new BfGenericParamDef();
  19587. *copiedGenericParamDef = *genericParam;
  19588. methodDef->mGenericParams.Add(copiedGenericParamDef);
  19589. }
  19590. }
  19591. }
  19592. methodDef->mIdx = ~methodLocalIdx;
  19593. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  19594. methodDef->mName = localMethod->mExpectedFullName;
  19595. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  19596. //
  19597. // if (!localMethod->mExpectedFullName.IsEmpty())
  19598. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  19599. methodDef->mIsStatic = true;
  19600. methodDef->mIsLocalMethod = true;
  19601. methodDef->mIsVirtual = false;
  19602. localMethod->mMethodDef = methodDef;
  19603. auto methodInstanceGroup = new BfMethodInstanceGroup();
  19604. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  19605. methodInstanceGroup->mMethodIdx = -1;
  19606. methodInstanceGroup->mOwner = mCurTypeInstance;
  19607. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  19608. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  19609. {
  19610. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  19611. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  19612. }
  19613. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  19614. {
  19615. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  19616. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19617. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  19618. {
  19619. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  19620. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  19621. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  19622. autoComplete->mDefType = typeInst->mTypeDef;
  19623. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  19624. autoComplete->mReplaceLocalId = methodLocalIdx;
  19625. }
  19626. }
  19627. return localMethod->mMethodDef;
  19628. }
  19629. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  19630. {
  19631. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  19632. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  19633. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19634. auto declMethodState = localMethod->mDeclMethodState;
  19635. auto declMixinState = localMethod->mDeclMixinState;
  19636. auto callerMethodState = mCurMethodState;
  19637. auto typeInst = mCurTypeInstance;
  19638. if (mCurMethodState->mMixinState != NULL)
  19639. {
  19640. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  19641. }
  19642. auto methodDef = GetLocalMethodDef(localMethod);
  19643. BfAstNode* body = NULL;
  19644. auto methodDeclaration = localMethod->mMethodDeclaration;
  19645. if (methodDeclaration != NULL)
  19646. {
  19647. body = methodDeclaration->mBody;
  19648. }
  19649. else
  19650. {
  19651. body = localMethod->mLambdaBindExpr->mBody;
  19652. }
  19653. bool hadConcreteInterfaceGenericArgument = false;
  19654. BfTypeVector sanitizedMethodGenericArguments;
  19655. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  19656. // version of this method for this pass through the outermost method
  19657. int dependentGenericStartIdx = 0;
  19658. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19659. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  19660. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  19661. if (methodGenericArguments.size() == 0)
  19662. {
  19663. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19664. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  19665. }
  19666. else
  19667. {
  19668. int genericArgIdx = 0;
  19669. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  19670. // {
  19671. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  19672. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  19673. // }
  19674. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  19675. {
  19676. auto genericArgType = methodGenericArguments[genericArgIdx];
  19677. BF_ASSERT(!genericArgType->IsRef());
  19678. if (genericArgType->IsConcreteInterfaceType())
  19679. {
  19680. hadConcreteInterfaceGenericArgument = true;
  19681. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  19682. genericArgType = concreteInterfaceType->mInterface;
  19683. }
  19684. sanitizedMethodGenericArguments.push_back(genericArgType);
  19685. }
  19686. }
  19687. bool wantPrematureMethodInstance = false;
  19688. if (!force)
  19689. {
  19690. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  19691. }
  19692. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  19693. bool isDefaultPass = true;
  19694. BfTypeVector lookupMethodGenericArguments;
  19695. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  19696. {
  19697. auto genericArgType = methodGenericArguments[genericArgIdx];
  19698. BF_ASSERT(!genericArgType->IsRef());
  19699. lookupMethodGenericArguments.Add(genericArgType);
  19700. if (genericArgType->IsGenericParam())
  19701. {
  19702. auto genericParam = (BfGenericParamType*)genericArgType;
  19703. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  19704. isDefaultPass = false;
  19705. }
  19706. else
  19707. {
  19708. isDefaultPass = false;
  19709. }
  19710. }
  19711. bool hadExistingMethodInstance = false;
  19712. if (methodInstance != NULL)
  19713. {
  19714. hadExistingMethodInstance = true;
  19715. }
  19716. else
  19717. {
  19718. if (isDefaultPass)
  19719. {
  19720. methodInstance = methodInstGroup->mDefault;
  19721. if (methodInstance != NULL)
  19722. {
  19723. hadExistingMethodInstance = true;
  19724. }
  19725. else
  19726. {
  19727. methodInstance = new BfMethodInstance();
  19728. methodInstGroup->mDefault = methodInstance;
  19729. }
  19730. }
  19731. else
  19732. {
  19733. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  19734. if (methodInstGroup->mMethodSpecializationMap == NULL)
  19735. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  19736. BfMethodInstance** methodInstancePtr = NULL;
  19737. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  19738. {
  19739. methodInstance = *methodInstancePtr;
  19740. hadExistingMethodInstance = true;
  19741. }
  19742. else
  19743. {
  19744. methodInstance = new BfMethodInstance();
  19745. *methodInstancePtr = methodInstance;
  19746. }
  19747. }
  19748. }
  19749. if (hadExistingMethodInstance)
  19750. {
  19751. if ((!methodInstance->mDisallowCalling) ||
  19752. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  19753. return BfModuleMethodInstance(methodInstance);
  19754. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  19755. }
  19756. else
  19757. {
  19758. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  19759. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  19760. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  19761. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  19762. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  19763. methodInstance->mMethodDef = methodDef;
  19764. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  19765. if (hadConcreteInterfaceGenericArgument)
  19766. methodInstance->mIgnoreBody = true;
  19767. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  19768. for (auto genericArg : sanitizedMethodGenericArguments)
  19769. {
  19770. if (genericArg->IsPrimitiveType())
  19771. genericArg = GetWrappedStructType(genericArg);
  19772. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  19773. }
  19774. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  19775. {
  19776. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  19777. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  19778. }
  19779. SetupMethodIdHash(methodInstance);
  19780. }
  19781. auto _SetupMethodInstance = [&]()
  19782. {
  19783. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  19784. // Generic constraints
  19785. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  19786. {
  19787. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  19788. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  19789. }
  19790. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  19791. {
  19792. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  19793. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  19794. }
  19795. };
  19796. //////////////////////////////////////////////////////////////////////////
  19797. auto _VisitLambdaBody = [&]()
  19798. {
  19799. if (localMethod->mDeclOnly)
  19800. return;
  19801. if (mCompiler->mCanceling)
  19802. return;
  19803. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  19804. {
  19805. VisitCodeBlock(blockBody);
  19806. }
  19807. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  19808. {
  19809. BfType* expectType = NULL;
  19810. if (!methodInstance->mReturnType->IsVoid())
  19811. expectType = methodInstance->mReturnType;
  19812. CreateValueFromExpression(bodyExpr, expectType, BfEvalExprFlags_AllowRefExpr);
  19813. }
  19814. };
  19815. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  19816. {
  19817. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  19818. auto result = ResolveTypeRef(typeRef);
  19819. if (result == NULL)
  19820. result = mContext->mBfObjectType;
  19821. return result;
  19822. };
  19823. BfTypeInstance* outerClosure = NULL;
  19824. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  19825. outerClosure = declMethodState->mClosureState->mClosureType;
  19826. BfMethodState methodState;
  19827. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  19828. BfIRFunctionType funcType;
  19829. auto voidType = GetPrimitiveType(BfTypeCode_None);
  19830. SizedArray<BfIRType, 0> paramTypes;
  19831. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  19832. mBfIRBuilder->SaveDebugLocation();
  19833. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  19834. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  19835. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  19836. BfDeferredLocalAssignData deferredLocalAssignData;
  19837. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  19838. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  19839. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  19840. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  19841. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  19842. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  19843. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  19844. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  19845. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  19846. methodState.mIRFunction = declMethodState->mIRFunction;
  19847. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  19848. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  19849. {
  19850. methodState.mCurScope->mAstBlock = blockBody;
  19851. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  19852. }
  19853. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  19854. BfClosureState closureState;
  19855. if (methodDef->mMethodType == BfMethodType_Mixin)
  19856. {
  19857. if (declMethodState != NULL)
  19858. {
  19859. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  19860. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  19861. else if (declMethodState->mMethodInstance != NULL)
  19862. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  19863. }
  19864. }
  19865. if (closureState.mReturnType == NULL)
  19866. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  19867. closureState.mCapturing = true;
  19868. closureState.mLocalMethod = localMethod;
  19869. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  19870. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  19871. methodState.mClosureState = &closureState;
  19872. closureState.mClosureType = outerClosure;
  19873. int outerLocalsCount = (int)methodState.mLocals.size();
  19874. if (!hadExistingMethodInstance)
  19875. {
  19876. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  19877. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  19878. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  19879. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  19880. auto declareModule = this;
  19881. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  19882. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  19883. BF_ASSERT(declareModule != NULL);
  19884. methodInstance->mDeclModule = declareModule;
  19885. _SetupMethodInstance();
  19886. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  19887. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  19888. }
  19889. if (wantPrematureMethodInstance)
  19890. {
  19891. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  19892. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  19893. // its true method instance
  19894. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  19895. //BF_ASSERT(moduleMethodInstance);
  19896. return BfModuleMethodInstance(methodInstance);
  19897. }
  19898. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  19899. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  19900. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  19901. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  19902. closureState.mClosureMethodDef = methodDef;
  19903. bool wantsVisitBody = true;
  19904. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  19905. wantsVisitBody = false;
  19906. if (methodInstance->IsOrInUnspecializedVariation())
  19907. wantsVisitBody = false;
  19908. bool allowCapture = (methodDeclaration == NULL) || (methodDeclaration->mStaticSpecifier == NULL);
  19909. if (wantsVisitBody)
  19910. {
  19911. BP_ZONE("VisitLambdaBody");
  19912. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  19913. // this capture stage for each of those times
  19914. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  19915. /*
  19916. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  19917. // that will not occur during the actual lambda method generation, for example: returning a value
  19918. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  19919. // our AST nodes will still be visited
  19920. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  19921. */
  19922. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  19923. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  19924. mBfIRBuilder->SaveDebugLocation();
  19925. closureState.mCaptureVisitingBody = true;
  19926. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  19927. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  19928. methodState.mMethodInstance = methodInstance;
  19929. NewScopeState();
  19930. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  19931. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  19932. {
  19933. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  19934. for (auto localDef : methodState.mLocals)
  19935. {
  19936. if (localDef->mResolvedType->IsVar())
  19937. continue;
  19938. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  19939. }
  19940. }
  19941. // Keep outs from being marked as assigned
  19942. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19943. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  19944. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  19945. auto prevDLA = rootMethodState->mDeferredLocalAssignData;
  19946. while ((prevDLA != NULL) && (prevDLA->mIsChained))
  19947. prevDLA = prevDLA->mChainedAssignData;
  19948. if (prevDLA != NULL)
  19949. {
  19950. deferredLocalAssignData.mAssignedLocals = prevDLA->mAssignedLocals;
  19951. deferredLocalAssignData.mLeftBlockUncond = prevDLA->mLeftBlockUncond;
  19952. }
  19953. SetAndRestoreValue<BfDeferredLocalAssignData*> sarDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  19954. if (!mIgnoreErrors)
  19955. localMethod->mDidBodyErrorPass = true;
  19956. _VisitLambdaBody();
  19957. RestoreScopeState();
  19958. closureState.mCaptureVisitingBody = false;
  19959. mBfIRBuilder->RestoreDebugLocation();
  19960. }
  19961. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  19962. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  19963. {
  19964. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  19965. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  19966. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  19967. }
  19968. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  19969. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  19970. closureState.mClosureMethodDef = NULL;
  19971. for (auto methodInstance : closureState.mLocalMethodRefs)
  19972. {
  19973. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  19974. }
  19975. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  19976. prevIgnoreWrites.Restore();
  19977. std::multiset<BfClosureCapturedEntry> capturedEntries;
  19978. //
  19979. {
  19980. auto varMethodState = declMethodState;
  19981. while (varMethodState != NULL)
  19982. {
  19983. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  19984. {
  19985. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  19986. methodDef->mIsStatic = false;
  19987. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  19988. methodDef->mIsMutating = true;
  19989. }
  19990. bool copyOuterCaptures = false;
  19991. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  19992. {
  19993. auto localVar = varMethodState->mLocals[localIdx];
  19994. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  19995. {
  19996. if (!allowCapture)
  19997. {
  19998. if ((!localVar->mIsStatic) && (!localVar->mConstValue))
  19999. continue;
  20000. }
  20001. if (localVar->mIsThis)
  20002. {
  20003. // We can only set mutating if our owning type is mutating
  20004. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  20005. {
  20006. if (typeInst->IsValueType())
  20007. {
  20008. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20009. methodDef->mIsMutating = true;
  20010. }
  20011. }
  20012. methodDef->mIsStatic = false;
  20013. continue;
  20014. }
  20015. if ((localVar->mIsThis) && (outerClosure != NULL))
  20016. {
  20017. continue;
  20018. }
  20019. if ((localVar->mConstValue) || (localVar->mIsStatic) || (localVar->mResolvedType->IsValuelessType()))
  20020. {
  20021. closureState.mConstLocals.push_back(*localVar);
  20022. continue;
  20023. }
  20024. BfClosureCapturedEntry capturedEntry;
  20025. auto capturedType = localVar->mResolvedType;
  20026. bool captureByRef = false;
  20027. if (!capturedType->IsRef())
  20028. {
  20029. if (localVar->mIsThis)
  20030. {
  20031. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  20032. captureByRef = true;
  20033. }
  20034. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20035. captureByRef = true;
  20036. }
  20037. else
  20038. {
  20039. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  20040. {
  20041. capturedType = ((BfRefType*)capturedType)->mElementType;
  20042. }
  20043. }
  20044. if (captureByRef)
  20045. {
  20046. //capturedEntry.mIsByReference = true;
  20047. capturedType = CreateRefType(capturedType);
  20048. }
  20049. else
  20050. {
  20051. //capturedEntry.mIsByReference = false;
  20052. }
  20053. capturedEntry.mNameNode = localVar->mNameNode;
  20054. capturedEntry.mType = capturedType;
  20055. capturedEntry.mName = localVar->mName;
  20056. //capturedEntry.mLocalVarDef = localVar;
  20057. capturedEntries.insert(capturedEntry);
  20058. }
  20059. }
  20060. varMethodState = varMethodState->mPrevMethodState;
  20061. if ((varMethodState == NULL) ||
  20062. (varMethodState->mMixinState != NULL) ||
  20063. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  20064. break;
  20065. }
  20066. }
  20067. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  20068. {
  20069. auto fieldDef = copyField->GetFieldDef();
  20070. BfClosureCapturedEntry capturedEntry;
  20071. capturedEntry.mName = copyField->GetFieldDef()->mName;
  20072. capturedEntry.mType = copyField->mResolvedType;
  20073. if (capturedEntry.mType->IsRef())
  20074. {
  20075. // Keep by ref
  20076. }
  20077. else if (!fieldDef->mIsReadOnly)
  20078. {
  20079. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  20080. }
  20081. capturedEntries.insert(capturedEntry);
  20082. }
  20083. int captureIdx = 0;
  20084. for (auto& capturedEntry : capturedEntries)
  20085. {
  20086. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  20087. }
  20088. /*if (isDefaultPass)
  20089. {
  20090. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  20091. int captureIdx = 0;
  20092. for (auto& capturedEntry : capturedEntries)
  20093. {
  20094. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  20095. BfParameterDef* paramDef = new BfParameterDef();
  20096. paramDef->mName = capturedEntry.mName;
  20097. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  20098. directTypeRef->mType = capturedEntry.mType;
  20099. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  20100. paramDef->mTypeRef = directTypeRef;
  20101. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  20102. methodDef->mParams.Insert(captureIdx, paramDef);
  20103. captureIdx++;
  20104. }
  20105. }
  20106. else
  20107. {
  20108. auto defaultMethodInstance = methodInstGroup->mDefault;
  20109. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  20110. }*/
  20111. methodState.Reset();
  20112. closureState.mCapturing = false;
  20113. //////////////////////////////////////////////////////////////////////////
  20114. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  20115. if (methodInstance->mReturnType != NULL)
  20116. {
  20117. BF_ASSERT(methodInstance->mDisallowCalling);
  20118. // We did a premature declaration (without captures)
  20119. methodInstance->UndoDeclaration();
  20120. methodInstance->mDisallowCalling = false;
  20121. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  20122. }
  20123. auto declareModule = this;
  20124. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  20125. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  20126. BF_ASSERT(declareModule != NULL);
  20127. methodInstance->mDeclModule = declareModule;
  20128. _SetupMethodInstance();
  20129. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  20130. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  20131. closureState.mReturnType = methodInstance->mReturnType;
  20132. mCompiler->mStats.mMethodsQueued++;
  20133. mCompiler->UpdateCompletion();
  20134. declareModule->mIncompleteMethodCount++;
  20135. mCompiler->mStats.mMethodsProcessed++;
  20136. if (!methodInstance->mIsReified)
  20137. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  20138. auto deferMethodState = rootMethodState;
  20139. // 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)
  20140. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  20141. (methodDef->mMethodType != BfMethodType_Mixin) &&
  20142. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)) &&
  20143. (!mCompiler->IsDataResolvePass()))
  20144. {
  20145. BP_ZONE("BfDeferredLocalMethod:create");
  20146. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  20147. deferredLocalMethod->mLocalMethod = localMethod;
  20148. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  20149. deferredLocalMethod->mMethodInstance = methodInstance;
  20150. auto checkMethodState = declMethodState;
  20151. while (checkMethodState != NULL)
  20152. {
  20153. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  20154. {
  20155. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  20156. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20157. }
  20158. if (checkMethodState->mMixinState != NULL)
  20159. {
  20160. BfMixinRecord mixinRecord;
  20161. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  20162. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20163. }
  20164. checkMethodState = checkMethodState->mPrevMethodState;
  20165. }
  20166. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  20167. }
  20168. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  20169. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  20170. mBfIRBuilder->RestoreDebugLocation();
  20171. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  20172. {
  20173. auto checkMethodState = mCurMethodState;
  20174. while (checkMethodState != NULL)
  20175. {
  20176. BfLocalMethod* nextLocalMethod = NULL;
  20177. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  20178. {
  20179. while (nextLocalMethod != NULL)
  20180. {
  20181. auto checkLocalMethod = nextLocalMethod;
  20182. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  20183. if (checkLocalMethod == localMethod)
  20184. continue;
  20185. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  20186. continue;
  20187. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  20188. if (checkMethodInstance == NULL)
  20189. continue; // Not generated yet
  20190. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  20191. {
  20192. String error = "Method already declared with the same parameter types";
  20193. auto bfError = Fail(error, methodInstance->mMethodDef->GetRefNode(), true);
  20194. if ((bfError != NULL) && (methodInstance->mMethodDef->GetRefNode() != checkMethodInstance->mMethodDef->GetRefNode()))
  20195. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  20196. }
  20197. }
  20198. }
  20199. checkMethodState = checkMethodState->mPrevMethodState;
  20200. }
  20201. }
  20202. return BfModuleMethodInstance(methodInstance);
  20203. }
  20204. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  20205. {
  20206. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  20207. return 0;
  20208. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20209. int rootMethodGenericParamCount = 0;
  20210. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  20211. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  20212. if (mCurMethodInstance == NULL)
  20213. return rootMethodGenericParamCount;
  20214. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  20215. return rootMethodGenericParamCount;
  20216. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  20217. if (callerLocalMethod == NULL)
  20218. return rootMethodGenericParamCount;
  20219. BfLocalMethod* calledLocalMethod = NULL;
  20220. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  20221. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  20222. {
  20223. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  20224. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  20225. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  20226. }
  20227. return rootMethodGenericParamCount;
  20228. }
  20229. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  20230. {
  20231. auto methodDef = methodInstance->mMethodDef;
  20232. auto customAttributes = methodInstance->GetCustomAttributes();
  20233. if (customAttributes != NULL)
  20234. return;
  20235. auto methodDeclaration = methodDef->GetMethodDeclaration();
  20236. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  20237. auto typeInstance = methodInstance->GetOwner();
  20238. if (typeInstance->IsInstanceOf(mCompiler->mValueTypeTypeDef))
  20239. return;
  20240. BfTypeState typeState(typeInstance);
  20241. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20242. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  20243. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20244. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  20245. BfAttributeDirective* attributeDirective = NULL;
  20246. if (methodDeclaration != NULL)
  20247. attributeDirective = methodDeclaration->mAttributes;
  20248. else if (propertyMethodDeclaration != NULL)
  20249. {
  20250. attributeDirective = propertyMethodDeclaration->mAttributes;
  20251. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  20252. {
  20253. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  20254. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  20255. }
  20256. }
  20257. if (attributeDirective != NULL)
  20258. {
  20259. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20260. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20261. if ((methodInstance == methodInstance->mMethodInstanceGroup->mDefault) && (methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes != NULL))
  20262. {
  20263. // Take over prevoiusly-generated custom attributes
  20264. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes;
  20265. methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes = NULL;
  20266. }
  20267. else
  20268. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  20269. }
  20270. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mPropertyDeclaration->mAttributes != NULL) && ((attrTarget & BfAttributeTargets_Property) == 0))
  20271. {
  20272. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes != NULL)
  20273. {
  20274. GetCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20275. }
  20276. else
  20277. {
  20278. methodInstance->GetMethodInfoEx()->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20279. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20280. }
  20281. }
  20282. customAttributes = methodInstance->GetCustomAttributes();
  20283. if (customAttributes == NULL)
  20284. {
  20285. auto owner = methodInstance->GetOwner();
  20286. if ((owner->IsDelegate()) || (owner->IsFunction()))
  20287. customAttributes = owner->mCustomAttributes;
  20288. }
  20289. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  20290. if (customAttributes != NULL)
  20291. {
  20292. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  20293. if (linkNameAttr != NULL)
  20294. {
  20295. if (linkNameAttr->mCtorArgs.size() == 1)
  20296. {
  20297. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  20298. if (constant != NULL)
  20299. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  20300. }
  20301. }
  20302. if (methodDef->mHasComptime)
  20303. methodInstance->mComptimeFlags = BfComptimeFlag_Comptime;
  20304. auto comptimeAttr = customAttributes->Get(mCompiler->mComptimeAttributeTypeDef);
  20305. if (comptimeAttr != NULL)
  20306. {
  20307. for (auto setProp : comptimeAttr->mSetProperties)
  20308. {
  20309. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  20310. if (propertyDef->mName == "OnlyFromComptime")
  20311. {
  20312. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  20313. if ((constant != NULL) && (constant->mBool))
  20314. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_OnlyFromComptime);
  20315. }
  20316. else if (propertyDef->mName == "ConstEval")
  20317. {
  20318. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  20319. if ((constant != NULL) && (constant->mBool))
  20320. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_ConstEval);
  20321. }
  20322. }
  20323. }
  20324. }
  20325. auto delegateInfo = typeInstance->GetDelegateInfo();
  20326. if ((delegateInfo != NULL) && (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) && (methodInstance->mMethodDef->mName == "Invoke"))
  20327. methodInstance->mCallingConvention = delegateInfo->mCallingConvention;
  20328. }
  20329. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  20330. {
  20331. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  20332. {
  20333. // Don't create a func
  20334. return;
  20335. }
  20336. auto typeInstance = methodInstance->GetOwner();
  20337. auto methodDef = methodInstance->mMethodDef;
  20338. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  20339. if (isTemporaryFunc)
  20340. {
  20341. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  20342. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  20343. mangledName = "autocomplete_tmp";
  20344. }
  20345. if (!mBfIRBuilder->mIgnoreWrites)
  20346. {
  20347. BfIRFunction prevFunc;
  20348. // Remove old version (if we have one)
  20349. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  20350. if (prevFunc)
  20351. {
  20352. if ((methodDef->mIsOverride) && (mCurTypeInstance->mTypeDef->mIsCombinedPartial))
  20353. {
  20354. bool takeover = false;
  20355. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  20356. BfMethodDef* nextMethod = NULL;
  20357. BfMemberSetEntry* entry = NULL;
  20358. if (mCurTypeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  20359. nextMethod = (BfMethodDef*)entry->mMemberDef;
  20360. while (nextMethod != NULL)
  20361. {
  20362. auto checkMethod = nextMethod;
  20363. nextMethod = nextMethod->mNextWithSameName;
  20364. if (checkMethod == methodDef)
  20365. continue;
  20366. if (checkMethod->mIsOverride)
  20367. {
  20368. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20369. if (checkMethodInstance == NULL)
  20370. continue;
  20371. if ((checkMethodInstance->mIRFunction == prevFunc) &&
  20372. (checkMethodInstance->mMethodDef->mMethodDeclaration != NULL) &&
  20373. (checkMethodInstance->mVirtualTableIdx < 0))
  20374. {
  20375. BfAstNode* refNode = methodDef->GetRefNode();
  20376. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  20377. refNode = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  20378. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  20379. refNode = methodDeclaration->mVirtualSpecifier;
  20380. auto error = Fail(StrFormat("Conflicting extension override method '%s'", MethodToString(mCurMethodInstance).c_str()), refNode);
  20381. if (error != NULL)
  20382. mCompiler->mPassInstance->MoreInfo("See previous override", checkMethod->GetRefNode());
  20383. takeover = false;
  20384. break;
  20385. }
  20386. }
  20387. if (!checkMethod->mIsExtern)
  20388. continue;
  20389. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20390. if (checkMethodInstance == NULL)
  20391. continue;
  20392. if (!CompareMethodSignatures(checkMethodInstance, mCurMethodInstance))
  20393. continue;
  20394. // Take over function
  20395. takeover = true;
  20396. }
  20397. if (takeover)
  20398. mCurMethodInstance->mIRFunction = prevFunc;
  20399. if (!mCurMethodInstance->mIRFunction)
  20400. {
  20401. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  20402. if (!mIsComptimeModule)
  20403. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  20404. }
  20405. }
  20406. else if (methodDef->mIsExtern)
  20407. {
  20408. // Allow this
  20409. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  20410. }
  20411. else if (typeInstance->IsIRFuncUsed(prevFunc))
  20412. {
  20413. // We can have a collision of names when we have generic methods that differ only in
  20414. // their constraints, but they should only collide in their unspecialized form
  20415. // since only one will be chosen for a given concrete type
  20416. if (!mIsComptimeModule)
  20417. mCurMethodInstance->mMangleWithIdx = true;
  20418. mangledName.Clear();
  20419. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  20420. BfLogSysM("Function collision forced mangleWithIdx for %p: %d GenericArgs: %d Unspecialized: %d\n", methodInstance, prevFunc.mId, methodInstance->GetNumGenericArguments(), methodInstance->mIsUnspecialized);
  20421. }
  20422. else
  20423. {
  20424. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  20425. if (!mIsComptimeModule)
  20426. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  20427. }
  20428. }
  20429. }
  20430. if (typeInstance != mContext->mBfObjectType)
  20431. {
  20432. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  20433. GetMethodCustomAttributes(methodInstance);
  20434. }
  20435. // if (prevFunc)
  20436. // {
  20437. // if (methodDef->mIsExtern)
  20438. // {
  20439. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  20440. // methodInstance->mIRFunction = prevFunc;
  20441. // }
  20442. // else
  20443. // {
  20444. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  20445. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  20446. // {
  20447. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  20448. // BfLogSysM("Ignoring function name collision\n");
  20449. // }
  20450. // else
  20451. // {
  20452. // if (methodDef->mMethodDeclaration == NULL)
  20453. // {
  20454. // AssertErrorState();
  20455. // }
  20456. // else
  20457. // {
  20458. // BF_ASSERT(mIsSpecialModule);
  20459. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  20460. // {
  20461. // // We shouldn't have name collisions on the first run!
  20462. // AssertErrorState();
  20463. // }
  20464. // }
  20465. // }
  20466. // BfLogSysM("Before erase\n");
  20467. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  20468. // }
  20469. // }
  20470. bool isIntrinsic = false;
  20471. if (!methodInstance->mIRFunction)
  20472. {
  20473. BfIRFunction func;
  20474. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType() || (mIsComptimeModule)) &&
  20475. (!methodDef->IsEmptyPartial())) && (funcType);
  20476. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  20477. {
  20478. if (!mIsReified)
  20479. wantsLLVMFunc = false;
  20480. }*/
  20481. if (wantsLLVMFunc)
  20482. {
  20483. func = GetIntrinsic(methodInstance, true);
  20484. if (func)
  20485. {
  20486. isIntrinsic = true;
  20487. }
  20488. else
  20489. {
  20490. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  20491. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  20492. if (methodInstance->mAlwaysInline)
  20493. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  20494. // if (prevFunc)
  20495. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  20496. }
  20497. methodInstance->mIRFunction = func;
  20498. //if (!ignoreWrites)
  20499. //BF_ASSERT(!func.IsFake());
  20500. }
  20501. }
  20502. if (outIsIntrinsic != NULL)
  20503. *outIsIntrinsic = isIntrinsic;
  20504. if (!isIntrinsic)
  20505. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  20506. }
  20507. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  20508. {
  20509. if (methodInstance->mHotMethod != NULL)
  20510. return;
  20511. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  20512. {
  20513. auto srcTypeInst = methodInstance->GetOwner();
  20514. if (srcTypeInst->mHotTypeData == NULL)
  20515. return;
  20516. StringT<128> mangledName = inMangledName;
  20517. if (mangledName.IsEmpty())
  20518. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  20519. // We always keep the current primary method at the same address
  20520. BfHotMethod* hotMethod;
  20521. BfHotMethod** hotMethodPtr;
  20522. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  20523. {
  20524. hotMethod = new BfHotMethod();
  20525. *hotMethodPtr = hotMethod;
  20526. hotMethod->mRefCount = 1;
  20527. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20528. #ifdef BF_DBG_HOTMETHOD_IDX
  20529. static int sMethodIdx = 0;
  20530. hotMethod->mMethodIdx = sMethodIdx++;
  20531. #endif
  20532. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20533. }
  20534. else
  20535. {
  20536. hotMethod = *hotMethodPtr;
  20537. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  20538. {
  20539. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  20540. auto prevHotMethod = *hotMethodPtr;
  20541. hotMethod = new BfHotMethod();
  20542. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20543. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  20544. hotDupMethod->mRefCount++;
  20545. prevHotMethod->mReferences.Add(hotDupMethod);
  20546. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  20547. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20548. }
  20549. else if (mCompiler->IsHotCompile())
  20550. {
  20551. // Link the previous version into the mPrevVersion
  20552. BfHotMethod* prevMethod = new BfHotMethod();
  20553. prevMethod->mRefCount = 1;
  20554. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  20555. hotMethod->mPrevVersion = prevMethod;
  20556. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  20557. hotMethod->mSrcTypeVersion = NULL;
  20558. prevMethod->mFlags = hotMethod->mFlags;
  20559. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  20560. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  20561. #ifdef BF_DBG_HOTMETHOD_NAME
  20562. prevMethod->mMangledName = hotMethod->mMangledName;
  20563. #endif
  20564. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  20565. }
  20566. else
  20567. {
  20568. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20569. hotMethod->Clear(true);
  20570. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20571. }
  20572. }
  20573. if (methodInstance->mIsClosure)
  20574. {
  20575. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  20576. }
  20577. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  20578. hotMethod->mSrcTypeVersion->mRefCount++;
  20579. hotMethod->mRefCount++;
  20580. #ifdef BF_DBG_HOTMETHOD_NAME
  20581. hotMethod->mMangledName = mangledName;
  20582. #endif
  20583. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!IsHotCompile()))
  20584. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  20585. methodInstance->mHotMethod = hotMethod;
  20586. }
  20587. }
  20588. static void StackOverflow()
  20589. {
  20590. int i = 0;
  20591. if (i == 0)
  20592. StackOverflow();
  20593. }
  20594. void BfModule::StartMethodDeclaration(BfMethodInstance* methodInstance, BfMethodState* prevMethodState)
  20595. {
  20596. methodInstance->mHasStartedDeclaration = true;
  20597. auto methodDef = methodInstance->mMethodDef;
  20598. auto typeInstance = methodInstance->GetOwner();
  20599. bool hasNonGenericParams = false;
  20600. bool hasGenericParams = false;
  20601. int dependentGenericStartIdx = 0;
  20602. if (methodDef->mIsLocalMethod)
  20603. {
  20604. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  20605. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  20606. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  20607. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  20608. // over the local method each time
  20609. auto rootMethodInstance = prevMethodState->GetRootMethodState()->mMethodInstance;
  20610. dependentGenericStartIdx = 0;
  20611. if (rootMethodInstance != NULL)
  20612. {
  20613. if (rootMethodInstance->mMethodInfoEx != NULL)
  20614. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  20615. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  20616. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  20617. }
  20618. }
  20619. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodInstance->GetNumGenericArguments(); genericArgIdx++)
  20620. {
  20621. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  20622. if (genericArgType->IsGenericParam())
  20623. {
  20624. hasGenericParams = true;
  20625. auto genericParam = (BfGenericParamType*)genericArgType;
  20626. methodInstance->mIsUnspecialized = true;
  20627. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  20628. methodInstance->mIsUnspecializedVariation = true;
  20629. }
  20630. else
  20631. {
  20632. hasNonGenericParams = true;
  20633. if (genericArgType->IsUnspecializedType())
  20634. {
  20635. methodInstance->mIsUnspecialized = true;
  20636. methodInstance->mIsUnspecializedVariation = true;
  20637. }
  20638. }
  20639. }
  20640. if ((hasGenericParams) && (hasNonGenericParams))
  20641. {
  20642. methodInstance->mIsUnspecializedVariation = true;
  20643. }
  20644. if (typeInstance->IsUnspecializedType())
  20645. {
  20646. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  20647. // actually want to do method processing on it
  20648. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  20649. methodInstance->mIsUnspecializedVariation = true;
  20650. methodInstance->mIsUnspecialized = true;
  20651. }
  20652. if (methodInstance->mIsUnspecializedVariation)
  20653. BF_ASSERT(methodInstance->mIsUnspecialized);
  20654. //TODO: Why did we do this?
  20655. if (methodDef->mMethodType == BfMethodType_Mixin)
  20656. {
  20657. if (methodInstance->IsSpecializedGenericMethod())
  20658. methodInstance->mIsUnspecializedVariation = true;
  20659. methodInstance->mIsUnspecialized = true;
  20660. }
  20661. }
  20662. // methodDeclaration is NULL for default constructors
  20663. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  20664. {
  20665. BF_ASSERT((mCompiler->mCeMachine == NULL) || (!mCompiler->mCeMachine->mDbgPaused));
  20666. BP_ZONE("BfModule::DoMethodDeclaration");
  20667. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  20668. // to effectively make mIgnoreWrites method-scoped
  20669. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  20670. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  20671. SetAndRestoreValue<bool> prevAllowLockYield(mContext->mAllowLockYield, false);
  20672. BfTypeState typeState(mCurTypeInstance);
  20673. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20674. BfModule* resolveModule = mContext->mUnreifiedModule;
  20675. if (mCompiler->IsAutocomplete())
  20676. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  20677. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  20678. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  20679. BfMethodState methodState;
  20680. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  20681. methodState.mTempKind = BfMethodState::TempKind_Static;
  20682. defer({ mCurMethodInstance->mHasBeenDeclared = true; });
  20683. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  20684. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  20685. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  20686. // if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  20687. // {
  20688. // BF_ASSERT(mContext->mResolvingVarField);
  20689. // isTemporaryFunc = true;
  20690. // }
  20691. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  20692. FinishInit();
  20693. auto typeInstance = mCurTypeInstance;
  20694. auto typeDef = typeInstance->mTypeDef;
  20695. auto methodDef = mCurMethodInstance->mMethodDef;
  20696. if (methodDef->mName.StartsWith('_'))
  20697. {
  20698. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  20699. if (methodDef->mName == "__FATALERRORNAME")
  20700. BFMODULE_FATAL(this, "__FATALERRORNAME");
  20701. if (methodDef->mName == "__STACKOVERFLOW")
  20702. StackOverflow();
  20703. if (methodDef->mName == "__INTERNALERROR")
  20704. InternalError("Bad method name", methodDef->GetRefNode());
  20705. }
  20706. if (typeInstance->IsClosure())
  20707. {
  20708. if (methodDef->mName == "Invoke")
  20709. return;
  20710. }
  20711. auto methodInstance = mCurMethodInstance;
  20712. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  20713. addToWorkList = false;
  20714. if (!methodInstance->mHasStartedDeclaration)
  20715. StartMethodDeclaration(methodInstance, prevMethodState.mPrevVal);
  20716. BfAutoComplete* bfAutocomplete = NULL;
  20717. if (mCompiler->mResolvePassData != NULL)
  20718. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  20719. if (methodInstance->mMethodInfoEx != NULL)
  20720. {
  20721. BfTypeInstance* unspecializedTypeInstance = NULL;
  20722. Array<BfTypeReference*> deferredResolveTypes;
  20723. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  20724. {
  20725. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  20726. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  20727. {
  20728. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  20729. }
  20730. else
  20731. {
  20732. auto externConstraintDef = genericParam->GetExternConstraintDef();
  20733. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  20734. auto autoComplete = mCompiler->GetAutoComplete();
  20735. if (autoComplete != NULL)
  20736. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  20737. if (genericParam->mExternType != NULL)
  20738. {
  20739. //
  20740. }
  20741. else
  20742. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  20743. }
  20744. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized, &deferredResolveTypes);
  20745. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  20746. {
  20747. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  20748. if (bfAutocomplete != NULL)
  20749. {
  20750. for (auto nameNode : genericParamDef->mNameNodes)
  20751. {
  20752. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  20753. }
  20754. }
  20755. }
  20756. }
  20757. for (auto typeRef : deferredResolveTypes)
  20758. auto constraintType = ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_None);
  20759. if (methodInstance->mMethodInfoEx != NULL)
  20760. {
  20761. ValidateGenericParams(BfGenericParamKind_Method,
  20762. Span<BfGenericParamInstance*>((BfGenericParamInstance**)methodInstance->mMethodInfoEx->mGenericParams.mVals,
  20763. methodInstance->mMethodInfoEx->mGenericParams.mSize));
  20764. }
  20765. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  20766. AddDependency(genericParam, mCurTypeInstance);
  20767. }
  20768. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  20769. {
  20770. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  20771. BfAstNode* nameNode = methodDeclaration->mNameNode;
  20772. if (nameNode == NULL)
  20773. {
  20774. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  20775. nameNode = ctorDeclaration->mThisToken;
  20776. }
  20777. if ((autoComplete->IsAutocompleteNode(nameNode)) && (autoComplete->mResolveType != BfResolveType_Autocomplete))
  20778. {
  20779. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  20780. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  20781. autoComplete->mDefType = typeDef;
  20782. autoComplete->mDefMethod = methodDef;
  20783. autoComplete->SetDefinitionLocation(nameNode);
  20784. if (methodDef->mIsOverride)
  20785. {
  20786. bool found = false;
  20787. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  20788. {
  20789. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  20790. if (ventry.mDeclaringMethod.mMethodNum == -1)
  20791. continue;
  20792. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  20793. if (virtMethod != NULL)
  20794. {
  20795. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  20796. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  20797. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  20798. {
  20799. // Is matching method
  20800. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  20801. {
  20802. auto baseType = typeInstance->mBaseType;
  20803. if (baseType != NULL)
  20804. {
  20805. found = true;
  20806. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  20807. baseType = baseType->mBaseType;
  20808. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  20809. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  20810. autoComplete->mDefType = baseType->mTypeDef;
  20811. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  20812. }
  20813. }
  20814. break;
  20815. }
  20816. }
  20817. }
  20818. if ((!found) && (autoComplete->mIsGetDefinition) && (methodDef->mDeclaringType->IsExtension()))
  20819. {
  20820. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  20821. {
  20822. auto defaultMethod = methodGroup.mDefault;
  20823. if (defaultMethod == NULL)
  20824. continue;
  20825. if (!defaultMethod->mMethodDef->mIsExtern)
  20826. continue;
  20827. if (!CompareMethodSignatures(defaultMethod, methodInstance))
  20828. continue;
  20829. autoComplete->SetDefinitionLocation(defaultMethod->mMethodDef->GetRefNode(), true);
  20830. autoComplete->mDefType = typeInstance->mTypeDef;
  20831. autoComplete->mDefMethod = defaultMethod->mMethodDef;
  20832. }
  20833. }
  20834. }
  20835. }
  20836. }
  20837. bool reportErrors = true;
  20838. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  20839. reportErrors = true;
  20840. // Only the defining contexts needs to report errors here
  20841. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  20842. if (methodDef->mMethodType == BfMethodType_Dtor)
  20843. {
  20844. if (methodDef->mIsStatic)
  20845. {
  20846. }
  20847. else
  20848. {
  20849. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  20850. {
  20851. BfAstNode* refNode = methodDeclaration;
  20852. if (refNode == NULL)
  20853. {
  20854. // Whatever caused this ctor to be generated should have caused another failure
  20855. // But that failure might not be generated until the ctor is generated
  20856. }
  20857. else
  20858. {
  20859. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  20860. if (dtorDecl != NULL)
  20861. refNode = dtorDecl->mThisToken;
  20862. Fail("Structs cannot have destructors", refNode);
  20863. }
  20864. }
  20865. auto methodDeclaration = methodDef->GetMethodDeclaration();
  20866. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  20867. (mCurTypeInstance != mContext->mBfObjectType))
  20868. {
  20869. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  20870. }
  20871. }
  20872. }
  20873. BfType* resolvedReturnType = NULL;
  20874. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  20875. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  20876. (methodDef->mReturnTypeRef != NULL))
  20877. {
  20878. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  20879. if (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>())
  20880. {
  20881. // An invalid 'var' error would not have been caught in the original property type pass
  20882. mIgnoreErrors = false;
  20883. }
  20884. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_NoReify);
  20885. if ((((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0) || (methodInstance->mIsAutocompleteMethod))
  20886. && (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>()))
  20887. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  20888. else
  20889. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration, flags);
  20890. if (resolvedReturnType == NULL)
  20891. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  20892. if ((methodDef->mIsReadOnly) && (!resolvedReturnType->IsRef()))
  20893. {
  20894. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration))
  20895. if (methodDeclaration->mReadOnlySpecifier != NULL)
  20896. Fail("Readonly specifier is only valid on 'ref' return types", methodDeclaration->mReadOnlySpecifier);
  20897. }
  20898. }
  20899. else
  20900. {
  20901. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  20902. }
  20903. BF_ASSERT(resolvedReturnType != NULL);
  20904. mCurMethodInstance->mReturnType = resolvedReturnType;
  20905. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  20906. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  20907. //if (!methodInstance->IsSpecializedGenericMethod())
  20908. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  20909. if (methodDef->mExplicitInterface != NULL)
  20910. {
  20911. auto autoComplete = mCompiler->GetAutoComplete();
  20912. if (autoComplete != NULL)
  20913. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  20914. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  20915. BfTypeInstance* explicitInterface = NULL;
  20916. if (explicitType != NULL)
  20917. explicitInterface = explicitType->ToTypeInstance();
  20918. if (explicitInterface != NULL)
  20919. {
  20920. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  20921. if (autoComplete != NULL)
  20922. {
  20923. BfTokenNode* dotToken = NULL;
  20924. BfAstNode* nameNode = NULL;
  20925. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  20926. {
  20927. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  20928. nameNode = methodDeclaration->mNameNode;
  20929. }
  20930. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  20931. }
  20932. }
  20933. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  20934. {
  20935. bool interfaceFound = false;
  20936. for (auto ifaceInst : typeInstance->mInterfaces)
  20937. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  20938. if ((!interfaceFound) && (!typeInstance->mTypeFailed))
  20939. {
  20940. if (methodDef->mMethodDeclaration != NULL)
  20941. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  20942. else
  20943. {
  20944. // For property decls, we should have already given the error during type population
  20945. if (mCompiler->mRevision == 1)
  20946. AssertErrorState();
  20947. }
  20948. }
  20949. }
  20950. }
  20951. bool isThisStruct = mCurTypeInstance->IsStruct();
  20952. BfType* thisType = NULL;
  20953. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  20954. {
  20955. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  20956. {
  20957. thisType = mCurTypeInstance;
  20958. if (thisType == NULL)
  20959. return;
  20960. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  20961. {
  20962. BfTypeUtils::SplatIterate([&](BfType* checkType)
  20963. {
  20964. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  20965. }, thisType);
  20966. }
  20967. }
  20968. else
  20969. {
  20970. thisType = mCurTypeInstance;
  20971. resolveModule->PopulateType(thisType, BfPopulateType_Declaration);
  20972. }
  20973. }
  20974. int implicitParamCount = 0;
  20975. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  20976. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  20977. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  20978. bool hadDelegateParams = false;
  20979. bool hadParams = false;
  20980. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  20981. {
  20982. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  20983. BfParameterDef* paramDef = NULL;
  20984. int paramDefIdx = -1;
  20985. if (paramIdx < implicitParamCount)
  20986. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  20987. else
  20988. {
  20989. paramDefIdx = paramIdx - implicitParamCount;
  20990. paramDef = methodDef->mParams[paramDefIdx];
  20991. }
  20992. if (hadParams)
  20993. break;
  20994. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  20995. continue;
  20996. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  20997. (paramDef->mParamKind != BfParamKind_AppendIdx))
  20998. {
  20999. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  21000. if (mCompiler->mResolvePassData->mAutoComplete->IsAutocompleteNode(paramDef->mTypeRef))
  21001. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("token", "in"), paramDef->mTypeRef->ToString());
  21002. }
  21003. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  21004. {
  21005. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  21006. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  21007. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  21008. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  21009. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  21010. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  21011. }
  21012. BfType* resolvedParamType = NULL;
  21013. if (closureCaptureEntry != NULL)
  21014. resolvedParamType = closureCaptureEntry->mType;
  21015. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfLetTypeReference>()))
  21016. {
  21017. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  21018. resolvedParamType = mContext->mBfObjectType;
  21019. }
  21020. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfVarTypeReference>()))
  21021. {
  21022. if (methodDef->mMethodType != BfMethodType_Mixin)
  21023. {
  21024. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  21025. resolvedParamType = mContext->mBfObjectType;
  21026. }
  21027. else
  21028. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21029. }
  21030. BfType* unresolvedParamType = resolvedParamType;
  21031. bool wasGenericParam = false;
  21032. if (resolvedParamType == NULL)
  21033. {
  21034. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue | BfResolveTypeRefFlag_NoReify);
  21035. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  21036. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  21037. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  21038. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  21039. resolvedParamType = resolvedParamType->GetUnderlyingType();
  21040. }
  21041. if (resolvedParamType == NULL)
  21042. {
  21043. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21044. unresolvedParamType = resolvedParamType;
  21045. if (mCurTypeInstance->IsBoxed())
  21046. {
  21047. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  21048. // If we failed a lookup here then we better have also failed it in the original type
  21049. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.ContainsKey(boxedType->mElementType->ToTypeInstance()));
  21050. }
  21051. }
  21052. BF_ASSERT(!resolvedParamType->IsDeleting());
  21053. if (!methodInstance->IsSpecializedGenericMethod())
  21054. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21055. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  21056. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  21057. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  21058. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  21059. {
  21060. if (paramDef->mParamKind == BfParamKind_Params)
  21061. {
  21062. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  21063. if (refNode != NULL)
  21064. refNode = paramDef->mParamDeclaration->mModToken;
  21065. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  21066. }
  21067. BfTypedValue defaultValue;
  21068. if (resolvedParamType->IsConstExprValue())
  21069. {
  21070. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  21071. BfExprEvaluator exprEvaluator(this);
  21072. exprEvaluator.mExpectingType = constExprType->mType;
  21073. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  21074. defaultValue = exprEvaluator.GetResult();
  21075. }
  21076. else
  21077. {
  21078. BfTypeState typeState;
  21079. typeState.mType = mCurTypeInstance;
  21080. typeState.mCurTypeDef = methodDef->mDeclaringType;
  21081. //typeState.mCurMethodDef = methodDef;
  21082. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  21083. BfConstResolver constResolver(this);
  21084. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  21085. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  21086. {
  21087. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  21088. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  21089. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  21090. {
  21091. defaultValue = castedDefaultValue; // Good!
  21092. }
  21093. else if (!CanCast(defaultValue, resolvedParamType))
  21094. {
  21095. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  21096. // a conversion operator.
  21097. // This should throw an error
  21098. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  21099. AssertErrorState();
  21100. if (!defaultValue.mValue.IsConst())
  21101. defaultValue = BfTypedValue();
  21102. }
  21103. }
  21104. }
  21105. if (!defaultValue)
  21106. {
  21107. defaultValue = GetDefaultTypedValue(resolvedParamType);
  21108. if (!defaultValue.mValue.IsConst())
  21109. defaultValue = BfTypedValue();
  21110. }
  21111. if (defaultValue)
  21112. {
  21113. if (defaultValue.mType->IsVar())
  21114. {
  21115. AssertErrorState();
  21116. }
  21117. else
  21118. {
  21119. BF_ASSERT(defaultValue.mValue.IsConst());
  21120. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  21121. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  21122. CurrentAddToConstHolder(defaultValue.mValue);
  21123. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  21124. }
  21125. }
  21126. }
  21127. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  21128. {
  21129. bool addParams = true;
  21130. bool isValid = false;
  21131. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  21132. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->IsInstanceOf(mCompiler->mSpanTypeDef)))
  21133. {
  21134. // Span<T>
  21135. isValid = true;
  21136. }
  21137. else if (resolvedParamType->IsArray())
  21138. {
  21139. // Array is the 'normal' params type
  21140. isValid = true;
  21141. }
  21142. else if (resolvedParamType->IsSizedArray())
  21143. {
  21144. isValid = true;
  21145. }
  21146. else if (resolvedParamType->IsVar())
  21147. {
  21148. isValid = true;
  21149. }
  21150. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()) || (resolvedParamType->IsMethodRef()))
  21151. {
  21152. hadDelegateParams = true;
  21153. // This means we copy the params from a delegate
  21154. BfMethodParam methodParam;
  21155. methodParam.mResolvedType = resolvedParamType;
  21156. methodParam.mParamDefIdx = paramDefIdx;
  21157. methodParam.mDelegateParamIdx = 0;
  21158. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21159. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  21160. {
  21161. methodParam.mDelegateParamIdx = delegateParamIdx;
  21162. mCurMethodInstance->mParams.Add(methodParam);
  21163. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  21164. if (!methodInstance->IsSpecializedGenericMethod())
  21165. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21166. }
  21167. isValid = true;
  21168. addParams = false;
  21169. }
  21170. else if (resolvedParamType->IsGenericParam())
  21171. {
  21172. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  21173. if (genericParamInstance->mTypeConstraint != NULL)
  21174. {
  21175. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  21176. if ((genericParamInstance->mTypeConstraint->IsArray()) || (genericParamInstance->mTypeConstraint->IsSizedArray()))
  21177. {
  21178. BfMethodParam methodParam;
  21179. methodParam.mResolvedType = resolvedParamType;
  21180. methodParam.mParamDefIdx = paramDefIdx;
  21181. mCurMethodInstance->mParams.Add(methodParam);
  21182. isValid = true;
  21183. }
  21184. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  21185. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  21186. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  21187. {
  21188. mCurMethodInstance->mHadGenericDelegateParams = true;
  21189. isValid = true;
  21190. addParams = false;
  21191. }
  21192. }
  21193. }
  21194. else
  21195. {
  21196. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  21197. if ((paramTypeInst != NULL) &&
  21198. ((paramTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef))))
  21199. {
  21200. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  21201. isValid = true;
  21202. addParams = false;
  21203. }
  21204. }
  21205. if (!isValid)
  21206. {
  21207. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  21208. // Failure case, make it an Object[]
  21209. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  21210. }
  21211. if ((addParams) && (resolvedParamType != NULL))
  21212. {
  21213. BfMethodParam methodParam;
  21214. methodParam.mResolvedType = resolvedParamType;
  21215. methodParam.mParamDefIdx = paramDefIdx;
  21216. mCurMethodInstance->mParams.push_back(methodParam);
  21217. }
  21218. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  21219. {
  21220. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  21221. }
  21222. }
  21223. else
  21224. {
  21225. BfMethodParam methodParam;
  21226. methodParam.mResolvedType = resolvedParamType;
  21227. methodParam.mParamDefIdx = paramDefIdx;
  21228. mCurMethodInstance->mParams.Add(methodParam);
  21229. }
  21230. }
  21231. if (hadDelegateParams)
  21232. {
  21233. HashSet<String> usedNames;
  21234. Dictionary<int, int> usedParamDefIdx;
  21235. for (auto methodParam : methodDef->mParams)
  21236. {
  21237. usedNames.Add(methodParam->mName);
  21238. }
  21239. for (auto& methodParam : mCurMethodInstance->mParams)
  21240. {
  21241. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  21242. {
  21243. int* refCount = NULL;
  21244. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  21245. (*refCount)++;
  21246. }
  21247. }
  21248. for (auto& methodParam : mCurMethodInstance->mParams)
  21249. {
  21250. if (methodParam.mDelegateParamIdx != -1)
  21251. {
  21252. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  21253. methodParam.mDelegateParamNameCombine = true;
  21254. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21255. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  21256. if (usedNames.Contains(paramName))
  21257. methodParam.mDelegateParamNameCombine = true;
  21258. }
  21259. }
  21260. }
  21261. int argIdx = 0;
  21262. resolveModule->PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  21263. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  21264. {
  21265. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  21266. auto thisType = methodInstance->GetOwner();
  21267. if (methodInstance->GetParamIsSplat(thisIdx))
  21268. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  21269. else if (!thisType->IsValuelessType())
  21270. {
  21271. BfTypeCode loweredTypeCode = BfTypeCode_None;
  21272. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  21273. if ((!mIsComptimeModule) && (!methodDef->mIsMutating))
  21274. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  21275. argIdx++;
  21276. if (loweredTypeCode2 != BfTypeCode_None)
  21277. argIdx++;
  21278. }
  21279. }
  21280. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  21281. argIdx++;
  21282. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  21283. {
  21284. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  21285. BfType* checkType = methodParam.mResolvedType;
  21286. int checkArgIdx = argIdx;
  21287. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  21288. {
  21289. checkArgIdx = 0;
  21290. checkType = methodInstance->GetThisType();
  21291. }
  21292. if (checkType->IsMethodRef())
  21293. {
  21294. methodParam.mIsSplat = true;
  21295. }
  21296. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting(paramIdx)))
  21297. {
  21298. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  21299. if (checkType->IsSplattable())
  21300. {
  21301. bool isSplat = false;
  21302. auto checkTypeInstance = checkType->ToTypeInstance();
  21303. if ((checkTypeInstance != NULL) && (checkTypeInstance->mIsCRepr))
  21304. isSplat = true;
  21305. int splatCount = checkType->GetSplatCount();
  21306. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  21307. isSplat = true;
  21308. if (isSplat)
  21309. {
  21310. methodParam.mIsSplat = true;
  21311. argIdx += splatCount;
  21312. continue;
  21313. }
  21314. }
  21315. else if (!checkType->IsValuelessType())
  21316. {
  21317. BfTypeCode loweredTypeCode = BfTypeCode_None;
  21318. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  21319. if (!mIsComptimeModule)
  21320. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  21321. argIdx++;
  21322. if (loweredTypeCode2 != BfTypeCode_None)
  21323. argIdx++;
  21324. continue;
  21325. }
  21326. }
  21327. argIdx++;
  21328. }
  21329. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  21330. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  21331. {
  21332. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  21333. }
  21334. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  21335. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  21336. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  21337. (!methodDef->mIsSkipCall))
  21338. {
  21339. if (methodDeclaration->mEndSemicolon == NULL)
  21340. {
  21341. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  21342. {
  21343. //
  21344. }
  21345. else
  21346. AssertParseErrorState();
  21347. }
  21348. else
  21349. {
  21350. bool isError = true;
  21351. if (typeInstance->IsTypedPrimitive())
  21352. {
  21353. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  21354. {
  21355. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  21356. {
  21357. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  21358. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  21359. {
  21360. isError = false;
  21361. }
  21362. }
  21363. }
  21364. }
  21365. if (isError)
  21366. {
  21367. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  21368. MethodToString(methodInstance).c_str()),
  21369. methodDef->GetRefNode());
  21370. }
  21371. }
  21372. }
  21373. if (methodDef->IsEmptyPartial())
  21374. hasExternSpecifier = true;
  21375. if (!methodInstance->IsAutocompleteMethod())
  21376. {
  21377. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  21378. int implicitParamCount = methodInstance->GetImplicitParamCount();
  21379. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  21380. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  21381. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  21382. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  21383. int paramIdx = 0;
  21384. int defaultParamIdx = 0;
  21385. while (true)
  21386. {
  21387. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  21388. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  21389. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  21390. {
  21391. paramIdx++;
  21392. continue;
  21393. }
  21394. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  21395. {
  21396. defaultParamIdx++;
  21397. continue;
  21398. }
  21399. if ((isDone) || (isDefaultDone))
  21400. {
  21401. // 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
  21402. // to cause us to throw an assertion in the declaration here
  21403. if ((!defaultMethodInstance->mHadGenericDelegateParams) && (!methodInstance->mHasFailed) && (!defaultMethodInstance->mHasFailed))
  21404. BF_ASSERT((isDone) && (isDefaultDone));
  21405. break;
  21406. }
  21407. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  21408. if (paramType->IsRef())
  21409. paramType = paramType->GetUnderlyingType();
  21410. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  21411. paramIdx++;
  21412. defaultParamIdx++;
  21413. }
  21414. }
  21415. StringT<4096> mangledName;
  21416. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  21417. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  21418. {
  21419. auto paramType = methodInstance->GetParamType(paramIdx);
  21420. if (paramType->IsComposite())
  21421. resolveModule->PopulateType(paramType, BfPopulateType_Data);
  21422. if (!methodInstance->IsParamSkipped(paramIdx))
  21423. {
  21424. if (paramType->IsStruct())
  21425. {
  21426. //
  21427. }
  21428. else
  21429. {
  21430. PopulateType(paramType, BfPopulateType_Declaration);
  21431. }
  21432. }
  21433. }
  21434. // Only process method in default unspecialized mode, not in variations
  21435. if (methodInstance->mIsUnspecializedVariation)
  21436. return;
  21437. resolveModule->PopulateType(resolvedReturnType, BfPopulateType_Data);
  21438. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  21439. if (resolvedReturnType->IsValuelessType())
  21440. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  21441. if (!mBfIRBuilder->mIgnoreWrites)
  21442. {
  21443. bool isIntrinsic = false;
  21444. if (!methodInstance->mIRFunction)
  21445. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  21446. if (isIntrinsic)
  21447. {
  21448. addToWorkList = false;
  21449. }
  21450. }
  21451. else
  21452. {
  21453. GetMethodCustomAttributes(methodInstance);
  21454. }
  21455. auto func = methodInstance->mIRFunction;
  21456. // if (methodInstance->mIsReified)
  21457. // CheckHotMethod(methodInstance, mangledName);
  21458. for (auto& param : methodInstance->mParams)
  21459. {
  21460. BF_ASSERT(!param.mResolvedType->IsDeleting());
  21461. }
  21462. 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);
  21463. SizedArray<BfIRMDNode, 8> diParams;
  21464. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  21465. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  21466. {
  21467. //CS0708
  21468. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  21469. }
  21470. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  21471. {
  21472. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  21473. methodDef->mIsVirtual = false;
  21474. }
  21475. BfAstNode* mutSpecifier = NULL;
  21476. if (methodDeclaration != NULL)
  21477. mutSpecifier = methodDeclaration->mMutSpecifier;
  21478. else if (methodDef->GetPropertyMethodDeclaration() != NULL)
  21479. {
  21480. mutSpecifier = methodDef->GetPropertyMethodDeclaration()->mMutSpecifier;
  21481. if (mutSpecifier == NULL)
  21482. {
  21483. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21484. if (propertyDeclaration != NULL)
  21485. {
  21486. if (auto propExprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  21487. mutSpecifier = propExprBody->mMutSpecifier;
  21488. }
  21489. }
  21490. }
  21491. if ((mutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  21492. {
  21493. if (methodDef->mIsStatic)
  21494. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", mutSpecifier);
  21495. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  21496. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", mutSpecifier);
  21497. else if (methodDef->mMethodType == BfMethodType_Ctor)
  21498. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", mutSpecifier);
  21499. else if (methodDef->mMethodType == BfMethodType_Dtor)
  21500. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", mutSpecifier);
  21501. }
  21502. if (isTemporaryFunc)
  21503. {
  21504. // This handles temporary methods for autocomplete types
  21505. //BF_ASSERT(mIsScratchModule);
  21506. //BF_ASSERT(mCompiler->IsAutocomplete());
  21507. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  21508. return; // Bail out early for autocomplete pass
  21509. }
  21510. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  21511. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  21512. // autocompleter. Why did we have this check anyway?
  21513. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  21514. {
  21515. AddMethodReference(methodInstance);
  21516. mFuncReferences[methodInstance] = func;
  21517. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  21518. }*/
  21519. if (mParentModule != NULL)
  21520. {
  21521. // For extension modules we need to keep track of our own methods so we can know which methods
  21522. // we have defined ourselves and which are from the parent module or other extensions
  21523. if (!func.IsFake())
  21524. {
  21525. if (func)
  21526. mFuncReferences[methodInstance] = func;
  21527. }
  21528. }
  21529. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  21530. {
  21531. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  21532. auto owningModule = methodInstance->GetOwner()->mModule;
  21533. if (!owningModule->mIsScratchModule)
  21534. owningModule->mOnDemandMethodCount++;
  21535. VerifyOnDemandMethods();
  21536. }
  21537. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  21538. if (wasAwaitingDecl)
  21539. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  21540. if (addToWorkList)
  21541. {
  21542. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  21543. {
  21544. AddMethodToWorkList(methodInstance);
  21545. }
  21546. else
  21547. {
  21548. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  21549. methodInstance->mIgnoreBody = true;
  21550. if (typeInstance->IsUnspecializedType())
  21551. {
  21552. // Don't hold on to actual Function for unspecialized types
  21553. methodInstance->mIRFunction = BfIRFunction();
  21554. }
  21555. }
  21556. }
  21557. else
  21558. {
  21559. //BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  21560. }
  21561. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  21562. (!methodDef->mIsLocalMethod) &&
  21563. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  21564. (!methodDef->mReturnTypeRef->IsTemporary()))
  21565. {
  21566. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  21567. {
  21568. //TODO:
  21569. //CS0053
  21570. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  21571. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  21572. methodDef->mReturnTypeRef, true);
  21573. }
  21574. else
  21575. {
  21576. //CS0050
  21577. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  21578. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  21579. methodDef->mReturnTypeRef, true);
  21580. }
  21581. }
  21582. if (typeInstance->IsInterface())
  21583. {
  21584. if (methodDef->mMethodType == BfMethodType_Ctor)
  21585. Fail("Interfaces cannot contain constructors", methodDeclaration);
  21586. if (methodDeclaration != NULL)
  21587. {
  21588. if (methodDef->mBody == NULL)
  21589. {
  21590. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  21591. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  21592. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  21593. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  21594. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  21595. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  21596. }
  21597. }
  21598. }
  21599. bool foundHiddenMethod = false;
  21600. BfTokenNode* virtualToken = NULL;
  21601. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21602. if (propertyDeclaration != NULL)
  21603. virtualToken = propertyDeclaration->mVirtualSpecifier;
  21604. else if (methodDeclaration != NULL)
  21605. virtualToken = methodDeclaration->mVirtualSpecifier;
  21606. // Don't compare specialized generic methods against normal methods
  21607. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  21608. (!methodDef->mIsLocalMethod) && (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  21609. {
  21610. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  21611. {
  21612. typeDef->PopulateMemberSets();
  21613. BfMethodDef* nextMethod = NULL;
  21614. BfMemberSetEntry* entry = NULL;
  21615. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21616. nextMethod = (BfMethodDef*)entry->mMemberDef;
  21617. while (nextMethod != NULL)
  21618. {
  21619. auto checkMethod = nextMethod;
  21620. nextMethod = nextMethod->mNextWithSameName;
  21621. if (checkMethod == methodDef)
  21622. continue;
  21623. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21624. if (checkMethodInstance == NULL)
  21625. {
  21626. if ((methodDef->mDeclaringType->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension()))
  21627. checkMethodInstance = GetRawMethodInstanceAtIdx(typeInstance, checkMethod->mIdx);
  21628. if (checkMethodInstance == NULL)
  21629. continue;
  21630. }
  21631. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  21632. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  21633. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  21634. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  21635. {
  21636. bool canChain = false;
  21637. if ((methodDef->mParams.empty()) &&
  21638. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  21639. {
  21640. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  21641. canChain = true;
  21642. else if (methodDef->mMethodType == BfMethodType_Normal)
  21643. {
  21644. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  21645. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  21646. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  21647. canChain = true;
  21648. }
  21649. }
  21650. if (canChain)
  21651. {
  21652. bool isBetter;
  21653. bool isWorse;
  21654. CompareDeclTypes(typeInstance, checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  21655. if (isBetter && !isWorse)
  21656. {
  21657. methodInstance->mChainType = BfMethodChainType_ChainHead;
  21658. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  21659. }
  21660. else
  21661. {
  21662. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  21663. methodInstance->mChainType = BfMethodChainType_ChainMember;
  21664. }
  21665. }
  21666. else
  21667. {
  21668. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  21669. continue;
  21670. bool silentlyAllow = false;
  21671. bool extensionWarn = false;
  21672. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  21673. {
  21674. if (typeInstance->IsInterface())
  21675. {
  21676. if (methodDef->mIsOverride)
  21677. silentlyAllow = true;
  21678. }
  21679. else
  21680. {
  21681. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  21682. {
  21683. silentlyAllow = true;
  21684. methodInstance->mIsInnerOverride = true;
  21685. CheckOverridenMethod(methodInstance, checkMethodInstance);
  21686. }
  21687. else if (!checkMethod->mDeclaringType->IsExtension())
  21688. {
  21689. foundHiddenMethod = true;
  21690. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  21691. silentlyAllow = true;
  21692. else if (methodDef->mIsNew)
  21693. {
  21694. silentlyAllow = true;
  21695. }
  21696. else if (checkMethod->GetMethodDeclaration() == NULL)
  21697. silentlyAllow = true;
  21698. else if (methodDef->mIsOverride)
  21699. silentlyAllow = true;
  21700. else
  21701. extensionWarn = true;
  21702. }
  21703. else
  21704. silentlyAllow = true;
  21705. }
  21706. }
  21707. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  21708. silentlyAllow = true;
  21709. if (!silentlyAllow)
  21710. {
  21711. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  21712. {
  21713. auto refNode = methodDef->GetRefNode();
  21714. BfError* bfError;
  21715. if (extensionWarn)
  21716. {
  21717. if (methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject)
  21718. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  21719. 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'.",
  21720. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  21721. else
  21722. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  21723. "This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional.", refNode);
  21724. }
  21725. else
  21726. {
  21727. bfError = Fail(StrFormat("Method '%s' already declared with the same parameter types", MethodToString(checkMethodInstance).c_str()), refNode, true);
  21728. }
  21729. if ((bfError != NULL) && (checkMethod->GetRefNode() != refNode))
  21730. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  21731. }
  21732. }
  21733. }
  21734. }
  21735. }
  21736. }
  21737. // Virtual methods give their error while slotting
  21738. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  21739. (!methodDef->mIsLocalMethod) &&
  21740. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  21741. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  21742. {
  21743. auto baseType = typeInstance->mBaseType;
  21744. while (baseType != NULL)
  21745. {
  21746. auto baseTypeDef = baseType->mTypeDef;
  21747. baseTypeDef->PopulateMemberSets();
  21748. BfMethodDef* checkMethod = NULL;
  21749. BfMemberSetEntry* entry = NULL;
  21750. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21751. checkMethod = (BfMethodDef*)entry->mMemberDef;
  21752. while (checkMethod != NULL)
  21753. {
  21754. if (checkMethod->mMethodDeclaration == NULL)
  21755. {
  21756. checkMethod = checkMethod->mNextWithSameName;
  21757. continue;
  21758. }
  21759. if (baseType->mMethodInstanceGroups.size() == 0)
  21760. {
  21761. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  21762. break;
  21763. }
  21764. if (checkMethod == methodDef)
  21765. {
  21766. checkMethod = checkMethod->mNextWithSameName;
  21767. continue;
  21768. }
  21769. if (checkMethod->mName != methodDef->mName)
  21770. {
  21771. checkMethod = checkMethod->mNextWithSameName;
  21772. continue;
  21773. }
  21774. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  21775. if (checkMethodInstance != NULL)
  21776. {
  21777. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  21778. (checkMethod->mProtection != BfProtection_Private) &&
  21779. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  21780. {
  21781. if ((!methodDef->mIsNew) && (!checkMethod->mDeclaringType->IsExtension()))
  21782. {
  21783. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  21784. if (refNode != NULL)
  21785. {
  21786. 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?
  21787. if (bfError != NULL)
  21788. {
  21789. bfError->mIsPersistent = true;
  21790. mCompiler->mPassInstance->MoreInfo("See inherited method", checkMethod->GetRefNode());
  21791. }
  21792. }
  21793. }
  21794. foundHiddenMethod = true;
  21795. break;
  21796. }
  21797. }
  21798. checkMethod = checkMethod->mNextWithSameName;
  21799. }
  21800. if (foundHiddenMethod)
  21801. break;
  21802. baseType = baseType->mBaseType;
  21803. }
  21804. if ((methodDef->mIsNew) && (!foundHiddenMethod) && (!mCurTypeInstance->IsSpecializedType()))
  21805. {
  21806. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21807. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  21808. methodDeclaration->mNewSpecifier;
  21809. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  21810. }
  21811. }
  21812. }
  21813. if ((methodDef->mIsConcrete) && (!methodInstance->mIsForeignMethodDef) && (!mCurTypeInstance->IsInterface()))
  21814. {
  21815. Fail("Only interfaces methods can be declared as 'concrete'", methodDeclaration->mVirtualSpecifier);
  21816. }
  21817. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic) && (!methodInstance->mIsInnerOverride))
  21818. {
  21819. if ((virtualToken != NULL) && (virtualToken->mToken == BfToken_Override) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  21820. Fail("No suitable method found to override", virtualToken, true);
  21821. else
  21822. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  21823. }
  21824. else if (methodDef->mIsVirtual)
  21825. {
  21826. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  21827. Fail("Virtual or abstract members cannot be 'private'", virtualToken, true);
  21828. if ((methodDef->mProtection == BfProtection_Internal) && (virtualToken != NULL))
  21829. Fail("Virtual or abstract members cannot be 'internal'. Consider using the 'protected internal' access specifier.", virtualToken, true);
  21830. }
  21831. mCompiler->mStats.mMethodDeclarations++;
  21832. mCompiler->UpdateCompletion();
  21833. }
  21834. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  21835. {
  21836. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  21837. auto typeInstance = mCurTypeInstance;
  21838. auto methodDef = methodInstance->mMethodDef;
  21839. int virtualMethodMatchIdx = -1;
  21840. if (typeInstance->mHotTypeData != NULL)
  21841. {
  21842. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  21843. {
  21844. BF_ASSERT(mCompiler->IsHotCompile());
  21845. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  21846. // may slot this override anyway (?)
  21847. int vTableStart = 0;
  21848. auto implBaseType = typeInstance->GetImplBaseType();
  21849. if (implBaseType != NULL)
  21850. vTableStart = implBaseType->mVirtualMethodTableSize;
  21851. StringT<512> mangledName;
  21852. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  21853. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  21854. {
  21855. // O(1) checking when virtual methods haven't changed
  21856. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  21857. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  21858. if (mangledName == entry.mFuncName)
  21859. {
  21860. virtualMethodMatchIdx = vTableStart + checkIdx;
  21861. break;
  21862. }
  21863. }
  21864. if (virtualMethodMatchIdx != -1)
  21865. {
  21866. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21867. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  21868. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  21869. }
  21870. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  21871. }
  21872. }
  21873. if (virtualMethodMatchIdx == -1)
  21874. {
  21875. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  21876. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  21877. typeInstance->mVirtualMethodTable.push_back(entry);
  21878. }
  21879. }
  21880. void BfModule::CompareDeclTypes(BfTypeInstance* typeInst, BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  21881. {
  21882. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  21883. {
  21884. // When we provide an extension override in the same project a root type override
  21885. isBetter = true;
  21886. isWorse = false;
  21887. }
  21888. else
  21889. {
  21890. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  21891. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  21892. }
  21893. if ((isBetter == isWorse) && (typeInst != NULL) && (newDeclType->IsExtension()) && (prevDeclType->IsExtension()))
  21894. {
  21895. if ((typeInst->mGenericTypeInfo != NULL) && (typeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL))
  21896. {
  21897. isBetter = false;
  21898. isWorse = false;
  21899. auto newConstraints = typeInst->GetGenericParamsVector(newDeclType);
  21900. auto prevConstraints = typeInst->GetGenericParamsVector(prevDeclType);
  21901. for (int genericIdx = 0; genericIdx < (int)newConstraints->size(); genericIdx++)
  21902. {
  21903. auto newConstraint = (*newConstraints)[genericIdx];
  21904. auto prevConstraint = (*prevConstraints)[genericIdx];
  21905. bool newIsSubset = AreConstraintsSubset(newConstraint, prevConstraint);
  21906. bool prevIsSubset = AreConstraintsSubset(prevConstraint, newConstraint);
  21907. if ((prevIsSubset) && (!newIsSubset))
  21908. isBetter = true;
  21909. if ((!prevIsSubset) && (newIsSubset))
  21910. isWorse = true;
  21911. }
  21912. }
  21913. }
  21914. }
  21915. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  21916. {
  21917. BP_ZONE("BfModule::SlotVirtualMethod");
  21918. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  21919. return false;
  21920. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  21921. {
  21922. if (!mCompiler->mOptions.mAllowHotSwapping)
  21923. return;
  21924. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  21925. return;
  21926. if (methodInstance->mHotMethod == NULL)
  21927. CheckHotMethod(methodInstance, "");
  21928. if (methodInstance->mHotMethod == NULL)
  21929. return;
  21930. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  21931. if (declMethodInstance->mHotMethod == NULL)
  21932. CheckHotMethod(declMethodInstance, "");
  21933. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  21934. virtualDecl->mRefCount++;
  21935. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  21936. };
  21937. auto typeInstance = mCurTypeInstance;
  21938. auto typeDef = typeInstance->mTypeDef;
  21939. auto methodDef = methodInstance->mMethodDef;
  21940. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21941. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21942. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  21943. if (methodInstance->mIsInnerOverride)
  21944. return false;
  21945. BfAstNode* declaringNode = methodDeclaration;
  21946. if (propertyMethodDeclaration != NULL)
  21947. declaringNode = propertyMethodDeclaration->mNameNode;
  21948. BfMethodInstance* methodOverriden = NULL;
  21949. bool usedMethod = false;
  21950. BfTokenNode* virtualToken = NULL;
  21951. if (propertyDeclaration != NULL)
  21952. virtualToken = propertyDeclaration->mVirtualSpecifier;
  21953. else if (methodDeclaration != NULL)
  21954. virtualToken = methodDeclaration->mVirtualSpecifier;
  21955. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  21956. {
  21957. //Fail: Static members cannot be marked as override, virtual, or abstract
  21958. }
  21959. else if (methodDef->mIsVirtual)
  21960. {
  21961. if (IsHotCompile())
  21962. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  21963. BfTypeInstance* checkBase = typeInstance;
  21964. // If we are in an extension, look in ourselves first
  21965. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  21966. checkBase = checkBase->mBaseType;
  21967. if (typeInstance->IsValueType())
  21968. {
  21969. if (typeInstance->mBaseType == NULL)
  21970. return false; // It's actually ValueType
  21971. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  21972. if (!methodDef->mIsOverride)
  21973. {
  21974. Fail("Structs cannot have virtual methods", virtualToken, true);
  21975. return false;
  21976. }
  21977. checkBase = mContext->mBfObjectType;
  21978. if (checkBase->mVirtualMethodTableSize == 0)
  21979. PopulateType(checkBase, BfPopulateType_Full);
  21980. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  21981. return false; // System circular ref, don't do struct checking on those
  21982. }
  21983. int virtualMethodMatchIdx = -1;
  21984. bool hadHidingError = false;
  21985. BfMethodInstance* bestOverrideMethodInstance = NULL;
  21986. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  21987. int bestOverrideMethodIdx = -1;
  21988. int ambiguousOverrideMethodIdx = -1;
  21989. if (checkBase != NULL)
  21990. {
  21991. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  21992. auto lookupType = checkBase;
  21993. while (lookupType != NULL)
  21994. {
  21995. lookupType->mTypeDef->PopulateMemberSets();
  21996. BfMethodDef* nextMethodDef = NULL;
  21997. BfMemberSetEntry* entry;
  21998. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  21999. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  22000. while (nextMethodDef != NULL)
  22001. {
  22002. auto checkMethodDef = nextMethodDef;
  22003. nextMethodDef = nextMethodDef->mNextWithSameName;
  22004. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  22005. continue;
  22006. BfMethodInstance* baseMethodInstance = NULL;
  22007. int checkMethodIdx = -1;
  22008. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  22009. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  22010. {
  22011. if (lookupType->IsUnspecializedTypeVariation())
  22012. {
  22013. if (!lookupMethodInstance->mMethodDef->mIsOverride)
  22014. {
  22015. baseMethodInstance = lookupMethodInstance;
  22016. checkMethodIdx = -2;
  22017. }
  22018. }
  22019. if (baseMethodInstance == NULL)
  22020. continue;
  22021. }
  22022. if (baseMethodInstance == NULL)
  22023. {
  22024. checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  22025. if (checkMethodIdx >= baseVirtualMethodTable.mSize)
  22026. {
  22027. Fail("SlotVirtualMethod out of bounds", checkMethodDef->GetRefNode());
  22028. continue;
  22029. }
  22030. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22031. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22032. {
  22033. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22034. continue;
  22035. }
  22036. baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22037. if (baseMethodInstance == NULL)
  22038. {
  22039. AssertErrorState();
  22040. continue;
  22041. }
  22042. }
  22043. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22044. {
  22045. if (methodDef->mIsOverride)
  22046. {
  22047. BfMethodInstance* checkMethodInstance;
  22048. if (checkMethodIdx == -2)
  22049. checkMethodInstance = baseMethodInstance;
  22050. else if (typeInstance->IsValueType())
  22051. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22052. else
  22053. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22054. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22055. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22056. continue;
  22057. if (bestOverrideMethodInstance != NULL)
  22058. {
  22059. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22060. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22061. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22062. if (isBetter == isWorse)
  22063. {
  22064. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22065. }
  22066. else
  22067. {
  22068. if (isWorse)
  22069. continue;
  22070. ambiguousOverrideMethodInstance = NULL;
  22071. }
  22072. }
  22073. bestOverrideMethodInstance = checkMethodInstance;
  22074. bestOverrideMethodIdx = checkMethodIdx;
  22075. }
  22076. else
  22077. {
  22078. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22079. {
  22080. if (!hadHidingError)
  22081. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22082. hadHidingError = true;
  22083. }
  22084. }
  22085. }
  22086. }
  22087. lookupType = lookupType->mBaseType;
  22088. }
  22089. }
  22090. //TODO:
  22091. if ((checkBase != NULL)
  22092. && (false)
  22093. )
  22094. {
  22095. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22096. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  22097. {
  22098. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22099. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22100. {
  22101. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22102. continue;
  22103. }
  22104. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22105. if (baseMethodInstance == NULL)
  22106. {
  22107. AssertErrorState();
  22108. continue;
  22109. }
  22110. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22111. {
  22112. if (methodDef->mIsOverride)
  22113. {
  22114. BfMethodInstance* checkMethodInstance;
  22115. if (typeInstance->IsValueType())
  22116. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22117. else
  22118. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22119. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22120. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22121. continue;
  22122. if (bestOverrideMethodInstance != NULL)
  22123. {
  22124. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22125. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22126. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22127. if (isBetter == isWorse)
  22128. {
  22129. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22130. }
  22131. else
  22132. {
  22133. if (isWorse)
  22134. continue;
  22135. ambiguousOverrideMethodInstance = NULL;
  22136. }
  22137. }
  22138. bestOverrideMethodInstance = checkMethodInstance;
  22139. bestOverrideMethodIdx = checkMethodIdx;
  22140. }
  22141. else
  22142. {
  22143. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22144. {
  22145. if (!hadHidingError)
  22146. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22147. hadHidingError = true;
  22148. }
  22149. }
  22150. }
  22151. }
  22152. }
  22153. if (bestOverrideMethodInstance != NULL)
  22154. {
  22155. if (ambiguousOverrideMethodInstance != NULL)
  22156. {
  22157. bool allow = false;
  22158. // 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.
  22159. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  22160. bool canSeeEachOther = false;
  22161. //
  22162. {
  22163. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  22164. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  22165. canSeeEachOther = true;
  22166. }
  22167. //
  22168. {
  22169. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  22170. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  22171. canSeeEachOther = true;
  22172. }
  22173. if (!canSeeEachOther)
  22174. {
  22175. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  22176. }
  22177. else
  22178. {
  22179. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  22180. if (error != NULL)
  22181. {
  22182. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  22183. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  22184. }
  22185. }
  22186. }
  22187. }
  22188. if (bestOverrideMethodIdx == -2)
  22189. {
  22190. // Comes from an unspecialized variation
  22191. virtualMethodMatchIdx = bestOverrideMethodIdx;
  22192. }
  22193. else if ((bestOverrideMethodInstance != NULL) && (bestOverrideMethodIdx != -1))
  22194. {
  22195. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22196. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  22197. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  22198. {
  22199. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  22200. {
  22201. BfTypeReference* returnTypeRef;
  22202. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22203. {
  22204. returnTypeRef = propertyDeclaration->mTypeRef;
  22205. Fail("Property differs from overridden property by type", returnTypeRef, true);
  22206. }
  22207. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22208. {
  22209. returnTypeRef = methodDeclaration->mReturnType;
  22210. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  22211. }
  22212. else
  22213. {
  22214. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  22215. }
  22216. return usedMethod;
  22217. }
  22218. }
  22219. if (methodDef->mIsOverride)
  22220. {
  22221. // We can have multiple matches when a virtual method is used to implement interface methods
  22222. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  22223. // vtable entries for this method signature
  22224. virtualMethodMatchIdx = bestOverrideMethodIdx;
  22225. if (!typeInstance->IsValueType())
  22226. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22227. if (typeInstance->IsValueType())
  22228. {
  22229. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22230. }
  22231. else
  22232. {
  22233. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22234. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  22235. BfMethodInstance* setMethodInstance = methodInstance;
  22236. bool doOverride = false;
  22237. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22238. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  22239. {
  22240. methodOverriden = overridenRef;
  22241. doOverride = true;
  22242. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  22243. {
  22244. bool isBetter = false;
  22245. bool isWorse = false;
  22246. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  22247. if (isBetter == isWorse)
  22248. {
  22249. // We have to resolve later per-project
  22250. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  22251. {
  22252. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22253. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  22254. }
  22255. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  22256. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  22257. doOverride = false;
  22258. }
  22259. else
  22260. {
  22261. if ((isBetter) && (ambiguityContext != NULL))
  22262. {
  22263. ambiguityContext->Remove(virtualMethodMatchIdx);
  22264. }
  22265. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  22266. {
  22267. if (preferRootDefinition)
  22268. {
  22269. // Leave the master GCMarkMember
  22270. isBetter = false;
  22271. isWorse = true;
  22272. }
  22273. }
  22274. doOverride = isBetter;
  22275. }
  22276. }
  22277. }
  22278. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  22279. {
  22280. methodOverriden = overridenRef;
  22281. doOverride = true;
  22282. }
  22283. if (doOverride)
  22284. {
  22285. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22286. _AddVirtualDecl(declMethodInstance);
  22287. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22288. auto& implMethodRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22289. if ((!mCompiler->mIsResolveOnly) && (implMethodRef.mMethodNum >= 0) &&
  22290. (implMethodRef.mTypeInstance == typeInstance) && (methodInstance->GetOwner() == typeInstance))
  22291. {
  22292. auto prevImplMethodInstance = (BfMethodInstance*)implMethodRef;
  22293. if (prevImplMethodInstance->mMethodDef->mDeclaringType->mProject != methodInstance->mMethodDef->mDeclaringType->mProject)
  22294. {
  22295. // We may need to have to previous method reified when we must re-slot in another project during vdata creation
  22296. BfReifyMethodDependency dep;
  22297. dep.mDepMethod = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  22298. dep.mMethodIdx = implMethodRef.mMethodNum;
  22299. typeInstance->mReifyMethodDependencies.Add(dep);
  22300. }
  22301. if (!methodInstance->mMangleWithIdx)
  22302. {
  22303. // Keep mangled names from conflicting
  22304. methodInstance->mMangleWithIdx = true;
  22305. if ((methodInstance->mIRFunction) && (methodInstance->mDeclModule->mIsModuleMutable))
  22306. {
  22307. StringT<4096> mangledName;
  22308. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  22309. methodInstance->mDeclModule->mBfIRBuilder->SetFunctionName(methodInstance->mIRFunction, mangledName);
  22310. }
  22311. }
  22312. }
  22313. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  22314. }
  22315. }
  22316. if (methodOverriden != NULL)
  22317. {
  22318. CheckOverridenMethod(methodInstance, methodOverriden);
  22319. }
  22320. }
  22321. }
  22322. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  22323. {
  22324. if (methodDef->mIsOverride)
  22325. {
  22326. BfTokenNode* overrideToken = NULL;
  22327. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  22328. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  22329. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22330. overrideToken = methodDeclaration->mVirtualSpecifier;
  22331. if (overrideToken != NULL)
  22332. {
  22333. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  22334. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  22335. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  22336. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  22337. else
  22338. Fail("No suitable method found to override", overrideToken, true);
  22339. }
  22340. return usedMethod;
  22341. }
  22342. UniqueSlotVirtualMethod(methodInstance);
  22343. }
  22344. else
  22345. usedMethod = true;
  22346. if (typeInstance->IsValueType())
  22347. return usedMethod;
  22348. }
  22349. bool foundInterface = false;
  22350. bool hadAnyMatch = false;
  22351. // See if this method matches interfaces
  22352. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  22353. {
  22354. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  22355. if (ifaceInst->IsIncomplete())
  22356. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  22357. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  22358. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  22359. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  22360. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  22361. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  22362. continue;
  22363. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  22364. continue;
  22365. bool hadMatch = false;
  22366. BfMethodInstance* hadNameMatch = NULL;
  22367. BfType* expectedReturnType = NULL;
  22368. bool showedError = false;
  22369. // We go through our VTable looking for NULL entries within the interface sections
  22370. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  22371. // because a normal method declared in this type could have matched earlier
  22372. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  22373. ifaceInst->mTypeDef->PopulateMemberSets();
  22374. BfMethodDef* checkMethodDef = NULL;
  22375. BfMemberSetEntry* entry;
  22376. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  22377. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  22378. while (checkMethodDef != NULL)
  22379. {
  22380. int iMethodIdx = checkMethodDef->mIdx;
  22381. int iTableIdx = iMethodIdx + startIdx;
  22382. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  22383. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  22384. bool storeIFaceMethod = false;
  22385. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  22386. {
  22387. checkMethodDef = checkMethodDef->mNextWithSameName;
  22388. continue;
  22389. }
  22390. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  22391. auto iMethodInst = iMethodGroup.mDefault;
  22392. if (iMethodInst == NULL)
  22393. {
  22394. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  22395. AssertErrorState();
  22396. checkMethodDef = checkMethodDef->mNextWithSameName;
  22397. continue;
  22398. }
  22399. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  22400. hadNameMatch = iMethodInst;
  22401. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  22402. if ((!doesMethodSignatureMatch) && (interfaceMethodEntry->mMethodRef.IsNull()))
  22403. {
  22404. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  22405. }
  22406. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  22407. {
  22408. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  22409. {
  22410. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  22411. {
  22412. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  22413. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  22414. if (error != NULL)
  22415. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  22416. showedError = true;
  22417. }
  22418. }
  22419. }
  22420. if (doesMethodSignatureMatch)
  22421. {
  22422. usedMethod = true;
  22423. hadMatch = true;
  22424. hadAnyMatch = true;
  22425. storeIFaceMethod = true;
  22426. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  22427. {
  22428. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  22429. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance) && (!mIsComptimeModule))
  22430. {
  22431. // When autocompletion regenerates a single method body but not the whole type then
  22432. // we will see ourselves in the vtable already
  22433. return usedMethod;
  22434. }
  22435. bool isBetter = false;
  22436. bool isWorse = false;
  22437. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  22438. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  22439. if (isBetter == isWorse)
  22440. {
  22441. isBetter = methodInstance->mReturnType == iMethodInst->mReturnType;
  22442. isWorse = prevMethod->mReturnType == iMethodInst->mReturnType;
  22443. }
  22444. if (isBetter == isWorse)
  22445. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  22446. if (isBetter == isWorse)
  22447. {
  22448. if (ambiguityContext != NULL)
  22449. {
  22450. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  22451. }
  22452. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  22453. storeIFaceMethod = true;
  22454. }
  22455. else
  22456. {
  22457. if ((isBetter) && (ambiguityContext != NULL))
  22458. ambiguityContext->Remove(~iTableIdx);
  22459. storeIFaceMethod = isBetter;
  22460. }
  22461. }
  22462. }
  22463. if (storeIFaceMethod)
  22464. {
  22465. if (methodInstance->GetNumGenericParams() != 0)
  22466. _AddVirtualDecl(iMethodInst);
  22467. *iMethodPtr = methodInstance;
  22468. }
  22469. checkMethodDef = checkMethodDef->mNextWithSameName;
  22470. }
  22471. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  22472. {
  22473. if (expectedReturnType != NULL)
  22474. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  22475. else if (hadNameMatch != NULL)
  22476. {
  22477. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  22478. if (error != NULL)
  22479. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  22480. }
  22481. else
  22482. {
  22483. auto propertyDecl = methodDef->GetPropertyDeclaration();
  22484. if (propertyDecl != NULL)
  22485. {
  22486. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  22487. String name;
  22488. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  22489. name = "this[]";
  22490. else if (propertyDecl->mNameNode != NULL)
  22491. propertyDecl->mNameNode->ToString(name);
  22492. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  22493. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  22494. }
  22495. else
  22496. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  22497. }
  22498. }
  22499. }
  22500. // Any overriden virtual methods that were used in interfaces also need to be replaced
  22501. if (methodOverriden != NULL)
  22502. {
  22503. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  22504. {
  22505. if (methodEntry.mMethodRef == methodOverriden)
  22506. methodEntry.mMethodRef = methodInstance;
  22507. }
  22508. }
  22509. return usedMethod;
  22510. }
  22511. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  22512. {
  22513. auto methodDef = methodInstance->mMethodDef;
  22514. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  22515. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  22516. {
  22517. const char* protectionNames[] = { "hidden", "private", "internal", "protected", "protected internal", "public" };
  22518. BF_STATIC_ASSERT(BF_ARRAY_COUNT(protectionNames) == BfProtection_COUNT);
  22519. BfAstNode* protectionRefNode = NULL;
  22520. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  22521. {
  22522. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  22523. if (protectionRefNode == NULL)
  22524. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  22525. if (protectionRefNode == NULL)
  22526. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  22527. }
  22528. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22529. {
  22530. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  22531. if (protectionRefNode == NULL)
  22532. protectionRefNode = methodDeclaration->mNameNode;
  22533. }
  22534. if (protectionRefNode != NULL)
  22535. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  22536. }
  22537. }
  22538. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  22539. {
  22540. auto typeInstance = mCurTypeInstance;
  22541. auto methodDef = methodInstance->mMethodDef;
  22542. if (methodDef->mMethodType == BfMethodType_Ctor)
  22543. return true;
  22544. bool foundOverride = false;
  22545. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  22546. {
  22547. auto methodDeclaration = methodDef->GetMethodDeclaration();
  22548. BfAstNode* refNode = NULL;
  22549. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22550. refNode = propertyDeclaration->mProtectionSpecifier;
  22551. else if (methodDeclaration != NULL)
  22552. refNode = methodDeclaration->mProtectionSpecifier;
  22553. Fail("Private interface methods must provide a body", refNode);
  22554. }
  22555. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  22556. {
  22557. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  22558. }
  22559. BfAstNode* declaringNode = methodDef->GetRefNode();
  22560. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  22561. {
  22562. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  22563. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  22564. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  22565. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  22566. continue;
  22567. ifaceInst->mTypeDef->PopulateMemberSets();
  22568. BfMethodDef* nextMethod = NULL;
  22569. BfMemberSetEntry* entry = NULL;
  22570. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22571. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22572. while (nextMethod != NULL)
  22573. {
  22574. auto checkMethod = nextMethod;
  22575. nextMethod = nextMethod->mNextWithSameName;
  22576. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22577. if (ifaceMethod == NULL)
  22578. continue;
  22579. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22580. {
  22581. if (methodDef->mIsOverride)
  22582. {
  22583. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  22584. {
  22585. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  22586. if (error != NULL)
  22587. {
  22588. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  22589. }
  22590. }
  22591. foundOverride = true;
  22592. }
  22593. else if (!methodDef->mIsNew)
  22594. {
  22595. 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);
  22596. if (error != NULL)
  22597. {
  22598. mCompiler->mPassInstance->MoreInfo("See inherited method", ifaceMethod->mMethodDef->GetRefNode());
  22599. }
  22600. }
  22601. }
  22602. }
  22603. }
  22604. if ((methodDef->mIsOverride) && (!foundOverride))
  22605. {
  22606. // This allows us to declare a method in the base definition or in an extension and then provide
  22607. // an implementation in a more-specific extension
  22608. typeInstance->mTypeDef->PopulateMemberSets();
  22609. BfMethodDef* nextMethod = NULL;
  22610. BfMemberSetEntry* entry = NULL;
  22611. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22612. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22613. while (nextMethod != NULL)
  22614. {
  22615. auto checkMethod = nextMethod;
  22616. nextMethod = nextMethod->mNextWithSameName;
  22617. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22618. if (ifaceMethod == NULL)
  22619. continue;
  22620. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  22621. continue;
  22622. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22623. {
  22624. foundOverride = true;
  22625. }
  22626. }
  22627. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  22628. // {
  22629. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  22630. // if (ifaceMethod == NULL)
  22631. // continue;
  22632. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  22633. // continue;
  22634. //
  22635. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22636. // {
  22637. // foundOverride = true;
  22638. // }
  22639. // }
  22640. }
  22641. if (methodDef->mIsOverride)
  22642. {
  22643. if (!foundOverride)
  22644. {
  22645. BfTokenNode* overrideToken = NULL;
  22646. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22647. overrideToken = propertyDeclaration->mVirtualSpecifier;
  22648. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22649. overrideToken = methodDeclaration->mVirtualSpecifier;
  22650. if (overrideToken != NULL)
  22651. {
  22652. Fail("No suitable method found to override", overrideToken, true);
  22653. }
  22654. else
  22655. {
  22656. // Possible cause - DTOR with params
  22657. AssertErrorState();
  22658. }
  22659. }
  22660. return true;
  22661. }
  22662. // Generic methods can't be called virtually
  22663. if (methodInstance->GetNumGenericParams() != 0)
  22664. return true;
  22665. // Only public methods can be called virtually
  22666. if (methodDef->mProtection != BfProtection_Public)
  22667. return true;
  22668. UniqueSlotVirtualMethod(methodInstance);
  22669. return true;
  22670. }
  22671. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  22672. {
  22673. if (methodInstance->mMethodInfoEx == NULL)
  22674. return;
  22675. int wantMinDepth = -1;
  22676. if (mCurTypeInstance != NULL)
  22677. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  22678. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  22679. {
  22680. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  22681. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  22682. wantMinDepth = wantTypeMinDepth;
  22683. }
  22684. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  22685. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  22686. }
  22687. void BfModule::DbgFinish()
  22688. {
  22689. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  22690. return;
  22691. if (mAwaitingInitFinish)
  22692. FinishInit();
  22693. if (mHasForceLinkMarker)
  22694. return;
  22695. String markerName;
  22696. BfIRValue linkMarker;
  22697. if (mBfIRBuilder->DbgHasInfo())
  22698. {
  22699. bool needForceLinking = false;
  22700. if (WantsDebugHelpers())
  22701. {
  22702. for (auto& ownedType : mOwnedTypeInstances)
  22703. {
  22704. bool hasConfirmedReference = false;
  22705. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  22706. {
  22707. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  22708. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  22709. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)) &&
  22710. (methodInstGroup.mHasEmittedReference))
  22711. {
  22712. hasConfirmedReference = true;
  22713. }
  22714. }
  22715. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  22716. needForceLinking = true;
  22717. }
  22718. }
  22719. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  22720. {
  22721. BfMethodState methodState;
  22722. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  22723. methodState.mTempKind = BfMethodState::TempKind_Static;
  22724. mHasForceLinkMarker = true;
  22725. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  22726. SizedArray<BfIRType, 0> paramTypes;
  22727. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  22728. String linkName = "FORCELINKMOD_" + mModuleName;
  22729. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  22730. mBfIRBuilder->SetActiveFunction(func);
  22731. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  22732. mBfIRBuilder->SetInsertPoint(entryBlock);
  22733. auto firstType = mOwnedTypeInstances[0];
  22734. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  22735. SizedArray<BfIRMDNode, 1> diParamTypes;
  22736. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  22737. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  22738. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  22739. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  22740. methodState.mCurScope->mDIScope = diScope;
  22741. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  22742. SizedArray<BfIRValue, 8> args;
  22743. BfExprEvaluator exprEvaluator(this);
  22744. for (auto& ownedType : mOwnedTypeInstances)
  22745. {
  22746. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  22747. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  22748. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  22749. }
  22750. mBfIRBuilder->CreateRetVoid();
  22751. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  22752. }
  22753. }
  22754. }
  22755. bool BfModule::Finish()
  22756. {
  22757. BP_ZONE("BfModule::Finish");
  22758. BfLogSysM("BfModule finish: %p\n", this);
  22759. if (mHadBuildError)
  22760. {
  22761. // Don't AssertErrorState here, this current pass may not have failed but
  22762. // the module was still queued in mFinishedModuleWorkList
  22763. ClearModule();
  22764. return true;
  22765. }
  22766. if (mUsedSlotCount != -1)
  22767. {
  22768. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  22769. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  22770. }
  22771. if ((!mGeneratesCode) && (!mAddedToCount))
  22772. return true;
  22773. BF_ASSERT(mAddedToCount);
  22774. mAddedToCount = false;
  22775. mAwaitingFinish = false;
  22776. mCompiler->mStats.mModulesFinished++;
  22777. if (HasCompiledOutput())
  22778. {
  22779. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  22780. DbgFinish();
  22781. if (mAwaitingInitFinish)
  22782. FinishInit();
  22783. for (auto ownedTypeInst : mOwnedTypeInstances)
  22784. {
  22785. // Generate dbg info and add global variables if we haven't already
  22786. mBfIRBuilder->PopulateType(ownedTypeInst);
  22787. }
  22788. if (mBfIRBuilder->DbgHasInfo())
  22789. {
  22790. mBfIRBuilder->DbgFinalize();
  22791. }
  22792. String objOutputPath;
  22793. String irOutputPath;
  22794. mIsModuleMutable = false;
  22795. //mOutFileNames.Clear();
  22796. BF_ASSERT(((int)mOutFileNames.size() >= mExtensionCount) || (mParentModule != NULL));
  22797. bool writeModule = mBfIRBuilder->HasExports();
  22798. String outputPath;
  22799. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  22800. auto& compilerOpts = mCompiler->mOptions;
  22801. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  22802. auto moduleOptions = GetModuleOptions();
  22803. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  22804. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  22805. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  22806. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  22807. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  22808. codeGenOptions.mVirtualMethodOfs = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  22809. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  22810. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  22811. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  22812. bool allowWriteToLib = true;
  22813. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  22814. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  22815. {
  22816. codeGenOptions.mWriteToLib = true;
  22817. mWroteToLib = true;
  22818. }
  22819. else
  22820. {
  22821. mWroteToLib = false;
  22822. }
  22823. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  22824. {
  22825. outputPath = mModuleName;
  22826. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  22827. BfModuleFileName moduleFileName;
  22828. if (mParentModule != NULL)
  22829. {
  22830. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  22831. {
  22832. if (checkPair.mValue == this)
  22833. moduleFileName.mProjects = checkPair.mKey;
  22834. }
  22835. }
  22836. moduleFileName.mProjects.Add(mProject);
  22837. if (fileIdx > 0)
  22838. outputPath += StrFormat("@%d", fileIdx + 1);
  22839. if (mCompiler->mOptions.mWriteIR)
  22840. irOutputPath = outputPath + ".ll";
  22841. if (mCompiler->mOptions.mGenerateObj)
  22842. {
  22843. objOutputPath = outputPath + BF_OBJ_EXT;
  22844. moduleFileName.mFileName = objOutputPath;
  22845. }
  22846. else if (mCompiler->mOptions.mWriteIR)
  22847. {
  22848. moduleFileName.mFileName = irOutputPath;
  22849. }
  22850. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  22851. {
  22852. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  22853. }
  22854. moduleFileName.mModuleWritten = writeModule;
  22855. moduleFileName.mWroteToLib = mWroteToLib;
  22856. if (!mOutFileNames.Contains(moduleFileName))
  22857. mOutFileNames.Add(moduleFileName);
  22858. }
  22859. if (mCompiler->IsHotCompile())
  22860. {
  22861. codeGenOptions.mIsHotCompile = true;
  22862. if (mParentModule != NULL)
  22863. mParentModule->mHadHotObjectWrites = true;
  22864. mHadHotObjectWrites = true;
  22865. }
  22866. //TODO: Testing VDATA
  22867. /*if (mModuleName == "vdata")
  22868. {
  22869. codeGenOptions.mOptLevel = 4;
  22870. }*/
  22871. codeGenOptions.GenerateHash();
  22872. BP_ZONE("BfModule::Finish.WriteObjectFile");
  22873. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  22874. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  22875. mLastModuleWrittenRevision = mCompiler->mRevision;
  22876. }
  22877. else
  22878. {
  22879. for (auto type : mOwnedTypeInstances)
  22880. {
  22881. BF_ASSERT((!type->IsIncomplete()) || (type->IsSpecializedByAutoCompleteMethod()));
  22882. }
  22883. }
  22884. for (auto& specModulePair : mSpecializedMethodModules)
  22885. {
  22886. auto specModule = specModulePair.mValue;
  22887. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  22888. {
  22889. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  22890. }
  22891. }
  22892. CleanupFileInstances();
  22893. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  22894. return true;
  22895. }
  22896. void BfModule::ReportMemory(MemReporter* memReporter)
  22897. {
  22898. memReporter->Add(sizeof(BfModule));
  22899. if (mBfIRBuilder != NULL)
  22900. {
  22901. memReporter->BeginSection("IRBuilder_ConstData");
  22902. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  22903. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  22904. memReporter->EndSection();
  22905. memReporter->BeginSection("IRBuilder_BFIR");
  22906. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  22907. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  22908. memReporter->EndSection();
  22909. memReporter->Add(sizeof(BfIRBuilder));
  22910. }
  22911. memReporter->BeginSection("FileInstanceMap");
  22912. memReporter->AddMap(mFileInstanceMap);
  22913. memReporter->AddMap(mNamedFileInstanceMap);
  22914. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  22915. memReporter->EndSection();
  22916. memReporter->AddVec(mOwnedTypeInstances, false);
  22917. memReporter->AddVec(mSpecializedMethodModules, false);
  22918. memReporter->AddVec(mOutFileNames, false);
  22919. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  22920. memReporter->AddMap(mInterfaceSlotRefs, false);
  22921. memReporter->AddMap(mStaticFieldRefs, false);
  22922. memReporter->AddMap(mClassVDataRefs, false);
  22923. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  22924. memReporter->AddMap(mTypeDataRefs, false);
  22925. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  22926. memReporter->AddMap(mDeferredMethodCallData, false);
  22927. memReporter->AddHashSet(mDeferredMethodIds, false);
  22928. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  22929. }
  22930. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  22931. // be transient through the next compile
  22932. void BfModule::ClearModuleData(bool clearTransientData)
  22933. {
  22934. BfLogSysM("ClearModuleData %p\n", this);
  22935. if (mAddedToCount)
  22936. {
  22937. mCompiler->mStats.mModulesFinished++;
  22938. mAddedToCount = false;
  22939. }
  22940. mDICompileUnit = BfIRMDNode();
  22941. if (clearTransientData)
  22942. mIncompleteMethodCount = 0;
  22943. mHasGenericMethods = false;
  22944. // We don't want to clear these because we want it to persist through module extensions-
  22945. // otherwise we may think an extension succeeds even though the base module failed
  22946. //mHadBuildError = false;
  22947. //mHadBuildWarning = false;
  22948. mClassVDataRefs.Clear();
  22949. mClassVDataExtRefs.Clear();
  22950. for (auto& kv : mTypeDataRefs)
  22951. kv.mValue = BfIRValue();
  22952. mStringCharPtrPool.Clear();
  22953. mStringObjectPool.Clear();
  22954. mStaticFieldRefs.Clear();
  22955. BF_ASSERT(!mIgnoreErrors);
  22956. for (auto prevIRBuilder : mPrevIRBuilders)
  22957. delete prevIRBuilder;
  22958. mPrevIRBuilders.Clear();
  22959. for (auto& specPair : mSpecializedMethodModules)
  22960. {
  22961. auto specModule = specPair.mValue;
  22962. specModule->ClearModuleData();
  22963. }
  22964. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  22965. mBuiltInFuncs[i] = BfIRFunction();
  22966. if (mNextAltModule != NULL)
  22967. mNextAltModule->ClearModuleData();
  22968. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  22969. mIsModuleMutable = false;
  22970. delete mBfIRBuilder;
  22971. mBfIRBuilder = NULL;
  22972. mWantsIRIgnoreWrites = false;
  22973. }
  22974. void BfModule::DisownMethods()
  22975. {
  22976. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  22977. mBuiltInFuncs[i] = BfIRFunction();
  22978. BfModule* methodModule = this;
  22979. if (mParentModule != NULL)
  22980. methodModule = mParentModule;
  22981. for (auto typeInst : methodModule->mOwnedTypeInstances)
  22982. {
  22983. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  22984. {
  22985. if (methodGroup.mDefault != NULL)
  22986. {
  22987. if (methodGroup.mDefault->mIRFunction)
  22988. {
  22989. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  22990. if (methodGroup.mDefault->mDeclModule == this)
  22991. {
  22992. methodGroup.mDefault->mIRFunction = BfIRFunction();
  22993. }
  22994. }
  22995. }
  22996. if (methodGroup.mMethodSpecializationMap != NULL)
  22997. {
  22998. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  22999. {
  23000. auto methodInstance = mapPair.mValue;
  23001. if (methodInstance->mDeclModule == this)
  23002. {
  23003. methodInstance->mIRFunction = BfIRFunction();
  23004. }
  23005. }
  23006. }
  23007. }
  23008. }
  23009. }
  23010. void BfModule::ClearModule()
  23011. {
  23012. ClearModuleData();
  23013. DisownMethods();
  23014. for (auto& specPair : mSpecializedMethodModules)
  23015. {
  23016. auto specModule = specPair.mValue;
  23017. specModule->ClearModule();
  23018. }
  23019. if (mNextAltModule != NULL)
  23020. mNextAltModule->ClearModule();
  23021. }