BfModule.cpp 778 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968
  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 <fcntl.h>
  25. #include <time.h>
  26. #pragma warning(pop)
  27. //////////////////////////////////////////////////////////////////////////
  28. static bool gDebugStuff = false;
  29. USING_NS_BF;
  30. //////////////////////////////////////////////////////////////////////////
  31. void BfLocalVariable::Init()
  32. {
  33. if (mResolvedType->IsValuelessType())
  34. {
  35. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  36. return;
  37. }
  38. if (mAssignedKind != BfLocalVarAssignKind_None)
  39. return;
  40. bool isStruct = mResolvedType->IsStruct();
  41. if (mResolvedType->IsRef())
  42. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  43. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  44. {
  45. auto resolvedTypeRef = mResolvedType;
  46. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  47. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  48. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  49. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  50. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  51. {
  52. // Base ctor is responsible for initializing its own fields
  53. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  54. }
  55. if (mUnassignedFieldFlags == 0)
  56. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  57. }
  58. else
  59. {
  60. mUnassignedFieldFlags = 1;
  61. }
  62. }
  63. BfLocalMethod::~BfLocalMethod()
  64. {
  65. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  66. if (mMethodDeclaration != NULL)
  67. {
  68. mSource->mRefCount--;
  69. BF_ASSERT(mSource->mRefCount >= 0);
  70. }
  71. delete mMethodDef;
  72. delete mMethodInstanceGroup;
  73. }
  74. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  75. {
  76. mIsChained = doChain;
  77. if (outerLocalAssignData == NULL)
  78. return;
  79. mChainedAssignData = outerLocalAssignData;
  80. if (!doChain)
  81. {
  82. outerLocalAssignData->BreakExtendChain();
  83. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  84. }
  85. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  86. }
  87. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  88. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  89. // if ((GetValue(out a)) && (GetValue(out b)) {}
  90. void BfDeferredLocalAssignData::BreakExtendChain()
  91. {
  92. if (!mIsChained)
  93. return;
  94. mIsChained = false;
  95. if (mChainedAssignData == NULL)
  96. return;
  97. mChainedAssignData->BreakExtendChain();
  98. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  99. }
  100. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  101. {
  102. BreakExtendChain();
  103. for (int i = 0; i < (int)mAssignedLocals.size(); )
  104. {
  105. auto& local = mAssignedLocals[i];
  106. bool wantRemove = true;
  107. bool foundOtherFields = false;
  108. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  109. {
  110. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  111. {
  112. if ((otherLocalAssignData.mLocalVarField == local.mLocalVarField) || (otherLocalAssignData.mLocalVarField == -1))
  113. {
  114. if (otherLocalAssignData.mAssignKind == BfLocalVarAssignKind_Conditional)
  115. local.mAssignKind = BfLocalVarAssignKind_Conditional;
  116. wantRemove = false;
  117. }
  118. else
  119. foundOtherFields = true;
  120. }
  121. }
  122. if ((wantRemove) && (foundOtherFields))
  123. {
  124. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  125. {
  126. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  127. {
  128. mAssignedLocals.Add(otherLocalAssignData);
  129. }
  130. }
  131. }
  132. if (wantRemove)
  133. {
  134. mAssignedLocals.RemoveAt(i);
  135. }
  136. else
  137. i++;
  138. }
  139. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  140. }
  141. void BfDeferredLocalAssignData::Validate() const
  142. {
  143. for (auto var : mAssignedLocals)
  144. {
  145. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  146. }
  147. }
  148. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  149. {
  150. BreakExtendChain();
  151. Validate();
  152. otherLocalAssignData.Validate();
  153. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  154. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  155. {
  156. if (!mAssignedLocals.Contains(*otherItr))
  157. mAssignedLocals.push_back(*otherItr);
  158. ++otherItr;
  159. }
  160. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  161. }
  162. BfMethodState::~BfMethodState()
  163. {
  164. BF_ASSERT(mPendingNullConditional == NULL);
  165. if (mPrevMethodState != NULL)
  166. {
  167. BF_ASSERT(mCurAccessId == 1);
  168. BF_ASSERT(mCurLocalVarId <= 0);
  169. }
  170. for (auto local : mLocals)
  171. delete local;
  172. for (auto& kv : mLambdaCache)
  173. delete kv.mValue;
  174. }
  175. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  176. {
  177. auto checkMethodState = this;
  178. while (checkMethodState != NULL)
  179. {
  180. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  181. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  182. return checkMethodState;
  183. checkMethodState = checkMethodState->mPrevMethodState;
  184. }
  185. BF_FATAL("Failed to find method state for localvar");
  186. return NULL;
  187. }
  188. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx, BfLocalVarAssignKind assignKind, bool isFromDeferredAssignData)
  189. {
  190. auto localVarMethodState = GetMethodStateForLocal(localVar);
  191. if (localVarMethodState != this)
  192. {
  193. return;
  194. }
  195. //BF_ASSERT(localVarMethodState == this);
  196. // if (assignKind == BfLocalVarAssignKind_None)
  197. // assignKind = ((localVarMethodState->mLeftBlockCond) && ((mDeferredLocalAssignData != NULL) || isFromDeferredAssignData)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  198. //
  199. // //assignKind = BfLocalVarAssignKind_Unconditional;
  200. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  201. {
  202. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  203. // 'a' is always defined, but 'b' isn't:
  204. // if (Check(out a) || Check(out b)) { } int z = a;
  205. auto deferredLocalAssignData = mDeferredLocalAssignData;
  206. if ((deferredLocalAssignData != NULL) &&
  207. (deferredLocalAssignData->mIsIfCondition) &&
  208. (!deferredLocalAssignData->mIfMayBeSkipped))
  209. {
  210. ifDeferredLocalAssignData = deferredLocalAssignData;
  211. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  212. }
  213. while ((deferredLocalAssignData != NULL) &&
  214. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  215. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  216. if (assignKind == BfLocalVarAssignKind_None)
  217. assignKind = ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mLeftBlock)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  218. if (localVar->mAssignedKind >= assignKind)
  219. {
  220. // Leave it alone
  221. }
  222. else if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  223. {
  224. if (fieldIdx >= 0)
  225. {
  226. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  227. if (localVar->mUnassignedFieldFlags == 0)
  228. {
  229. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  230. localVar->mAssignedKind = assignKind;
  231. }
  232. }
  233. else
  234. {
  235. localVar->mAssignedKind = assignKind;
  236. }
  237. }
  238. else
  239. {
  240. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  241. BfAssignedLocal defineVal = {localVar, fieldIdx, assignKind};
  242. if (!deferredLocalAssignData->Contains(defineVal))
  243. deferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  244. if (ifDeferredLocalAssignData != NULL)
  245. {
  246. if (!ifDeferredLocalAssignData->Contains(defineVal))
  247. ifDeferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  248. }
  249. }
  250. }
  251. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  252. }
  253. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  254. {
  255. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  256. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  257. {
  258. LocalDefined(assignedLocal.mLocalVar, assignedLocal.mLocalVarField, assignedLocal.mAssignKind, true);
  259. }
  260. }
  261. void BfMethodState::Reset()
  262. {
  263. mHeadScope.mDeferredCallEntries.DeleteAll();
  264. }
  265. //////////////////////////////////////////////////////////////////////////
  266. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  267. {
  268. Entry* entry = NULL;
  269. if (mEntries.TryAdd(id, NULL, &entry))
  270. {
  271. entry->mInterfaceEntry = interfaceEntry;
  272. entry->mMethodIdx = methodIdx;
  273. }
  274. if (!entry->mCandidates.Contains(candidateA))
  275. entry->mCandidates.push_back(candidateA);
  276. if (!entry->mCandidates.Contains(candidateB))
  277. entry->mCandidates.push_back(candidateB);
  278. }
  279. void BfAmbiguityContext::Remove(int id)
  280. {
  281. mEntries.Remove(id);
  282. }
  283. void BfAmbiguityContext::Finish()
  284. {
  285. for (auto& entryPair : mEntries)
  286. {
  287. int id = entryPair.mKey;
  288. auto entry = &entryPair.mValue;
  289. if (id >= 0)
  290. {
  291. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  292. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  293. for (auto candidate : entry->mCandidates)
  294. {
  295. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  296. }
  297. }
  298. else
  299. {
  300. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  301. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  302. for (auto candidate : entry->mCandidates)
  303. {
  304. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  305. }
  306. }
  307. }
  308. }
  309. //////////////////////////////////////////////////////////////////////////
  310. class HasAppendAllocVisitor : BfElementVisitor
  311. {
  312. public:
  313. bool mHas;
  314. public:
  315. HasAppendAllocVisitor()
  316. {
  317. mHas = false;
  318. }
  319. void Visit(BfObjectCreateExpression* objCreateExpr)
  320. {
  321. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  322. {
  323. if (newToken->GetToken() == BfToken_Append)
  324. {
  325. mHas = true;
  326. }
  327. }
  328. }
  329. bool HasAppendAlloc(BfAstNode* node)
  330. {
  331. mHas = false;
  332. VisitChild(node);
  333. return mHas;
  334. }
  335. };
  336. class AppendAllocVisitor : public BfStructuralVisitor
  337. {
  338. public:
  339. BfModule* mModule;
  340. HasAppendAllocVisitor mHasAppendAllocVisitor;
  341. BfTypedValue mConstAccum;
  342. bool mFailed;
  343. bool mIsFirstConstPass;
  344. int mCurAppendAlign;
  345. public:
  346. AppendAllocVisitor()
  347. {
  348. mFailed = false;
  349. mIsFirstConstPass = false;
  350. mCurAppendAlign = 0;
  351. }
  352. void EmitAppendAlign(int align, int sizeMultiple = 0)
  353. {
  354. if (mIsFirstConstPass)
  355. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  356. if (sizeMultiple == 0)
  357. sizeMultiple = align;
  358. if (mCurAppendAlign == 0)
  359. mCurAppendAlign = sizeMultiple;
  360. else
  361. {
  362. if (sizeMultiple % align == 0)
  363. mCurAppendAlign = align;
  364. else
  365. mCurAppendAlign = sizeMultiple % align;
  366. }
  367. if (mConstAccum)
  368. {
  369. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  370. if (constant != NULL)
  371. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  372. else
  373. BF_ASSERT(mIsFirstConstPass);
  374. return;
  375. }
  376. mModule->EmitAppendAlign(align, sizeMultiple);
  377. }
  378. void Visit(BfAstNode* astNode) override
  379. {
  380. mModule->VisitChild(astNode);
  381. }
  382. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  383. {
  384. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  385. {
  386. if (newToken->GetToken() == BfToken_Append)
  387. {
  388. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  389. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  390. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  391. BfArrayType* arrayType = NULL;
  392. bool isArrayAlloc = false;
  393. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  394. SizedArray<BfIRValue, 2> dimLengthVals;
  395. BfType* origResolvedTypeRef = NULL;
  396. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  397. {
  398. if (variableDecl != NULL)
  399. {
  400. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  401. if (origResolvedTypeRef->IsObject())
  402. {
  403. if (origResolvedTypeRef->IsArray())
  404. {
  405. arrayType = (BfArrayType*)origResolvedTypeRef;
  406. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  407. isArrayAlloc = true;
  408. }
  409. }
  410. else if (origResolvedTypeRef->IsPointer())
  411. {
  412. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  413. }
  414. }
  415. }
  416. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  417. {
  418. isArrayAlloc = true;
  419. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  420. int dimensions = 1;
  421. if (arrayTypeRef->mParams.size() != 0)
  422. {
  423. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  424. for (auto arg : arrayTypeRef->mParams)
  425. {
  426. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  427. {
  428. if (tokenNode->GetToken() == BfToken_Comma)
  429. {
  430. if (isRawArrayAlloc)
  431. {
  432. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  433. continue;
  434. }
  435. dimensions++;
  436. continue;
  437. }
  438. }
  439. auto expr = BfNodeDynCast<BfExpression>(arg);
  440. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  441. {
  442. mModule->CreateValueFromExpression(expr, intType);
  443. continue;
  444. }
  445. BfTypedValue dimLength;
  446. if (expr == NULL)
  447. {
  448. // Not specified
  449. dimLengthVals.push_back(BfIRValue());
  450. continue;
  451. }
  452. if (arg != NULL)
  453. dimLength = mModule->CreateValueFromExpression(expr, intType);
  454. if (!dimLength)
  455. {
  456. dimLength = mModule->GetDefaultTypedValue(intType);
  457. }
  458. dimLengthVals.push_back(dimLength.mValue);
  459. }
  460. }
  461. if (!isRawArrayAlloc)
  462. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  463. }
  464. if (origResolvedTypeRef == NULL)
  465. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  466. if (origResolvedTypeRef == NULL)
  467. {
  468. mModule->AssertErrorState();
  469. return;
  470. }
  471. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  472. auto resolvedTypeRef = origResolvedTypeRef;
  473. auto resultType = resolvedTypeRef;
  474. BfIRValue sizeValue;
  475. int curAlign = 0;
  476. if (isArrayAlloc)
  477. {
  478. int dimensions = 1;
  479. if (arrayType != NULL)
  480. dimensions = arrayType->mDimensions;
  481. bool sizeFailed = false;
  482. //
  483. {
  484. BfAstNode* initNode = objCreateExpr;
  485. for (int dim = 0; dim < dimensions; dim++)
  486. {
  487. BfAstNode* nextInitNode = NULL;
  488. int dimSize = -1;
  489. if (initNode == objCreateExpr)
  490. {
  491. dimSize = objCreateExpr->mArguments.size();
  492. if (!objCreateExpr->mArguments.IsEmpty())
  493. nextInitNode = objCreateExpr->mArguments[0];
  494. }
  495. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  496. {
  497. dimSize = (int)tupleNode->mCommas.size() + 1;
  498. }
  499. if (dimSize >= 0)
  500. {
  501. if (dim >= dimLengthVals.size())
  502. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  503. }
  504. else
  505. {
  506. sizeFailed = true;
  507. }
  508. }
  509. }
  510. BfIRValue allocCount;
  511. if (!sizeFailed)
  512. {
  513. if (!dimLengthVals.IsEmpty())
  514. {
  515. allocCount = dimLengthVals[0];
  516. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  517. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  518. }
  519. }
  520. if (!allocCount)
  521. {
  522. mFailed = true;
  523. if (!mIsFirstConstPass)
  524. {
  525. if (!mConstAccum)
  526. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  527. return;
  528. }
  529. }
  530. if (isRawArrayAlloc)
  531. {
  532. curAlign = resultType->mAlign;
  533. EmitAppendAlign(resultType->mAlign);
  534. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  535. }
  536. else
  537. {
  538. if (arrayType == NULL)
  539. arrayType = mModule->CreateArrayType(resultType, 1);
  540. // Array is a special case where the total size isn't aligned with mAlign
  541. // since we add arbitrary elements to the end without padding the end to align
  542. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  543. curAlign = arrayType->mAlign;
  544. auto firstElementField = &arrayType->mFieldInstances.back();
  545. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  546. sizeValue = mModule->GetConstValue(arrayClassSize);
  547. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  548. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  549. }
  550. }
  551. else
  552. {
  553. auto typeInst = resultType->ToTypeInstance();
  554. if (typeInst != NULL)
  555. {
  556. curAlign = typeInst->mInstAlign;
  557. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  558. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  559. }
  560. else
  561. {
  562. curAlign = resultType->mAlign;
  563. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  564. sizeValue = mModule->GetConstValue(resultType->mSize);
  565. }
  566. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  567. BfExprEvaluator exprEvaluator(mModule);
  568. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  569. BfFunctionBindResult bindResult;
  570. bindResult.mWantsArgs = true;
  571. exprEvaluator.mFunctionBindResult = &bindResult;
  572. SizedArray<BfExpression*, 8> copiedArgs;
  573. for (BfExpression* arg : objCreateExpr->mArguments)
  574. copiedArgs.push_back(arg);
  575. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  576. BfResolvedArgs argValues(&sizedArgExprs);
  577. if (typeInst != NULL)
  578. {
  579. exprEvaluator.ResolveArgValues(argValues);
  580. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  581. }
  582. exprEvaluator.mFunctionBindResult = NULL;
  583. if (bindResult.mMethodInstance != NULL)
  584. {
  585. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  586. {
  587. auto calcAppendArgs = bindResult.mIRArgs;
  588. BF_ASSERT(calcAppendArgs[0].IsFake());
  589. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  590. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  591. auto subDependSize = mModule->TryConstCalcAppend(bindResult.mMethodInstance, calcAppendArgs);
  592. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  593. {
  594. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  595. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  596. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  597. }
  598. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  599. if ((!subDependSize) && (!mConstAccum))
  600. {
  601. BF_ASSERT(calcAppendMethodModule.mFunc);
  602. subDependSize = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  603. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  604. }
  605. if (subDependSize)
  606. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  607. else
  608. mFailed = true;
  609. }
  610. }
  611. }
  612. if (sizeValue)
  613. {
  614. if (mConstAccum)
  615. {
  616. if (!sizeValue.IsConst())
  617. {
  618. mFailed = true;
  619. if (!mIsFirstConstPass)
  620. return;
  621. }
  622. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  623. }
  624. else
  625. {
  626. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  627. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  628. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  629. }
  630. }
  631. }
  632. }
  633. }
  634. void Visit(BfObjectCreateExpression* objCreateExpr) override
  635. {
  636. DoObjectCreate(objCreateExpr, NULL);
  637. }
  638. void Visit(BfVariableDeclaration* varDecl) override
  639. {
  640. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  641. {
  642. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  643. DoObjectCreate(objectCreateExpr, varDecl);
  644. else
  645. VisitChild(varDecl->mInitializer);
  646. if (varDecl->mNameNode != NULL)
  647. {
  648. BfLocalVariable* localDef = new BfLocalVariable();
  649. localDef->mName = varDecl->mNameNode->ToString();
  650. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  651. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  652. localDef->mIsReadOnly = true;
  653. localDef->mParamFailed = true;
  654. localDef->mReadFromId = 0;
  655. mModule->AddLocalVariableDef(localDef);
  656. }
  657. }
  658. else
  659. {
  660. mModule->Visit(varDecl);
  661. }
  662. }
  663. void Visit(BfExpressionStatement* exprStatement) override
  664. {
  665. VisitChild(exprStatement->mExpression);
  666. }
  667. // void Visit(BfIfStatement* ifStmt) override
  668. // {
  669. // mModule->DoIfStatement(ifStmt,
  670. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  671. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  672. // }
  673. void Visit(BfBlock* block) override
  674. {
  675. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  676. return;
  677. int appendAllocIdx = -1;
  678. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  679. {
  680. auto child = block->mChildArr.mVals[childIdx];
  681. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  682. {
  683. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  684. {
  685. auto emitChild = block->mChildArr.mVals[emitIdx];
  686. mModule->UpdateSrcPos(emitChild);
  687. VisitChild(emitChild);
  688. if ((mFailed) && (!mIsFirstConstPass))
  689. break;
  690. }
  691. break;
  692. }
  693. }
  694. }
  695. };
  696. //////////////////////////////////////////////////////////////////////////
  697. BfModule* gLastCreatedModule = NULL;
  698. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  699. {
  700. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  701. gLastCreatedModule = this;
  702. mContext = context;
  703. mModuleName = moduleName;
  704. if (!moduleName.empty())
  705. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  706. mAddedToCount = false;
  707. mParentModule = NULL;
  708. mNextAltModule = NULL;
  709. mBfIRBuilder = NULL;
  710. mWantsIRIgnoreWrites = false;
  711. mModuleOptions = NULL;
  712. mLastUsedRevision = -1;
  713. mUsedSlotCount = -1;
  714. mIsReified = true;
  715. mReifyQueued = false;
  716. mIsSpecialModule = false;
  717. mIsScratchModule = false;
  718. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  719. mHadBuildError = false;
  720. mHadBuildWarning = false;
  721. mIgnoreErrors = false;
  722. mIgnoreWarnings = false;
  723. mReportErrors = true;
  724. mIsInsideAutoComplete = false;
  725. mIsDeleting = false;
  726. mSkipInnerLookup = false;
  727. mIsHotModule = false;
  728. mSetIllegalSrcPosition = false;
  729. mNoResolveGenericParams = false;
  730. mWroteToLib = false;
  731. mContext = context;
  732. mCompiler = context->mCompiler;
  733. mSystem = mCompiler->mSystem;
  734. mProject = NULL;
  735. mCurMethodState = NULL;
  736. mAttributeState = NULL;
  737. mCurLocalMethodId = 0;
  738. mParentNodeEntry = NULL;
  739. mRevision = -1;
  740. mRebuildIdx = 0;
  741. mLastModuleWrittenRevision = 0;
  742. mIsModuleMutable = false;
  743. mExtensionCount = 0;
  744. mIncompleteMethodCount = 0;
  745. mOnDemandMethodCount = 0;
  746. mHasGenericMethods = false;
  747. mCurMethodInstance = NULL;
  748. mCurTypeInstance = NULL;
  749. mAwaitingInitFinish = false;
  750. mAwaitingFinish = false;
  751. mHasFullDebugInfo = false;
  752. mHadHotObjectWrites = false;
  753. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  754. mBuiltInFuncs[i] = BfIRFunction();
  755. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  756. }
  757. void BfReportMemory();
  758. BfModule::~BfModule()
  759. {
  760. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  761. if (!mIsDeleting)
  762. RemoveModuleData();
  763. }
  764. void BfModule::RemoveModuleData()
  765. {
  766. BF_ASSERT(!mIsDeleting);
  767. if (!mModuleName.empty())
  768. {
  769. // Note: module names not necessarily unique
  770. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  771. }
  772. CleanupFileInstances();
  773. delete mBfIRBuilder;
  774. mBfIRBuilder = NULL;
  775. //delete mCpu;
  776. for (auto prevModule : mPrevIRBuilders)
  777. delete prevModule;
  778. mPrevIRBuilders.Clear();
  779. for (auto& pairVal : mDeferredMethodCallData)
  780. delete pairVal.mValue;
  781. mDeferredMethodCallData.Clear();
  782. mDeferredMethodIds.Clear();
  783. for (auto& specModulePair : mSpecializedMethodModules)
  784. delete specModulePair.mValue;
  785. mSpecializedMethodModules.Clear();
  786. if (mNextAltModule != NULL)
  787. delete mNextAltModule;
  788. mNextAltModule = NULL;
  789. if (mModuleOptions != NULL)
  790. delete mModuleOptions;
  791. mModuleOptions = NULL;
  792. BfReportMemory();
  793. }
  794. void BfModule::Init(bool isFullRebuild)
  795. {
  796. mContext->mFinishedModuleWorkList.Remove(this);
  797. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  798. BF_ASSERT(mIsReified);
  799. if (!mIsScratchModule)
  800. {
  801. mCompiler->mStats.mModulesStarted++;
  802. if (mIsReified)
  803. mCompiler->mStats.mReifiedModuleCount++;
  804. mAddedToCount = true;
  805. }
  806. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  807. mFuncReferences.Clear();
  808. mClassVDataRefs.Clear();
  809. mClassVDataExtRefs.Clear();
  810. //mTypeDataRefs.Clear();
  811. mDbgRawAllocDataRefs.Clear();
  812. CleanupFileInstances();
  813. mStaticFieldRefs.Clear();
  814. //mInterfaceSlotRefs.Clear();
  815. // If we are just doing an extension then the ownede types aren't rebuilt.
  816. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  817. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  818. if (isFullRebuild)
  819. mRevision = mCompiler->mRevision;
  820. BF_ASSERT(mCurTypeInstance == NULL);
  821. mIsModuleMutable = true;
  822. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  823. #ifdef _DEBUG
  824. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  825. #else
  826. EnsureIRBuilder(false);
  827. #endif
  828. mCurMethodState = NULL;
  829. mAwaitingInitFinish = true;
  830. mOnDemandMethodCount = 0;
  831. mAwaitingFinish = false;
  832. mHasForceLinkMarker = false;
  833. mUsedSlotCount = -1;
  834. }
  835. bool BfModule::WantsFinishModule()
  836. {
  837. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  838. }
  839. void BfModule::FinishInit()
  840. {
  841. BF_ASSERT(mAwaitingInitFinish);
  842. auto moduleOptions = GetModuleOptions();
  843. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  844. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple);
  845. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  846. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  847. {
  848. // Og+ requires debug info
  849. moduleOptions.mEmitDebugInfo = 1;
  850. }
  851. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  852. if ((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified))
  853. {
  854. mBfIRBuilder->DbgInit();
  855. }
  856. else
  857. mHasFullDebugInfo = false;
  858. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  859. ((moduleOptions.mEmitDebugInfo != 0)))
  860. {
  861. if (mCompiler->mOptions.IsCodeView())
  862. {
  863. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  864. }
  865. else
  866. {
  867. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  868. }
  869. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  870. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  871. }
  872. mAwaitingInitFinish = false;
  873. }
  874. void BfModule::ReifyModule()
  875. {
  876. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  877. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  878. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  879. mIsReified = true;
  880. mReifyQueued = false;
  881. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  882. mCompiler->mStats.mModulesReified++;
  883. }
  884. void BfModule::UnreifyModule()
  885. {
  886. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  887. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  888. mIsReified = false;
  889. mReifyQueued = false;
  890. StartNewRevision(RebuildKind_None, true);
  891. mCompiler->mStats.mModulesUnreified++;
  892. }
  893. void BfModule::CleanupFileInstances()
  894. {
  895. for (auto& itr : mNamedFileInstanceMap)
  896. {
  897. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  898. delete itr.mValue;
  899. }
  900. mCurFilePosition.mFileInstance = NULL;//
  901. mFileInstanceMap.Clear();
  902. mNamedFileInstanceMap.Clear();
  903. }
  904. void BfModule::Cleanup()
  905. {
  906. CleanupFileInstances();
  907. }
  908. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  909. {
  910. if (HasCompiledOutput())
  911. {
  912. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  913. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  914. {
  915. StartExtension();
  916. }
  917. }
  918. else
  919. {
  920. EnsureIRBuilder();
  921. }
  922. }
  923. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  924. {
  925. BF_ASSERT(!mIsDeleting);
  926. if (mBfIRBuilder == NULL)
  927. {
  928. if ((!mIsScratchModule) && (!mAddedToCount))
  929. {
  930. mCompiler->mStats.mModulesStarted++;
  931. mAddedToCount = true;
  932. }
  933. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  934. /*if (mCompiler->mIsResolveOnly)
  935. BF_ASSERT(mIsResolveOnly);*/
  936. mBfIRBuilder = new BfIRBuilder(this);
  937. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  938. if (mIsScratchModule)
  939. {
  940. mBfIRBuilder->mIgnoreWrites = true;
  941. BF_ASSERT(!dbgVerifyCodeGen);
  942. }
  943. #ifdef _DEBUG
  944. if (mCompiler->mIsResolveOnly)
  945. {
  946. // For "deep" verification testing
  947. /*if (!mIsSpecialModule)
  948. dbgVerifyCodeGen = true;*/
  949. // We only want to turn this off on smaller builds for testing
  950. mBfIRBuilder->mIgnoreWrites = true;
  951. if (dbgVerifyCodeGen)
  952. mBfIRBuilder->mIgnoreWrites = false;
  953. if (!mBfIRBuilder->mIgnoreWrites)
  954. {
  955. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  956. mBfIRBuilder->mDbgVerifyCodeGen = true;
  957. }
  958. }
  959. else if (!mIsReified)
  960. {
  961. mBfIRBuilder->mIgnoreWrites = true;
  962. }
  963. else
  964. {
  965. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  966. // code as we walk the AST
  967. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  968. if (
  969. (mModuleName == "-")
  970. //|| (mModuleName == "BeefTest2_ClearColorValue")
  971. //|| (mModuleName == "Tests_FuncRefs")
  972. )
  973. mBfIRBuilder->mDbgVerifyCodeGen = true;
  974. // Just for testing!
  975. //mBfIRBuilder->mIgnoreWrites = true;
  976. }
  977. #else
  978. if (mCompiler->mIsResolveOnly)
  979. {
  980. // Always ignore writes in resolveOnly for release builds
  981. mBfIRBuilder->mIgnoreWrites = true;
  982. }
  983. else
  984. {
  985. // Just for memory testing! This breaks everything.
  986. //mBfIRBuilder->mIgnoreWrites = true;
  987. // For "deep" verification testing
  988. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  989. }
  990. #endif
  991. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  992. }
  993. }
  994. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  995. {
  996. String name = "FORCELINKMOD_" + module->mModuleName;
  997. if (outName != NULL)
  998. *outName = name;
  999. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1000. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1001. }
  1002. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1003. {
  1004. BP_ZONE("BfModule::StartNewRevision");
  1005. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1006. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1007. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1008. // Already on new revision?
  1009. if ((mRevision == mCompiler->mRevision) && (!force))
  1010. return;
  1011. mHadBuildError = false;
  1012. mHadBuildWarning = false;
  1013. mExtensionCount = 0;
  1014. mRevision = mCompiler->mRevision;
  1015. mRebuildIdx++;
  1016. ClearModuleData(!force);
  1017. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1018. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1019. mStringPoolRefs.Clear();
  1020. mDllImportEntries.Clear();
  1021. mImportFileNames.Clear();
  1022. for (auto& pairVal : mDeferredMethodCallData)
  1023. delete pairVal.mValue;
  1024. mDeferredMethodCallData.Clear();
  1025. mDeferredMethodIds.Clear();
  1026. mModuleRefs.Clear();
  1027. mOutFileNames.Clear();
  1028. mTypeDataRefs.Clear();
  1029. mInterfaceSlotRefs.Clear();
  1030. if (rebuildKind == BfModule::RebuildKind_None)
  1031. {
  1032. for (auto& specPair : mSpecializedMethodModules)
  1033. {
  1034. auto specModule = specPair.mValue;
  1035. if (specModule->mIsReified != mIsReified)
  1036. {
  1037. if (mIsReified)
  1038. specModule->ReifyModule();
  1039. else
  1040. specModule->UnreifyModule();
  1041. }
  1042. }
  1043. }
  1044. else
  1045. {
  1046. for (auto& specPair : mSpecializedMethodModules)
  1047. {
  1048. auto specModule = specPair.mValue;
  1049. delete specModule;
  1050. }
  1051. }
  1052. mSpecializedMethodModules.Clear();
  1053. delete mNextAltModule;
  1054. mNextAltModule = NULL;
  1055. BF_ASSERT(mModuleOptions == NULL);
  1056. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1057. bool needsTypePopulated = false;
  1058. int oldOnDemandCount = 0;
  1059. // We don't have to rebuild types in the unspecialized module because there is no
  1060. // data that's needed -- their method instances are all NULL and the module
  1061. // doesn't get included in the build
  1062. if (this != mContext->mScratchModule)
  1063. {
  1064. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1065. {
  1066. auto typeInst = mOwnedTypeInstances[typeIdx];
  1067. if (!typeInst->IsDeleting())
  1068. {
  1069. typeInst->mIsReified = mIsReified;
  1070. if (rebuildKind != BfModule::RebuildKind_None)
  1071. {
  1072. if (typeInst->IsOnDemand())
  1073. {
  1074. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1075. if (rebuildKind == BfModule::RebuildKind_All)
  1076. mContext->DeleteType(typeInst);
  1077. else
  1078. {
  1079. RebuildMethods(typeInst);
  1080. }
  1081. }
  1082. else
  1083. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1084. mContext->RebuildType(typeInst, false, false, true);
  1085. //mContext->RebuildType(typeInst, false, false, false);
  1086. }
  1087. else
  1088. {
  1089. auto _HandleMethod = [&](BfMethodInstance* methodInstance)
  1090. {
  1091. if ((methodInstance != NULL) && (methodInstance->mDeclModule != NULL))
  1092. methodInstance->mDeclModule = this;
  1093. };
  1094. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1095. {
  1096. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1097. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference))
  1098. {
  1099. oldOnDemandCount++;
  1100. }
  1101. _HandleMethod(methodGroup.mDefault);
  1102. if (methodGroup.mMethodSpecializationMap != NULL)
  1103. for (auto& kv : *methodGroup.mMethodSpecializationMap)
  1104. _HandleMethod(kv.mValue);
  1105. }
  1106. }
  1107. if (typeInst->IsDeleting())
  1108. typeIdx--;
  1109. }
  1110. }
  1111. }
  1112. if (!mIsDeleting)
  1113. Init();
  1114. mOnDemandMethodCount += oldOnDemandCount;
  1115. }
  1116. void BfModule::StartExtension()
  1117. {
  1118. BF_ASSERT(!mIsModuleMutable);
  1119. BfLogSysM("Extension started of module %p\n", this);
  1120. mExtensionCount++;
  1121. if (mBfIRBuilder != NULL)
  1122. mPrevIRBuilders.push_back(mBfIRBuilder);
  1123. mBfIRBuilder = NULL;
  1124. mWantsIRIgnoreWrites = false;
  1125. mFuncReferences.Clear();
  1126. mClassVDataRefs.Clear();
  1127. mClassVDataExtRefs.Clear();
  1128. for (auto& kv : mTypeDataRefs)
  1129. kv.mValue = BfIRValue();
  1130. mDbgRawAllocDataRefs.Clear();
  1131. mStringCharPtrPool.Clear();
  1132. mStringObjectPool.Clear();
  1133. mStaticFieldRefs.Clear();
  1134. for (auto& kv : mInterfaceSlotRefs)
  1135. kv.mValue = BfIRValue();
  1136. mDeferredMethodCallData.Clear();
  1137. mDeferredMethodIds.Clear();
  1138. DisownMethods();
  1139. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1140. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1141. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1142. Init(false);
  1143. if (!wasAwaitingInitFinish)
  1144. FinishInit();
  1145. mOnDemandMethodCount = prevOnDemandMethodCount;
  1146. }
  1147. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1148. {
  1149. BfIRValue vDataValue;
  1150. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1151. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1152. else
  1153. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1154. typeValueParams.push_back(vDataValue);
  1155. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1156. {
  1157. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1158. typeValueParams.push_back(GetDefaultValue(primType));
  1159. }
  1160. }
  1161. BfIRValue BfModule::GetConstValue(int64 val)
  1162. {
  1163. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1164. }
  1165. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1166. {
  1167. BfType* checkType = type;
  1168. if (type->IsTypedPrimitive())
  1169. {
  1170. checkType = type->GetUnderlyingType();
  1171. }
  1172. if (checkType->IsPrimitiveType())
  1173. {
  1174. auto primType = (BfPrimitiveType*)checkType;
  1175. if (checkType->IsFloat())
  1176. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1177. else
  1178. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1179. }
  1180. return BfIRValue();
  1181. }
  1182. BfIRValue BfModule::GetConstValue8(int val)
  1183. {
  1184. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1185. }
  1186. BfIRValue BfModule::GetConstValue32(int32 val)
  1187. {
  1188. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1189. }
  1190. BfIRValue BfModule::GetConstValue64(int64 val)
  1191. {
  1192. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1193. }
  1194. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1195. {
  1196. PopulateType(type, BfPopulateType_Data);
  1197. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1198. if (type->IsTypedPrimitive())
  1199. {
  1200. auto underlyingType = type->GetUnderlyingType();
  1201. if (underlyingType == NULL)
  1202. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1203. return GetDefaultValue(type->GetUnderlyingType());
  1204. }
  1205. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1206. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1207. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1208. if ((type->IsIntegral()) || (type->IsBoolean()))
  1209. {
  1210. auto primType = (BfPrimitiveType*)type;
  1211. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1212. }
  1213. if (type->IsFloat())
  1214. {
  1215. auto primType = (BfPrimitiveType*)type;
  1216. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1217. }
  1218. if (type->IsVoid())
  1219. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1220. return mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(type));
  1221. }
  1222. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1223. {
  1224. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1225. if (type->mSize == 0)
  1226. return BfTypedValue(BfIRValue::sValueless, type);
  1227. else
  1228. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1229. }
  1230. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1231. {
  1232. if (type->IsVar())
  1233. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1234. PopulateType(type, BfPopulateType_Data);
  1235. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1236. if (defaultValueKind == BfDefaultValueKind_Undef)
  1237. {
  1238. auto primType = type->ToPrimitiveType();
  1239. if (primType != NULL)
  1240. {
  1241. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode), type);
  1242. }
  1243. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(type)), type);
  1244. }
  1245. BfTypedValue typedValue;
  1246. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1247. {
  1248. if (type->IsRef())
  1249. {
  1250. BfRefType* refType = (BfRefType*)type;
  1251. BfType* underlyingType = refType->GetUnderlyingType();
  1252. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1253. }
  1254. else
  1255. {
  1256. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1257. }
  1258. if (!mBfIRBuilder->mIgnoreWrites)
  1259. {
  1260. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1261. GetConstValue(type->mSize), type->mAlign);
  1262. }
  1263. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1264. typedValue = LoadValue(typedValue);
  1265. return typedValue;
  1266. }
  1267. if ((type->IsRef()) && (!allowRef))
  1268. {
  1269. BfRefType* refType = (BfRefType*)type;
  1270. BfType* underlyingType = refType->GetUnderlyingType();
  1271. if (underlyingType->IsValuelessType())
  1272. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1273. else
  1274. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1275. }
  1276. else
  1277. {
  1278. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1279. }
  1280. return typedValue;
  1281. }
  1282. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1283. {
  1284. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1285. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1286. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1287. BfIRValue strConstant;
  1288. if (define)
  1289. {
  1290. strConstant = mBfIRBuilder->CreateConstString(str);
  1291. }
  1292. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1293. true, BfIRLinkageType_External,
  1294. strConstant, stringDataName);
  1295. if (define)
  1296. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1297. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1298. }
  1299. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1300. {
  1301. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1302. mBfIRBuilder->PopulateType(stringTypeInst);
  1303. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1304. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1305. BfIRValue stringValData;
  1306. if (define)
  1307. {
  1308. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1309. mStringCharPtrPool[stringId] = stringCharsVal;
  1310. SizedArray<BfIRValue, 8> typeValueParams;
  1311. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1312. auto objData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1313. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1314. typeValueParams.clear();
  1315. typeValueParams.push_back(objData);
  1316. if (lenByteCount == 4)
  1317. {
  1318. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1319. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1320. }
  1321. else
  1322. {
  1323. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1324. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1325. }
  1326. typeValueParams.push_back(stringCharsVal); // mPtr
  1327. for (int fieldIdx = 0; fieldIdx < (int)stringTypeInst->mFieldInstances.size(); fieldIdx++)
  1328. {
  1329. auto fieldInstance = &stringTypeInst->mFieldInstances[fieldIdx];
  1330. if (fieldInstance->mDataIdx < 4)
  1331. continue;
  1332. while (fieldInstance->mDataIdx >= typeValueParams.size())
  1333. typeValueParams.Add(BfIRValue());
  1334. typeValueParams[fieldInstance->mDataIdx] = GetDefaultValue(fieldInstance->mResolvedType);
  1335. }
  1336. stringValData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1337. }
  1338. mBfIRBuilder->PopulateType(stringTypeInst);
  1339. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1340. mBfIRBuilder->MapTypeInst(stringTypeInst),
  1341. true,
  1342. BfIRLinkageType_External,
  1343. define ? stringValData : BfIRValue(),
  1344. stringObjName);
  1345. auto stringVal = mBfIRBuilder->CreateBitCast(stringValLiteral, mBfIRBuilder->MapType(stringTypeInst, BfIRPopulateType_Full));
  1346. return stringVal;
  1347. }
  1348. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1349. {
  1350. BF_ASSERT(constantStr.IsConst());
  1351. if (constHolder == NULL)
  1352. constHolder = mBfIRBuilder;
  1353. auto constant = constHolder->GetConstant(constantStr);
  1354. if (constant->mTypeCode == BfTypeCode_StringId)
  1355. {
  1356. return constant->mInt32;
  1357. }
  1358. while (constant->mConstType == BfConstType_BitCast)
  1359. {
  1360. auto constBitCast = (BfConstantBitCast*)constant;
  1361. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1362. }
  1363. if (constant->mConstType == BfConstType_GEP32_2)
  1364. {
  1365. auto constGEP = (BfConstantGEP32_2*)constant;
  1366. constant = constHolder->GetConstantById(constGEP->mTarget);
  1367. }
  1368. if (constant->mConstType == BfConstType_GlobalVar)
  1369. {
  1370. auto constGV = (BfGlobalVar*)constant;
  1371. const char* strDataPrefix = "__bfStrData";
  1372. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1373. return atoi(constGV->mName + strlen(strDataPrefix));
  1374. const char* strObjPrefix = "__bfStrObj";
  1375. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1376. return atoi(constGV->mName + strlen(strObjPrefix));
  1377. }
  1378. return -1;
  1379. }
  1380. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1381. {
  1382. int strId = GetStringPoolIdx(constantStr, constHolder);
  1383. if (strId != -1)
  1384. {
  1385. auto& entry = mContext->mStringObjectIdMap[strId];
  1386. return &entry.mString;
  1387. }
  1388. return NULL;
  1389. }
  1390. BfIRValue BfModule::GetStringCharPtr(int stringId)
  1391. {
  1392. BfIRValue* irValue = NULL;
  1393. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1394. return *irValue;
  1395. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1396. if (!mStringObjectPool.ContainsKey(stringId))
  1397. mStringPoolRefs.Add(stringId);
  1398. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1399. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1400. *irValue = strCharPtrConst;
  1401. return strCharPtrConst;
  1402. }
  1403. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue)
  1404. {
  1405. if (strValue.IsConst())
  1406. {
  1407. int stringId = GetStringPoolIdx(strValue);
  1408. BF_ASSERT(stringId != -1);
  1409. return GetStringCharPtr(stringId);
  1410. }
  1411. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1412. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1413. return charPtr;
  1414. }
  1415. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str)
  1416. {
  1417. return GetStringCharPtr(GetStringObjectValue(str));
  1418. }
  1419. BfIRValue BfModule::GetStringObjectValue(int strId)
  1420. {
  1421. BfIRValue* objValue;
  1422. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1423. return *objValue;
  1424. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1425. return GetStringObjectValue(stringPoolEntry.mString, true);
  1426. }
  1427. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define)
  1428. {
  1429. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1430. mBfIRBuilder->PopulateType(stringType);
  1431. int strId = mContext->GetStringLiteralId(str);
  1432. BfIRValue* irValuePtr = NULL;
  1433. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1434. return *irValuePtr;
  1435. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1436. if (!mStringCharPtrPool.ContainsKey(strId))
  1437. mStringPoolRefs.Add(strId);
  1438. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1439. *irValuePtr = strObject;
  1440. mStringPoolRefs.Add(strId);
  1441. return strObject;
  1442. }
  1443. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1444. {
  1445. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1446. type,
  1447. true,
  1448. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1449. constant,
  1450. name.c_str());
  1451. return newConst;
  1452. }
  1453. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1454. {
  1455. auto curScope = mCurMethodState->mCurScope;
  1456. if (curScope->mLabelNode != NULL)
  1457. {
  1458. curScope->mLabelNode->ToString(curScope->mLabel);
  1459. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1460. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1461. auto autoComplete = mCompiler->GetAutoComplete();
  1462. if (autoComplete != NULL)
  1463. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1464. }
  1465. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1466. {
  1467. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1468. while (checkScope != NULL)
  1469. {
  1470. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1471. {
  1472. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1473. if (errorNode != NULL)
  1474. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1475. break;
  1476. }
  1477. checkScope = checkScope->mPrevScope;
  1478. }
  1479. }
  1480. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1481. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1482. {
  1483. if (prevScope->mHadScopeValueRetain)
  1484. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1485. else
  1486. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1487. }
  1488. mCurMethodState->mBlockNestLevel++;
  1489. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1490. {
  1491. // DIScope could be NULL if we're in an unspecialized method (for example)
  1492. if (mCurMethodState->mCurScope->mDIScope)
  1493. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1494. }
  1495. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1496. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1497. }
  1498. void BfModule::RestoreScoreState_LocalVariables()
  1499. {
  1500. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1501. {
  1502. auto localVar = mCurMethodState->mLocals.back();
  1503. LocalVariableDone(localVar, false);
  1504. mCurMethodState->mLocals.pop_back();
  1505. if (localVar->mShadowedLocal != NULL)
  1506. {
  1507. BfLocalVarEntry* localVarEntryPtr;
  1508. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1509. {
  1510. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1511. }
  1512. }
  1513. else
  1514. {
  1515. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1516. }
  1517. delete localVar;
  1518. }
  1519. }
  1520. void BfModule::RestoreScopeState()
  1521. {
  1522. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1523. mCurMethodState->mBlockNestLevel--;
  1524. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1525. {
  1526. BfIRBlock afterEndBlock;
  1527. if (!mCurMethodState->mLeftBlockUncond)
  1528. {
  1529. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1530. mBfIRBuilder->CreateBr(afterEndBlock);
  1531. mBfIRBuilder->ClearDebugLocation_Last();
  1532. }
  1533. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1534. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1535. if (afterEndBlock)
  1536. {
  1537. mBfIRBuilder->AddBlock(afterEndBlock);
  1538. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1539. }
  1540. }
  1541. if (!mCurMethodState->mLeftBlockUncond)
  1542. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1543. RestoreScoreState_LocalVariables();
  1544. if (mCurMethodState->mCurScope->mValueScopeStart)
  1545. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1546. mCurMethodState->mCurScope = prevScopeData;
  1547. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1548. }
  1549. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1550. {
  1551. if (mBfIRBuilder->mIgnoreWrites)
  1552. return mBfIRBuilder->GetFakeVal();
  1553. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1554. mBfIRBuilder->PopulateType(type);
  1555. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1556. if (!mBfIRBuilder->mIgnoreWrites)
  1557. BF_ASSERT(!prevInsertBlock.IsFake());
  1558. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1559. BfIRValue allocaInst;
  1560. if (arraySize)
  1561. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1562. else
  1563. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1564. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1565. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1566. if (name != NULL)
  1567. mBfIRBuilder->SetName(allocaInst, name);
  1568. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1569. if ((addLifetime) && (WantsLifetimes()))
  1570. {
  1571. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1572. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1573. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1574. }
  1575. return allocaInst;
  1576. }
  1577. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1578. {
  1579. if (mBfIRBuilder->mIgnoreWrites)
  1580. return mBfIRBuilder->GetFakeVal();
  1581. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1582. mBfIRBuilder->PopulateType(typeInst);
  1583. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1584. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1585. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1586. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1587. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1588. if (name != NULL)
  1589. mBfIRBuilder->SetName(allocaInst, name);
  1590. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1591. if ((addLifetime) && (WantsLifetimes()))
  1592. {
  1593. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1594. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1595. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1596. }
  1597. return allocaInst;
  1598. }
  1599. void BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape)
  1600. {
  1601. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1602. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1603. /*if (mCurMethodState->mInHeadScope)
  1604. isScopeAlloc = true;*/
  1605. if (scopeData == NULL)
  1606. return;
  1607. auto checkBaseType = val.mType->ToTypeInstance();
  1608. if ((checkBaseType != NULL) && (checkBaseType->IsObject()))
  1609. {
  1610. bool hadDtorCall = false;
  1611. while (checkBaseType != NULL)
  1612. {
  1613. if ((checkBaseType->mTypeDef->mDtorDef != NULL) /*&& (checkBaseType != mContext->mBfObjectType)*/)
  1614. {
  1615. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  1616. if (dtorMethodInstance)
  1617. {
  1618. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1619. BfIRValue useVal = val.mValue;
  1620. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1621. if (isDynAlloc)
  1622. {
  1623. //
  1624. }
  1625. else if (condAlloca)
  1626. {
  1627. BF_ASSERT(!IsTargetingBeefBackend());
  1628. BF_ASSERT(!isDynAlloc);
  1629. auto valPtr = CreateAlloca(checkBaseType);
  1630. mBfIRBuilder->CreateStore(useVal, valPtr);
  1631. useVal = valPtr;
  1632. }
  1633. SizedArray<BfIRValue, 1> llvmArgs;
  1634. llvmArgs.push_back(useVal);
  1635. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1636. if (deferredCall != NULL)
  1637. {
  1638. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1639. if (condAlloca)
  1640. deferredCall->mArgsNeedLoad = true;
  1641. }
  1642. hadDtorCall = true;
  1643. break;
  1644. }
  1645. }
  1646. checkBaseType = checkBaseType->mBaseType;
  1647. }
  1648. return;
  1649. }
  1650. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1651. if (mayEscape)
  1652. {
  1653. if ((!IsOptimized()) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1654. {
  1655. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1656. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1657. if (!isDyn)
  1658. {
  1659. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1660. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1661. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1662. if (!dtorMethodInstance.mMethodInstance)
  1663. {
  1664. Fail(StrFormat("Unable to find %s", methodName));
  1665. }
  1666. else
  1667. {
  1668. SizedArray<BfIRValue, 1> llvmArgs;
  1669. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1670. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1671. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1672. if (arraySize)
  1673. llvmArgs.push_back(arraySize);
  1674. AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1675. }
  1676. }
  1677. else
  1678. {
  1679. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1680. {
  1681. BfIRValue clearSize = arraySize;
  1682. if (val.mType->GetStride() > 1)
  1683. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1684. const char* methodName = "SetDeletedX";
  1685. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1686. BF_ASSERT(dtorMethodInstance);
  1687. if (!dtorMethodInstance)
  1688. {
  1689. Fail(StrFormat("Unable to find %s", methodName));
  1690. }
  1691. else
  1692. {
  1693. SizedArray<BfIRValue, 1> llvmArgs;
  1694. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1695. llvmArgs.push_back(clearSize);
  1696. AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1697. }
  1698. }
  1699. else
  1700. {
  1701. intptr clearSize = val.mType->mSize;
  1702. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1703. if (constant != NULL)
  1704. clearSize = (intptr)(clearSize * constant->mInt64);
  1705. const char* funcName = "SetDeleted1";
  1706. if (clearSize >= 16)
  1707. funcName = "SetDeleted16";
  1708. else if (clearSize >= 8)
  1709. funcName = "SetDeleted8";
  1710. else if (clearSize >= 4)
  1711. funcName = "SetDeleted4";
  1712. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1713. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1714. if (!dtorMethodInstance)
  1715. {
  1716. Fail(StrFormat("Unable to find %s", funcName));
  1717. }
  1718. else
  1719. {
  1720. SizedArray<BfIRValue, 1> llvmArgs;
  1721. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1722. AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1723. }
  1724. }
  1725. }
  1726. }
  1727. }
  1728. }
  1729. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1730. {
  1731. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1732. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1733. return false;
  1734. auto checkTypeInstance = startTypeInstance;
  1735. while (checkTypeInstance != NULL)
  1736. {
  1737. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1738. {
  1739. if (fieldInstance.mMergedDataIdx != -1)
  1740. {
  1741. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1742. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1743. {
  1744. // For fields added in extensions, we automatically initialize those if necessary
  1745. auto fieldDef = fieldInstance.GetFieldDef();
  1746. if (!fieldDef->mDeclaringType->IsExtension())
  1747. return false;
  1748. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1749. {
  1750. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1751. mBfIRBuilder->SaveDebugLocation();
  1752. if (localVar->IsParam())
  1753. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1754. else
  1755. {
  1756. BF_ASSERT(localVar->mDeclBlock);
  1757. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1758. }
  1759. mBfIRBuilder->ClearDebugLocation();
  1760. BfIRValue curVal;
  1761. if (localVar->mIsThis)
  1762. curVal = mBfIRBuilder->GetArgument(0);
  1763. else
  1764. curVal = localVar->mAddr;
  1765. auto subTypeInstance = startTypeInstance;
  1766. while (subTypeInstance != checkTypeInstance)
  1767. {
  1768. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1769. subTypeInstance = subTypeInstance->mBaseType;
  1770. }
  1771. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1772. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1773. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1774. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1775. mBfIRBuilder->RestoreDebugLocation();
  1776. }
  1777. localVar->mUnassignedFieldFlags &= ~checkMask;
  1778. if (localVar->mUnassignedFieldFlags == 0)
  1779. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1780. }
  1781. }
  1782. }
  1783. checkTypeInstance = checkTypeInstance->mBaseType;
  1784. }
  1785. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  1786. }
  1787. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1788. {
  1789. //if (localVar->mAddr == NULL)
  1790. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1791. {
  1792. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1793. {
  1794. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1795. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1796. }
  1797. }*/
  1798. BfAstNode* localNameNode = localVar->mNameNode;
  1799. if (localVar->mIsThis)
  1800. {
  1801. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1802. }
  1803. if (localNameNode != NULL)
  1804. {
  1805. bool isOut = false;
  1806. if (localVar->mResolvedType->IsRef())
  1807. {
  1808. auto refType = (BfRefType*)localVar->mResolvedType;
  1809. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1810. }
  1811. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1812. {
  1813. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  1814. TryLocalVariableInit(localVar);
  1815. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1816. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1817. // We may have init blocks that we aren't processing here...
  1818. if ((mCurMethodInstance->mIsAutocompleteMethod) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  1819. deferFullAnalysis = true;
  1820. //bool deferFullAnalysis = true;
  1821. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1822. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  1823. (!localVar->mIsImplicitParam))
  1824. {
  1825. if (deferUsageWarning)
  1826. {
  1827. // Ignore
  1828. }
  1829. else if (localVar->mIsThis)
  1830. {
  1831. bool foundFields = false;
  1832. auto checkTypeInstance = mCurTypeInstance;
  1833. while (checkTypeInstance != NULL)
  1834. {
  1835. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1836. {
  1837. if (fieldInstance.mMergedDataIdx != -1)
  1838. {
  1839. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1840. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1841. {
  1842. auto fieldDef = fieldInstance.GetFieldDef();
  1843. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  1844. {
  1845. String propName;
  1846. if (propertyDeclaration->mNameNode != NULL)
  1847. propertyDeclaration->mNameNode->ToString(propName);
  1848. if (checkTypeInstance == mCurTypeInstance)
  1849. {
  1850. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  1851. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1852. }
  1853. else
  1854. {
  1855. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  1856. TypeToString(checkTypeInstance).c_str(),
  1857. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1858. }
  1859. }
  1860. else
  1861. {
  1862. if (checkTypeInstance == mCurTypeInstance)
  1863. {
  1864. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  1865. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1866. }
  1867. else
  1868. {
  1869. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  1870. TypeToString(checkTypeInstance).c_str(),
  1871. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1872. }
  1873. }
  1874. foundFields = true;
  1875. }
  1876. }
  1877. }
  1878. checkTypeInstance = checkTypeInstance->mBaseType;
  1879. }
  1880. if (!foundFields)
  1881. {
  1882. if (mCurTypeInstance->mInstSize > 0)
  1883. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  1884. }
  1885. }
  1886. else if (localVar->IsParam())
  1887. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  1888. else if (!deferUsageWarning)
  1889. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1890. }
  1891. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  1892. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1893. }
  1894. }
  1895. }
  1896. void BfModule::MarkDynStack(BfScopeData* scopeData)
  1897. {
  1898. auto checkScope = mCurMethodState->mCurScope;
  1899. while (true)
  1900. {
  1901. if (checkScope == scopeData)
  1902. break;
  1903. checkScope->mHadOuterDynStack = true;
  1904. checkScope = checkScope->mPrevScope;
  1905. }
  1906. }
  1907. void BfModule::SaveStackState(BfScopeData* scopeData)
  1908. {
  1909. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  1910. // scopes within scopeData restore the stack
  1911. auto checkScope = mCurMethodState->mCurScope;
  1912. while (true)
  1913. {
  1914. if (checkScope == scopeData)
  1915. {
  1916. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  1917. {
  1918. if (mBfIRBuilder->mHasDebugInfo)
  1919. mBfIRBuilder->SaveDebugLocation();
  1920. auto prevPos = mBfIRBuilder->GetInsertBlock();
  1921. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  1922. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  1923. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  1924. mBfIRBuilder->SetInsertPoint(prevPos);
  1925. if (mBfIRBuilder->mHasDebugInfo)
  1926. mBfIRBuilder->RestoreDebugLocation();
  1927. }
  1928. break;
  1929. }
  1930. if (checkScope->mSavedStack)
  1931. {
  1932. for (auto usage : checkScope->mSavedStackUses)
  1933. mBfIRBuilder->EraseInstFromParent(usage);
  1934. checkScope->mSavedStackUses.Clear();
  1935. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  1936. checkScope->mSavedStack = BfIRValue();
  1937. }
  1938. checkScope = checkScope->mPrevScope;
  1939. }
  1940. }
  1941. BfIRValue BfModule::ValueScopeStart()
  1942. {
  1943. if (IsTargetingBeefBackend())
  1944. return mBfIRBuilder->CreateValueScopeStart();
  1945. return BfIRValue();
  1946. }
  1947. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  1948. {
  1949. if (valueScopeStart)
  1950. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  1951. }
  1952. BfProjectSet* BfModule::GetVisibleProjectSet()
  1953. {
  1954. if (mCurMethodState == NULL)
  1955. return NULL;
  1956. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  1957. {
  1958. HashSet<BfType*> seenTypes;
  1959. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  1960. {
  1961. if (mCurMethodState->mVisibleProjectSet.Add(project))
  1962. {
  1963. for (auto dep : project->mDependencies)
  1964. _AddProject(dep);
  1965. }
  1966. };
  1967. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  1968. {
  1969. auto typeInstance = type->ToTypeInstance();
  1970. if (typeInstance == NULL)
  1971. {
  1972. if (type->IsSizedArray())
  1973. _AddType(type->GetUnderlyingType());
  1974. return;
  1975. }
  1976. if (typeInstance->IsTuple())
  1977. {
  1978. for (auto& fieldInst : typeInstance->mFieldInstances)
  1979. {
  1980. if (fieldInst.mDataIdx != -1)
  1981. _AddType(fieldInst.mResolvedType);
  1982. }
  1983. }
  1984. _AddProject(typeInstance->mTypeDef->mProject);
  1985. if (typeInstance->mGenericTypeInfo == NULL)
  1986. return;
  1987. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  1988. {
  1989. if (seenTypes.Add(type))
  1990. _AddType(type);
  1991. }
  1992. };
  1993. if (mCurTypeInstance != NULL)
  1994. _AddType(mCurTypeInstance);
  1995. auto methodState = mCurMethodState;
  1996. while (methodState != NULL)
  1997. {
  1998. if (methodState->mMethodInstance != NULL)
  1999. {
  2000. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  2001. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  2002. {
  2003. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2004. _AddType(type);
  2005. }
  2006. }
  2007. methodState = methodState->mPrevMethodState;
  2008. }
  2009. }
  2010. return &mCurMethodState->mVisibleProjectSet;
  2011. }
  2012. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2013. {
  2014. auto bfParser = astNode->GetSourceData()->ToParserData();
  2015. if (bfParser == NULL)
  2016. return NULL;
  2017. BfFileInstance** fileInstancePtr = NULL;
  2018. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2019. {
  2020. return *fileInstancePtr;
  2021. }
  2022. else
  2023. {
  2024. // It's possible two parsers have the same file name (ie: mNextRevision)
  2025. BfFileInstance** namedFileInstancePtr = NULL;
  2026. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2027. {
  2028. auto bfFileInstance = *namedFileInstancePtr;
  2029. *fileInstancePtr = bfFileInstance;
  2030. return bfFileInstance;
  2031. }
  2032. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2033. auto bfFileInstance = new BfFileInstance();
  2034. *fileInstancePtr = bfFileInstance;
  2035. *namedFileInstancePtr = bfFileInstance;
  2036. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2037. bfFileInstance->mParser = bfParser;
  2038. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2039. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasInfo()))
  2040. {
  2041. String fileName = bfParser->mFileName;
  2042. for (int i = 0; i < (int)fileName.length(); i++)
  2043. {
  2044. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2045. fileName[i] = DIR_SEP_CHAR;
  2046. }
  2047. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, slashPos), bfParser->mMD5Hash);
  2048. }
  2049. return bfFileInstance;
  2050. }
  2051. }
  2052. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2053. {
  2054. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2055. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2056. return;
  2057. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2058. if (astNode == NULL)
  2059. return;
  2060. auto bfParser = astNode->GetSourceData()->ToParserData();
  2061. if (bfParser == NULL)
  2062. return;
  2063. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2064. {
  2065. if (mCurFilePosition.mFileInstance != NULL)
  2066. {
  2067. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2068. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2069. }
  2070. auto bfFileInstance = GetFileFromNode(astNode);
  2071. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2072. {
  2073. mCurFilePosition = bfFileInstance->mPrevPosition;
  2074. }
  2075. else
  2076. {
  2077. mCurFilePosition.mFileInstance = bfFileInstance;
  2078. mCurFilePosition.mCurLine = 0;
  2079. mCurFilePosition.mCurSrcPos = 0;
  2080. }
  2081. }
  2082. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2083. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2084. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2085. if (jumpEntry->mCharIdx > srcPos)
  2086. jumpEntry--;
  2087. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2088. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2089. mCurFilePosition.mCurColumn = 0;
  2090. while (mCurFilePosition.mCurSrcPos < srcPos)
  2091. {
  2092. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2093. {
  2094. mCurFilePosition.mCurLine++;
  2095. mCurFilePosition.mCurColumn = 0;
  2096. }
  2097. else
  2098. {
  2099. mCurFilePosition.mCurColumn++;
  2100. }
  2101. mCurFilePosition.mCurSrcPos++;
  2102. }
  2103. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2104. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2105. {
  2106. int column = mCurFilePosition.mCurColumn + 1;
  2107. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2108. {
  2109. // Set to illegal position
  2110. column = 0;
  2111. }
  2112. if (mSetIllegalSrcPosition)
  2113. column = 0;
  2114. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2115. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2116. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2117. {
  2118. // This is from a different scope...
  2119. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2120. {
  2121. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2122. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2123. }
  2124. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2125. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2126. }
  2127. else
  2128. {
  2129. if (mCurMethodState->mCurScope->mAltDIFile)
  2130. {
  2131. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2132. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2133. }
  2134. }
  2135. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2136. if (mCurMethodState->mCrossingMixin)
  2137. inlineAt = BfIRMDNode();
  2138. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2139. if ((flags & BfSrcPosFlag_Expression) == 0)
  2140. mBfIRBuilder->CreateStatementStart();
  2141. }
  2142. }
  2143. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2144. {
  2145. // We've turned off expr src pos (for now?)
  2146. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2147. }
  2148. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2149. {
  2150. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2151. SetIllegalSrcPos();
  2152. }
  2153. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2154. {
  2155. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2156. {
  2157. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2158. {
  2159. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2160. mBfIRBuilder->SetCurrentDebugLocation(0, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2161. }
  2162. else
  2163. {
  2164. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2165. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2166. }
  2167. if ((flags & BfSrcPosFlag_Expression) == 0)
  2168. mBfIRBuilder->CreateStatementStart();
  2169. }
  2170. }
  2171. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2172. {
  2173. // We've turned off expr src pos (for now?)
  2174. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2175. }
  2176. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2177. {
  2178. if ((protection == BfProtection_Public) ||
  2179. ((protection == BfProtection_Protected) && (allowProtected)) ||
  2180. ((protection == BfProtection_Private) && (allowPrivate)))
  2181. return true;
  2182. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2183. {
  2184. mAttributeState->mUsed = true;
  2185. return true;
  2186. }
  2187. if ((protection == BfProtection_Internal) && (checkType != NULL))
  2188. {
  2189. if (CheckInternalProtection(checkType))
  2190. return true;
  2191. }
  2192. return false;
  2193. }
  2194. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2195. {
  2196. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2197. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2198. {
  2199. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2200. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2201. }
  2202. allowProtected = allowPrivate;
  2203. }
  2204. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2205. {
  2206. if (memberProtection == BfProtection_Hidden)
  2207. return false;
  2208. if (memberProtection == BfProtection_Public)
  2209. return true;
  2210. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2211. {
  2212. BfTypeInstance* curCheckType = mCurTypeInstance;
  2213. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2214. {
  2215. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2216. curCheckType = mixinOwner;
  2217. }
  2218. bool allowPrivate = (curCheckType != NULL) && (memberOwner->mTypeDef == curCheckType->mTypeDef);
  2219. if (curCheckType != NULL)
  2220. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2221. if (allowPrivate)
  2222. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2223. else
  2224. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2225. }
  2226. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2227. return true;
  2228. if (memberProtection == BfProtection_Protected)
  2229. {
  2230. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2231. {
  2232. bool allowProtected = false;
  2233. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2234. auto curCheckType = mCurTypeInstance;
  2235. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2236. {
  2237. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2238. curCheckType = mixinOwner;
  2239. }
  2240. auto lookupCheckType = lookupStartType;
  2241. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2242. {
  2243. if (lookupCheckType == curCheckType)
  2244. {
  2245. allowProtected = true;
  2246. break;
  2247. }
  2248. if (lookupCheckType == memberOwner)
  2249. break;
  2250. lookupCheckType = lookupCheckType->mBaseType;
  2251. if (lookupCheckType == NULL)
  2252. break;
  2253. }
  2254. if (!allowProtected)
  2255. {
  2256. // It's possible our outer type is derived from 'memberOwner'
  2257. while (curCheckType->mTypeDef->mNestDepth > 0)
  2258. {
  2259. curCheckType = GetOuterType(curCheckType);
  2260. if (curCheckType == NULL)
  2261. break;
  2262. auto lookupCheckType = lookupStartType;
  2263. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2264. {
  2265. if (lookupCheckType == curCheckType)
  2266. {
  2267. allowProtected = true;
  2268. break;
  2269. }
  2270. if (lookupCheckType == memberOwner)
  2271. break;
  2272. lookupCheckType = lookupCheckType->mBaseType;
  2273. if (lookupCheckType == NULL)
  2274. break;
  2275. }
  2276. }
  2277. }
  2278. if (allowProtected)
  2279. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2280. else
  2281. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2282. }
  2283. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2284. return true;
  2285. }
  2286. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2287. {
  2288. mAttributeState->mUsed = true;
  2289. return true;
  2290. }
  2291. if ((memberProtection == BfProtection_Internal) && (memberOwner != NULL))
  2292. {
  2293. if (CheckInternalProtection(memberOwner->mTypeDef))
  2294. return true;
  2295. }
  2296. return false;
  2297. }
  2298. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2299. {
  2300. if ((mCompiler->mResolvePassData != NULL) &&
  2301. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2302. (astNode->IsFromParser( mCompiler->mResolvePassData->mParser)))
  2303. {
  2304. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2305. }
  2306. }
  2307. void BfModule::SetFail()
  2308. {
  2309. if (mIgnoreErrors)
  2310. {
  2311. if (mAttributeState != NULL)
  2312. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2313. }
  2314. }
  2315. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent)
  2316. {
  2317. BP_ZONE("BfModule::Fail");
  2318. if (mIgnoreErrors)
  2319. {
  2320. if (mAttributeState != NULL)
  2321. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2322. return NULL;
  2323. }
  2324. if (!mReportErrors)
  2325. {
  2326. mCompiler->mPassInstance->SilentFail();
  2327. return NULL;
  2328. }
  2329. if (refNode != NULL)
  2330. refNode = BfNodeToNonTemporary(refNode);
  2331. //BF_ASSERT(refNode != NULL);
  2332. if (mCurMethodInstance != NULL)
  2333. mCurMethodInstance->mHasFailed = true;
  2334. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2335. return NULL;
  2336. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2337. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2338. if (!mHadBuildError)
  2339. mHadBuildError = true;
  2340. if (mParentModule != NULL)
  2341. mParentModule->mHadBuildError = true;
  2342. if (mCurTypeInstance != NULL)
  2343. AddFailType(mCurTypeInstance);
  2344. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2345. String errorString = error;
  2346. bool isWhileSpecializing = false;
  2347. bool isWhileSpecializingMethod = false;
  2348. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2349. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2350. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2351. errorString += StrFormat("\n while generating append size calculating method");
  2352. else if (refNode == NULL)
  2353. {
  2354. if (mCurTypeInstance != NULL)
  2355. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2356. else if (mProject != NULL)
  2357. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2358. }
  2359. if (mCurTypeInstance != NULL)
  2360. {
  2361. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2362. {
  2363. // Propogatea the fail all the way to the main method (assuming we're in a local method or lambda)
  2364. methodInstance->mHasFailed = true;
  2365. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2366. if (isSpecializedMethod)
  2367. {
  2368. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2369. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2370. if (unspecializedMethod->mHasFailed)
  2371. return false; // At least SOME error has already been reported
  2372. }
  2373. if (isSpecializedMethod)
  2374. {
  2375. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2376. isWhileSpecializing = true;
  2377. isWhileSpecializingMethod = true;
  2378. }
  2379. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2380. {
  2381. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2382. isWhileSpecializing = true;
  2383. isWhileSpecializingMethod = true;
  2384. }
  2385. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2386. {
  2387. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2388. isWhileSpecializing = true;
  2389. }
  2390. return true;
  2391. };
  2392. if (mCurMethodState != NULL)
  2393. {
  2394. auto checkMethodState = mCurMethodState;
  2395. while (checkMethodState != NULL)
  2396. {
  2397. auto methodInstance = checkMethodState->mMethodInstance;
  2398. if (methodInstance == NULL)
  2399. {
  2400. checkMethodState = checkMethodState->mPrevMethodState;
  2401. continue;
  2402. }
  2403. if (!_CheckMethodInstance(methodInstance))
  2404. return NULL;
  2405. checkMethodState = checkMethodState->mPrevMethodState;
  2406. }
  2407. }
  2408. else if (mCurMethodInstance != NULL)
  2409. {
  2410. if (!_CheckMethodInstance(mCurMethodInstance))
  2411. return NULL;
  2412. }
  2413. // Keep in mind that all method specializations with generic type instances as its method generic params
  2414. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2415. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2416. // those method specializations if that occurs
  2417. if (isWhileSpecializing)
  2418. {
  2419. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2420. if (bfError != NULL)
  2421. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2422. return bfError;
  2423. }
  2424. }
  2425. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2426. {
  2427. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2428. isWhileSpecializing = true;
  2429. }
  2430. if (!mHadBuildError)
  2431. mHadBuildError = true;
  2432. // Check mixins
  2433. {
  2434. auto checkMethodInstance = mCurMethodState;
  2435. while (checkMethodInstance != NULL)
  2436. {
  2437. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2438. if (rootMixinState != NULL)
  2439. {
  2440. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2441. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2442. auto mixinState = checkMethodInstance->mMixinState;
  2443. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2444. {
  2445. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2446. mixinState = mixinState->mPrevMixinState;
  2447. }
  2448. return bfError;
  2449. }
  2450. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2451. }
  2452. }
  2453. BfError* bfError = NULL;
  2454. if (refNode == NULL)
  2455. bfError = mCompiler->mPassInstance->Fail(errorString);
  2456. else
  2457. {
  2458. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2459. }
  2460. if (bfError != NULL)
  2461. {
  2462. bfError->mProject = mProject;
  2463. bfError->mIsPersistent = isPersistent;
  2464. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2465. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2466. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2467. }
  2468. return bfError;
  2469. }
  2470. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2471. {
  2472. if (mHadBuildError)
  2473. return NULL;
  2474. return Fail(error, refNode);
  2475. }
  2476. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2477. {
  2478. if (mIgnoreErrors)
  2479. return NULL;
  2480. if (refNode != NULL)
  2481. refNode = BfNodeToNonTemporary(refNode);
  2482. mHadBuildError = true;
  2483. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2484. if (bfError != NULL)
  2485. bfError->mProject = mProject;
  2486. return bfError;
  2487. }
  2488. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2489. {
  2490. if (mIgnoreErrors || mIgnoreWarnings)
  2491. return NULL;
  2492. if (!mReportErrors)
  2493. {
  2494. mCompiler->mPassInstance->SilentFail();
  2495. return NULL;
  2496. }
  2497. BfAstNode* unwarnNode = refNode;
  2498. //
  2499. {
  2500. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2501. while (parentNodeEntry != NULL)
  2502. {
  2503. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2504. break;
  2505. unwarnNode = parentNodeEntry->mNode;
  2506. parentNodeEntry = parentNodeEntry->mPrev;
  2507. }
  2508. }
  2509. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2510. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2511. {
  2512. return NULL;
  2513. }
  2514. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2515. if (mCurMethodInstance != NULL)
  2516. {
  2517. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2518. return NULL;
  2519. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2520. return NULL; // No ctorCalcAppend warnings
  2521. }
  2522. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2523. return NULL;
  2524. if (refNode != NULL)
  2525. refNode = BfNodeToNonTemporary(refNode);
  2526. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2527. {
  2528. // We used to bubble up warnings into the mixin injection site, BUT
  2529. // we are now assuming any relevant warnings will be given at the declaration site
  2530. return NULL;
  2531. }
  2532. BfError* bfError;
  2533. if (refNode != NULL)
  2534. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2535. else
  2536. bfError = mCompiler->mPassInstance->Warn(warningNum, warning);
  2537. if (bfError != NULL)
  2538. {
  2539. bfError->mProject = mProject;
  2540. AddFailType(mCurTypeInstance);
  2541. mHadBuildWarning = true;
  2542. bfError->mIsPersistent = isPersistent;
  2543. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2544. {
  2545. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2546. if (parser != NULL)
  2547. {
  2548. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2549. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2550. if (warningNum != 0)
  2551. {
  2552. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  2553. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  2554. }
  2555. }
  2556. }
  2557. }
  2558. return bfError;
  2559. }
  2560. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  2561. {
  2562. auto _AddDeclarationMoreInfo = [&]()
  2563. {
  2564. if (methodInstance != NULL)
  2565. {
  2566. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  2567. mCompiler->mPassInstance->MoreInfo(
  2568. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  2569. methodInstance->mMethodDef->GetRefNode());
  2570. }
  2571. else
  2572. {
  2573. mCompiler->mPassInstance->MoreInfo(
  2574. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  2575. typeInstance->mTypeDef->GetRefNode());
  2576. }
  2577. };
  2578. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  2579. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  2580. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2581. {
  2582. String err;
  2583. if (methodInstance != NULL)
  2584. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  2585. else
  2586. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2587. bool isError = false;
  2588. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  2589. if (constant->mTypeCode == BfTypeCode_Boolean)
  2590. {
  2591. isError = constant->mBool;
  2592. }
  2593. else if (customAttribute->mCtorArgs.size() >= 2)
  2594. {
  2595. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2596. if (str != NULL)
  2597. {
  2598. err += ":\n '";
  2599. err += *str;
  2600. err += "'";
  2601. }
  2602. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  2603. isError = constant->mBool;
  2604. }
  2605. BfError* error = NULL;
  2606. if (isError)
  2607. error = Fail(err, targetSrc);
  2608. else
  2609. error = Warn(0, err, targetSrc);
  2610. if (error != NULL)
  2611. _AddDeclarationMoreInfo();
  2612. }
  2613. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  2614. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2615. {
  2616. String err;
  2617. if (methodInstance != NULL)
  2618. StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  2619. else
  2620. StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2621. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2622. if (str != NULL)
  2623. err += *str;
  2624. err += "'";
  2625. if (Fail(err, targetSrc) != NULL)
  2626. _AddDeclarationMoreInfo();
  2627. }
  2628. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  2629. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2630. {
  2631. String err;
  2632. if (methodInstance != NULL)
  2633. StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  2634. else
  2635. StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2636. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2637. if (str != NULL)
  2638. err += *str;
  2639. err += "'";
  2640. if (Warn(0, err, targetSrc) != NULL)
  2641. _AddDeclarationMoreInfo();
  2642. }
  2643. }
  2644. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2645. {
  2646. if (mBfIRBuilder->mOpFailed)
  2647. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2648. }
  2649. void BfModule::FatalError(const StringImpl& error, const char* file, int line)
  2650. {
  2651. static bool sHadFatalError = false;
  2652. static bool sHadReentrancy = false;
  2653. if (sHadFatalError)
  2654. {
  2655. return;
  2656. sHadReentrancy = true;
  2657. }
  2658. sHadFatalError = true;
  2659. String fullError = error;
  2660. if (file != NULL)
  2661. fullError += StrFormat(" at %s:%d", file, line);
  2662. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  2663. if (mCurTypeInstance != NULL)
  2664. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  2665. if (mCurMethodInstance != NULL)
  2666. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  2667. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  2668. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  2669. if (sHadReentrancy)
  2670. fullError += "\nError had reentrancy";
  2671. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  2672. }
  2673. void BfModule::NotImpl(BfAstNode* astNode)
  2674. {
  2675. Fail("INTERNAL ERROR: Not implemented", astNode);
  2676. }
  2677. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  2678. {
  2679. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2680. if (!allowPrivate)
  2681. allowPrivate |= memberType->IsInterface();
  2682. bool allowProtected = allowPrivate;
  2683. //TODO: We had this commented out, but this makes accessing protected properties fail
  2684. if (mCurTypeInstance != NULL)
  2685. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2686. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  2687. {
  2688. return false;
  2689. }
  2690. return true;
  2691. }
  2692. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2693. {
  2694. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2695. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2696. auto memberTypeInstance = memberType->ToTypeInstance();
  2697. if (memberTypeInstance == NULL)
  2698. {
  2699. auto underlyingType = memberType->GetUnderlyingType();
  2700. if (underlyingType != NULL)
  2701. return CheckDefineMemberProtection(protection, underlyingType);
  2702. return true;
  2703. }
  2704. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2705. return false;
  2706. if (memberTypeInstance->IsGenericTypeInstance())
  2707. {
  2708. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2709. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  2710. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2711. {
  2712. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2713. return false;
  2714. }
  2715. }
  2716. return true;
  2717. }
  2718. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags)
  2719. {
  2720. if (usedType == userType)
  2721. return;
  2722. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2723. {
  2724. if (userType->IsMethodRef())
  2725. {
  2726. // We cannot short-circuit dependencies because of method group ref counting
  2727. }
  2728. else
  2729. return;
  2730. }
  2731. if (usedType->IsSpecializedByAutoCompleteMethod())
  2732. return;
  2733. // if (usedType->IsBoxed())
  2734. // {
  2735. // NOP;
  2736. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  2737. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  2738. // {
  2739. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  2740. // }
  2741. // }
  2742. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  2743. // BfType* origUsedType = usedType;
  2744. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  2745. // if (isDataAccess)
  2746. // {
  2747. // while (true)
  2748. // {
  2749. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  2750. // usedType = usedType->GetUnderlyingType();
  2751. // else if (usedType->IsArray())
  2752. // {
  2753. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  2754. // }
  2755. // else
  2756. // break;
  2757. // }
  2758. // }
  2759. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  2760. {
  2761. bool addType = true;
  2762. auto checkType = usedType;
  2763. PopulateType(checkType, BfPopulateType_Data);
  2764. if (checkType->IsValuelessType())
  2765. addType = false;
  2766. else if (checkType->IsPrimitiveType())
  2767. addType = false;
  2768. else
  2769. {
  2770. auto checkTypeInst = checkType->ToTypeInstance();
  2771. if (checkTypeInst == NULL)
  2772. {
  2773. addType = false;
  2774. }
  2775. else
  2776. {
  2777. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2778. addType = false;
  2779. }
  2780. }
  2781. if (addType)
  2782. {
  2783. auto checkTypeInst = checkType->ToTypeInstance();
  2784. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2785. BF_ASSERT(hotTypeVersion != NULL);
  2786. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2787. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2788. (checkType->IsComposite()))
  2789. isAllocation = true;
  2790. if (isAllocation)
  2791. {
  2792. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2793. }
  2794. else
  2795. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2796. }
  2797. }
  2798. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2799. {
  2800. auto usingModule = userType->GetModule();
  2801. BfModule* usedModule;
  2802. if (usedType->IsFunction())
  2803. {
  2804. auto typeInst = usedType->ToTypeInstance();
  2805. if (typeInst->mBaseType == NULL)
  2806. PopulateType(typeInst);
  2807. usedModule = typeInst->mBaseType->GetModule();
  2808. }
  2809. else
  2810. usedModule = usedType->GetModule();
  2811. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2812. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2813. {
  2814. usingModule->mModuleRefs.Add(usedModule);
  2815. }
  2816. }
  2817. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2818. {
  2819. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2820. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2821. if (genericArg == usedType)
  2822. return;
  2823. }
  2824. auto depFlag = flags;
  2825. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  2826. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef; // Will cause a rebuild but not an outright deletion of the type
  2827. auto underlyingType = usedType->GetUnderlyingType();
  2828. if (underlyingType != NULL)
  2829. AddDependency(underlyingType, userType, depFlag);
  2830. BfDependedType* checkDType = usedType->ToDependedType();
  2831. if (checkDType == NULL)
  2832. return;
  2833. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2834. mContext->MarkAsReferenced(checkDType);
  2835. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  2836. return;
  2837. if (checkDType->IsGenericTypeInstance())
  2838. {
  2839. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  2840. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2841. {
  2842. AddDependency(genericArg, userType, depFlag);
  2843. }
  2844. }
  2845. if (checkDType->IsTuple())
  2846. {
  2847. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  2848. {
  2849. if (field.mDataIdx != -1)
  2850. AddDependency(field.mResolvedType, userType, depFlag);
  2851. }
  2852. }
  2853. }
  2854. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  2855. {
  2856. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  2857. {
  2858. if (methodInstance->mHotMethod == NULL)
  2859. CheckHotMethod(methodInstance, "");
  2860. BF_ASSERT(methodInstance->mHotMethod != NULL);
  2861. if (devirtualized)
  2862. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  2863. else
  2864. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  2865. }
  2866. }
  2867. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  2868. {
  2869. auto checkTypeInst = typeInst;
  2870. while (checkTypeInst != NULL)
  2871. {
  2872. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  2873. return true;
  2874. checkTypeInst = checkTypeInst->mBaseType;
  2875. }
  2876. return false;
  2877. }
  2878. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  2879. {
  2880. if (mContext->mCurTypeState == NULL)
  2881. return;
  2882. BP_ZONE("PopulateGlobalContainersList");
  2883. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  2884. if ((userTypeDef == NULL) && (mCurMethodInstance != NULL))
  2885. userTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  2886. if (userTypeDef == NULL)
  2887. userTypeDef = mCurTypeInstance->mTypeDef;
  2888. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  2889. {
  2890. mContext->mCurTypeState->mGlobalContainers.Clear();
  2891. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  2892. {
  2893. BfAtomComposite findStr;
  2894. if (namespaceIdx != -1)
  2895. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  2896. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  2897. while (typeDefItr)
  2898. {
  2899. auto typeDef = *typeDefItr;
  2900. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  2901. {
  2902. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  2903. {
  2904. BfGlobalContainerEntry globalEntry;
  2905. globalEntry.mTypeDef = typeDef;
  2906. globalEntry.mTypeInst = NULL;
  2907. typeDef->PopulateMemberSets();
  2908. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  2909. }
  2910. }
  2911. else if (!typeDef->mIsPartial)
  2912. {
  2913. //break;
  2914. }
  2915. typeDefItr.MoveToNextHashMatch();
  2916. }
  2917. }
  2918. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  2919. }
  2920. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  2921. // reifing types
  2922. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  2923. {
  2924. if (globalEntry.mTypeInst == NULL)
  2925. {
  2926. bool include = false;
  2927. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  2928. include = true;
  2929. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  2930. {
  2931. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  2932. include = true;
  2933. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  2934. include = true;
  2935. }
  2936. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  2937. {
  2938. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  2939. include = true;
  2940. }
  2941. if (include)
  2942. {
  2943. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  2944. if (type != NULL)
  2945. globalEntry.mTypeInst = type->ToTypeInstance();
  2946. }
  2947. }
  2948. }
  2949. }
  2950. BfStaticSearch* BfModule::GetStaticSearch()
  2951. {
  2952. auto activeTypeDef = GetActiveTypeDef();
  2953. BfStaticSearch* staticSearch = NULL;
  2954. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  2955. return staticSearch;
  2956. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  2957. return staticSearch;
  2958. return NULL;
  2959. }
  2960. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  2961. {
  2962. auto activeTypeDef = GetActiveTypeDef();
  2963. BfInternalAccessSet* internalAccessSet = NULL;
  2964. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  2965. return internalAccessSet;
  2966. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  2967. return internalAccessSet;
  2968. return NULL;
  2969. }
  2970. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  2971. {
  2972. auto internalAccessSet = GetInternalAccessSet();
  2973. if (internalAccessSet == NULL)
  2974. return false;
  2975. for (auto& nameComposite : internalAccessSet->mNamespaces)
  2976. {
  2977. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  2978. return true;
  2979. }
  2980. for (auto internalType : internalAccessSet->mTypes)
  2981. {
  2982. auto checkTypeDef = usingTypeDef;
  2983. while (checkTypeDef != NULL)
  2984. {
  2985. if (checkTypeDef == internalType->mTypeDef)
  2986. return true;
  2987. checkTypeDef = checkTypeDef->mOuterType;
  2988. }
  2989. }
  2990. return false;
  2991. }
  2992. void PrintUsers(llvm::MDNode* md);
  2993. BfModuleOptions BfModule::GetModuleOptions()
  2994. {
  2995. if (mIsScratchModule)
  2996. return BfModuleOptions();
  2997. if (mModuleOptions != NULL)
  2998. return *mModuleOptions;
  2999. BfModuleOptions moduleOptions;
  3000. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3001. if (mProject != NULL)
  3002. {
  3003. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3004. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3005. }
  3006. auto headModule = this;
  3007. while (headModule->mParentModule != NULL)
  3008. headModule = headModule->mParentModule;
  3009. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata"));
  3010. if (headModule->mOwnedTypeInstances.size() > 0)
  3011. {
  3012. auto typeInst = headModule->mOwnedTypeInstances[0];
  3013. PopulateType(typeInst);
  3014. if (typeInst->mTypeOptionsIdx != -1)
  3015. {
  3016. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3017. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3018. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3019. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3020. }
  3021. }
  3022. return moduleOptions;
  3023. }
  3024. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3025. {
  3026. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3027. return BfCheckedKind_Unchecked;
  3028. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3029. auto typeOptions = GetTypeOptions();
  3030. if (typeOptions != NULL)
  3031. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3032. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3033. }
  3034. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3035. {
  3036. BF_ASSERT(typeInstance != NULL);
  3037. mContext->mFailTypes.Add(typeInstance);
  3038. }
  3039. void BfModule::CheckAddFailType()
  3040. {
  3041. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3042. // but we still need to add the owning type to the FailTypes list
  3043. //.. OLD:
  3044. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3045. /*if (mCurTypeInstance->mModule != this)
  3046. return;*/
  3047. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3048. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3049. // being recompiled. This forces types with warnings to be recompiled.
  3050. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3051. // constantly warning-aware
  3052. if ((mHadBuildError) ||
  3053. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3054. {
  3055. //mContext->mFailTypes.Add(mCurTypeInstance);
  3056. }
  3057. }
  3058. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3059. {
  3060. if (!mCompiler->IsHotCompile())
  3061. return;
  3062. typeInst->mDirty = true;
  3063. for (auto& dep : typeInst->mDependencyMap)
  3064. {
  3065. auto depType = dep.mKey;
  3066. auto depFlags = dep.mValue.mFlags;
  3067. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3068. {
  3069. MarkDerivedDirty(depType->ToTypeInstance());
  3070. }
  3071. }
  3072. }
  3073. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3074. {
  3075. auto fieldType = fieldInstance->GetResolvedType();
  3076. auto field = fieldInstance->GetFieldDef();
  3077. if (fieldType->IsVar())
  3078. return;
  3079. BfIRValue initValue;
  3080. if (field->mIsConst)
  3081. {
  3082. if (fieldType->IsPointer())
  3083. fieldType = fieldType->GetUnderlyingType();
  3084. }
  3085. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3086. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3087. storageKind = BfIRStorageKind_Export;
  3088. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3089. storageKind = BfIRStorageKind_Import;
  3090. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3091. initValue = GetDefaultValue(fieldType);
  3092. if (fieldInstance->mOwner->IsUnspecializedType())
  3093. {
  3094. // Placeholder
  3095. auto ptrVal = CreatePointerType(fieldType);
  3096. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3097. }
  3098. else
  3099. {
  3100. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3101. StringT<128> staticVarName;
  3102. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3103. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3104. {
  3105. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3106. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  3107. false,
  3108. BfIRLinkageType_External,
  3109. initValue,
  3110. staticVarName,
  3111. isThreadLocal);
  3112. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3113. if (storageKind != BfIRStorageKind_Normal)
  3114. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3115. BF_ASSERT(globalVar);
  3116. mStaticFieldRefs[fieldInstance] = globalVar;
  3117. }
  3118. }
  3119. }
  3120. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3121. {
  3122. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3123. BfType* fieldType = NULL;
  3124. if (fieldInstance != NULL)
  3125. {
  3126. fieldType = fieldInstance->GetResolvedType();
  3127. if (fieldType == NULL)
  3128. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3129. }
  3130. else
  3131. {
  3132. BF_ASSERT(mCompiler->IsAutocomplete());
  3133. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3134. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3135. {
  3136. fieldType = typeInstance;
  3137. }
  3138. else
  3139. {
  3140. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3141. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3142. if (isLet || isVar)
  3143. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3144. else
  3145. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3146. if (fieldType == NULL)
  3147. fieldType = mContext->mBfObjectType;
  3148. }
  3149. }
  3150. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3151. return;
  3152. if (mContext->mFieldResolveReentrys.size() > 1)
  3153. {
  3154. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3155. {
  3156. String failStr = "Circular data reference detected between the following fields:";
  3157. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3158. {
  3159. if (i > 1)
  3160. failStr += ",";
  3161. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3162. }
  3163. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3164. if (err)
  3165. err->mIsPersistent = true;
  3166. return;
  3167. }
  3168. }
  3169. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3170. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3171. if (fieldInstance == NULL)
  3172. popTypeResolveReentry.Pop();
  3173. auto typeDef = typeInstance->mTypeDef;
  3174. BfIRValue constValue;
  3175. if (fieldDef->mIsExtern)
  3176. {
  3177. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3178. {
  3179. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3180. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  3181. }
  3182. if (fieldDef->mInitializer != NULL)
  3183. {
  3184. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3185. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  3186. }
  3187. }
  3188. else if (fieldDef->mInitializer == NULL)
  3189. {
  3190. if (fieldDef->IsEnumCaseEntry())
  3191. {
  3192. if (typeInstance->IsTypedPrimitive())
  3193. {
  3194. BfFieldInstance* prevFieldInstance = NULL;
  3195. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3196. {
  3197. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3198. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3199. {
  3200. prevFieldInstance = checkFieldInst;
  3201. break;
  3202. }
  3203. }
  3204. if (prevFieldInstance == NULL)
  3205. constValue = GetConstValue(0, typeInstance);
  3206. else
  3207. {
  3208. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3209. if (prevFieldInstance->mConstIdx == -1)
  3210. {
  3211. if (!mCompiler->IsAutocomplete())
  3212. AssertErrorState();
  3213. constValue = GetConstValue(0, typeInstance);
  3214. }
  3215. else
  3216. {
  3217. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3218. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3219. }
  3220. }
  3221. }
  3222. }
  3223. else
  3224. {
  3225. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  3226. }
  3227. }
  3228. else if (mBfIRBuilder != NULL)
  3229. {
  3230. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3231. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3232. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3233. BfMethodState methodState;
  3234. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3235. methodState.mTempKind = BfMethodState::TempKind_Static;
  3236. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3237. if (fieldType->IsVar())
  3238. {
  3239. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  3240. if (!initValue)
  3241. {
  3242. AssertErrorState();
  3243. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3244. }
  3245. if (fieldInstance != NULL)
  3246. {
  3247. fieldInstance->mResolvedType = initValue.mType;
  3248. }
  3249. constValue = initValue.mValue;
  3250. }
  3251. else
  3252. {
  3253. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  3254. constValue = uncastedInitValue.mValue;
  3255. }
  3256. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3257. {
  3258. // Illegal
  3259. constValue = BfIRValue();
  3260. }
  3261. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3262. }
  3263. if (fieldInstance != NULL)
  3264. {
  3265. fieldType = fieldInstance->GetResolvedType();
  3266. if ((fieldType == NULL) || (fieldType->IsVar()))
  3267. {
  3268. AssertErrorState();
  3269. // Default const type is 'int'
  3270. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3271. if (fieldInstance != NULL)
  3272. {
  3273. fieldInstance->mResolvedType = initValue.mType;
  3274. }
  3275. constValue = initValue.mValue;
  3276. }
  3277. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3278. {
  3279. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3280. CurrentAddToConstHolder(constValue);
  3281. fieldInstance->mConstIdx = constValue.mId;
  3282. }
  3283. }
  3284. }
  3285. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3286. {
  3287. bool isDeclType = BfNodeDynCastExact<BfDeclTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  3288. auto fieldType = fieldInstance->GetResolvedType();
  3289. if ((field->mIsConst) && (!isDeclType))
  3290. {
  3291. ResolveConstField(typeInstance, fieldInstance, field);
  3292. return fieldInstance->GetResolvedType();
  3293. }
  3294. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3295. if (!fieldInstance->mIsInferredType)
  3296. return fieldType;
  3297. if (!fieldType->IsVar())
  3298. return fieldType;
  3299. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3300. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3301. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mTypeInstance != typeInstance);
  3302. auto typeDef = typeInstance->mTypeDef;
  3303. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3304. {
  3305. AssertErrorState();
  3306. return GetPrimitiveType(BfTypeCode_Var);
  3307. }
  3308. bool hadInferenceCycle = false;
  3309. if (mContext->mFieldResolveReentrys.size() > 1)
  3310. {
  3311. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3312. {
  3313. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3314. {
  3315. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3316. auto fieldDef = fieldInst->GetFieldDef();
  3317. auto fieldOwner = fieldInst->mOwner;
  3318. auto fieldModule = fieldOwner->mModule;
  3319. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3320. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3321. }
  3322. return GetPrimitiveType(BfTypeCode_Var);
  3323. }
  3324. }
  3325. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3326. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3327. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3328. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3329. if ((field->mInitializer == NULL) && (!isDeclType))
  3330. {
  3331. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3332. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3333. return GetPrimitiveType(BfTypeCode_Var);
  3334. }
  3335. BfType* resolvedType = NULL;
  3336. if (!hadInferenceCycle)
  3337. {
  3338. BfTypeState typeState;
  3339. typeState.mPrevState = mContext->mCurTypeState;
  3340. typeState.mTypeInstance = typeInstance;
  3341. typeState.mCurFieldDef = field;
  3342. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3343. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3344. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3345. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3346. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3347. BfMethodState methodState;
  3348. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3349. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3350. if (!staticOnly)
  3351. {
  3352. //BfLocalVariable localVar;
  3353. //methodState.mLocals.push_back(localVar);
  3354. }
  3355. if (isDeclType)
  3356. {
  3357. auto fieldDef = fieldInstance->GetFieldDef();
  3358. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3359. }
  3360. else
  3361. {
  3362. BfTypedValue valueFromExpr;
  3363. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3364. FixIntUnknown(valueFromExpr);
  3365. resolvedType = valueFromExpr.mType;
  3366. }
  3367. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3368. }
  3369. if (resolvedType == NULL)
  3370. return GetPrimitiveType(BfTypeCode_Var);
  3371. fieldInstance->SetResolvedType(resolvedType);
  3372. if (field->mIsStatic)
  3373. {
  3374. }
  3375. else if (fieldInstance->mDataIdx >= 0)
  3376. {
  3377. }
  3378. else
  3379. {
  3380. BF_ASSERT(typeInstance->IsIncomplete());
  3381. }
  3382. return resolvedType;
  3383. }
  3384. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3385. {
  3386. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3387. auto fieldType = fieldInstance->GetResolvedType();
  3388. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3389. {
  3390. int fieldIdx = 0;
  3391. int fieldCount = 0;
  3392. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  3393. fieldIdx--;
  3394. int count = fieldCount;
  3395. if (fieldIdx == -1)
  3396. count = 1;
  3397. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3398. auto thisVariable = GetThisVariable();
  3399. if (thisVariable != NULL)
  3400. {
  3401. for (int i = 0; i < count; i++)
  3402. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  3403. }
  3404. }
  3405. }
  3406. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3407. {
  3408. if (fieldInstance->mCustomAttributes == NULL)
  3409. return false;
  3410. auto fieldDef = fieldInstance->GetFieldDef();
  3411. if (!fieldDef->mIsStatic)
  3412. return false;
  3413. bool isThreadLocal = false;
  3414. if (fieldInstance->mCustomAttributes != NULL)
  3415. {
  3416. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3417. {
  3418. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  3419. return true;
  3420. }
  3421. }
  3422. return false;
  3423. }
  3424. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  3425. {
  3426. if (fieldDef == NULL)
  3427. fieldDef = fieldInstance->GetFieldDef();
  3428. if (fieldType == NULL)
  3429. fieldType = fieldInstance->GetResolvedType();
  3430. if (initializer == NULL)
  3431. {
  3432. if (fieldDef == NULL)
  3433. return BfTypedValue();
  3434. initializer = fieldDef->mInitializer;
  3435. }
  3436. BfTypedValue staticVarRef;
  3437. BfTypedValue result;
  3438. if (initializer == NULL)
  3439. {
  3440. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3441. }
  3442. else
  3443. {
  3444. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3445. {
  3446. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3447. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3448. }
  3449. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3450. {
  3451. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3452. BfConstResolver constResolver(this);
  3453. constResolver.Resolve(initializer);
  3454. return GetDefaultTypedValue(fieldType);
  3455. }
  3456. else if (fieldDef->mIsConst)
  3457. {
  3458. BfTypeState typeState;
  3459. typeState.mTypeInstance = mCurTypeInstance;
  3460. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3461. typeState.mCurFieldDef = fieldDef;
  3462. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3463. BfConstResolver constResolver(this);
  3464. if (fieldType->IsVar())
  3465. return constResolver.Resolve(initializer);
  3466. else
  3467. {
  3468. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  3469. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  3470. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  3471. {
  3472. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  3473. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  3474. resolveFlags = BfConstResolveFlag_NoCast;
  3475. }
  3476. UpdateSrcPos(initializer);
  3477. return constResolver.Resolve(initializer, fieldType, resolveFlags);
  3478. }
  3479. }
  3480. BfExprEvaluator exprEvaluator(this);
  3481. if (doStore)
  3482. {
  3483. staticVarRef = ReferenceStaticField(fieldInstance);
  3484. exprEvaluator.mReceivingValue = &staticVarRef;
  3485. }
  3486. if (fieldType->IsVar())
  3487. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3488. else
  3489. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3490. if (doStore)
  3491. {
  3492. if (exprEvaluator.mReceivingValue == NULL)
  3493. doStore = false; // Already stored
  3494. }
  3495. }
  3496. if (fieldInstance != NULL)
  3497. MarkFieldInitialized(fieldInstance);
  3498. if ((doStore) && (result))
  3499. {
  3500. result = LoadValue(result);
  3501. if (!result.mType->IsValuelessType())
  3502. mBfIRBuilder->CreateStore(result.mValue, staticVarRef.mValue);
  3503. }
  3504. return result;
  3505. }
  3506. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3507. {
  3508. }
  3509. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3510. {
  3511. PopulateType(classType);
  3512. if (isInterfacePass)
  3513. {
  3514. for (auto ifaceInst : classType->mInterfaces)
  3515. {
  3516. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3517. continue;
  3518. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3519. continue;
  3520. if (ifaceInst.mDeclaringType->IsExtension())
  3521. {
  3522. bool needsExCheck = false;
  3523. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3524. {
  3525. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  3526. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  3527. {
  3528. exChecks->push_back(ifaceInst.mInterfaceType);
  3529. continue;
  3530. }
  3531. else
  3532. {
  3533. // We can only do an 'exCheck' if we're actually going to slot this interface
  3534. }
  3535. }
  3536. }
  3537. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3538. }
  3539. }
  3540. else
  3541. {
  3542. outVals->push_back(classType->mTypeId);
  3543. }
  3544. if (classType->mBaseType != NULL)
  3545. {
  3546. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3547. }
  3548. }
  3549. void BfModule::CreateDynamicCastMethod()
  3550. {
  3551. auto objType = mContext->mBfObjectType;
  3552. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3553. {
  3554. // The main reason to punt on this method for ResolveOnly is because types can be created
  3555. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3556. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3557. // remove this punt when we recycle typeId's
  3558. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3559. mCurMethodState->mHadReturn = true;
  3560. return;
  3561. }
  3562. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3563. auto func = mCurMethodState->mIRFunction;
  3564. auto thisValue = mBfIRBuilder->GetArgument(0);
  3565. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3566. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3567. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3568. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3569. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3570. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3571. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3572. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3573. SizedArray<int, 8> typeMatches;
  3574. SizedArray<BfTypeInstance*, 8> exChecks;
  3575. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3576. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3577. {
  3578. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3579. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3580. BfTypeVector genericArgs;
  3581. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3582. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3583. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3584. typeMatches.push_back(unboundType->mTypeId);
  3585. }
  3586. if (mCurTypeInstance->IsBoxed())
  3587. {
  3588. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3589. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  3590. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3591. if (innerType->IsTypedPrimitive())
  3592. {
  3593. auto underlyingType = innerType->GetUnderlyingType();
  3594. typeMatches.push_back(underlyingType->mTypeId);
  3595. }
  3596. auto innerTypeInst = innerType->ToTypeInstance();
  3597. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3598. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3599. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3600. {
  3601. PopulateType(innerTypeInst);
  3602. //TODO: What case was this supposed to handle?
  3603. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3604. }
  3605. }
  3606. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3607. BfIRValue vDataPtr;
  3608. if (!exChecks.empty())
  3609. {
  3610. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3611. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3612. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3613. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3614. }
  3615. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3616. for (auto typeMatch : typeMatches)
  3617. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3618. Array<BfIRValue> incomingFalses;
  3619. for (auto ifaceTypeInst : exChecks)
  3620. {
  3621. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3622. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3623. mBfIRBuilder->SetInsertPoint(nextBB);
  3624. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3625. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3626. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3627. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3628. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3629. incomingFalses.push_back(nextBB);
  3630. }
  3631. mBfIRBuilder->AddBlock(trueBB);
  3632. mBfIRBuilder->SetInsertPoint(trueBB);
  3633. mBfIRBuilder->CreateBr(exitBB);
  3634. mBfIRBuilder->AddBlock(exitBB);
  3635. mBfIRBuilder->SetInsertPoint(exitBB);
  3636. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3637. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3638. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3639. for (auto incomingFalseBlock : incomingFalses)
  3640. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3641. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3642. mBfIRBuilder->CreateRet(phi);
  3643. mCurMethodState->mHadReturn = true;
  3644. }
  3645. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  3646. {
  3647. BfExprEvaluator exprEvaluator(this);
  3648. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3649. auto typeInst = rightValue.mType->ToTypeInstance();
  3650. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  3651. BfTypedValue result = exprEvaluator.GetResult();
  3652. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  3653. {
  3654. // Fail?
  3655. }
  3656. if ((result) && (!result.mType->IsVar()))
  3657. {
  3658. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3659. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3660. mBfIRBuilder->AddBlock(nextBB);
  3661. mBfIRBuilder->SetInsertPoint(nextBB);
  3662. }
  3663. }
  3664. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3665. {
  3666. if (mCurMethodInstance->mHasFailed)
  3667. return;
  3668. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  3669. return;
  3670. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3671. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3672. SizedArray<BfIRType, 4> paramTypes;
  3673. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3674. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3675. mBfIRBuilder->SetActiveFunction(func);
  3676. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3677. mBfIRBuilder->SetInsertPoint(entryBlock);
  3678. BfMethodState methodState;
  3679. methodState.mIRHeadBlock = entryBlock;
  3680. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3681. SizedArray<BfIRValue, 8> args;
  3682. BfExprEvaluator exprEvaluator(this);
  3683. if (mCurMethodInstance->GetStructRetIdx() == 0)
  3684. {
  3685. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  3686. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  3687. }
  3688. if (mCurMethodInstance->HasThis())
  3689. {
  3690. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  3691. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3692. }
  3693. if (mCurMethodInstance->GetStructRetIdx() == 1)
  3694. {
  3695. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  3696. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  3697. }
  3698. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3699. {
  3700. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3701. if (paramType->IsValuelessType())
  3702. continue;
  3703. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  3704. }
  3705. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3706. mBfIRBuilder->CreateRetVoid();
  3707. }
  3708. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  3709. {
  3710. if (mCurMethodInstance->mIsUnspecialized)
  3711. return;
  3712. if (mBfIRBuilder->mIgnoreWrites)
  3713. return;
  3714. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3715. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3716. bool isValid = true;
  3717. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3718. if (compareType->IsValuelessType())
  3719. {
  3720. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3721. return;
  3722. }
  3723. if (compareType->IsTypedPrimitive())
  3724. {
  3725. BfExprEvaluator exprEvaluator(this);
  3726. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  3727. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  3728. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  3729. mBfIRBuilder->CreateRet(cmpResult);
  3730. return;
  3731. }
  3732. auto compareDType = compareType->ToDependedType();
  3733. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3734. if (compareTypeInst != NULL)
  3735. {
  3736. if (compareType->IsPrimitiveType())
  3737. compareTypeInst = GetWrappedStructType(compareType);
  3738. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3739. {
  3740. isValid = false;
  3741. }
  3742. mBfIRBuilder->PopulateType(compareTypeInst);
  3743. }
  3744. if (!isValid)
  3745. {
  3746. ClearLifetimeEnds();
  3747. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3748. return;
  3749. }
  3750. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3751. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3752. if (refNode == NULL)
  3753. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3754. UpdateSrcPos(refNode);
  3755. SetIllegalSrcPos();
  3756. auto resultVal = CreateAlloca(boolType);
  3757. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3758. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3759. if (compareType->IsValuelessType())
  3760. {
  3761. // Always equal, nothing to do
  3762. }
  3763. else if (compareType->IsSizedArray())
  3764. {
  3765. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3766. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  3767. {
  3768. BfTypedValue result;
  3769. if (sizedArrayType->mElementType->IsSizeAligned())
  3770. {
  3771. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  3772. auto ptrValue = mBfIRBuilder->CreateBitCast(target, mBfIRBuilder->MapType(ptrType));
  3773. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, index);
  3774. result = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3775. }
  3776. else
  3777. {
  3778. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index);
  3779. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3780. }
  3781. if (!result.mType->IsValueType())
  3782. result = LoadValue(result);
  3783. return result;
  3784. };
  3785. if (sizedArrayType->mElementCount > 6)
  3786. {
  3787. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3788. auto itr = CreateAlloca(intPtrType);
  3789. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3790. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3791. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  3792. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  3793. mBfIRBuilder->CreateBr(loopBB);
  3794. mBfIRBuilder->SetInsertPoint(loopBB);
  3795. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  3796. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  3797. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  3798. mBfIRBuilder->SetInsertPoint(bodyBB);
  3799. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  3800. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  3801. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3802. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  3803. mBfIRBuilder->CreateStore(incValue, itr);
  3804. mBfIRBuilder->CreateBr(loopBB);
  3805. mBfIRBuilder->SetInsertPoint(doneBB);
  3806. }
  3807. else
  3808. {
  3809. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  3810. {
  3811. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  3812. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  3813. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3814. }
  3815. }
  3816. }
  3817. else if (compareType->IsMethodRef())
  3818. {
  3819. auto methodRefType = (BfMethodRefType*)compareType;
  3820. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  3821. BfExprEvaluator exprEvaluator(this);
  3822. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3823. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3824. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  3825. // values for the same method reference -- they will always refer back to the same local variables.
  3826. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  3827. if (dataIdx != -1)
  3828. {
  3829. bool failed = false;
  3830. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  3831. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  3832. BF_ASSERT(!failed);
  3833. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3834. }
  3835. }
  3836. else if (compareTypeInst->IsEnum())
  3837. {
  3838. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3839. BfExprEvaluator exprEvaluator(this);
  3840. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3841. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3842. auto dscrType = compareTypeInst->GetDiscriminatorType();
  3843. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  3844. leftValue = LoadValue(leftValue);
  3845. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  3846. rightValue = LoadValue(rightValue);
  3847. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  3848. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  3849. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3850. int enumCount = 0;
  3851. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3852. {
  3853. BfFieldInstance* fieldInstance = &fieldRef;
  3854. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3855. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3856. {
  3857. enumCount = -fieldInstance->mDataIdx;
  3858. }
  3859. }
  3860. if (enumCount > 0)
  3861. {
  3862. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  3863. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  3864. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3865. {
  3866. BfFieldInstance* fieldInstance = &fieldRef;
  3867. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3868. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3869. {
  3870. int enumIdx = -fieldInstance->mDataIdx - 1;
  3871. if (fieldInstance->mResolvedType->mSize == 0)
  3872. {
  3873. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  3874. }
  3875. else
  3876. {
  3877. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  3878. mBfIRBuilder->SetInsertPoint(caseBlock);
  3879. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  3880. BfTypedValue leftTuple;
  3881. BfTypedValue rightTuple;
  3882. if (leftPayload.IsAddr())
  3883. {
  3884. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3885. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3886. }
  3887. else
  3888. {
  3889. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3890. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3891. }
  3892. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  3893. mBfIRBuilder->CreateBr(matchedBlock);
  3894. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  3895. }
  3896. }
  3897. }
  3898. mBfIRBuilder->AddBlock(matchedBlock);
  3899. mBfIRBuilder->SetInsertPoint(matchedBlock);
  3900. }
  3901. }
  3902. else if (compareTypeInst->IsUnion())
  3903. {
  3904. auto innerType = compareTypeInst->GetUnionInnerType();
  3905. if (!innerType->IsValuelessType())
  3906. {
  3907. BfExprEvaluator exprEvaluator(this);
  3908. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3909. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  3910. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3911. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  3912. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  3913. }
  3914. }
  3915. else
  3916. {
  3917. BfExprEvaluator exprEvaluator(this);
  3918. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3919. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3920. bool hadComparison = false;
  3921. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3922. {
  3923. BfFieldInstance* fieldInstance = &fieldRef;
  3924. if (fieldInstance->mDataOffset == -1)
  3925. continue;
  3926. if (fieldInstance->mResolvedType->IsValuelessType())
  3927. continue;
  3928. if (fieldInstance->mResolvedType->IsVar())
  3929. continue;
  3930. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3931. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3932. if (!fieldInstance->mResolvedType->IsComposite())
  3933. {
  3934. leftValue = LoadValue(leftValue);
  3935. rightValue = LoadValue(rightValue);
  3936. }
  3937. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3938. }
  3939. auto baseTypeInst = compareTypeInst->mBaseType;
  3940. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  3941. {
  3942. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  3943. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  3944. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3945. }
  3946. }
  3947. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  3948. mBfIRBuilder->CreateBr(exitBB);
  3949. mBfIRBuilder->AddBlock(exitBB);
  3950. mBfIRBuilder->SetInsertPoint(exitBB);
  3951. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  3952. ClearLifetimeEnds();
  3953. mBfIRBuilder->CreateRet(loadedResult);
  3954. mCurMethodState->mHadReturn = true;
  3955. }
  3956. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  3957. {
  3958. if (mBfIRBuilder->mIgnoreWrites)
  3959. return mBfIRBuilder->GetFakeVal();
  3960. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3961. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3962. BfIRValue* globalVariablePtr = NULL;
  3963. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  3964. int numElements = 1;
  3965. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  3966. {
  3967. numElements += mCompiler->mMaxInterfaceSlots;
  3968. auto maxIFaceVirtIdx = 0;
  3969. if (!typeInstance->IsInterface())
  3970. {
  3971. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3972. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  3973. numElements += typeInstance->GetOrigVTableSize();
  3974. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  3975. if (typeInstance->mHotTypeData != NULL)
  3976. {
  3977. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  3978. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  3979. }
  3980. numElements += ifaceMethodLen;
  3981. }
  3982. if (outNumElements != NULL)
  3983. *outNumElements = numElements;
  3984. }
  3985. StringT<128> classVDataName;
  3986. String memberName = "sBfClassVData";
  3987. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  3988. {
  3989. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3990. memberName += "_";
  3991. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  3992. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  3993. }
  3994. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  3995. if (outMangledName != NULL)
  3996. *outMangledName = classVDataName;
  3997. /*if (itr != mClassVDataRefs.end())
  3998. {
  3999. globalVariable = itr->second;
  4000. }*/
  4001. BfIRValue globalVariable;
  4002. if (globalVariablePtr != NULL)
  4003. {
  4004. globalVariable = *globalVariablePtr;
  4005. }
  4006. else
  4007. {
  4008. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4009. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4010. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4011. arrayType,
  4012. true,
  4013. BfIRLinkageType_External,
  4014. BfIRValue(),
  4015. classVDataName);
  4016. mClassVDataRefs[typeInstance] = globalVariable;
  4017. }
  4018. return globalVariable;
  4019. }
  4020. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4021. {
  4022. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4023. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4024. }
  4025. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4026. {
  4027. if (mBfIRBuilder->mIgnoreWrites)
  4028. return mBfIRBuilder->GetFakeVal();
  4029. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4030. BF_ASSERT(numElements >= 0);
  4031. if (numElements <= 0)
  4032. return BfIRValue();
  4033. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4034. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4035. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4036. BF_ASSERT(declTypeInst == implTypeInst);
  4037. else
  4038. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4039. if (declTypeInst != implTypeInst)
  4040. {
  4041. BfTypeInstance* highestImpl = declTypeInst;
  4042. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4043. {
  4044. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4045. break; // Start of an ext entry for another type
  4046. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4047. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4048. highestImpl = checkImplTypeInst;
  4049. }
  4050. if (highestImpl != implTypeInst)
  4051. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4052. }
  4053. BfVDataExtEntry mapEntry;
  4054. mapEntry.mDeclTypeInst = declTypeInst;
  4055. mapEntry.mImplTypeInst = implTypeInst;
  4056. BfIRValue* irValuePtr = NULL;
  4057. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4058. return *irValuePtr;
  4059. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4060. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4061. StringT<128> classVDataName;
  4062. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4063. if (declTypeInst != implTypeInst)
  4064. {
  4065. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4066. }
  4067. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4068. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4069. SizedArray<BfIRValue, 32> vData;
  4070. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4071. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4072. {
  4073. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4074. break; // Start of an ext entry for another type
  4075. BfIRValue vValue;
  4076. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4077. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4078. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4079. {
  4080. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4081. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4082. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4083. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4084. {
  4085. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4086. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4087. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4088. vValue = funcPtr;
  4089. }
  4090. }
  4091. if (!vValue)
  4092. vValue = voidPtrNull;
  4093. vData.Add(vValue);
  4094. }
  4095. BF_ASSERT((int)vData.size() == numElements);
  4096. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4097. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4098. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4099. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4100. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4101. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, vData);
  4102. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4103. mClassVDataExtRefs[mapEntry] = globalVariable;
  4104. return globalVariable;
  4105. }
  4106. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  4107. {
  4108. if (mBfIRBuilder->mIgnoreWrites)
  4109. {
  4110. return mBfIRBuilder->CreateTypeOf(type);
  4111. }
  4112. BfIRValue globalVariable;
  4113. BfIRValue* globalVariablePtr = NULL;
  4114. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  4115. {
  4116. globalVariable = *globalVariablePtr;
  4117. if (globalVariable)
  4118. return globalVariable;
  4119. }
  4120. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4121. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4122. auto typeInstance = type->ToTypeInstance();
  4123. StringT<128> typeDataName;
  4124. if (typeInstance != NULL)
  4125. {
  4126. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4127. }
  4128. else
  4129. {
  4130. typeDataName += "sBfTypeData.";
  4131. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  4132. }
  4133. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  4134. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  4135. mTypeDataRefs[type] = globalVariable;
  4136. return globalVariable;
  4137. }
  4138. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  4139. {
  4140. if ((mCompiler->IsHotCompile()) && (!type->mDirty))
  4141. return BfIRValue();
  4142. BfIRValue* irValuePtr = NULL;
  4143. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  4144. {
  4145. return *irValuePtr;
  4146. }
  4147. BfTypeInstance* typeInstance = type->ToTypeInstance();
  4148. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  4149. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  4150. if (typeInstanceType == NULL)
  4151. {
  4152. AssertErrorState();
  4153. return BfIRValue();
  4154. }
  4155. BfIRValue typeTypeData;
  4156. int typeFlags = 0;
  4157. if (needsTypeData)
  4158. {
  4159. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  4160. BfTypeInstance* typeDataSource = NULL;
  4161. if (typeInstance != NULL)
  4162. {
  4163. if (typeInstance->IsUnspecializedType())
  4164. {
  4165. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  4166. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  4167. }
  4168. else if (typeInstance->IsArray())
  4169. {
  4170. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  4171. typeFlags |= BfTypeFlags_Array;
  4172. }
  4173. else if (typeInstance->IsGenericTypeInstance())
  4174. {
  4175. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  4176. typeFlags |= BfTypeFlags_SpecializedGeneric;
  4177. }
  4178. else
  4179. typeDataSource = typeInstanceTypeInstance;
  4180. }
  4181. else if (type->IsPointer())
  4182. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  4183. else if (type->IsRef())
  4184. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  4185. else if (type->IsSizedArray())
  4186. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  4187. else
  4188. typeDataSource = mContext->mBfTypeType;
  4189. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  4190. {
  4191. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  4192. }
  4193. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  4194. }
  4195. else
  4196. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  4197. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  4198. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  4199. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4200. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  4201. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  4202. BfType* typeIdType = intType;
  4203. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4204. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4205. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  4206. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4207. SizedArray<BfIRValue, 4> typeValueParams;
  4208. GetConstClassValueParam(typeTypeData, typeValueParams);
  4209. BfIRValue objectData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  4210. StringT<128> typeDataName;
  4211. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  4212. {
  4213. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4214. if (typeInstance->mTypeDef->IsGlobalsContainer())
  4215. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  4216. }
  4217. else
  4218. {
  4219. typeDataName += "sBfTypeData.";
  4220. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  4221. }
  4222. int typeCode = BfTypeCode_None;
  4223. if (typeInstance != NULL)
  4224. {
  4225. typeCode = typeInstance->mTypeDef->mTypeCode;
  4226. }
  4227. else if (type->IsPrimitiveType())
  4228. {
  4229. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  4230. typeCode = primType->mTypeDef->mTypeCode;
  4231. }
  4232. else if (type->IsPointer())
  4233. {
  4234. typeCode = BfTypeCode_Pointer;
  4235. typeFlags |= BfTypeFlags_Pointer;
  4236. }
  4237. else if (type->IsRef())
  4238. {
  4239. typeCode = BfTypeCode_Pointer;
  4240. typeFlags |= BfTypeFlags_Pointer;
  4241. }
  4242. if (type->IsObject())
  4243. {
  4244. typeFlags |= BfTypeFlags_Object;
  4245. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  4246. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  4247. typeFlags |= BfTypeFlags_HasDestructor;
  4248. }
  4249. if (type->IsStruct())
  4250. typeFlags |= BfTypeFlags_Struct;
  4251. if (type->IsInterface())
  4252. typeFlags |= BfTypeFlags_Interface;
  4253. if (type->IsBoxed())
  4254. {
  4255. typeFlags |= BfTypeFlags_Boxed;
  4256. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  4257. typeFlags |= BfTypeFlags_Pointer;
  4258. }
  4259. if (type->IsPrimitiveType())
  4260. typeFlags |= BfTypeFlags_Primitive;
  4261. if (type->IsTypedPrimitive())
  4262. typeFlags |= BfTypeFlags_TypedPrimitive;
  4263. if (type->IsTuple())
  4264. typeFlags |= BfTypeFlags_Tuple;
  4265. if (type->IsNullable())
  4266. typeFlags |= BfTypeFlags_Nullable;
  4267. if (type->IsSizedArray())
  4268. typeFlags |= BfTypeFlags_SizedArray;
  4269. if (type->IsSplattable())
  4270. typeFlags |= BfTypeFlags_Splattable;
  4271. if (type->IsUnion())
  4272. typeFlags |= BfTypeFlags_Union;
  4273. if (type->IsDelegate())
  4274. typeFlags |= BfTypeFlags_Delegate;
  4275. if (type->IsFunction())
  4276. typeFlags |= BfTypeFlags_Function;
  4277. if (type->WantsGCMarking())
  4278. typeFlags |= BfTypeFlags_WantsMarking;
  4279. int virtSlotIdx = -1;
  4280. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  4281. virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  4282. int memberDataOffset = 0;
  4283. if (type->IsInterface())
  4284. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  4285. else if (typeInstance != NULL)
  4286. {
  4287. for (auto& fieldInstance : typeInstance->mFieldInstances)
  4288. {
  4289. if (fieldInstance.mDataOffset != -1)
  4290. {
  4291. memberDataOffset = fieldInstance.mDataOffset;
  4292. break;
  4293. }
  4294. }
  4295. }
  4296. int boxedTypeId = 0;
  4297. if ((type->IsValueType()) || (type->IsWrappableType()))
  4298. {
  4299. auto boxedType = CreateBoxedType(type, false);
  4300. if ((boxedType != NULL) && (boxedType->mIsReified))
  4301. boxedTypeId = boxedType->mTypeId;
  4302. }
  4303. SizedArray<BfIRValue, 8> typeDataParams =
  4304. {
  4305. objectData,
  4306. GetConstValue(type->mSize, intType), // mSize
  4307. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  4308. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  4309. GetConstValue(typeFlags, intType), // mTypeFlags
  4310. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  4311. GetConstValue(typeCode, byteType), // mTypeCode
  4312. GetConstValue(type->mAlign, byteType),
  4313. };
  4314. auto typeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  4315. if (typeInstance == NULL)
  4316. {
  4317. BfIRValue typeDataVar;
  4318. if (needsTypeData)
  4319. {
  4320. if (type->IsPointer())
  4321. {
  4322. auto pointerType = (BfPointerType*)type;
  4323. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  4324. {
  4325. typeData,
  4326. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  4327. };
  4328. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  4329. auto pointerTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  4330. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  4331. BfIRLinkageType_External, pointerTypeData, typeDataName);
  4332. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4333. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  4334. }
  4335. else if (type->IsRef())
  4336. {
  4337. auto refType = (BfRefType*)type;
  4338. SizedArray<BfIRValue, 3> refTypeDataParms =
  4339. {
  4340. typeData,
  4341. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  4342. GetConstValue((int8)refType->mRefKind, byteType),
  4343. };
  4344. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  4345. auto refTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  4346. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  4347. BfIRLinkageType_External, refTypeData, typeDataName);
  4348. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4349. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  4350. }
  4351. else if (type->IsSizedArray())
  4352. {
  4353. auto sizedArrayType = (BfSizedArrayType*)type;
  4354. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  4355. {
  4356. typeData,
  4357. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  4358. GetConstValue(sizedArrayType->mElementCount, intType)
  4359. };
  4360. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  4361. auto sizedArrayTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  4362. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  4363. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  4364. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4365. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  4366. }
  4367. else
  4368. {
  4369. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  4370. BfIRLinkageType_External, typeData, typeDataName);
  4371. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4372. }
  4373. }
  4374. else
  4375. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  4376. mTypeDataRefs[typeInstance] = typeDataVar;
  4377. return typeDataVar;
  4378. }
  4379. // Reserve position
  4380. mTypeDataRefs[typeInstance] = BfIRValue();
  4381. if (typeInstance->IsReified())
  4382. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  4383. BfTypeDef* typeDef = typeInstance->mTypeDef;
  4384. StringT<128> mangledName;
  4385. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  4386. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4387. {
  4388. auto methodDef = typeDef->mMethods[methodIdx];
  4389. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  4390. if (methodInstance == NULL)
  4391. continue;
  4392. if (typeInstance->IsUnspecializedType())
  4393. continue;
  4394. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4395. {
  4396. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  4397. {
  4398. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  4399. // We need to create an empty thunk for this chained method
  4400. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  4401. mBfIRBuilder->SetActiveFunction(func);
  4402. auto block = mBfIRBuilder->CreateBlock("entry", true);
  4403. mBfIRBuilder->SetInsertPoint(block);
  4404. mBfIRBuilder->CreateRetVoid();
  4405. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  4406. }
  4407. }
  4408. }
  4409. SizedArray<BfIRValue, 32> vData;
  4410. BfIRValue classVDataVar;
  4411. String classVDataName;
  4412. if (typeInstance->mSlotNum >= 0)
  4413. {
  4414. // For interfaces we ONLY emit the slot num
  4415. StringT<128> slotVarName;
  4416. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  4417. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4418. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  4419. GetConstValue32(virtSlotIdx), slotVarName);
  4420. }
  4421. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  4422. {
  4423. int dynCastDataElems = 0;
  4424. int numElements = 1;
  4425. int vDataOfs = 1; // The number of intptrs before the iface slot map
  4426. numElements += mCompiler->mMaxInterfaceSlots;
  4427. if (!typeInstance->IsInterface())
  4428. {
  4429. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4430. numElements += mCompiler->GetDynCastVDataCount();
  4431. numElements += typeInstance->mVirtualMethodTableSize;
  4432. }
  4433. int expectNumElements = 0;
  4434. if (!typeDef->mIsStatic)
  4435. {
  4436. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  4437. }
  4438. vData.push_back(BfIRValue()); // Type*
  4439. SizedArray<BfIRValue, 1> extVTableData;
  4440. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  4441. if (!typeInstance->IsInterface())
  4442. {
  4443. Array<int32> dynCastData;
  4444. if (typeInstance->IsBoxed())
  4445. {
  4446. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  4447. dynCastData.Add(underlyingType->mInheritanceId);
  4448. }
  4449. else
  4450. dynCastData.Add(typeInstance->mInheritanceId);
  4451. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  4452. dynCastData.Add(0);
  4453. dynCastData.Add(0);
  4454. auto checkTypeInst = typeInstance;
  4455. while (checkTypeInst != NULL)
  4456. {
  4457. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  4458. {
  4459. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  4460. {
  4461. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  4462. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  4463. }
  4464. }
  4465. checkTypeInst = checkTypeInst->GetImplBaseType();
  4466. }
  4467. if (mSystem->mPtrSize == 8)
  4468. {
  4469. int intPtrCount = (dynCastDataElems + 1) / 2;
  4470. vDataOfs += intPtrCount;
  4471. uint64* intPtrData = (uint64*)&dynCastData[0];
  4472. for (int i = 0; i < intPtrCount; i++)
  4473. {
  4474. uint64 val = intPtrData[i];
  4475. if (val == 0)
  4476. {
  4477. vData.push_back(voidPtrNull);
  4478. }
  4479. else
  4480. {
  4481. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  4482. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  4483. }
  4484. }
  4485. }
  4486. else
  4487. {
  4488. int intPtrCount = dynCastDataElems;
  4489. vDataOfs += intPtrCount;
  4490. uint32* intPtrData = (uint32*)&dynCastData[0];
  4491. for (int i = 0; i < intPtrCount; i++)
  4492. {
  4493. uint32 val = intPtrData[i];
  4494. if (val == 0)
  4495. {
  4496. vData.push_back(voidPtrNull);
  4497. }
  4498. else
  4499. {
  4500. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  4501. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  4502. }
  4503. }
  4504. }
  4505. }
  4506. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  4507. vData.push_back(voidPtrNull);
  4508. struct _InterfaceMatchEntry
  4509. {
  4510. BfTypeInterfaceEntry* mEntry;
  4511. BfTypeInstance* mEntrySource;
  4512. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  4513. };
  4514. int highestIFaceVirtIdx = 0;
  4515. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  4516. auto checkTypeInst = typeInstance;
  4517. bool forceInterfaceSet = false;
  4518. while (checkTypeInst != NULL)
  4519. {
  4520. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  4521. {
  4522. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  4523. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject))
  4524. continue;
  4525. _InterfaceMatchEntry* matchEntry = NULL;
  4526. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  4527. {
  4528. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  4529. if (compareCheckTypeInst->IsBoxed())
  4530. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  4531. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  4532. if (compareEntrySource->IsBoxed())
  4533. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  4534. auto prevEntry = matchEntry->mEntry;
  4535. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  4536. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  4537. if ((!isBetter) && (!isWorse))
  4538. {
  4539. // Unboxed comparison to Object fix
  4540. if (compareCheckTypeInst == mContext->mBfObjectType)
  4541. isWorse = true;
  4542. else if (compareEntrySource == mContext->mBfObjectType)
  4543. isBetter = true;
  4544. }
  4545. if (forceInterfaceSet)
  4546. {
  4547. isBetter = true;
  4548. isWorse = false;
  4549. }
  4550. if (isBetter == isWorse)
  4551. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  4552. if (isBetter == isWorse)
  4553. {
  4554. if (matchEntry->mAmbiguousEntries.empty())
  4555. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  4556. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  4557. continue;
  4558. }
  4559. else if (isBetter)
  4560. {
  4561. matchEntry->mEntry = &interfaceEntry;
  4562. matchEntry->mEntrySource = checkTypeInst;
  4563. matchEntry->mAmbiguousEntries.Clear();
  4564. }
  4565. else
  4566. continue;
  4567. }
  4568. else
  4569. {
  4570. _InterfaceMatchEntry matchEntry;
  4571. matchEntry.mEntry = &interfaceEntry;
  4572. matchEntry.mEntrySource = checkTypeInst;
  4573. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  4574. }
  4575. }
  4576. checkTypeInst = checkTypeInst->GetImplBaseType();
  4577. }
  4578. for (auto interfacePair : interfaceMap)
  4579. {
  4580. auto& interfaceMatchEntry = interfacePair.mValue;
  4581. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  4582. {
  4583. 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());
  4584. if (error != NULL)
  4585. {
  4586. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  4587. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  4588. }
  4589. }
  4590. }
  4591. if ((!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4592. {
  4593. int startTabIdx = (int)vData.size();
  4594. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4595. BfTypeInstance* checkTypeInst = typeInstance;
  4596. while (checkTypeInst != NULL)
  4597. {
  4598. origVirtTypeStack.push_back(checkTypeInst);
  4599. checkTypeInst = checkTypeInst->GetImplBaseType();
  4600. }
  4601. Array<BfVirtualMethodEntry> origVTable;
  4602. int origVirtIdx = 0;
  4603. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4604. {
  4605. HashSet<String> reslotNames;
  4606. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4607. {
  4608. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4609. if (entry.mDeclaringMethod.mMethodNum == -1)
  4610. continue;
  4611. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4612. if ((methodInstance == NULL) || (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4613. {
  4614. if (origVTable.empty())
  4615. origVTable = typeInstance->mVirtualMethodTable;
  4616. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4617. if (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject))
  4618. {
  4619. // Prepare to reslot...
  4620. entry.mImplementingMethod = entry.mDeclaringMethod;
  4621. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4622. }
  4623. else
  4624. {
  4625. // Decl isn't accessible, null out entry
  4626. entry.mImplementingMethod = BfMethodRef();
  4627. }
  4628. }
  4629. }
  4630. if (!reslotNames.IsEmpty())
  4631. {
  4632. BfAmbiguityContext ambiguityContext;
  4633. ambiguityContext.mTypeInstance = typeInstance;
  4634. ambiguityContext.mModule = this;
  4635. ambiguityContext.mIsProjectSpecific = true;
  4636. ambiguityContext.mIsReslotting = true;
  4637. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4638. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4639. {
  4640. auto methodInstance = methodGroup.mDefault;
  4641. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4642. continue;
  4643. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4644. continue;
  4645. if (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))
  4646. continue;
  4647. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4648. continue;
  4649. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4650. }
  4651. ambiguityContext.Finish();
  4652. }
  4653. }
  4654. bool isInExts = false;
  4655. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4656. {
  4657. BfIRValue vValue = voidPtrNull;
  4658. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4659. BfModuleMethodInstance moduleMethodInst;
  4660. if (entry.mDeclaringMethod.mMethodNum == -1)
  4661. {
  4662. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4663. isInExts = true;
  4664. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4665. if (vExt)
  4666. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4667. }
  4668. else
  4669. {
  4670. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4671. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4672. {
  4673. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4674. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4675. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4676. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4677. {
  4678. BF_ASSERT(typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4679. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4680. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4681. vValue = funcPtr;
  4682. }
  4683. }
  4684. }
  4685. while (origVirtTypeStack.size() != 0)
  4686. {
  4687. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4688. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4689. {
  4690. // Moved past current base vtable size
  4691. origVirtTypeStack.pop_back();
  4692. continue;
  4693. }
  4694. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4695. {
  4696. // We are within the original vtable size
  4697. int idx = startTabIdx + origVirtIdx;
  4698. origVirtIdx++;
  4699. vData.push_back(vValue);
  4700. }
  4701. else
  4702. {
  4703. // This is a new entry, it only gets added to the ext
  4704. BF_ASSERT(isInExts);
  4705. }
  4706. break;
  4707. }
  4708. }
  4709. if (!origVTable.empty())
  4710. typeInstance->mVirtualMethodTable = origVTable;
  4711. }
  4712. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4713. if (typeInstance->mHotTypeData != NULL)
  4714. {
  4715. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4716. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4717. }
  4718. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4719. int iFaceMethodStartIdx = (int)vData.size();
  4720. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4721. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4722. vData[i] = voidPtrNull;
  4723. if (expectNumElements != 0)
  4724. BF_ASSERT(expectNumElements == vData.size());
  4725. //BF_ASSERT(vData.size() == expectNumElements);
  4726. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4727. // ifaceMethodExtData.Add(voidPtrNull);
  4728. int ifaceEntryIdx = iFaceMethodStartIdx;
  4729. for (auto& interfacePair : interfaceMap)
  4730. {
  4731. auto interfaceEntry = interfacePair.mValue.mEntry;
  4732. bool makeEmpty = false;
  4733. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject))
  4734. makeEmpty = true;
  4735. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4736. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4737. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4738. {
  4739. BfIRValue pushValue;
  4740. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4741. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4742. continue;
  4743. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4744. continue;
  4745. if (makeEmpty)
  4746. {
  4747. pushValue = voidPtrNull;
  4748. }
  4749. else
  4750. {
  4751. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4752. auto methodInstance = (BfMethodInstance*)methodRef;
  4753. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4754. {
  4755. BF_ASSERT(methodInstance->mIsReified);
  4756. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4757. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4758. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  4759. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4760. pushValue = funcPtr;
  4761. }
  4762. else
  4763. {
  4764. pushValue = voidPtrNull;
  4765. }
  4766. }
  4767. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4768. if (idx < ifaceMethodExtStart)
  4769. {
  4770. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  4771. vData[iFaceMethodStartIdx + idx] = pushValue;
  4772. }
  4773. else
  4774. {
  4775. BF_ASSERT(useExt);
  4776. int extIdx = idx - ifaceMethodExtStart;
  4777. while (extIdx >= ifaceMethodExtData.size())
  4778. ifaceMethodExtData.Add(voidPtrNull);
  4779. ifaceMethodExtData[extIdx] = pushValue;
  4780. }
  4781. }
  4782. }
  4783. if (typeInstance->IsBoxed())
  4784. {
  4785. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  4786. if (boxedType->IsBoxedStructPtr())
  4787. {
  4788. // Force override of GetHashCode so we use the pointer address as the hash code
  4789. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  4790. // Force override of GetHashCode so we use the pointer address as the hash code
  4791. for (auto& checkIFace : checkTypeInst->mInterfaces)
  4792. {
  4793. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4794. {
  4795. BfIRValue pushValue;
  4796. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4797. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4798. continue;
  4799. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4800. continue;
  4801. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4802. auto methodInstance = (BfMethodInstance*)methodRef;
  4803. BF_ASSERT(methodInstance->mIsReified);
  4804. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4805. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4806. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  4807. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4808. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4809. vData[iFaceMethodStartIdx + idx] = funcPtr;
  4810. }
  4811. }
  4812. }
  4813. }
  4814. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic))
  4815. {
  4816. BfIRValue ifaceMethodExtVar;
  4817. if (!ifaceMethodExtData.IsEmpty())
  4818. {
  4819. StringT<128> classVDataName;
  4820. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  4821. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  4822. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4823. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4824. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  4825. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, ifaceMethodExtData);
  4826. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  4827. }
  4828. for (auto& ifaceInstPair : interfaceMap)
  4829. {
  4830. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  4831. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  4832. if (slotNum >= 0)
  4833. {
  4834. BfIRValue vtablePtr;
  4835. int idx = interfaceEntry->mStartVirtualIdx;
  4836. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4837. if (endVirtualIdx > ifaceMethodExtStart)
  4838. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  4839. else
  4840. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  4841. int slotVirtIdx = slotNum + vDataOfs;
  4842. if (vData[slotVirtIdx] == voidPtrNull)
  4843. {
  4844. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  4845. }
  4846. else
  4847. {
  4848. if (mCompiler->IsHotCompile())
  4849. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  4850. else
  4851. Fail("Interface slot collision error", typeDef->GetRefNode());
  4852. }
  4853. }
  4854. }
  4855. }
  4856. }
  4857. BfIRValue typeNameConst;
  4858. BfIRValue namespaceConst;
  4859. if (needsTypeNames)
  4860. {
  4861. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  4862. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  4863. }
  4864. else
  4865. {
  4866. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  4867. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4868. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4869. }
  4870. int baseTypeId = 0;
  4871. if (typeInstance->mBaseType != NULL)
  4872. {
  4873. baseTypeId = typeInstance->mBaseType->mTypeId;
  4874. }
  4875. BfTypeOptions* typeOptions = NULL;
  4876. if (typeInstance->mTypeOptionsIdx >= 0)
  4877. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  4878. SizedArray<BfIRValue, 16> customAttrs;
  4879. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  4880. BfIRValue castedClassVData;
  4881. if (classVDataVar)
  4882. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  4883. else
  4884. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  4885. bool freflectIncludeTypeData = false;
  4886. bool reflectIncludeAllFields = false;
  4887. bool reflectIncludeAllMethods = false;
  4888. if (TypeIsSubTypeOf(typeInstance, attributeType))
  4889. {
  4890. reflectIncludeAllFields = true;
  4891. reflectIncludeAllMethods = true;
  4892. }
  4893. BfReflectKind reflectKind = BfReflectKind_Type;
  4894. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  4895. {
  4896. BfReflectKind reflectKind = BfReflectKind_None;
  4897. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  4898. if (customAttrs != NULL)
  4899. {
  4900. for (auto& attr : customAttrs->mAttributes)
  4901. {
  4902. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  4903. }
  4904. }
  4905. return reflectKind;
  4906. };
  4907. reflectKind = GetReflectKind(reflectKind, typeInstance);
  4908. // Fields
  4909. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  4910. BfIRValue emptyValueType = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  4911. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  4912. {
  4913. if (customAttributes == NULL)
  4914. return -1;
  4915. Array<BfCustomAttribute*> reflectAttributes;
  4916. for (auto& attr : customAttributes->mAttributes)
  4917. {
  4918. bool wantAttribute = false;
  4919. if (attr.mType->mCustomAttributes != NULL)
  4920. {
  4921. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  4922. if (usageAttribute != NULL)
  4923. {
  4924. // Check for Flags arg
  4925. if (usageAttribute->mCtorArgs.size() < 2)
  4926. continue;
  4927. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  4928. if (constant == NULL)
  4929. continue;
  4930. if (constant->mTypeCode == BfTypeCode_Boolean)
  4931. continue;
  4932. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4933. wantAttribute = true;
  4934. }
  4935. }
  4936. if ((wantAttribute) && (attr.mType->mIsReified))
  4937. {
  4938. reflectAttributes.Add(&attr);
  4939. }
  4940. }
  4941. if (reflectAttributes.size() == 0)
  4942. return -1;
  4943. #define PUSH_INT8(val) data.push_back((uint8)val)
  4944. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4945. #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); }
  4946. #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); \
  4947. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4948. SizedArray<uint8, 16> data;
  4949. int customAttrIdx = (int)customAttrs.size();
  4950. data.push_back((uint8)reflectAttributes.size());
  4951. for (auto attr : reflectAttributes)
  4952. {
  4953. // Size prefix
  4954. int sizeIdx = (int)data.size();
  4955. PUSH_INT16(0); // mSize
  4956. PUSH_INT32(attr->mType->mTypeId); // mType
  4957. PUSH_INT16(attr->mCtor->mIdx);
  4958. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  4959. int argIdx = 0;
  4960. for (auto arg : attr->mCtorArgs)
  4961. {
  4962. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4963. bool handled = false;
  4964. if (constant != NULL)
  4965. {
  4966. auto argType = ctorMethodInstance->GetParamType(argIdx);
  4967. if (argType->IsObject())
  4968. {
  4969. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  4970. int stringId = constant->mInt32;
  4971. int* orderedIdPtr;
  4972. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4973. {
  4974. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4975. }
  4976. GetStringObjectValue(stringId);
  4977. PUSH_INT8(0xFF); // String
  4978. PUSH_INT32(*orderedIdPtr);
  4979. argIdx++;
  4980. continue;
  4981. }
  4982. if (argType->IsPointer())
  4983. {
  4984. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  4985. {
  4986. if (constant->mTypeCode == BfTypeCode_StringId)
  4987. {
  4988. int stringId = constant->mInt32;
  4989. int* orderedIdPtr;
  4990. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4991. {
  4992. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4993. }
  4994. GetStringObjectValue(stringId);
  4995. PUSH_INT8(0xFF); // String
  4996. PUSH_INT32(*orderedIdPtr);
  4997. argIdx++;
  4998. continue;
  4999. }
  5000. }
  5001. }
  5002. PUSH_INT8(constant->mTypeCode);
  5003. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  5004. (constant->mTypeCode == BfTypeCode_UInt64) ||
  5005. (constant->mTypeCode == BfTypeCode_Double))
  5006. {
  5007. PUSH_INT64(constant->mInt64);
  5008. }
  5009. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  5010. (constant->mTypeCode == BfTypeCode_UInt32) ||
  5011. (constant->mTypeCode == BfTypeCode_Char32))
  5012. {
  5013. PUSH_INT32(constant->mInt32);
  5014. }
  5015. else if (constant->mTypeCode == BfTypeCode_Float)
  5016. {
  5017. float val = (float)constant->mDouble;
  5018. PUSH_INT32(*(int*)&val);
  5019. }
  5020. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  5021. (constant->mTypeCode == BfTypeCode_UInt16) ||
  5022. (constant->mTypeCode == BfTypeCode_Char16))
  5023. {
  5024. PUSH_INT16(constant->mInt16);
  5025. }
  5026. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  5027. (constant->mTypeCode == BfTypeCode_UInt8) ||
  5028. (constant->mTypeCode == BfTypeCode_Boolean) ||
  5029. (constant->mTypeCode == BfTypeCode_Char8))
  5030. {
  5031. PUSH_INT8(constant->mInt8);
  5032. }
  5033. else
  5034. {
  5035. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(type).c_str()));
  5036. }
  5037. }
  5038. else if (!handled)
  5039. {
  5040. BFMODULE_FATAL(this, "Unhandled");
  5041. }
  5042. argIdx++;
  5043. }
  5044. int size = (int)data.size() - sizeIdx;
  5045. *((uint16*)&data[sizeIdx]) = size;
  5046. }
  5047. #undef PUSH_INT8
  5048. #undef PUSH_INT16
  5049. #undef PUSH_INT32
  5050. SizedArray<BfIRValue, 16> dataValues;
  5051. for (uint8 val : data)
  5052. dataValues.push_back(GetConstValue8(val));
  5053. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  5054. auto customAttrConst = mBfIRBuilder->CreateConstArray(dataArrayType, dataValues);
  5055. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  5056. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  5057. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  5058. customAttrs.push_back(customAttrArrayPtr);
  5059. return customAttrIdx;
  5060. };
  5061. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  5062. SizedArray<int, 16> reflectFieldIndices;
  5063. for (int pass = 0; pass < 2; pass++)
  5064. {
  5065. bool skippedField = false;
  5066. reflectFieldIndices.clear();
  5067. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  5068. {
  5069. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5070. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5071. if (fieldDef == NULL)
  5072. continue;
  5073. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  5074. bool includeField = reflectIncludeAllFields;
  5075. if (fieldInstance->mCustomAttributes != NULL)
  5076. {
  5077. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  5078. {
  5079. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  5080. {
  5081. includeField = true;
  5082. }
  5083. else
  5084. {
  5085. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  5086. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  5087. }
  5088. }
  5089. }
  5090. if ((fieldReflectKind & BfReflectKind_User) != 0)
  5091. includeField = true;
  5092. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  5093. includeField = true;
  5094. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  5095. includeField = true;
  5096. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  5097. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  5098. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  5099. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  5100. includeField |= forceReflectFields;
  5101. if (!includeField)
  5102. {
  5103. skippedField = true;
  5104. continue;
  5105. }
  5106. reflectFieldIndices.Add(fieldIdx);
  5107. }
  5108. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  5109. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  5110. // possible because we write out a SplatData structure containing just TypeIds in that case
  5111. if (pass == 0)
  5112. {
  5113. if (!typeInstance->IsSplattable())
  5114. break;
  5115. if (!skippedField)
  5116. break;
  5117. if (reflectFieldIndices.size() == 0)
  5118. break;
  5119. }
  5120. }
  5121. SizedArray<BfIRValue, 16> fieldTypes;
  5122. enum FieldFlags
  5123. {
  5124. FieldFlags_Protected = 3,
  5125. FieldFlags_Public = 6,
  5126. FieldFlags_Static = 0x10,
  5127. FieldFlags_Const = 0x40,
  5128. FieldFlags_SpecialName = 0x80,
  5129. FieldFlags_EnumPayload = 0x100,
  5130. FieldFlags_EnumDiscriminator = 0x200
  5131. };
  5132. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  5133. {
  5134. BfType* payloadType = typeInstance->GetUnionInnerType();
  5135. if (!payloadType->IsValuelessType())
  5136. {
  5137. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  5138. SizedArray<BfIRValue, 8> payloadFieldVals =
  5139. {
  5140. emptyValueType,
  5141. payloadNameConst, // mName
  5142. GetConstValue(0, intPtrType), // mData
  5143. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  5144. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  5145. GetConstValue(-1, intType), // mCustomAttributesIdx
  5146. };
  5147. auto payloadFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  5148. fieldTypes.push_back(payloadFieldData);
  5149. }
  5150. BfType* dscrType = typeInstance->GetDiscriminatorType();
  5151. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  5152. SizedArray<BfIRValue, 8> dscrFieldVals =
  5153. {
  5154. emptyValueType,
  5155. dscrNameConst, // mName
  5156. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  5157. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  5158. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  5159. GetConstValue(-1, intType), // mCustomAttributesIdx
  5160. };
  5161. auto dscrFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  5162. fieldTypes.push_back(dscrFieldData);
  5163. }
  5164. for (auto fieldIdx : reflectFieldIndices)
  5165. {
  5166. if (!needsTypeData)
  5167. break;
  5168. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5169. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5170. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  5171. int typeId = 0;
  5172. auto fieldType = fieldInstance->GetResolvedType();
  5173. if (fieldType->IsGenericParam())
  5174. {
  5175. //TODO:
  5176. }
  5177. else
  5178. typeId = fieldType->mTypeId;
  5179. FieldFlags fieldFlags = (FieldFlags)0;
  5180. if (fieldDef->mProtection == BfProtection_Protected)
  5181. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  5182. if (fieldDef->mProtection == BfProtection_Public)
  5183. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  5184. if (fieldDef->mIsStatic)
  5185. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  5186. if (fieldDef->mIsConst)
  5187. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  5188. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  5189. BfIRValue constValue;
  5190. if (fieldInstance->GetFieldDef()->mIsConst)
  5191. {
  5192. if (fieldInstance->mConstIdx != -1)
  5193. {
  5194. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  5195. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, constant->mUInt64);
  5196. }
  5197. }
  5198. else if (fieldInstance->GetFieldDef()->mIsStatic)
  5199. {
  5200. auto refVal = ReferenceStaticField(fieldInstance);
  5201. if (refVal.mValue.IsConst())
  5202. {
  5203. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  5204. if (constant->mConstType == BfConstType_GlobalVar)
  5205. {
  5206. auto globalVar = (BfGlobalVar*)constant;
  5207. if (globalVar->mName[0] == '#')
  5208. refVal = BfTypedValue();
  5209. }
  5210. }
  5211. if (refVal.IsAddr())
  5212. {
  5213. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5214. }
  5215. }
  5216. if (!constValue)
  5217. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  5218. SizedArray<BfIRValue, 8> fieldVals =
  5219. {
  5220. emptyValueType,
  5221. fieldNameConst, // mName
  5222. constValue, // mConstValue
  5223. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5224. GetConstValue(fieldFlags, shortType), // mFlags
  5225. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  5226. };
  5227. auto fieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  5228. fieldTypes.push_back(fieldData);
  5229. }
  5230. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  5231. BfIRValue fieldDataPtr;
  5232. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  5233. if (fieldTypes.size() == 0)
  5234. {
  5235. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  5236. {
  5237. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  5238. SizedArray<BfIRValue, 3> splatTypes;
  5239. SizedArray<BfIRValue, 3> splatOffsets;
  5240. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  5241. {
  5242. auto checkTypeInstance = checkType->ToTypeInstance();
  5243. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  5244. PopulateType(checkTypeInstance);
  5245. if (checkType->IsStruct())
  5246. {
  5247. int dataEnd = offset;
  5248. if (checkTypeInstance->mBaseType != NULL)
  5249. _CheckSplat(checkTypeInstance->mBaseType, offset);
  5250. if (checkTypeInstance->mIsUnion)
  5251. {
  5252. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  5253. _CheckSplat(unionInnerType, offset);
  5254. }
  5255. else
  5256. {
  5257. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  5258. {
  5259. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  5260. if (fieldInstance->mDataIdx >= 0)
  5261. {
  5262. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  5263. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  5264. }
  5265. }
  5266. }
  5267. if (checkTypeInstance->IsEnum())
  5268. {
  5269. // Add discriminator
  5270. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  5271. if (!checkTypeInstance->mIsPacked)
  5272. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  5273. _CheckSplat(dscrType, dataEnd);
  5274. }
  5275. }
  5276. else if (checkType->IsMethodRef())
  5277. {
  5278. // auto methodRefType = (BfMethodRefType*)checkType;
  5279. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  5280. // {
  5281. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  5282. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  5283. // else
  5284. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  5285. // }
  5286. }
  5287. else if (!checkType->IsValuelessType())
  5288. {
  5289. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  5290. splatOffsets.Add(GetConstValue(offset, intType));
  5291. }
  5292. };
  5293. _CheckSplat(type, 0);
  5294. while (splatTypes.size() < 3)
  5295. {
  5296. splatTypes.Add(GetConstValue(0, typeIdType));
  5297. splatOffsets.Add(GetConstValue(0, intType));
  5298. }
  5299. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  5300. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  5301. SizedArray<BfIRValue, 8> splatVals =
  5302. {
  5303. emptyValueType,
  5304. splatTypesConst,
  5305. splatOffsetsConst
  5306. };
  5307. auto fieldSplatData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  5308. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  5309. fieldSplatData, typeDataName + ".splats");
  5310. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  5311. }
  5312. else
  5313. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  5314. }
  5315. else
  5316. {
  5317. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  5318. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstArray(fieldDataConstType, fieldTypes);
  5319. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  5320. fieldDataConst, "fields." + typeDataName);
  5321. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  5322. }
  5323. /// Methods
  5324. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  5325. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  5326. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  5327. SizedArray<BfIRValue, 16> methodTypes;
  5328. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5329. {
  5330. if (!needsTypeData)
  5331. break;
  5332. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  5333. if (!methodInstanceGroup->IsImplemented())
  5334. continue;
  5335. auto methodDef = typeDef->mMethods[methodIdx];
  5336. if (methodDef->mIsNoReflect)
  5337. continue;
  5338. auto defaultMethod = methodInstanceGroup->mDefault;
  5339. if (defaultMethod == NULL)
  5340. continue;
  5341. if (defaultMethod->mIsUnspecialized)
  5342. continue;
  5343. if (!defaultMethod->mIsReified)
  5344. continue;
  5345. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  5346. continue;
  5347. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  5348. continue;
  5349. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  5350. bool includeMethod = reflectIncludeAllMethods;
  5351. BfCustomAttributes* methodCustomAttributes = NULL;
  5352. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  5353. {
  5354. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  5355. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  5356. {
  5357. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  5358. {
  5359. includeMethod = true;
  5360. }
  5361. else
  5362. {
  5363. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  5364. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  5365. }
  5366. }
  5367. }
  5368. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5369. continue;
  5370. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  5371. {
  5372. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  5373. {
  5374. if (paramDecl->mAttributes != NULL)
  5375. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  5376. }
  5377. if (methodDeclaration->mReturnAttributes != NULL)
  5378. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(methodDeclaration->mReturnAttributes, BfAttributeTargets_ReturnValue));
  5379. }
  5380. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  5381. includeMethod = true;
  5382. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  5383. includeMethod = true;
  5384. if ((!includeMethod) && (typeOptions != NULL))
  5385. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  5386. if (!includeMethod)
  5387. continue;
  5388. BfModuleMethodInstance moduleMethodInstance;
  5389. BfIRValue funcVal = voidPtrNull;
  5390. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  5391. (!typeInstance->IsUnspecializedType()) &&
  5392. (methodDef->mMethodType != BfMethodType_Ignore) &&
  5393. (methodDef->mMethodType != BfMethodType_Mixin) &&
  5394. (!methodDef->mIsAbstract) &&
  5395. (methodDef->mGenericParams.size() == 0))
  5396. {
  5397. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5398. if (moduleMethodInstance.mFunc)
  5399. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  5400. }
  5401. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  5402. enum MethodFlags
  5403. {
  5404. MethodFlags_Protected = 3,
  5405. MethodFlags_Public = 6,
  5406. MethodFlags_Static = 0x10,
  5407. MethodFlags_Virtual = 0x40,
  5408. MethodFlags_StdCall = 0x1000,
  5409. MethodFlags_FastCall = 0x2000,
  5410. MethodFlags_ThisCall = 0x3000,
  5411. MethodFlags_Mutating = 0x4000,
  5412. MethodFlags_Constructor = 0x8000,
  5413. };
  5414. MethodFlags methodFlags = (MethodFlags)0;
  5415. if (methodDef->mProtection == BfProtection_Protected)
  5416. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Protected);
  5417. if (methodDef->mProtection == BfProtection_Public)
  5418. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Public);
  5419. if (methodDef->mIsStatic)
  5420. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Static);
  5421. if ((methodDef->mIsVirtual) || (moduleMethodInstance.mMethodInstance->mVirtualTableIdx != -1))
  5422. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Virtual);
  5423. if (methodDef->mCallingConvention == BfCallingConvention_Fastcall)
  5424. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  5425. if (methodDef->mIsMutating)
  5426. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Mutating);
  5427. if (methodDef->mMethodType == BfMethodType_Ctor)
  5428. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Constructor);
  5429. auto callingConvention = GetIRCallingConvention(defaultMethod);
  5430. if (callingConvention == BfIRCallingConv_ThisCall)
  5431. methodFlags = (MethodFlags)(methodFlags | MethodFlags_ThisCall);
  5432. else if (callingConvention == BfIRCallingConv_StdCall)
  5433. methodFlags = (MethodFlags)(methodFlags | MethodFlags_StdCall);
  5434. else if (callingConvention == BfIRCallingConv_FastCall)
  5435. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  5436. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  5437. enum ParamFlags
  5438. {
  5439. ParamFlag_None = 0,
  5440. ParamFlag_Splat = 1,
  5441. ParamFlag_Implicit = 2,
  5442. };
  5443. SizedArray<BfIRValue, 8> paramVals;
  5444. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  5445. {
  5446. String paramName = defaultMethod->GetParamName(paramIdx);
  5447. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  5448. ParamFlags paramFlags = ParamFlag_None;
  5449. if (defaultMethod->GetParamIsSplat(paramIdx))
  5450. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  5451. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  5452. SizedArray<BfIRValue, 8> paramDataVals =
  5453. {
  5454. emptyValueType,
  5455. paramNameConst,
  5456. GetConstValue(paramType->mTypeId, typeIdType),
  5457. GetConstValue((int32)paramFlags, shortType),
  5458. GetConstValue(customAttrIdx, intType) // defaultIdx
  5459. };
  5460. auto paramData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  5461. paramVals.Add(paramData);
  5462. }
  5463. BfIRValue paramsVal;
  5464. if (paramVals.size() > 0)
  5465. {
  5466. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  5467. BfIRValue paramDataConst = mBfIRBuilder->CreateConstArray(paramDataArrayType, paramVals);
  5468. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  5469. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  5470. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  5471. }
  5472. else
  5473. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  5474. int vDataVal = -1;
  5475. if (defaultMethod->mVirtualTableIdx != -1)
  5476. {
  5477. int vDataIdx = -1;
  5478. if (type->IsInterface())
  5479. {
  5480. vDataIdx = defaultMethod->mVirtualTableIdx;
  5481. }
  5482. else
  5483. {
  5484. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  5485. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  5486. {
  5487. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  5488. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  5489. if (extMethodIdx >= 0)
  5490. {
  5491. // Extension?
  5492. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  5493. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  5494. }
  5495. else
  5496. {
  5497. // Map this new virtual index back to the original index
  5498. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  5499. }
  5500. }
  5501. else
  5502. {
  5503. vDataIdx += defaultMethod->mVirtualTableIdx;
  5504. }
  5505. }
  5506. if (vDataVal == -1)
  5507. vDataVal = vDataIdx * mSystem->mPtrSize;
  5508. }
  5509. SizedArray<BfIRValue, 8> methodDataVals =
  5510. {
  5511. emptyValueType,
  5512. methodNameConst, // mName
  5513. funcVal, // mFuncPtr
  5514. paramsVal,
  5515. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  5516. GetConstValue((int)paramVals.size(), shortType),
  5517. GetConstValue(methodFlags, shortType),
  5518. GetConstValue(methodIdx, intType),
  5519. GetConstValue(vDataVal, intType),
  5520. GetConstValue(customAttrIdx, intType),
  5521. };
  5522. auto methodData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  5523. methodTypes.push_back(methodData);
  5524. }
  5525. BfIRValue methodDataPtr;
  5526. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  5527. if (methodTypes.size() == 0)
  5528. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  5529. else
  5530. {
  5531. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  5532. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methodTypes);
  5533. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  5534. methodDataConst, "methods." + typeDataName);
  5535. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  5536. }
  5537. /////
  5538. int interfaceCount = 0;
  5539. BfIRValue interfaceDataPtr;
  5540. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  5541. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  5542. Array<bool> wantsIfaceMethod;
  5543. bool wantsIfaceMethods = false;
  5544. if (typeInstance->mInterfaces.IsEmpty())
  5545. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  5546. else
  5547. {
  5548. SizedArray<BfIRValue, 16> interfaces;
  5549. for (auto& interface : typeInstance->mInterfaces)
  5550. {
  5551. SizedArray<BfIRValue, 8> interfaceDataVals =
  5552. {
  5553. emptyValueType,
  5554. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  5555. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  5556. GetConstValue(interface.mStartVirtualIdx, intType),
  5557. };
  5558. auto interfaceData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  5559. interfaces.push_back(interfaceData);
  5560. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5561. {
  5562. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  5563. if (ifaceMethodGroup->mExplicitlyReflected)
  5564. {
  5565. wantsIfaceMethods = true;
  5566. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  5567. while (tableIdx >= wantsIfaceMethod.size())
  5568. wantsIfaceMethod.Add(false);
  5569. wantsIfaceMethod[tableIdx] = true;
  5570. }
  5571. }
  5572. }
  5573. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  5574. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstArray(interfaceDataArrayType, interfaces);
  5575. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  5576. interfaceDataConst, "interfaces." + typeDataName);
  5577. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  5578. interfaceCount = (int)interfaces.size();
  5579. }
  5580. BfIRValue interfaceMethodTable;
  5581. int ifaceMethodTableSize = 0;
  5582. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  5583. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  5584. {
  5585. SizedArray<BfIRValue, 16> methods;
  5586. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  5587. {
  5588. BfIRValue funcVal = voidPtrNull;
  5589. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  5590. {
  5591. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  5592. if (!methodEntry.mMethodRef.IsNull())
  5593. {
  5594. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  5595. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  5596. (!methodInstance->mMethodDef->mIsAbstract))
  5597. {
  5598. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  5599. if (moduleMethodInstance.mFunc)
  5600. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  5601. }
  5602. }
  5603. }
  5604. methods.Add(funcVal);
  5605. }
  5606. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  5607. methods.pop_back();
  5608. if (!methods.IsEmpty())
  5609. {
  5610. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  5611. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methods);
  5612. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  5613. methodDataConst, "imethods." + typeDataName);
  5614. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  5615. ifaceMethodTableSize = (int)methods.size();
  5616. }
  5617. }
  5618. if (!interfaceMethodTable)
  5619. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  5620. /////
  5621. int underlyingType = 0;
  5622. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  5623. {
  5624. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  5625. }
  5626. int outerTypeId = 0;
  5627. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  5628. if (outerType != NULL)
  5629. {
  5630. outerTypeId = outerType->mTypeId;
  5631. }
  5632. //
  5633. BfIRValue customAttrDataPtr;
  5634. if (customAttrs.size() > 0)
  5635. {
  5636. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  5637. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstArray(customAttrsArrayType, customAttrs);
  5638. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  5639. customAttrsConst, "customAttrs." + typeDataName);
  5640. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  5641. }
  5642. else
  5643. {
  5644. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  5645. }
  5646. SizedArray<BfIRValue, 32> typeDataVals =
  5647. {
  5648. typeData,
  5649. castedClassVData, // mTypeClassVData
  5650. typeNameConst, // mName
  5651. namespaceConst, // mNamespace
  5652. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  5653. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  5654. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  5655. GetConstValue(baseTypeId, typeIdType), // mBaseType
  5656. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  5657. GetConstValue(outerTypeId, typeIdType), // mOuterType
  5658. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  5659. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  5660. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  5661. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  5662. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  5663. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  5664. GetConstValue(0, shortType), // mPropertyDataCount
  5665. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  5666. interfaceDataPtr, // mInterfaceDataPtr
  5667. interfaceMethodTable, // mInterfaceMethodTable
  5668. methodDataPtr, // mMethodDataPtr
  5669. voidPtrNull, // mPropertyDataPtr
  5670. fieldDataPtr, // mFieldDataPtr
  5671. customAttrDataPtr, // mCustomAttrDataPtr
  5672. };
  5673. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5674. auto typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, typeDataVals);
  5675. if (!needsTypeData)
  5676. {
  5677. // No need for anything beyond typeInstanceData
  5678. }
  5679. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5680. {
  5681. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5682. SizedArray<BfIRValue, 4> unspecializedData =
  5683. {
  5684. typeInstanceData,
  5685. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5686. };
  5687. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5688. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5689. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, unspecializedData);
  5690. }
  5691. else if (typeInstance->IsGenericTypeInstance())
  5692. {
  5693. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5694. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5695. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5696. SizedArray<BfIRValue, 4> resolvedTypes;
  5697. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  5698. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5699. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5700. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5701. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5702. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstArray(genericArrayType, resolvedTypes);
  5703. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5704. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5705. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5706. SizedArray<BfIRValue, 3> specGenericData =
  5707. {
  5708. typeInstanceData,
  5709. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5710. resovledTypesPtr, // mFieldDataPtr
  5711. };
  5712. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5713. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, specGenericData);
  5714. if (typeInstance->IsArray())
  5715. {
  5716. auto arrayType = (BfArrayType*)typeInstance;
  5717. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  5718. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5719. SizedArray<BfIRValue, 4> arrayData =
  5720. {
  5721. typeInstanceData,
  5722. GetConstValue(elementType->mSize, intType), // mElementSize
  5723. GetConstValue(1, byteType), // mRank
  5724. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5725. };
  5726. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5727. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5728. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, arrayData);
  5729. }
  5730. }
  5731. BfIRValue typeDataVar;
  5732. if (needsTypeData)
  5733. {
  5734. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5735. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5736. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5737. if (mBfIRBuilder->DbgHasInfo())
  5738. {
  5739. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5740. }
  5741. }
  5742. else
  5743. {
  5744. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5745. }
  5746. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5747. mTypeDataRefs[typeInstance] = typeDataVar;
  5748. if (classVDataVar)
  5749. {
  5750. BF_ASSERT(!classVDataName.IsEmpty());
  5751. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5752. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5753. auto classVDataConstData = mBfIRBuilder->CreateConstArray(classVDataConstDataType, vData);
  5754. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5755. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5756. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5757. else
  5758. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5759. if (mBfIRBuilder->DbgHasInfo())
  5760. {
  5761. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5762. BfType* voidPtrType = CreatePointerType(voidType);
  5763. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5764. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5765. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  5766. }
  5767. }
  5768. return typeDataVar;
  5769. }
  5770. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5771. {
  5772. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  5773. return value;
  5774. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5775. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5776. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5777. }
  5778. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5779. {
  5780. // Note: this is not just for perf, it fixes a field var-type resolution issue
  5781. if (mBfIRBuilder->mIgnoreWrites)
  5782. return;
  5783. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5784. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  5785. // When we access classes with static constructors FROM a static constructor,
  5786. // we call that other class's static constructor first. Recursion cannot occur, since
  5787. // we simply ignore subsequent attempts to re-enter the constructor
  5788. if (!typeInstance->mHasStaticInitMethod)
  5789. return;
  5790. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  5791. return;
  5792. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  5793. return;
  5794. auto checkTypeDef = typeInstance->mTypeDef;
  5795. checkTypeDef->PopulateMemberSets();
  5796. BfMethodDef* nextMethodDef = NULL;
  5797. BfMemberSetEntry* entry;
  5798. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  5799. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5800. while (nextMethodDef != NULL)
  5801. {
  5802. auto checkMethod = nextMethodDef;
  5803. nextMethodDef = nextMethodDef->mNextWithSameName;
  5804. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  5805. if (methodModule)
  5806. {
  5807. auto methodInstance = methodModule.mMethodInstance;
  5808. if ((methodInstance != NULL) &&
  5809. (methodInstance->mMethodDef->mIsStatic) &&
  5810. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  5811. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  5812. {
  5813. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  5814. break;
  5815. }
  5816. }
  5817. }
  5818. }
  5819. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  5820. {
  5821. auto methodOwner = methodInstance->GetOwner();
  5822. auto methodDef = methodInstance->mMethodDef;
  5823. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5824. if (!methodDef->mIsExtern)
  5825. return BfIRFunction();
  5826. if (methodInstance->GetCustomAttributes() == NULL)
  5827. return BfIRFunction();
  5828. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  5829. {
  5830. String typeName = TypeToString(customAttribute.mType);
  5831. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  5832. {
  5833. methodInstance->mIsIntrinsic = true;
  5834. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  5835. String error;
  5836. if ((constant != NULL) && (constant->mTypeCode = BfTypeCode_StringId))
  5837. {
  5838. int stringId = constant->mInt32;
  5839. auto entry = mContext->mStringObjectIdMap[stringId];
  5840. String intrinName = entry.mString;
  5841. // if (intrinName.StartsWith(":"))
  5842. // {
  5843. // SizedArray<BfIRType, 2> paramTypes;
  5844. // for (auto& param : methodInstance->mParams)
  5845. // paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5846. // return mBfIRBuilder->GetIntrinsic(intrinName.Substring(1), mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  5847. // }
  5848. // else
  5849. {
  5850. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  5851. if (intrinId != -1)
  5852. {
  5853. if (intrinId == BfIRIntrinsic_Malloc)
  5854. {
  5855. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  5856. }
  5857. else if (intrinId == BfIRIntrinsic_Free)
  5858. {
  5859. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  5860. }
  5861. SizedArray<BfIRType, 2> paramTypes;
  5862. for (auto& param : methodInstance->mParams)
  5863. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5864. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  5865. }
  5866. else if (reportFailure)
  5867. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  5868. }
  5869. }
  5870. else if (reportFailure)
  5871. error = "Intrinsic name must be a constant string";
  5872. if (reportFailure)
  5873. {
  5874. Fail(error, customAttribute.mRef);
  5875. }
  5876. }
  5877. }
  5878. return BfIRFunction();
  5879. }
  5880. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  5881. {
  5882. if (mBfIRBuilder->mIgnoreWrites)
  5883. return mBfIRBuilder->GetFakeFunction();
  5884. if (!mBuiltInFuncs[(int)funcTypeId])
  5885. {
  5886. SizedArray<BfIRType, 4> paramTypes;
  5887. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  5888. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5889. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  5890. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5891. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  5892. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  5893. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  5894. BfIRFunctionType funcType;
  5895. BfIRFunction func;
  5896. switch (funcTypeId)
  5897. {
  5898. case BfBuiltInFuncType_PrintF:
  5899. paramTypes.Add(nullPtrType);
  5900. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  5901. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  5902. break;
  5903. case BfBuiltInFuncType_Malloc:
  5904. {
  5905. if (mCompiler->mOptions.mDebugAlloc)
  5906. {
  5907. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  5908. }
  5909. else
  5910. {
  5911. String funcName = mCompiler->mOptions.mMallocLinkName;
  5912. if (funcName.IsEmpty())
  5913. funcName = "malloc";
  5914. func = mBfIRBuilder->GetFunction(funcName);
  5915. if (!func)
  5916. {
  5917. paramTypes.clear();
  5918. paramTypes.push_back(intType);
  5919. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  5920. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5921. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  5922. }
  5923. }
  5924. }
  5925. break;
  5926. case BfBuiltInFuncType_Free:
  5927. {
  5928. if (mCompiler->mOptions.mDebugAlloc)
  5929. {
  5930. func = GetInternalMethod("Dbg_RawFree").mFunc;
  5931. }
  5932. else
  5933. {
  5934. String funcName = mCompiler->mOptions.mFreeLinkName;
  5935. if (funcName.IsEmpty())
  5936. funcName = "free";
  5937. func = mBfIRBuilder->GetFunction(funcName);
  5938. if (!func)
  5939. {
  5940. paramTypes.clear();
  5941. paramTypes.push_back(nullPtrType);
  5942. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5943. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5944. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  5945. }
  5946. }
  5947. }
  5948. break;
  5949. case BfBuiltInFuncType_LoadSharedLibraries:
  5950. paramTypes.clear();
  5951. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5952. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  5953. break;
  5954. default: break;
  5955. }
  5956. mBuiltInFuncs[(int)funcTypeId] = func;
  5957. return func;
  5958. }
  5959. return mBuiltInFuncs[(int)funcTypeId];
  5960. }
  5961. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized)
  5962. {
  5963. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  5964. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  5965. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  5966. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  5967. BfAutoComplete* bfAutocomplete = NULL;
  5968. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  5969. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  5970. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  5971. {
  5972. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  5973. {
  5974. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  5975. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  5976. {
  5977. String filter = nameNode->ToString();
  5978. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  5979. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  5980. if (nameIdx != 0)
  5981. {
  5982. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  5983. }
  5984. }
  5985. }
  5986. }
  5987. for (auto constraint : constraintDef->mConstraints)
  5988. {
  5989. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  5990. {
  5991. BfGenericOperatorConstraintInstance opConstraintInstance;
  5992. if (opConstraint->mLeftType != NULL)
  5993. {
  5994. if (bfAutocomplete != NULL)
  5995. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  5996. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces);
  5997. if (opConstraintInstance.mLeftType == NULL)
  5998. continue;
  5999. }
  6000. if (opConstraint->mRightType == NULL)
  6001. {
  6002. // We had a failure in parsing
  6003. continue;
  6004. }
  6005. if (opConstraint->mRightType != NULL)
  6006. {
  6007. if (bfAutocomplete != NULL)
  6008. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  6009. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces);
  6010. if (opConstraintInstance.mRightType == NULL)
  6011. continue;
  6012. }
  6013. if (opConstraint->mOpToken == NULL)
  6014. {
  6015. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  6016. continue;
  6017. }
  6018. if (opConstraint->mLeftType != NULL)
  6019. {
  6020. if (opConstraint->mRightType == NULL)
  6021. {
  6022. // Parse should have failed
  6023. continue;
  6024. }
  6025. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  6026. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  6027. {
  6028. Fail("Invalid binary operator", opConstraint->mOpToken);
  6029. continue;
  6030. }
  6031. }
  6032. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  6033. {
  6034. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  6035. }
  6036. else
  6037. {
  6038. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  6039. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  6040. {
  6041. Fail("Invalid unary operator", opConstraint->mOpToken);
  6042. continue;
  6043. }
  6044. }
  6045. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  6046. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_Op);
  6047. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  6048. continue;
  6049. }
  6050. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  6051. if (bfAutocomplete != NULL)
  6052. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  6053. //TODO: Constraints may refer to other generic params (of either type or method)
  6054. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  6055. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  6056. if (constraintType != NULL)
  6057. {
  6058. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6059. {
  6060. bool isValidTypeCode = false;
  6061. BfTypeCode typeCode = BfTypeCode_None;
  6062. if (constraintType->IsTypedPrimitive())
  6063. {
  6064. auto underlyingType = constraintType->GetUnderlyingType();
  6065. if (underlyingType->IsPrimitiveType())
  6066. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  6067. }
  6068. if (constraintType->IsPrimitiveType())
  6069. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  6070. switch (typeCode)
  6071. {
  6072. case BfTypeCode_Int8:
  6073. case BfTypeCode_UInt8:
  6074. case BfTypeCode_Int16:
  6075. case BfTypeCode_UInt16:
  6076. case BfTypeCode_Int32:
  6077. case BfTypeCode_UInt32:
  6078. case BfTypeCode_Int64:
  6079. case BfTypeCode_UInt64:
  6080. case BfTypeCode_IntPtr:
  6081. case BfTypeCode_UIntPtr:
  6082. case BfTypeCode_IntUnknown:
  6083. case BfTypeCode_UIntUnknown:
  6084. case BfTypeCode_Float:
  6085. case BfTypeCode_Double:
  6086. case BfTypeCode_Char8:
  6087. case BfTypeCode_Char16:
  6088. case BfTypeCode_Char32:
  6089. isValidTypeCode = true;
  6090. break;
  6091. default: break;
  6092. }
  6093. if (isValidTypeCode)
  6094. {
  6095. genericParamInstance->mTypeConstraint = constraintType;
  6096. }
  6097. else
  6098. {
  6099. Fail("Const constraint must be a primitive type", constraintTypeRef);
  6100. }
  6101. }
  6102. else
  6103. {
  6104. bool checkEquality = false;
  6105. if (constraintType->IsPrimitiveType())
  6106. {
  6107. if (isUnspecialized)
  6108. {
  6109. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  6110. continue;
  6111. }
  6112. checkEquality = true;
  6113. }
  6114. if (constraintType->IsArray())
  6115. {
  6116. if (isUnspecialized)
  6117. {
  6118. 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);
  6119. continue;
  6120. }
  6121. checkEquality = true;
  6122. }
  6123. if (constraintType->IsGenericParam())
  6124. {
  6125. continue;
  6126. }
  6127. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  6128. {
  6129. if (isUnspecialized)
  6130. {
  6131. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  6132. continue;
  6133. }
  6134. checkEquality = true;
  6135. }
  6136. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  6137. {
  6138. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_Type);
  6139. checkEquality = true;
  6140. }
  6141. if (checkEquality)
  6142. {
  6143. genericParamInstance->mTypeConstraint = constraintType;
  6144. }
  6145. else if (constraintType->IsInterface())
  6146. {
  6147. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  6148. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_IFace);
  6149. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  6150. }
  6151. else
  6152. {
  6153. auto constraintTypeInst = constraintType->ToTypeInstance();
  6154. if (genericParamInstance->mTypeConstraint != NULL)
  6155. {
  6156. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  6157. {
  6158. // Allow more specific type
  6159. genericParamInstance->mTypeConstraint = constraintTypeInst;
  6160. }
  6161. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  6162. {
  6163. // Silently ignore less-specific type
  6164. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  6165. {
  6166. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  6167. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  6168. }
  6169. }
  6170. else
  6171. {
  6172. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  6173. return;
  6174. }
  6175. }
  6176. else
  6177. genericParamInstance->mTypeConstraint = constraintType;
  6178. }
  6179. }
  6180. }
  6181. }
  6182. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  6183. (genericParamInstance->mTypeConstraint == NULL))
  6184. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  6185. }
  6186. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  6187. {
  6188. if (genericParamSource.mMethodInstance != NULL)
  6189. {
  6190. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  6191. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(methodInst, NULL);
  6192. return MethodToString(genericParamSource.mMethodInstance);
  6193. }
  6194. else
  6195. {
  6196. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  6197. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  6198. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  6199. return TypeToString(typeInst);
  6200. }
  6201. }
  6202. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  6203. {
  6204. Array<String> methodParamNameOverrides;
  6205. auto _TypeToString = [&](BfType* type)
  6206. {
  6207. if (genericParamSource.mMethodInstance != NULL)
  6208. {
  6209. if (methodParamNameOverrides.IsEmpty())
  6210. {
  6211. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  6212. methodParamNameOverrides.Add(genericParam->mName);
  6213. }
  6214. return TypeToString(type, &methodParamNameOverrides);
  6215. }
  6216. return TypeToString(type);
  6217. };
  6218. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  6219. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  6220. BfType* origCheckArgType = checkArgType;
  6221. if (origCheckArgType->IsRef())
  6222. origCheckArgType = origCheckArgType->GetUnderlyingType();
  6223. bool argMayBeReferenceType = false;
  6224. int checkGenericParamFlags = 0;
  6225. if (checkArgType->IsGenericParam())
  6226. {
  6227. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  6228. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  6229. if (checkGenericParamInst->mTypeConstraint != NULL)
  6230. checkArgType = checkGenericParamInst->mTypeConstraint;
  6231. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  6232. {
  6233. argMayBeReferenceType = false;
  6234. }
  6235. else
  6236. {
  6237. argMayBeReferenceType = true;
  6238. }
  6239. }
  6240. if (checkArgType->IsObjectOrInterface())
  6241. argMayBeReferenceType = true;
  6242. BfTypeInstance* typeConstraintInst = NULL;
  6243. if (genericParamInst->mTypeConstraint != NULL)
  6244. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  6245. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  6246. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  6247. {
  6248. if (!ignoreErrors)
  6249. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  6250. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6251. return false;
  6252. }
  6253. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  6254. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  6255. {
  6256. if (!ignoreErrors)
  6257. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  6258. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6259. return false;
  6260. }
  6261. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  6262. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  6263. {
  6264. if (!ignoreErrors)
  6265. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  6266. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6267. return false;
  6268. }
  6269. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6270. {
  6271. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  6272. {
  6273. if (!ignoreErrors)
  6274. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  6275. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6276. return false;
  6277. }
  6278. }
  6279. else
  6280. {
  6281. if (checkArgType->IsConstExprValue())
  6282. {
  6283. if (!ignoreErrors)
  6284. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  6285. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6286. return false;
  6287. }
  6288. }
  6289. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  6290. {
  6291. bool canDelete = false;
  6292. if (checkArgType->IsPointer())
  6293. canDelete = true;
  6294. else if (checkArgType->IsObjectOrInterface())
  6295. canDelete = true;
  6296. else if ((checkGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  6297. canDelete = true;
  6298. if (!canDelete)
  6299. {
  6300. if (!ignoreErrors)
  6301. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  6302. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6303. return false;
  6304. }
  6305. }
  6306. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  6307. {
  6308. bool canAlloc = false;
  6309. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  6310. {
  6311. if (checkTypeInst->IsObjectOrStruct())
  6312. {
  6313. checkTypeInst->mTypeDef->PopulateMemberSets();
  6314. BfMemberSetEntry* entry = NULL;
  6315. BfMethodDef* checkMethodDef = NULL;
  6316. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  6317. if (entry != NULL)
  6318. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  6319. bool hadProtected = false;
  6320. while (checkMethodDef != NULL)
  6321. {
  6322. if (checkMethodDef->mProtection == BfProtection_Public)
  6323. {
  6324. canAlloc = true;
  6325. break;
  6326. }
  6327. if (checkMethodDef->mProtection == BfProtection_Protected)
  6328. hadProtected = true;
  6329. checkMethodDef = checkMethodDef->mNextWithSameName;
  6330. }
  6331. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  6332. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  6333. }
  6334. }
  6335. else
  6336. {
  6337. // Any primitive types and stuff can be allocated
  6338. canAlloc = true;
  6339. }
  6340. if (!canAlloc)
  6341. {
  6342. if (!ignoreErrors)
  6343. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  6344. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6345. return false;
  6346. }
  6347. }
  6348. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  6349. return true;
  6350. if (checkArgType->IsPointer())
  6351. {
  6352. auto ptrType = (BfPointerType*)checkArgType;
  6353. checkArgType = ptrType->mElementType;
  6354. }
  6355. if (genericParamInst->mTypeConstraint != NULL)
  6356. {
  6357. bool constraintMatched = false;
  6358. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6359. {
  6360. if (checkArgType->IsConstExprValue())
  6361. {
  6362. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  6363. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  6364. {
  6365. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  6366. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  6367. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  6368. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  6369. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  6370. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  6371. {
  6372. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  6373. {
  6374. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  6375. {
  6376. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  6377. {
  6378. if (!ignoreErrors)
  6379. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  6380. constExprValueType->mValue.mInt64, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6381. return false;
  6382. }
  6383. }
  6384. else
  6385. {
  6386. if (!ignoreErrors)
  6387. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with integer const '%lld', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  6388. constExprValueType->mValue.mInt64, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6389. return false;
  6390. }
  6391. }
  6392. else
  6393. {
  6394. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  6395. {
  6396. char valStr[64];
  6397. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  6398. if (!ignoreErrors)
  6399. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with floating point const '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  6400. valStr, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6401. return false;
  6402. }
  6403. }
  6404. }
  6405. }
  6406. }
  6407. }
  6408. else
  6409. {
  6410. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  6411. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  6412. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs);
  6413. if (convCheckConstraint == NULL)
  6414. return false;
  6415. if (((checkArgType->IsMethodRef()) || (checkArgType->IsFunction())) && (convCheckConstraint->IsDelegate()))
  6416. {
  6417. BfMethodInstance* checkMethodInstance;
  6418. if (checkArgType->IsMethodRef())
  6419. {
  6420. auto methodRefType = (BfMethodRefType*)checkArgType;
  6421. checkMethodInstance = methodRefType->mMethodRef;
  6422. }
  6423. else
  6424. {
  6425. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  6426. }
  6427. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  6428. BfExprEvaluator exprEvaluator(this);
  6429. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  6430. constraintMatched = true;
  6431. }
  6432. else if (CanCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  6433. {
  6434. constraintMatched = true;
  6435. }
  6436. else if (origCheckArgType->IsWrappableType())
  6437. {
  6438. if (origCheckArgType->IsSizedArray())
  6439. {
  6440. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  6441. if (convCheckConstraint->IsGenericTypeInstance())
  6442. {
  6443. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  6444. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  6445. {
  6446. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  6447. {
  6448. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  6449. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  6450. constraintMatched = true;
  6451. }
  6452. }
  6453. }
  6454. }
  6455. if (!constraintMatched)
  6456. {
  6457. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  6458. if (CanCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  6459. constraintMatched = true;
  6460. }
  6461. }
  6462. if (!constraintMatched)
  6463. {
  6464. if (!ignoreErrors)
  6465. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  6466. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  6467. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  6468. return false;
  6469. }
  6470. }
  6471. }
  6472. if ((genericParamInst->mInterfaceConstraints.size() > 0) && (origCheckArgType->IsInterface()))
  6473. {
  6474. PopulateType(origCheckArgType);
  6475. auto checkTypeInst = origCheckArgType->ToTypeInstance();
  6476. if (checkTypeInst->mTypeDef->mIsConcrete)
  6477. {
  6478. if (!ignoreErrors)
  6479. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be concrete interface '%s' for '%s', must be a concrete type", genericParamInst->GetName().c_str(),
  6480. TypeToString(origCheckArgType).c_str()), checkArgTypeRef);
  6481. return false;
  6482. }
  6483. }
  6484. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  6485. {
  6486. BfType* convCheckConstraint = checkConstraint;
  6487. if (convCheckConstraint->IsUnspecializedType())
  6488. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs);
  6489. if (convCheckConstraint == NULL)
  6490. return false;
  6491. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  6492. bool implementsInterface = false;
  6493. if (origCheckArgType != checkArgType)
  6494. {
  6495. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  6496. }
  6497. if (!implementsInterface)
  6498. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  6499. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  6500. {
  6501. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  6502. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  6503. implementsInterface = true;
  6504. }
  6505. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  6506. {
  6507. auto underlyingType = origCheckArgType->GetUnderlyingType();
  6508. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  6509. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  6510. implementsInterface = true;
  6511. }
  6512. if (!implementsInterface)
  6513. {
  6514. if (!ignoreErrors)
  6515. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  6516. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), _TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  6517. return false;
  6518. }
  6519. }
  6520. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  6521. {
  6522. auto leftType = checkOpConstraint.mLeftType;
  6523. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  6524. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs);
  6525. if (leftType != NULL)
  6526. leftType = FixIntUnknown(leftType);
  6527. auto rightType = checkOpConstraint.mRightType;
  6528. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  6529. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs);
  6530. if (rightType != NULL)
  6531. rightType = FixIntUnknown(rightType);
  6532. BfConstraintState constraintSet;
  6533. constraintSet.mPrevState = mContext->mCurConstraintState;
  6534. constraintSet.mGenericParamInstance = genericParamInst;
  6535. constraintSet.mLeftType = leftType;
  6536. constraintSet.mRightType = rightType;
  6537. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  6538. if (!CheckConstraintState(NULL))
  6539. return false;
  6540. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  6541. {
  6542. BfExprEvaluator exprEvaluator(this);
  6543. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  6544. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  6545. //
  6546. {
  6547. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  6548. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  6549. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  6550. }
  6551. if ((!exprEvaluator.mResult) ||
  6552. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  6553. {
  6554. if (!ignoreErrors)
  6555. {
  6556. if (genericParamInst->mExternType != NULL)
  6557. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  6558. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  6559. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  6560. ), checkArgTypeRef);
  6561. else
  6562. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  6563. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  6564. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  6565. ), checkArgTypeRef);
  6566. }
  6567. return false;
  6568. }
  6569. }
  6570. else
  6571. {
  6572. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  6573. StringT<128> failedOpName;
  6574. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  6575. {
  6576. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  6577. failedOpName = "implicit conversion from '";
  6578. }
  6579. else
  6580. {
  6581. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  6582. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  6583. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  6584. {
  6585. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  6586. failedOpName = "explicit conversion from '";
  6587. }
  6588. else
  6589. {
  6590. BfExprEvaluator exprEvaluator(this);
  6591. exprEvaluator.mResult = rightValue;
  6592. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  6593. if ((!exprEvaluator.mResult) ||
  6594. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  6595. {
  6596. failedOpName += "unary operation '";
  6597. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  6598. }
  6599. }
  6600. }
  6601. if (!failedOpName.IsEmpty())
  6602. {
  6603. if (!ignoreErrors)
  6604. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  6605. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  6606. failedOpName.c_str(), TypeToString(rightType).c_str()
  6607. ), checkArgTypeRef);
  6608. return false;
  6609. }
  6610. }
  6611. }
  6612. return true;
  6613. }
  6614. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  6615. {
  6616. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  6617. {
  6618. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  6619. return genericParamType;
  6620. }
  6621. auto genericParamType = new BfGenericParamType();
  6622. genericParamType->mContext = mContext;
  6623. genericParamType->mGenericParamKind = paramKind;
  6624. genericParamType->mGenericParamIdx = paramIdx;
  6625. PopulateType(genericParamType);
  6626. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  6627. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  6628. BfResolvedTypeSet::LookupContext lookupCtx;
  6629. lookupCtx.mModule = this;
  6630. BfResolvedTypeSet::Entry* typeEntry = NULL;
  6631. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  6632. BF_ASSERT(inserted);
  6633. typeEntry->mValue = genericParamType;
  6634. return genericParamType;
  6635. }
  6636. static int sValueFromExprIdx = 0;
  6637. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  6638. {
  6639. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  6640. if ((result) && (!ignoreNullable))
  6641. {
  6642. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  6643. //TODO: Make this work, needed for 'void' and such
  6644. BfType* nullableType = NULL;
  6645. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  6646. {
  6647. BfTypeVector typeVec;
  6648. typeVec.push_back(result.mType);
  6649. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  6650. BF_ASSERT(nullableType != NULL);
  6651. }
  6652. // Go back to start and do any setup we need
  6653. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  6654. BfTypedValue nullableTypedValue;
  6655. if (nullableType != NULL)
  6656. {
  6657. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  6658. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  6659. GetConstValue(nullableType->mSize), nullableType->mAlign);
  6660. }
  6661. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  6662. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  6663. mBfIRBuilder->SetInsertPoint(notNullBB);
  6664. result = LoadValue(result);
  6665. if (nullableTypedValue)
  6666. {
  6667. auto elementType = nullableType->GetUnderlyingType();
  6668. if (elementType->IsVar())
  6669. {
  6670. // Do nothing
  6671. }
  6672. else if (elementType->IsValuelessType())
  6673. {
  6674. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  6675. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  6676. }
  6677. else
  6678. {
  6679. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  6680. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  6681. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  6682. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  6683. }
  6684. result = nullableTypedValue;
  6685. }
  6686. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  6687. AddBasicBlock(pendingNullCond->mDoneBB);
  6688. if (nullableType == NULL)
  6689. {
  6690. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  6691. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  6692. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  6693. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  6694. {
  6695. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  6696. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  6697. }
  6698. result.mValue = phi;
  6699. }
  6700. }
  6701. else
  6702. {
  6703. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  6704. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  6705. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  6706. AddBasicBlock(pendingNullCond->mDoneBB);
  6707. }
  6708. delete mCurMethodState->mPendingNullConditional;
  6709. mCurMethodState->mPendingNullConditional = NULL;
  6710. return result;
  6711. }
  6712. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  6713. {
  6714. BfScopeData newScope;
  6715. newScope.mOuterIsConditional = true;
  6716. newScope.mAllowTargeting = false;
  6717. mCurMethodState->AddScope(&newScope);
  6718. NewScopeState();
  6719. exprEvaluator.mBfEvalExprFlags = flags;
  6720. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  6721. RestoreScopeState();
  6722. }
  6723. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  6724. {
  6725. //
  6726. {
  6727. BP_ZONE("CreateValueFromExpression:CheckStack");
  6728. StackHelper stackHelper;
  6729. if (!stackHelper.CanStackExpand(64 * 1024))
  6730. {
  6731. BfTypedValue result;
  6732. if (!stackHelper.Execute([&]()
  6733. {
  6734. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  6735. }))
  6736. {
  6737. Fail("Expression too complex to compile", expr);
  6738. }
  6739. return result;
  6740. }
  6741. }
  6742. BP_ZONE("BfModule::CreateValueFromExpression");
  6743. if (outOrigType != NULL)
  6744. *outOrigType = NULL;
  6745. exprEvaluator.mExpectingType = wantTypeRef;
  6746. exprEvaluator.mBfEvalExprFlags = flags;
  6747. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  6748. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  6749. {
  6750. EvaluateWithNewScope(exprEvaluator, expr, flags);
  6751. }
  6752. else
  6753. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  6754. if (!exprEvaluator.mResult)
  6755. {
  6756. if (!mCompiler->mPassInstance->HasFailed())
  6757. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  6758. return BfTypedValue();
  6759. }
  6760. auto typedVal = exprEvaluator.mResult;
  6761. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  6762. {
  6763. BF_ASSERT(typedVal.mType->IsGenericParam());
  6764. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  6765. bool handled = false;
  6766. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6767. {
  6768. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  6769. if (genericTypeConstraint != NULL)
  6770. {
  6771. auto primType = genericTypeConstraint->ToPrimitiveType();
  6772. if (primType != NULL)
  6773. {
  6774. BfTypedValue result;
  6775. result.mKind = BfTypedValueKind_Value;
  6776. result.mType = genericTypeConstraint;
  6777. result.mValue = mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode);
  6778. typedVal = result;
  6779. handled = true;
  6780. }
  6781. }
  6782. }
  6783. if (!handled)
  6784. {
  6785. //Fail("Only const generic parameters can be used as values", expr);
  6786. AssertErrorState();
  6787. return BfTypedValue();
  6788. }
  6789. }
  6790. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  6791. FixIntUnknown(typedVal);
  6792. exprEvaluator.CheckResultForReading(typedVal);
  6793. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  6794. {
  6795. if ((flags & BfEvalExprFlags_NoCast) == 0)
  6796. {
  6797. // Only allow a 'ref' type if we have an explicit 'ref' operator
  6798. bool allowRef = false;
  6799. BfExpression* checkExpr = expr;
  6800. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  6801. checkExpr = parenExpr->mExpression;
  6802. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  6803. {
  6804. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  6805. allowRef = true;
  6806. }
  6807. if (!allowRef)
  6808. typedVal = RemoveRef(typedVal);
  6809. }
  6810. }
  6811. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  6812. {
  6813. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  6814. {
  6815. BF_ASSERT(!typedVal.mValue.IsFake());
  6816. }
  6817. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6818. }
  6819. if (wantTypeRef != NULL)
  6820. {
  6821. if (outOrigType != NULL)
  6822. *outOrigType = typedVal.mType;
  6823. if ((flags & BfEvalExprFlags_NoCast) == 0)
  6824. {
  6825. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  6826. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  6827. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  6828. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  6829. if (!typedVal)
  6830. return typedVal;
  6831. }
  6832. //WTF- why did we have this?
  6833. /*if ((flags & BfEvalExprFlags_ExplicitCast) == 0)
  6834. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);*/
  6835. if (exprEvaluator.mIsVolatileReference)
  6836. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6837. }
  6838. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  6839. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6840. return typedVal;
  6841. }
  6842. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  6843. {
  6844. BfExprEvaluator exprEvaluator(this);
  6845. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  6846. }
  6847. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  6848. {
  6849. BfExprEvaluator exprEvaluator(this);
  6850. exprEvaluator.Evaluate(expr);
  6851. if (!exprEvaluator.mResult)
  6852. {
  6853. Fail("Invalid expression type", expr);
  6854. return BfTypedValue();
  6855. }
  6856. if (!exprEvaluator.mResult.IsAddr())
  6857. {
  6858. Fail("Cannot assign to value", expr);
  6859. return BfTypedValue();
  6860. }
  6861. return exprEvaluator.mResult;
  6862. }
  6863. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  6864. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  6865. {
  6866. auto typeInstance = typedValue.mType->ToTypeInstance();
  6867. if (zeroMemory)
  6868. {
  6869. int zeroAlign = typedValue.mType->mAlign;
  6870. if (typeInstance != NULL)
  6871. zeroAlign = typeInstance->mInstAlign;
  6872. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  6873. }
  6874. if (!typedValue.mType->IsObject())
  6875. {
  6876. return;
  6877. }
  6878. if ((scopeData == NULL) && (mCurMethodState != NULL))
  6879. return; // Handled in heap alloc funcs
  6880. auto typeDef = typeInstance->mTypeDef;
  6881. mBfIRBuilder->PopulateType(typedValue.mType);
  6882. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  6883. bool isAutocomplete = mCompiler->IsAutocomplete();
  6884. BfIRValue vDataRef;
  6885. if (!isAutocomplete)
  6886. {
  6887. vDataRef = GetClassVDataPtr(typeInstance);
  6888. }
  6889. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6890. auto ptrType = CreatePointerType(i8Type);
  6891. auto ptrPtrType = CreatePointerType(ptrType);
  6892. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  6893. PopulateType(ptrType, BfPopulateType_Declaration);
  6894. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  6895. if (!isAutocomplete)
  6896. {
  6897. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6898. {
  6899. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  6900. SizedArray<BfIRValue, 4> llvmArgs;
  6901. llvmArgs.push_back(objectPtr);
  6902. llvmArgs.push_back(vDataRef);
  6903. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  6904. if (objectStackInitMethod)
  6905. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  6906. }
  6907. else
  6908. {
  6909. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  6910. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  6911. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6912. }
  6913. }
  6914. }
  6915. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  6916. {
  6917. BfIRValue result;
  6918. BfType* ptrType;
  6919. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  6920. ptrType = type;
  6921. else
  6922. ptrType = CreatePointerType(type);
  6923. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  6924. {
  6925. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6926. SizedArray<BfExpression*, 2> argExprs;
  6927. BfTypedValueExpression typedValueExpr;
  6928. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  6929. typedValueExpr.mRefNode = refNode;
  6930. argExprs.push_back(&typedValueExpr);
  6931. BfTypedValueExpression appendSizeValueExpr;
  6932. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  6933. appendSizeValueExpr.mRefNode = refNode;
  6934. argExprs.push_back(&appendSizeValueExpr);
  6935. BfExprEvaluator exprEvaluator(this);
  6936. BfTypedValue allocResult;
  6937. if (allocTarget.mScopedInvocationTarget != NULL)
  6938. {
  6939. SizedArray<BfTypeReference*, 2> genericArgs;
  6940. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  6941. allocResult = LoadValue(exprEvaluator.mResult);
  6942. }
  6943. else if (allocTarget.mCustomAllocator)
  6944. {
  6945. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6946. if (customTypeInst != NULL)
  6947. {
  6948. BfTypedValueExpression typeValueExpr;
  6949. String allocMethodName = "Alloc";
  6950. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  6951. {
  6952. allocMethodName = "AllocTyped";
  6953. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  6954. auto typeRefVal = CreateTypeDataRef(type);
  6955. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  6956. typeValueExpr.mRefNode = refNode;
  6957. argExprs.Insert(0, &typeValueExpr);
  6958. }
  6959. if (HasMixin(customTypeInst, allocMethodName, 2))
  6960. {
  6961. BfSizedArray<BfExpression*> argExprArr;
  6962. argExprArr.mSize = (int)argExprs.size();
  6963. argExprArr.mVals = &argExprs[0];
  6964. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  6965. allocResult = exprEvaluator.GetResult();
  6966. }
  6967. else
  6968. {
  6969. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6970. BfResolvedArgs argValues(&sizedArgExprs);
  6971. exprEvaluator.ResolveArgValues(argValues);
  6972. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  6973. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  6974. }
  6975. }
  6976. }
  6977. if (allocResult)
  6978. {
  6979. if (allocResult.mType->IsVoidPtr())
  6980. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  6981. else
  6982. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  6983. return result;
  6984. }
  6985. }
  6986. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  6987. return result;
  6988. if (mCompiler->mOptions.mDebugAlloc)
  6989. {
  6990. BfIRValue allocData = GetDbgRawAllocData(type);
  6991. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  6992. SizedArray<BfIRValue, 2> llvmArgs;
  6993. llvmArgs.push_back(sizeValue);
  6994. llvmArgs.push_back(allocData);
  6995. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  6996. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6997. }
  6998. BfModuleMethodInstance moduleMethodInstance;
  6999. moduleMethodInstance = GetInternalMethod("Malloc");
  7000. SizedArray<BfIRValue, 1> llvmArgs;
  7001. llvmArgs.push_back(sizeValue);
  7002. auto func = moduleMethodInstance.mFunc;
  7003. if ((!func) || (func.IsFake()))
  7004. {
  7005. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  7006. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  7007. }
  7008. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  7009. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  7010. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  7011. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  7012. return result;
  7013. }
  7014. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  7015. {
  7016. if (type->IsStruct())
  7017. {
  7018. auto typeInstance = type->ToTypeInstance();
  7019. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  7020. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7021. }
  7022. else if (type->IsObjectOrInterface())
  7023. {
  7024. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  7025. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  7026. BF_ASSERT(moduleMethodInst.mFunc);
  7027. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7028. }
  7029. else
  7030. {
  7031. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  7032. BfExprEvaluator exprEvaluator(this);
  7033. SizedArray<BfResolvedArg, 1> resolvedArgs;
  7034. BfResolvedArg resolvedArg;
  7035. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  7036. resolvedArgs.Add(resolvedArg);
  7037. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  7038. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  7039. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  7040. BF_ASSERT(moduleMethodInst.mFunc);
  7041. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7042. }
  7043. return BfIRValue();
  7044. }
  7045. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  7046. {
  7047. BfIRValue allocDataValue;
  7048. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  7049. return allocDataValue;
  7050. BfIRValue markFuncPtr;
  7051. if (type->WantsGCMarking())
  7052. markFuncPtr = GetMarkFuncPtr(type);
  7053. else
  7054. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7055. BfIRValue typeDataRef = CreateTypeDataRef(type);
  7056. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  7057. BfTypeInstance* typeInstance = type->ToTypeInstance();
  7058. if (typeInstance == NULL)
  7059. {
  7060. typeInstance = GetWrappedStructType(type);
  7061. if (typeInstance != NULL)
  7062. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  7063. }
  7064. if (typeInstance != NULL)
  7065. PopulateType(typeInstance);
  7066. int stackCount = mCompiler->mOptions.mAllocStackCount;
  7067. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  7068. {
  7069. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  7070. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  7071. }
  7072. SizedArray<BfIRValue, 2> dataValues;
  7073. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  7074. dataValues.Add(typeDataRef);
  7075. dataValues.Add(markFuncPtr);
  7076. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  7077. BfIRValue dataStruct = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  7078. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  7079. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  7080. return allocDataValue;
  7081. }
  7082. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  7083. {
  7084. BP_ZONE("AllocFromType");
  7085. BfScopeData* scopeData = allocTarget.mScopeData;
  7086. BF_ASSERT(!type->IsVar());
  7087. auto typeInstance = type->ToTypeInstance();
  7088. if ((typeInstance == NULL) && (type->IsGenericParam()))
  7089. typeInstance = mContext->mBfObjectType;
  7090. bool isHeapAlloc = scopeData == NULL;
  7091. bool isScopeAlloc = scopeData != NULL;
  7092. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  7093. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  7094. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  7095. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  7096. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  7097. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  7098. {
  7099. BfPointerType* ptrType = CreatePointerType(type);
  7100. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  7101. return val;
  7102. }
  7103. if (typeInstance != NULL)
  7104. mBfIRBuilder->PopulateType(typeInstance);
  7105. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  7106. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  7107. {
  7108. if (arraySize)
  7109. {
  7110. if (isRawArrayAlloc)
  7111. {
  7112. BfPointerType* ptrType = CreatePointerType(type);
  7113. return GetDefaultValue(ptrType);
  7114. }
  7115. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7116. return GetDefaultValue(arrayType);
  7117. }
  7118. if (type->IsValueType())
  7119. {
  7120. BfPointerType* ptrType = CreatePointerType(type);
  7121. return GetDefaultValue(ptrType);
  7122. }
  7123. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  7124. }
  7125. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  7126. BfIRValue sizeValue;
  7127. BfIRType allocType = mBfIRBuilder->MapType(type);
  7128. int allocSize = type->mSize;
  7129. int allocAlign = type->mAlign;
  7130. if (typeInstance != NULL)
  7131. {
  7132. if (!mBfIRBuilder->mIgnoreWrites)
  7133. typeInstance->mHasBeenInstantiated = true;
  7134. allocSize = typeInstance->mInstSize;
  7135. allocAlign = typeInstance->mInstAlign;
  7136. //if (typeInstance->IsEnum())
  7137. //allocType = typeInstance->mIRType;
  7138. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  7139. }
  7140. if (alignOverride != -1)
  7141. allocAlign = alignOverride;
  7142. // The "dynSize" cases:
  7143. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  7144. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  7145. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  7146. // though we'd expect their stack space to be released
  7147. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  7148. {
  7149. MarkDynStack(scopeData);
  7150. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7151. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  7152. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  7153. BfType* voidPtrType = CreatePointerType(voidType);
  7154. if (!mCurMethodState->mDynStackRevIdx)
  7155. {
  7156. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  7157. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7158. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7159. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  7160. mBfIRBuilder->ClearDebugLocation(storeInst);
  7161. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7162. }
  7163. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  7164. auto bytePtrType = CreatePointerType(byteType);
  7165. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  7166. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  7167. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7168. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7169. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  7170. mBfIRBuilder->ClearDebugLocation(storeInst);
  7171. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  7172. mBfIRBuilder->ClearDebugLocation(storeInst);
  7173. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7174. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  7175. if (IsTargetingBeefBackend())
  7176. {
  7177. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  7178. // to ensure there isn't any register collision during looping is just to not allow it to
  7179. // bind to a register at all
  7180. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  7181. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  7182. }
  7183. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  7184. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  7185. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  7186. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  7187. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  7188. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  7189. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  7190. mBfIRBuilder->AddBlock(verCheckBB);
  7191. mBfIRBuilder->SetInsertPoint(verCheckBB);
  7192. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  7193. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  7194. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  7195. mBfIRBuilder->AddBlock(resizeBB);
  7196. mBfIRBuilder->SetInsertPoint(resizeBB);
  7197. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  7198. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  7199. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  7200. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  7201. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  7202. mBfIRBuilder->CreateBr(endBB);
  7203. mBfIRBuilder->AddBlock(endBB);
  7204. mBfIRBuilder->SetInsertPoint(endBB);
  7205. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  7206. };
  7207. if (isScopeAlloc)
  7208. {
  7209. if (arraySize)
  7210. {
  7211. bool isConstantArraySize = arraySize.IsConst();
  7212. if (isRawArrayAlloc)
  7213. {
  7214. BfPointerType* ptrType = CreatePointerType(type);
  7215. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  7216. {
  7217. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7218. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  7219. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  7220. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  7221. }
  7222. else
  7223. {
  7224. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7225. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  7226. if (!isDynAlloc)
  7227. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7228. else
  7229. {
  7230. MarkDynStack(scopeData);
  7231. SaveStackState(scopeData);
  7232. }
  7233. int typeSize = type->GetStride();
  7234. BfIRValue allocaInst;
  7235. BfIRValue result;
  7236. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  7237. {
  7238. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  7239. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  7240. result = allocaInst;
  7241. }
  7242. else
  7243. {
  7244. if (typeInstance->IsStruct())
  7245. typeSize = typeInstance->GetInstStride();
  7246. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  7247. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  7248. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  7249. auto ptrType = CreatePointerType(typeInstance);
  7250. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  7251. if (!isDynAlloc)
  7252. mBfIRBuilder->ClearDebugLocation(result);
  7253. }
  7254. if (!isDynAlloc)
  7255. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7256. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7257. if (!isDynAlloc)
  7258. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7259. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  7260. if (arraySize.IsConst())
  7261. {
  7262. auto constant = mBfIRBuilder->GetConstant(arraySize);
  7263. if (constant->mInt64 == 0)
  7264. noDtorCall = true;
  7265. }
  7266. if (!noDtorCall)
  7267. {
  7268. bool isConstSize = arraySize.IsConst();
  7269. BfIRBlock clearBlock;
  7270. BfIRBlock contBlock;
  7271. if (!isConstSize)
  7272. {
  7273. clearBlock = mBfIRBuilder->CreateBlock("clear");
  7274. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  7275. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  7276. mBfIRBuilder->AddBlock(clearBlock);
  7277. mBfIRBuilder->SetInsertPoint(clearBlock);
  7278. }
  7279. AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  7280. if (!isConstSize)
  7281. {
  7282. mBfIRBuilder->CreateBr(contBlock);
  7283. mBfIRBuilder->AddBlock(contBlock);
  7284. mBfIRBuilder->SetInsertPoint(contBlock);
  7285. }
  7286. }
  7287. //InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7288. return result;
  7289. }
  7290. }
  7291. else
  7292. {
  7293. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  7294. {
  7295. // Generate and check new size
  7296. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7297. auto firstElementField = &arrayType->mFieldInstances.back();
  7298. int arrayClassSize = firstElementField->mDataOffset;
  7299. sizeValue = GetConstValue(arrayClassSize);
  7300. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7301. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  7302. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  7303. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  7304. if (!noDtorCall)
  7305. AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  7306. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7307. return typedVal.mValue;
  7308. }
  7309. else
  7310. {
  7311. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7312. auto firstElementField = &arrayType->mFieldInstances.back();
  7313. if (!type->IsValuelessType())
  7314. {
  7315. int arrayClassSize = firstElementField->mDataOffset;
  7316. sizeValue = GetConstValue(arrayClassSize);
  7317. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7318. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  7319. }
  7320. else
  7321. sizeValue = GetConstValue(arrayType->mInstSize);
  7322. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  7323. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  7324. if (!isDynAlloc)
  7325. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7326. else
  7327. {
  7328. MarkDynStack(scopeData);
  7329. SaveStackState(scopeData);
  7330. }
  7331. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  7332. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  7333. if (!isDynAlloc)
  7334. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7335. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7336. if (!isDynAlloc)
  7337. mBfIRBuilder->SetInsertPoint(prevBlock);
  7338. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  7339. mBfIRBuilder->ClearDebugLocation_Last();
  7340. if (!noDtorCall)
  7341. AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  7342. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7343. return typedVal.mValue;
  7344. }
  7345. }
  7346. }
  7347. else if (appendSizeValue)
  7348. {
  7349. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  7350. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  7351. // use the "dynSize" version conservatively
  7352. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  7353. {
  7354. // Generate and check new size
  7355. sizeValue = GetConstValue(typeInstance->mInstSize);
  7356. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  7357. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  7358. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  7359. if (!noDtorCall)
  7360. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  7361. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7362. return typedVal.mValue;
  7363. }
  7364. else // stack alloc, unlooped, with append
  7365. {
  7366. sizeValue = GetConstValue(typeInstance->mInstSize);
  7367. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  7368. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  7369. bool wasDynAlloc = isDynAlloc;
  7370. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  7371. if (!isDynAlloc)
  7372. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7373. else
  7374. {
  7375. MarkDynStack(scopeData);
  7376. SaveStackState(scopeData);
  7377. }
  7378. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  7379. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  7380. if (!isDynAlloc)
  7381. {
  7382. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7383. }
  7384. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7385. bool mayBeLarge = false;
  7386. if (sizeValue.IsConst())
  7387. {
  7388. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  7389. if (constantInt->mInt64 >= 4096)
  7390. mayBeLarge = true;
  7391. }
  7392. else
  7393. mayBeLarge = true;
  7394. if (((type->IsObject() && (!mayBeLarge))) ||
  7395. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  7396. ((zeroMemory) && (!mayBeLarge)))
  7397. {
  7398. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  7399. }
  7400. BfIRValue castedVal;
  7401. if (!isDynAlloc)
  7402. {
  7403. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7404. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  7405. mBfIRBuilder->ClearDebugLocation(castedVal);
  7406. mBfIRBuilder->SetInsertPoint(prevBlock);
  7407. if (WantsLifetimes())
  7408. {
  7409. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  7410. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  7411. }
  7412. }
  7413. else
  7414. {
  7415. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  7416. }
  7417. auto typedVal = BfTypedValue(castedVal, typeInstance);
  7418. if (!noDtorCall)
  7419. {
  7420. bool doCondAlloca = false;
  7421. if (!IsTargetingBeefBackend())
  7422. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  7423. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  7424. }
  7425. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7426. return typedVal.mValue;
  7427. }
  7428. }
  7429. else // "Normal" stack alloc
  7430. {
  7431. BF_ASSERT(!sizeValue);
  7432. //TODO: If sizeValue is a constant then do this in the head IR builder
  7433. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  7434. if (!isLoopedAlloc)
  7435. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7436. else
  7437. {
  7438. MarkDynStack(scopeData);
  7439. SaveStackState(scopeData);
  7440. }
  7441. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  7442. if (!isLoopedAlloc)
  7443. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7444. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7445. bool mayBeLarge = allocSize >= 4096;
  7446. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  7447. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  7448. ((zeroMemory) && (!mayBeLarge)))
  7449. {
  7450. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  7451. // and memset is always safe
  7452. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  7453. }
  7454. auto typedVal = BfTypedValue(allocaInst, type);
  7455. if (!isLoopedAlloc)
  7456. {
  7457. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7458. mBfIRBuilder->SetInsertPoint(prevBlock);
  7459. if (WantsLifetimes())
  7460. {
  7461. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  7462. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  7463. }
  7464. }
  7465. if (!noDtorCall)
  7466. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  7467. if (typeInstance != NULL)
  7468. {
  7469. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  7470. }
  7471. else
  7472. {
  7473. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  7474. }
  7475. return allocaInst;
  7476. }
  7477. }
  7478. else if (arraySize)
  7479. {
  7480. if (isRawArrayAlloc)
  7481. {
  7482. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7483. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  7484. }
  7485. else
  7486. {
  7487. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7488. typeInstance = arrayType;
  7489. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  7490. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  7491. appendSizeValue = elementDataSize;
  7492. if (!type->IsSizeAligned())
  7493. {
  7494. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  7495. }
  7496. }
  7497. }
  7498. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  7499. {
  7500. auto vDataRef = GetClassVDataPtr(typeInstance);
  7501. BfIRValue result;
  7502. bool isResultInitialized = false;
  7503. int stackCount = mCompiler->mOptions.mAllocStackCount;
  7504. if (typeInstance->mTypeOptionsIdx != -1)
  7505. {
  7506. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  7507. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  7508. }
  7509. if (!sizeValue)
  7510. sizeValue = GetConstValue(typeInstance->mInstSize);
  7511. if (appendSizeValue)
  7512. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  7513. BfIRValue origSizeValue = sizeValue;
  7514. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  7515. if (isAllocEx)
  7516. {
  7517. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  7518. if (prepareStackTraceMethod)
  7519. {
  7520. SizedArray<BfIRValue, 2> irArgs;
  7521. irArgs.Add(sizeValue);
  7522. irArgs.Add(GetConstValue(stackCount));
  7523. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  7524. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  7525. }
  7526. }
  7527. if (allocTarget.mCustomAllocator)
  7528. {
  7529. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  7530. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  7531. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  7532. {
  7533. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  7534. mBfIRBuilder->PopulateType(classVDataType);
  7535. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  7536. mBfIRBuilder->PopulateType(typeInstType);
  7537. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  7538. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  7539. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  7540. BfTypedValueExpression typedValueExpr;
  7541. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  7542. typedValueExpr.mRefNode = allocTarget.mRefNode;
  7543. BfExprEvaluator exprEvaluator(this);
  7544. SizedArray<BfExpression*, 2> argExprs;
  7545. argExprs.push_back(&typedValueExpr);
  7546. BfTypedValueExpression sizeValueExpr;
  7547. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  7548. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  7549. argExprs.push_back(&sizeValueExpr);
  7550. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  7551. BfResolvedArgs argValues(&sizedArgExprs);
  7552. exprEvaluator.ResolveArgValues(argValues);
  7553. exprEvaluator.mNoBind = true;
  7554. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  7555. if (allocResult)
  7556. {
  7557. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  7558. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  7559. else
  7560. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  7561. isResultInitialized = true;
  7562. }
  7563. }
  7564. }
  7565. bool wasAllocated = false;
  7566. if (!result)
  7567. {
  7568. if (hasCustomAllocator)
  7569. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  7570. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc))
  7571. {
  7572. SizedArray<BfIRValue, 4> llvmArgs;
  7573. llvmArgs.push_back(sizeValue);
  7574. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  7575. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  7576. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  7577. wasAllocated = true;
  7578. }
  7579. }
  7580. if (result)
  7581. {
  7582. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7583. {
  7584. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  7585. SizedArray<BfIRValue, 4> llvmArgs;
  7586. llvmArgs.push_back(objectPtr);
  7587. llvmArgs.push_back(origSizeValue);
  7588. llvmArgs.push_back(vDataRef);
  7589. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  7590. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  7591. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  7592. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  7593. if (wasAllocated)
  7594. {
  7595. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  7596. auto bytePtrType = CreatePointerType(byteType);
  7597. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  7598. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  7599. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  7600. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  7601. }
  7602. }
  7603. else
  7604. {
  7605. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  7606. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  7607. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  7608. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  7609. }
  7610. }
  7611. else
  7612. {
  7613. if ((mBfIRBuilder->mIgnoreWrites) || (mCompiler->mIsResolveOnly))
  7614. return GetDefaultValue(typeInstance);
  7615. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  7616. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  7617. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7618. {
  7619. SizedArray<BfIRValue, 4> llvmArgs;
  7620. llvmArgs.push_back(vData);
  7621. llvmArgs.push_back(sizeValue);
  7622. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  7623. llvmArgs.push_back(GetConstValue(stackCount));
  7624. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  7625. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  7626. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  7627. }
  7628. else
  7629. {
  7630. SizedArray<BfIRValue, 4> llvmArgs;
  7631. llvmArgs.push_back(sizeValue);
  7632. BfIRFunction irFunc;
  7633. if (mCompiler->mOptions.mDebugAlloc)
  7634. {
  7635. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  7636. irFunc = moduleMethodInstance.mFunc;
  7637. }
  7638. if (!irFunc)
  7639. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  7640. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  7641. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  7642. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  7643. mBfIRBuilder->CreateStore(vData, vdataPtr);
  7644. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  7645. }
  7646. }
  7647. if ((zeroMemory) && (arraySize))
  7648. {
  7649. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7650. typeInstance = arrayType;
  7651. auto firstElementField = &arrayType->mFieldInstances.back();
  7652. int arrayClassSize = firstElementField->mDataOffset;
  7653. BfIRValue elementDataSize;
  7654. bool skipZero = false;
  7655. if (arraySize.IsConst())
  7656. {
  7657. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  7658. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  7659. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  7660. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  7661. if (constVal->mInt64 <= 0)
  7662. skipZero = true;
  7663. }
  7664. else
  7665. {
  7666. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  7667. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7668. }
  7669. if (!skipZero)
  7670. {
  7671. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  7672. auto ptrType = CreatePointerType(i8Type);
  7673. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  7674. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  7675. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  7676. appendSizeValue = elementDataSize;
  7677. }
  7678. }
  7679. return result;
  7680. }
  7681. else
  7682. {
  7683. if (!sizeValue)
  7684. sizeValue = GetConstValue(allocSize);
  7685. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  7686. }
  7687. }
  7688. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  7689. {
  7690. if ((type == NULL) || (refNode == NULL))
  7691. return;
  7692. auto typeInstance = type->ToTypeInstance();
  7693. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  7694. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  7695. }
  7696. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  7697. {
  7698. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  7699. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  7700. }
  7701. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  7702. {
  7703. if (sizeMultiple == 0)
  7704. sizeMultiple = align;
  7705. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  7706. {
  7707. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  7708. {
  7709. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  7710. BF_ASSERT(localVar->mName == "appendIdx");
  7711. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  7712. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7713. if (align > 1)
  7714. {
  7715. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  7716. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  7717. }
  7718. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  7719. }
  7720. else
  7721. {
  7722. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  7723. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  7724. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  7725. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  7726. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  7727. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  7728. }
  7729. }
  7730. if (mCurMethodState->mCurAppendAlign == 0)
  7731. mCurMethodState->mCurAppendAlign = sizeMultiple;
  7732. else
  7733. {
  7734. if (sizeMultiple % align == 0)
  7735. mCurMethodState->mCurAppendAlign = align;
  7736. else
  7737. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  7738. }
  7739. }
  7740. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  7741. {
  7742. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  7743. BF_ASSERT(localVar->mName == "appendIdx");
  7744. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  7745. BfIRValue retValue;
  7746. BfTypeInstance* retTypeInstance = NULL;
  7747. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  7748. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  7749. if (arraySize)
  7750. {
  7751. if (isRawArrayAlloc)
  7752. {
  7753. EmitAppendAlign(type->mAlign);
  7754. BfPointerType* ptrType = CreatePointerType(type);
  7755. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  7756. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7757. if (mSystem->mPtrSize != 4)
  7758. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  7759. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7760. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7761. if (zeroMemory)
  7762. {
  7763. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  7764. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  7765. }
  7766. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  7767. }
  7768. else
  7769. {
  7770. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7771. EmitAppendAlign(arrayType->mAlign, type->mSize);
  7772. auto firstElementField = &arrayType->mFieldInstances.back();
  7773. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  7774. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  7775. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  7776. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  7777. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7778. if (mSystem->mPtrSize != 4)
  7779. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  7780. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7781. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7782. if (zeroMemory)
  7783. {
  7784. // Only zero out the actual elements
  7785. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  7786. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  7787. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  7788. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  7789. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  7790. }
  7791. retTypeInstance = arrayType;
  7792. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  7793. }
  7794. }
  7795. else
  7796. {
  7797. auto typeInst = type->ToTypeInstance();
  7798. BfIRValue sizeValue;
  7799. BfIRType toType;
  7800. if (typeInst != NULL)
  7801. {
  7802. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  7803. sizeValue = GetConstValue(typeInst->mInstSize);
  7804. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  7805. }
  7806. else
  7807. {
  7808. EmitAppendAlign(type->mAlign, type->mSize);
  7809. sizeValue = GetConstValue(type->mSize);
  7810. auto toPtrType = CreatePointerType(type);
  7811. toType = mBfIRBuilder->MapType(toPtrType);
  7812. }
  7813. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7814. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7815. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7816. retTypeInstance = typeInst;
  7817. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  7818. }
  7819. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  7820. {
  7821. mBfIRBuilder->PopulateType(retTypeInstance);
  7822. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  7823. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  7824. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  7825. auto curThis = GetThis();
  7826. BfIRValue newFlags;
  7827. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7828. {
  7829. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  7830. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  7831. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  7832. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  7833. }
  7834. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  7835. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  7836. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  7837. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  7838. mBfIRBuilder->CreateStore(srcVal, destAddr);
  7839. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7840. {
  7841. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  7842. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  7843. }
  7844. }
  7845. if (appendSizeValue)
  7846. {
  7847. EmitAppendAlign(appendAllocAlign);
  7848. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7849. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  7850. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7851. }
  7852. return retValue;
  7853. }
  7854. bool BfModule::IsOptimized()
  7855. {
  7856. if (mProject == NULL)
  7857. return false;
  7858. int optLevel = GetModuleOptions().mOptLevel;
  7859. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  7860. }
  7861. bool BfModule::IsTargetingBeefBackend()
  7862. {
  7863. if (mProject == NULL)
  7864. return false;
  7865. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  7866. }
  7867. bool BfModule::WantsLifetimes()
  7868. {
  7869. if (mProject == NULL)
  7870. return false;
  7871. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  7872. }
  7873. bool BfModule::HasCompiledOutput()
  7874. {
  7875. return (!mSystem->mIsResolveOnly) && (mIsReified);
  7876. }
  7877. // We will skip the object access check for any occurances of this value
  7878. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  7879. {
  7880. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  7881. return;
  7882. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  7883. return;
  7884. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  7885. return;
  7886. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  7887. }
  7888. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  7889. {
  7890. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  7891. return;
  7892. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  7893. return;
  7894. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  7895. auto typeOptions = GetTypeOptions();
  7896. if (typeOptions != NULL)
  7897. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  7898. if (!emitObjectAccessCheck)
  7899. return;
  7900. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  7901. {
  7902. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  7903. return;
  7904. }
  7905. if (typedVal.IsAddr())
  7906. typedVal = LoadValue(typedVal);
  7907. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  7908. }
  7909. void BfModule::EmitEnsureInstructionAt()
  7910. {
  7911. if (mProject == NULL)
  7912. return;
  7913. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  7914. return;
  7915. mBfIRBuilder->CreateEnsureInstructionAt();
  7916. }
  7917. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  7918. {
  7919. if (mBfIRBuilder->mIgnoreWrites)
  7920. return; // Nothing needed here
  7921. auto irb = mBfIRBuilder;
  7922. auto checkBB = irb->CreateBlock("as.check");
  7923. auto isNull = irb->CreateIsNull(targetValue.mValue);
  7924. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  7925. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7926. auto intPtrType = CreatePointerType(intType);
  7927. auto intPtrPtrType = CreatePointerType(intPtrType);
  7928. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  7929. auto int32PtrType = CreatePointerType(int32Type);
  7930. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  7931. if (mCompiler->mOptions.mAllowHotSwapping)
  7932. {
  7933. BfExprEvaluator exprEvaluator(this);
  7934. AddBasicBlock(checkBB);
  7935. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7936. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  7937. SizedArray<BfIRValue, 4> irArgs;
  7938. irArgs.push_back(objectParam);
  7939. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  7940. auto callResult = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  7941. auto resultType = ResolveTypeDef(mSystem->mTypeBool);
  7942. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  7943. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7944. }
  7945. else
  7946. {
  7947. AddBasicBlock(checkBB);
  7948. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  7949. vDataPtr = irb->CreateLoad(vDataPtr);
  7950. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7951. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  7952. if (targetType->IsInterface())
  7953. {
  7954. auto targetTypeInst = targetType->ToTypeInstance();
  7955. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7956. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  7957. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  7958. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7959. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  7960. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  7961. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  7962. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  7963. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  7964. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7965. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  7966. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  7967. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7968. }
  7969. else
  7970. {
  7971. if (!targetType->IsTypeInstance())
  7972. targetType = GetWrappedStructType(targetType);
  7973. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7974. int inheritanceIdOfs = mSystem->mPtrSize;
  7975. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7976. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7977. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  7978. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  7979. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  7980. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  7981. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  7982. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7983. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  7984. fieldInst = &typeTypeInstance->mFieldInstances[10];
  7985. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  7986. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7987. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  7988. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  7989. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  7990. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7991. }
  7992. }
  7993. }
  7994. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  7995. {
  7996. if (mBfIRBuilder->mIgnoreWrites)
  7997. return;
  7998. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  7999. auto typeOptions = GetTypeOptions();
  8000. if (typeOptions != NULL)
  8001. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  8002. if (emitDynamicCastCheck)
  8003. {
  8004. int wantTypeId = 0;
  8005. if (!type->IsGenericParam())
  8006. wantTypeId = type->mTypeId;
  8007. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  8008. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  8009. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  8010. AddBasicBlock(failBlock);
  8011. SizedArray<BfIRValue, 8> llvmArgs;
  8012. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8013. llvmArgs.push_back(bitAddr);
  8014. llvmArgs.push_back(GetConstValue32(wantTypeId));
  8015. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  8016. BF_ASSERT(objDynCheck);
  8017. if (objDynCheck)
  8018. {
  8019. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  8020. }
  8021. mBfIRBuilder->CreateBr(endBlock);
  8022. AddBasicBlock(endBlock);
  8023. }
  8024. }
  8025. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  8026. {
  8027. if (mBfIRBuilder->mIgnoreWrites)
  8028. {
  8029. if (toType == mContext->mBfObjectType)
  8030. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  8031. if (toType->IsBoxed())
  8032. {
  8033. BfBoxedType* boxedType = (BfBoxedType*)toType;
  8034. if (boxedType->mElementType->IsGenericParam())
  8035. {
  8036. if (typedVal.mType == boxedType->mElementType)
  8037. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  8038. else
  8039. return BfTypedValue();
  8040. }
  8041. }
  8042. }
  8043. BP_ZONE("BoxValue");
  8044. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  8045. if (typedVal.mType->IsNullable())
  8046. {
  8047. typedVal = MakeAddressable(typedVal);
  8048. auto innerType = typedVal.mType->GetUnderlyingType();
  8049. if (!innerType->IsValueType())
  8050. {
  8051. if (!mIgnoreErrors)
  8052. Fail("Only value types can be boxed", srcNode);
  8053. return BfTypedValue();
  8054. }
  8055. auto boxedType = CreateBoxedType(innerType);
  8056. auto resultType = toType;
  8057. if (resultType == NULL)
  8058. resultType = boxedType;
  8059. if (mBfIRBuilder->mIgnoreWrites)
  8060. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  8061. auto prevBB = mBfIRBuilder->GetInsertBlock();
  8062. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  8063. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  8064. mBfIRBuilder->PopulateType(typedVal.mType);
  8065. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  8066. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  8067. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  8068. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  8069. mBfIRBuilder->AddBlock(boxBB);
  8070. mBfIRBuilder->SetInsertPoint(boxBB);
  8071. BfScopeData newScope;
  8072. newScope.mOuterIsConditional = true;
  8073. mCurMethodState->AddScope(&newScope);
  8074. NewScopeState();
  8075. BfIRValue nullableValueAddr;
  8076. BfIRValue loadedVal;
  8077. if (innerType->IsValuelessType())
  8078. {
  8079. loadedVal = mBfIRBuilder->GetFakeVal();
  8080. }
  8081. else
  8082. {
  8083. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  8084. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  8085. }
  8086. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  8087. RestoreScopeState();
  8088. if (!boxedVal)
  8089. return BfTypedValue();
  8090. mBfIRBuilder->CreateBr(endBB);
  8091. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  8092. mBfIRBuilder->AddBlock(endBB);
  8093. mBfIRBuilder->SetInsertPoint(endBB);
  8094. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  8095. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  8096. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  8097. return BfTypedValue(phi, resultType);
  8098. }
  8099. bool alreadyCheckedCast = false;
  8100. BfTypeInstance* toTypeInstance = NULL;
  8101. if (toType != NULL)
  8102. toTypeInstance = toType->ToTypeInstance();
  8103. bool isStructPtr = typedVal.mType->IsStructPtr();
  8104. if (fromStructTypeInstance == NULL)
  8105. {
  8106. auto primType = (BfPrimitiveType*)typedVal.mType;
  8107. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  8108. {
  8109. // Can always do IHashable
  8110. alreadyCheckedCast = true;
  8111. }
  8112. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  8113. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  8114. if (isStructPtr)
  8115. {
  8116. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  8117. alreadyCheckedCast = true;
  8118. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  8119. }
  8120. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  8121. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  8122. }
  8123. if (fromStructTypeInstance == NULL)
  8124. return BfTypedValue();
  8125. // Need to box it
  8126. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  8127. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  8128. {
  8129. if (mBfIRBuilder->mIgnoreWrites)
  8130. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  8131. auto boxedType = CreateBoxedType(typedVal.mType);
  8132. mBfIRBuilder->PopulateType(boxedType);
  8133. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  8134. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  8135. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  8136. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  8137. if (boxedType->IsUnspecializedType())
  8138. {
  8139. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  8140. }
  8141. else
  8142. {
  8143. PopulateType(fromStructTypeInstance);
  8144. if (!fromStructTypeInstance->IsValuelessType())
  8145. {
  8146. typedVal = LoadValue(typedVal);
  8147. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  8148. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  8149. {
  8150. auto ptrType = CreatePointerType(typedVal.mType);
  8151. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  8152. }
  8153. if (typedVal.IsSplat())
  8154. {
  8155. AggregateSplatIntoAddr(typedVal, valPtr);
  8156. }
  8157. else
  8158. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  8159. }
  8160. }
  8161. if (toType == NULL)
  8162. {
  8163. return BfTypedValue(allocaInst, boxedType);
  8164. }
  8165. else
  8166. {
  8167. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  8168. return BfTypedValue(castedValue, toType);
  8169. }
  8170. }
  8171. return BfTypedValue();
  8172. }
  8173. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  8174. {
  8175. BfTypeInstance* checkTypeInst = typeInst;
  8176. while (checkTypeInst != NULL)
  8177. {
  8178. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  8179. {
  8180. if (checkProp->mName == propDef->mName)
  8181. {
  8182. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  8183. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  8184. {
  8185. propDef = checkProp;
  8186. typeInst = checkTypeInst;
  8187. return true;
  8188. }
  8189. }
  8190. }
  8191. checkTypeInst = checkTypeInst->mBaseType;
  8192. }
  8193. return false;
  8194. }
  8195. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  8196. {
  8197. if (!typeInstance->mResolvingVarField)
  8198. {
  8199. if (typeInstance->IsIncomplete())
  8200. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8201. }
  8202. else
  8203. {
  8204. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  8205. {
  8206. AssertErrorState();
  8207. return NULL;
  8208. }
  8209. }
  8210. if (assertName != NULL)
  8211. {
  8212. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  8213. }
  8214. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  8215. if (methodGroup.mDefault == NULL)
  8216. {
  8217. if (!mCompiler->mIsResolveOnly)
  8218. {
  8219. // Get it from the owning module so we don't create a reference prematurely...
  8220. auto declModule = typeInstance->mModule;
  8221. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  8222. {
  8223. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  8224. declModule->mOnDemandMethodCount++;
  8225. }
  8226. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) || (typeInstance->mTypeFailed));
  8227. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  8228. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  8229. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified)).mMethodInstance;
  8230. }
  8231. else
  8232. {
  8233. auto declModule = typeInstance->mModule;
  8234. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass)).mMethodInstance;
  8235. }
  8236. }
  8237. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  8238. //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
  8239. // be from a call to the NON-raw version
  8240. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  8241. // {
  8242. // methodInstance->mIsReified = mIsReified;
  8243. // if (methodInstance->mMethodProcessRequest == NULL)
  8244. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  8245. // }
  8246. return methodInstance;
  8247. }
  8248. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  8249. {
  8250. if (methodDef->mIsLocalMethod)
  8251. {
  8252. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  8253. }
  8254. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  8255. }
  8256. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  8257. {
  8258. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8259. while (typeInstance != NULL)
  8260. {
  8261. typeInstance->mTypeDef->PopulateMemberSets();
  8262. BfMemberSetEntry* entry = NULL;
  8263. BfMethodDef* methodDef = NULL;
  8264. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8265. methodDef = (BfMethodDef*)entry->mMemberDef;
  8266. while (methodDef != NULL)
  8267. {
  8268. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  8269. (methodDef->mGenericParams.size() == 0) &&
  8270. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8271. return GetRawMethodInstance(typeInstance, methodDef);
  8272. methodDef = methodDef->mNextWithSameName;
  8273. }
  8274. if (!checkBase)
  8275. break;
  8276. typeInstance = typeInstance->mBaseType;
  8277. }
  8278. return NULL;
  8279. }
  8280. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  8281. {
  8282. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  8283. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  8284. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  8285. if (!useUnspecializedType)
  8286. return methodInstance;
  8287. if (!owner->IsGenericTypeInstance())
  8288. return methodInstance;
  8289. BF_ASSERT(!owner->IsDelegateFromTypeRef());
  8290. BF_ASSERT(!owner->IsTuple());
  8291. auto genericType = (BfTypeInstance*)owner;
  8292. if (genericType->IsUnspecializedType())
  8293. return methodInstance;
  8294. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  8295. if (unspecializedType == NULL)
  8296. {
  8297. AssertErrorState();
  8298. return methodInstance;
  8299. }
  8300. if (unspecializedType == NULL)
  8301. return methodInstance;
  8302. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  8303. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  8304. }
  8305. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  8306. {
  8307. int genericCount = 0;
  8308. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  8309. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  8310. {
  8311. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  8312. if (param->IsGenericParam())
  8313. genericCount++;
  8314. }
  8315. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  8316. genericCount++;
  8317. return genericCount;
  8318. }
  8319. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  8320. {
  8321. BF_ASSERT(!mIsScratchModule);
  8322. BF_ASSERT(mIsReified);
  8323. BfModule* mainModule = this;
  8324. if (mParentModule != NULL)
  8325. mainModule = mParentModule;
  8326. BfModule* specModule = NULL;
  8327. BfModule** specModulePtr = NULL;
  8328. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  8329. {
  8330. return *specModulePtr;
  8331. }
  8332. else
  8333. {
  8334. String specModuleName = mModuleName;
  8335. for (auto bfProject : projectList)
  8336. specModuleName += StrFormat("@%s", bfProject->mName.c_str());
  8337. specModule = new BfModule(mContext, specModuleName);
  8338. specModule->mProject = mainModule->mProject;
  8339. specModule->mParentModule = mainModule;
  8340. specModule->mIsSpecializedMethodModuleRoot = true;
  8341. specModule->Init();
  8342. Array<BfProject*> projList;
  8343. for (auto project : projectList)
  8344. projList.Add(project);
  8345. mainModule->mSpecializedMethodModules[projList] = specModule;
  8346. }
  8347. return specModule;
  8348. }
  8349. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  8350. {
  8351. if (mCompiler->IsSkippingExtraResolveChecks())
  8352. return BfIRValue();
  8353. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  8354. {
  8355. //BF_ASSERT(!methodInstance->mIRFunction);
  8356. return BfIRValue();
  8357. }
  8358. auto methodDef = methodInstance->mMethodDef;
  8359. StringT<128> methodName;
  8360. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  8361. if (isInlined != methodInstance->mAlwaysInline)
  8362. {
  8363. if (isInlined)
  8364. methodName += "__INLINE";
  8365. else
  8366. methodName += "__NOINLINE";
  8367. }
  8368. if (tryExisting)
  8369. {
  8370. auto func = mBfIRBuilder->GetFunction(methodName);
  8371. if (func)
  8372. return func;
  8373. }
  8374. auto intrinsic = GetIntrinsic(methodInstance);
  8375. if (intrinsic)
  8376. return intrinsic;
  8377. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  8378. {
  8379. return CreateDllImportGlobalVar(methodInstance, false);
  8380. }
  8381. BfIRType returnType;
  8382. SizedArray<BfIRType, 8> paramTypes;
  8383. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  8384. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  8385. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  8386. auto callingConv = GetIRCallingConvention(methodInstance);
  8387. if (callingConv != BfIRCallingConv_CDecl)
  8388. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  8389. SetupIRMethod(methodInstance, func, isInlined);
  8390. // auto srcModule = methodInstance->GetOwner()->GetModule();
  8391. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  8392. // {
  8393. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  8394. // {
  8395. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  8396. // }
  8397. // }
  8398. return func;
  8399. }
  8400. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  8401. {
  8402. if (assertName != NULL)
  8403. {
  8404. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  8405. }
  8406. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8407. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  8408. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  8409. {
  8410. // Can't use it, not reified
  8411. methodInstance = NULL;
  8412. }
  8413. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  8414. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  8415. {
  8416. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  8417. return BfModuleMethodInstance(methodInstance, func);
  8418. }
  8419. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  8420. }
  8421. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  8422. {
  8423. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8424. while (typeInstance != NULL)
  8425. {
  8426. typeInstance->mTypeDef->PopulateMemberSets();
  8427. BfMemberSetEntry* entry = NULL;
  8428. BfMethodDef* methodDef = NULL;
  8429. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8430. methodDef = (BfMethodDef*)entry->mMemberDef;
  8431. while (methodDef != NULL)
  8432. {
  8433. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  8434. (methodDef->mGenericParams.size() == 0) &&
  8435. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8436. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  8437. methodDef = methodDef->mNextWithSameName;
  8438. }
  8439. if (!checkBase)
  8440. break;
  8441. typeInstance = typeInstance->mBaseType;
  8442. }
  8443. return BfModuleMethodInstance();
  8444. }
  8445. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  8446. {
  8447. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8448. while (typeInstance != NULL)
  8449. {
  8450. typeInstance->mTypeDef->PopulateMemberSets();
  8451. BfMemberSetEntry* entry = NULL;
  8452. BfMethodDef* methodDef = NULL;
  8453. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8454. methodDef = (BfMethodDef*)entry->mMemberDef;
  8455. while (methodDef != NULL)
  8456. {
  8457. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  8458. (methodDef->mGenericParams.size() == 0) &&
  8459. (paramTypes.size() == methodDef->mParams.size()))
  8460. {
  8461. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  8462. if (moduleMethodInstance.mMethodInstance != NULL)
  8463. {
  8464. bool matches = true;
  8465. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  8466. {
  8467. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  8468. matches = false;
  8469. }
  8470. if (matches)
  8471. return moduleMethodInstance;
  8472. }
  8473. }
  8474. methodDef = methodDef->mNextWithSameName;
  8475. }
  8476. if (!checkBase)
  8477. break;
  8478. typeInstance = typeInstance->mBaseType;
  8479. }
  8480. return BfModuleMethodInstance();
  8481. }
  8482. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  8483. {
  8484. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  8485. PopulateType(internalType);
  8486. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  8487. if (!moduleMethodInstance)
  8488. {
  8489. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  8490. }
  8491. return moduleMethodInstance;
  8492. }
  8493. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  8494. {
  8495. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  8496. typeInstance->mOperatorInfo.Add(NULL);
  8497. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  8498. {
  8499. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  8500. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  8501. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  8502. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  8503. if (operatorDef->mReturnTypeRef != NULL)
  8504. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  8505. if (operatorDef->mParams.size() >= 1)
  8506. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  8507. if (operatorDef->mParams.size() >= 2)
  8508. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  8509. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  8510. }
  8511. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  8512. }
  8513. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  8514. {
  8515. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  8516. if (operatorInfo == NULL)
  8517. return NULL;
  8518. if (operatorInfo->mReturnType == NULL)
  8519. return NULL;
  8520. if (lhs)
  8521. {
  8522. if (operatorInfo->mLHSType == NULL)
  8523. return NULL;
  8524. if (!CanCast(lhs, operatorInfo->mLHSType, BfCastFlags_IsConstraintCheck))
  8525. return NULL;
  8526. }
  8527. if (rhs)
  8528. {
  8529. if (operatorInfo->mRHSType == NULL)
  8530. return NULL;
  8531. if (!CanCast(rhs, operatorInfo->mRHSType, BfCastFlags_IsConstraintCheck))
  8532. return NULL;
  8533. }
  8534. return operatorInfo->mReturnType;
  8535. }
  8536. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  8537. {
  8538. while (typeInstance != NULL)
  8539. {
  8540. typeInstance->mTypeDef->PopulateMemberSets();
  8541. BfMemberSetEntry* entry = NULL;
  8542. BfMethodDef* methodDef = NULL;
  8543. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8544. methodDef = (BfMethodDef*)entry->mMemberDef;
  8545. while (methodDef != NULL)
  8546. {
  8547. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  8548. (methodDef->mGenericParams.size() == 0) &&
  8549. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8550. {
  8551. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  8552. if (!methodInstanceGroup.IsImplemented())
  8553. return false;
  8554. if (methodInstanceGroup.mDefault == NULL)
  8555. return false;
  8556. return methodInstanceGroup.mDefault->mIsReified;
  8557. }
  8558. methodDef = methodDef->mNextWithSameName;
  8559. }
  8560. if (!checkBase)
  8561. break;
  8562. typeInstance = typeInstance->mBaseType;
  8563. }
  8564. return false;
  8565. }
  8566. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  8567. {
  8568. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8569. while (typeInstance != NULL)
  8570. {
  8571. typeInstance->mTypeDef->PopulateMemberSets();
  8572. BfMemberSetEntry* entry = NULL;
  8573. BfMethodDef* methodDef = NULL;
  8574. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8575. methodDef = (BfMethodDef*)entry->mMemberDef;
  8576. while (methodDef != NULL)
  8577. {
  8578. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  8579. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8580. return true;
  8581. methodDef = methodDef->mNextWithSameName;
  8582. }
  8583. if (!checkBase)
  8584. break;
  8585. typeInstance = typeInstance->mBaseType;
  8586. }
  8587. return BfModuleMethodInstance();
  8588. }
  8589. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* methodGenericArgs)
  8590. {
  8591. auto methodDef = methodInst->mMethodDef;
  8592. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  8593. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8594. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  8595. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  8596. type = ResolveGenericType(type, NULL, methodGenericArgs);
  8597. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  8598. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8599. if (allowResolveGenericParamNames)
  8600. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8601. StringT<128> methodName;
  8602. auto _AddTypeName = [&](BfType* type)
  8603. {
  8604. auto typeNameFlags = BfTypeNameFlags_None;
  8605. if (allowResolveGenericParamNames)
  8606. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8607. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  8608. type = ResolveGenericType(type, NULL, methodGenericArgs);
  8609. methodName += TypeToString(type, typeNameFlags);
  8610. };
  8611. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  8612. {
  8613. _AddTypeName(methodInst->mReturnType);
  8614. methodName += " ";
  8615. }
  8616. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  8617. {
  8618. methodName += TypeToString(type, typeNameFlags);
  8619. if (methodName == "$")
  8620. methodName = "";
  8621. else if (!methodName.IsEmpty())
  8622. methodName += ".";
  8623. }
  8624. String accessorString;
  8625. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  8626. if (methodInst->mMethodDef->mIsLocalMethod)
  8627. {
  8628. int atPos = (int)methodDefName.IndexOf('$');
  8629. methodDefName.RemoveToEnd(atPos);
  8630. methodDefName.Replace("@", ".");
  8631. }
  8632. else
  8633. {
  8634. int atPos = (int)methodDefName.IndexOf('$');
  8635. if (atPos != -1)
  8636. {
  8637. accessorString = methodDefName.Substring(0, atPos);
  8638. if ((accessorString == "get") || (accessorString == "set"))
  8639. {
  8640. methodDefName = methodDefName.Substring(atPos + 1);
  8641. }
  8642. else
  8643. accessorString = "";
  8644. }
  8645. }
  8646. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  8647. {
  8648. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8649. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  8650. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8651. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  8652. methodName += ".";
  8653. }
  8654. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  8655. {
  8656. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8657. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  8658. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8659. methodName += "[";
  8660. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  8661. methodName += "].";
  8662. }
  8663. if (methodDef->mMethodType == BfMethodType_Operator)
  8664. {
  8665. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  8666. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  8667. {
  8668. // Don't add explicit/implicit part, since that's not available in GCC mangling
  8669. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  8670. {
  8671. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  8672. methodName += "explicit ";
  8673. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  8674. methodName += "explicit ";
  8675. }*/
  8676. methodName += "operator ";
  8677. if (methodInst->mReturnType != NULL)
  8678. methodName += TypeToString(methodInst->mReturnType);
  8679. }
  8680. else
  8681. {
  8682. methodName += "operator";
  8683. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  8684. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  8685. }
  8686. }
  8687. else if (methodDef->mMethodType == BfMethodType_Ctor)
  8688. {
  8689. if (methodDef->mIsStatic)
  8690. methodName += "__BfStaticCtor";
  8691. else
  8692. methodName += "this";
  8693. accessorString = "";
  8694. }
  8695. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  8696. {
  8697. auto propertyDecl = methodDef->GetPropertyDeclaration();
  8698. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  8699. {
  8700. methodName += "get indexer";
  8701. }
  8702. else
  8703. {
  8704. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  8705. propertyDecl->mNameNode->ToString(methodName);
  8706. methodName += " get accessor";
  8707. return methodName;
  8708. }
  8709. }
  8710. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8711. {
  8712. auto propertyDecl = methodDef->GetPropertyDeclaration();
  8713. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  8714. {
  8715. methodName += "set indexer";
  8716. }
  8717. else
  8718. {
  8719. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  8720. propertyDecl->mNameNode->ToString(methodName);
  8721. methodName += " set accessor";
  8722. return methodName;
  8723. }
  8724. }
  8725. else
  8726. methodName += methodDefName;
  8727. if (methodDef->mMethodType == BfMethodType_Mixin)
  8728. methodName += "!";
  8729. BfTypeVector newMethodGenericArgs;
  8730. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  8731. {
  8732. methodName += "<";
  8733. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  8734. {
  8735. if (i > 0)
  8736. methodName += ", ";
  8737. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8738. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  8739. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  8740. if (allowResolveGenericParamNames)
  8741. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8742. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  8743. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  8744. {
  8745. bool hasEmpty = false;
  8746. for (auto arg : *methodGenericArgs)
  8747. {
  8748. if (arg == NULL)
  8749. hasEmpty = true;
  8750. }
  8751. if (hasEmpty)
  8752. {
  8753. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  8754. {
  8755. auto arg = (*methodGenericArgs)[genericIdx];
  8756. if (arg != NULL)
  8757. newMethodGenericArgs.push_back(arg);
  8758. else
  8759. {
  8760. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  8761. if (genericParamInst->mTypeConstraint != NULL)
  8762. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  8763. else
  8764. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  8765. }
  8766. }
  8767. methodGenericArgs = &newMethodGenericArgs;
  8768. }
  8769. if (type->IsUnspecializedType())
  8770. type = ResolveGenericType(type, NULL, methodGenericArgs);
  8771. }
  8772. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  8773. {
  8774. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  8775. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  8776. methodName += TypeToString(type, typeNameFlags);
  8777. }
  8778. else
  8779. methodName += TypeToString(type, typeNameFlags);
  8780. }
  8781. methodName += ">";
  8782. }
  8783. if (accessorString.length() == 0)
  8784. {
  8785. int dispParamIdx = 0;
  8786. methodName += "(";
  8787. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  8788. {
  8789. int paramKind = methodInst->GetParamKind(paramIdx);
  8790. if (paramKind == BfParamKind_ImplicitCapture)
  8791. continue;
  8792. if (dispParamIdx > 0)
  8793. methodName += ", ";
  8794. if (paramKind == BfParamKind_Params)
  8795. methodName += "params ";
  8796. BfType* type = methodInst->GetParamType(paramIdx);
  8797. _AddTypeName(type);
  8798. methodName += " ";
  8799. methodName += methodInst->GetParamName(paramIdx);
  8800. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  8801. if (paramInitializer != NULL)
  8802. {
  8803. methodName += " = ";
  8804. methodName += paramInitializer->ToString();
  8805. }
  8806. dispParamIdx++;
  8807. }
  8808. methodName += ")";
  8809. }
  8810. if (accessorString.length() != 0)
  8811. {
  8812. methodName += " " + accessorString;
  8813. }
  8814. return methodName;
  8815. }
  8816. void BfModule::pv(BfType* type)
  8817. {
  8818. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  8819. }
  8820. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  8821. {
  8822. if ((flagsLeft & checkFlag) == 0)
  8823. return;
  8824. if (!str.empty())
  8825. {
  8826. if (flagsLeft == checkFlag)
  8827. {
  8828. if ((int)str.IndexOf(',') != -1)
  8829. str += ", and ";
  8830. else
  8831. str += " and ";
  8832. }
  8833. else
  8834. str += ", ";
  8835. }
  8836. str += addString;
  8837. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  8838. }
  8839. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  8840. {
  8841. String resultStr;
  8842. auto flagsLeft = attrTarget;
  8843. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  8844. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  8845. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  8846. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  8847. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  8848. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  8849. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  8850. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  8851. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  8852. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  8853. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  8854. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  8855. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  8856. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  8857. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  8858. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  8859. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  8860. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  8861. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  8862. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  8863. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  8864. if (resultStr.IsEmpty())
  8865. return "<nothing>";
  8866. return resultStr;
  8867. }
  8868. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  8869. {
  8870. auto constant = mBfIRBuilder->GetConstant(irVal);
  8871. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  8872. if (stringPoolIdx != -1)
  8873. {
  8874. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  8875. return;
  8876. }
  8877. if (constant->mConstType == BfConstType_Array)
  8878. {
  8879. auto constArray = (BfConstantArray*)constant;
  8880. SizedArray<BfIRValue, 8> newVals;
  8881. for (auto val : constArray->mValues)
  8882. {
  8883. auto newVal = val;
  8884. CurrentAddToConstHolder(newVal);
  8885. newVals.push_back(newVal);
  8886. }
  8887. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstArray(constArray->mType, newVals);
  8888. return;
  8889. }
  8890. auto origConst = irVal;
  8891. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  8892. {
  8893. auto bitcast = (BfConstantBitCast*)constant;
  8894. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  8895. }
  8896. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  8897. }
  8898. void BfModule::ClearConstData()
  8899. {
  8900. mBfIRBuilder->ClearConstData();
  8901. mStringObjectPool.Clear();
  8902. mStringCharPtrPool.Clear();
  8903. mStringPoolRefs.Clear();
  8904. }
  8905. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8906. {
  8907. switch (constant->mTypeCode)
  8908. {
  8909. case BfTypeCode_StringId:
  8910. case BfTypeCode_Boolean:
  8911. case BfTypeCode_Int8:
  8912. case BfTypeCode_UInt8:
  8913. case BfTypeCode_Int16:
  8914. case BfTypeCode_UInt16:
  8915. case BfTypeCode_Int32:
  8916. case BfTypeCode_UInt32:
  8917. case BfTypeCode_Int64:
  8918. case BfTypeCode_UInt64:
  8919. case BfTypeCode_IntPtr:
  8920. case BfTypeCode_UIntPtr:
  8921. case BfTypeCode_IntUnknown:
  8922. case BfTypeCode_UIntUnknown:
  8923. case BfTypeCode_Char8:
  8924. case BfTypeCode_Char16:
  8925. case BfTypeCode_Char32:
  8926. case BfTypeCode_Float:
  8927. case BfTypeCode_Double:
  8928. {
  8929. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  8930. BfTypedValue typedValue;
  8931. if (constant->mTypeCode == BfTypeCode_StringId)
  8932. {
  8933. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  8934. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  8935. {
  8936. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType), wantType);
  8937. return typedValue;
  8938. }
  8939. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  8940. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType), stringType);
  8941. }
  8942. if (!typedValue)
  8943. {
  8944. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  8945. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  8946. }
  8947. if (typedValue.mType == wantType)
  8948. return typedValue;
  8949. if (wantType->IsTypedPrimitive())
  8950. {
  8951. if (typedValue.mType == wantType->GetUnderlyingType())
  8952. {
  8953. typedValue.mType = wantType;
  8954. return typedValue;
  8955. }
  8956. }
  8957. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  8958. if (!castedTypedValue)
  8959. return BfTypedValue();
  8960. return castedTypedValue;
  8961. }
  8962. break;
  8963. default: break;
  8964. }
  8965. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  8966. BF_ASSERT(irValue);
  8967. if (!irValue)
  8968. return BfTypedValue();
  8969. if (constant->mConstType == BfConstType_GlobalVar)
  8970. {
  8971. auto result = BfTypedValue(irValue, wantType, true);
  8972. if (!wantType->IsComposite())
  8973. result = LoadValue(result);
  8974. return result;
  8975. }
  8976. return BfTypedValue(irValue, wantType, false);
  8977. }
  8978. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8979. {
  8980. if (constant->mTypeCode == BfTypeCode_NullPtr)
  8981. {
  8982. return GetDefaultValue(wantType);
  8983. }
  8984. if (constant->mTypeCode == BfTypeCode_StringId)
  8985. {
  8986. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  8987. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  8988. {
  8989. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  8990. BfIRValue stringObjConst = GetStringObjectValue(str);
  8991. if (wantType->IsPointer())
  8992. return GetStringCharPtr(stringObjConst);
  8993. return stringObjConst;
  8994. }
  8995. }
  8996. if (constant->mConstType == BfConstType_Array)
  8997. {
  8998. auto elementType = wantType->GetUnderlyingType();
  8999. auto constArray = (BfConstantArray*)constant;
  9000. SizedArray<BfIRValue, 8> newVals;
  9001. for (auto val : constArray->mValues)
  9002. {
  9003. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  9004. }
  9005. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  9006. }
  9007. return mBfIRBuilder->CreateConst(constant, constHolder);
  9008. }
  9009. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  9010. {
  9011. if (attrTarget == BfAttributeTargets_SkipValidate)
  9012. return;
  9013. for (auto& customAttribute : customAttributes->mAttributes)
  9014. {
  9015. if (!customAttribute.mAwaitingValidation)
  9016. continue;
  9017. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  9018. {
  9019. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  9020. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  9021. }
  9022. customAttribute.mAwaitingValidation = false;
  9023. }
  9024. }
  9025. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, bool allowNonConstArgs, BfCaptureInfo* captureInfo)
  9026. {
  9027. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9028. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9029. {
  9030. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9031. }
  9032. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  9033. if (mCompiler->IsAutocomplete())
  9034. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  9035. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  9036. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  9037. BfAutoComplete* autoComplete = NULL;
  9038. if (mCompiler->mResolvePassData != NULL)
  9039. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  9040. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  9041. {
  9042. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  9043. {
  9044. if (captureInfo == NULL)
  9045. {
  9046. Fail("Capture specifiers can only be used in lambda allocations", attributesDirective);
  9047. continue;
  9048. }
  9049. BfCaptureInfo::Entry captureEntry;
  9050. captureEntry.mCaptureType = (tokenNode->mToken == BfToken_Ampersand) ? BfCaptureType_Reference : BfCaptureType_Copy;
  9051. if (!attributesDirective->mArguments.IsEmpty())
  9052. {
  9053. captureEntry.mNameNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]);
  9054. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  9055. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  9056. }
  9057. captureInfo->mCaptures.Add(captureEntry);
  9058. continue;
  9059. }
  9060. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  9061. BfCustomAttribute customAttribute;
  9062. customAttribute.mAwaitingValidation = true;
  9063. customAttribute.mRef = attributesDirective;
  9064. if (attributesDirective->mAttrOpenToken != NULL)
  9065. targetOverride = (BfAttributeTargets)0;
  9066. if (attributesDirective->mAttributeTypeRef == NULL)
  9067. {
  9068. AssertErrorState();
  9069. continue;
  9070. }
  9071. BfType* attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  9072. BfTypeDef* attrTypeDef = NULL;
  9073. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  9074. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  9075. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  9076. {
  9077. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  9078. if (attrTypeDef != NULL)
  9079. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  9080. }
  9081. bool isBypassedAttr = false;
  9082. if (attrTypeDef != NULL)
  9083. {
  9084. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  9085. // We solve it by having a 'bypass' for known attributes that Object depends on
  9086. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  9087. {
  9088. //if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  9089. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  9090. {
  9091. for (auto methodDef : attrTypeDef->mMethods)
  9092. {
  9093. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  9094. {
  9095. customAttribute.mType = attrType->ToTypeInstance();
  9096. customAttribute.mCtor = methodDef;
  9097. isBypassedAttr = true;
  9098. break;
  9099. }
  9100. }
  9101. }
  9102. }
  9103. if (isBypassedAttr)
  9104. {
  9105. customAttribute.mAwaitingValidation = false;
  9106. customAttributes->mAttributes.push_back(customAttribute);
  9107. continue;
  9108. }
  9109. if (mContext->mCurTypeState != NULL)
  9110. {
  9111. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  9112. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  9113. }
  9114. else
  9115. {
  9116. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  9117. }
  9118. }
  9119. BfTypeInstance* attrTypeInst = NULL;
  9120. if (attrType == NULL)
  9121. continue;
  9122. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  9123. attrTypeInst = attrType->ToTypeInstance();
  9124. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  9125. {
  9126. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  9127. continue;
  9128. }
  9129. if (mCurTypeInstance != NULL)
  9130. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  9131. customAttribute.mType = attrTypeInst;
  9132. BfConstResolver constResolver(this);
  9133. if (allowNonConstArgs)
  9134. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  9135. bool inPropSet = false;
  9136. SizedArray<BfResolvedArg, 2> argValues;
  9137. for (BfExpression* arg : attributesDirective->mArguments)
  9138. {
  9139. if (arg == NULL)
  9140. {
  9141. continue;
  9142. }
  9143. if (autoComplete != NULL)
  9144. autoComplete->mShowAttributeProperties = attrTypeInst;
  9145. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  9146. {
  9147. inPropSet = true;
  9148. if (autoComplete != NULL)
  9149. autoComplete->CheckNode(assignExpr->mLeft);
  9150. String findName = assignExpr->mLeft->ToString();
  9151. BfPropertyDef* bestProp = NULL;
  9152. BfTypeInstance* bestPropTypeInst = NULL;
  9153. BfFieldDef* bestField = NULL;
  9154. BfTypeInstance* bestFieldTypeInst = NULL;
  9155. auto checkTypeInst = attrTypeInst;
  9156. while (checkTypeInst != NULL)
  9157. {
  9158. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  9159. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  9160. {
  9161. if (prop->mName == findName)
  9162. {
  9163. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  9164. {
  9165. bestProp = prop;
  9166. bestPropTypeInst = checkTypeInst;
  9167. }
  9168. }
  9169. }
  9170. for (auto field : checkTypeInst->mTypeDef->mFields)
  9171. {
  9172. if (field->mName == findName)
  9173. {
  9174. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  9175. {
  9176. bestField = field;
  9177. bestFieldTypeInst = checkTypeInst;
  9178. }
  9179. }
  9180. }
  9181. if ((bestProp != NULL) || (bestField != NULL))
  9182. break;
  9183. checkTypeInst = checkTypeInst->mBaseType;
  9184. }
  9185. bool handledExpr = false;
  9186. if (bestField != NULL)
  9187. {
  9188. handledExpr = true;
  9189. if (mCompiler->mResolvePassData != NULL)
  9190. {
  9191. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  9192. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  9193. {
  9194. autoComplete->mDefField = bestField;
  9195. autoComplete->mDefType = attrTypeDef;
  9196. }
  9197. }
  9198. if (bestField->mProtection != BfProtection_Public)
  9199. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  9200. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  9201. BfCustomAttributeSetField setField;
  9202. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  9203. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  9204. if (assignExpr->mRight != NULL)
  9205. {
  9206. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  9207. if (result)
  9208. {
  9209. CurrentAddToConstHolder(result.mValue);
  9210. setField.mParam = result;
  9211. customAttribute.mSetField.push_back(setField);
  9212. }
  9213. }
  9214. }
  9215. else if (bestProp == NULL)
  9216. {
  9217. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  9218. }
  9219. else
  9220. {
  9221. BfMethodDef* setMethod = NULL;
  9222. for (auto methodDef : bestProp->mMethods)
  9223. {
  9224. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  9225. {
  9226. setMethod = methodDef;
  9227. break;
  9228. }
  9229. }
  9230. if (setMethod == NULL)
  9231. {
  9232. Fail("Property has no setter", assignExpr->mLeft);
  9233. }
  9234. else
  9235. {
  9236. if (mCompiler->mResolvePassData != NULL)
  9237. {
  9238. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  9239. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  9240. {
  9241. autoComplete->mDefProp = bestProp;
  9242. autoComplete->mDefType = attrTypeDef;
  9243. }
  9244. }
  9245. handledExpr = true;
  9246. if (bestProp->mProtection != BfProtection_Public)
  9247. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  9248. BfResolvedArg resolvedArg;
  9249. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  9250. BfCustomAttributeSetProperty setProperty;
  9251. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  9252. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  9253. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  9254. if (methodInstance.mMethodInstance != NULL)
  9255. {
  9256. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  9257. if (assignExpr->mRight != NULL)
  9258. {
  9259. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  9260. if (result)
  9261. {
  9262. BF_ASSERT(result.mType == propType);
  9263. CurrentAddToConstHolder(result.mValue);
  9264. setProperty.mParam = result;
  9265. customAttribute.mSetProperties.push_back(setProperty);
  9266. }
  9267. }
  9268. }
  9269. }
  9270. }
  9271. if ((!handledExpr) && (assignExpr->mRight != NULL))
  9272. constResolver.Resolve(assignExpr->mRight);
  9273. }
  9274. else
  9275. {
  9276. if (inPropSet)
  9277. {
  9278. Fail("Named attribute argument expected", arg); // CS1016
  9279. }
  9280. BfDeferEvalChecker deferEvalChecker;
  9281. arg->Accept(&deferEvalChecker);
  9282. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  9283. BfResolvedArg resolvedArg;
  9284. resolvedArg.mExpression = arg;
  9285. if (deferParamEval)
  9286. {
  9287. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  9288. }
  9289. else
  9290. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  9291. if (!inPropSet)
  9292. {
  9293. argValues.push_back(resolvedArg);
  9294. }
  9295. }
  9296. if (autoComplete != NULL)
  9297. autoComplete->mShowAttributeProperties = NULL;
  9298. }
  9299. auto wasCapturingMethodInfo = false;
  9300. if (autoComplete != NULL)
  9301. {
  9302. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  9303. if (attributesDirective->mCtorOpenParen != NULL)
  9304. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  9305. }
  9306. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  9307. attrTypeDef = attrTypeInst->mTypeDef;
  9308. bool success = true;
  9309. bool isFailurePass = false;
  9310. for (int pass = 0; pass < 2; pass++)
  9311. {
  9312. bool isFailurePass = pass == 1;
  9313. for (auto checkMethod : attrTypeDef->mMethods)
  9314. {
  9315. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  9316. continue; // Don't match private default ctor if there's a user-defined one
  9317. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  9318. continue;
  9319. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  9320. continue;
  9321. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  9322. }
  9323. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  9324. break;
  9325. }
  9326. if (autoComplete != NULL)
  9327. {
  9328. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  9329. {
  9330. autoComplete->mIsCapturingMethodMatchInfo = true;
  9331. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  9332. }
  9333. else
  9334. autoComplete->mIsCapturingMethodMatchInfo = false;
  9335. }
  9336. if (methodMatcher.mBestMethodDef == NULL)
  9337. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  9338. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  9339. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  9340. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  9341. {
  9342. Fail("Custom attribute circular reference", attributesDirective);
  9343. }
  9344. if (mCurTypeInstance != NULL)
  9345. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  9346. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  9347. success = false;
  9348. for (auto& arg : argValues)
  9349. {
  9350. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  9351. {
  9352. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  9353. constResolver.Resolve(expr);
  9354. }
  9355. }
  9356. // Move all those to the constHolder
  9357. for (auto& ctorArg : customAttribute.mCtorArgs)
  9358. {
  9359. if (ctorArg.IsConst())
  9360. CurrentAddToConstHolder(ctorArg);
  9361. }
  9362. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  9363. {
  9364. targetOverride = BfAttributeTargets_ReturnValue;
  9365. if (attrTarget != BfAttributeTargets_Method)
  9366. {
  9367. 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.",
  9368. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  9369. }
  9370. success = false;
  9371. }
  9372. if ((success) && (targetOverride != (BfAttributeTargets)0))
  9373. {
  9374. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  9375. {
  9376. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  9377. if (methodInfoEx->mMethodCustomAttributes == NULL)
  9378. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  9379. if (success)
  9380. {
  9381. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  9382. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  9383. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  9384. }
  9385. }
  9386. else
  9387. {
  9388. // Failed - ignore
  9389. success = false;
  9390. }
  9391. }
  9392. if (success)
  9393. {
  9394. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  9395. {
  9396. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  9397. {
  9398. if (prevCustomAttribute.mType == attrTypeInst)
  9399. {
  9400. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  9401. }
  9402. }
  9403. }
  9404. }
  9405. if (success)
  9406. {
  9407. customAttributes->mAttributes.push_back(customAttribute);
  9408. }
  9409. }
  9410. ValidateCustomAttributes(customAttributes, attrTarget);
  9411. }
  9412. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, bool allowNonConstArgs, BfCaptureInfo* captureInfo)
  9413. {
  9414. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  9415. GetCustomAttributes(customAttributes, attributesDirective, attrType, allowNonConstArgs, captureInfo);
  9416. return customAttributes;
  9417. }
  9418. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  9419. {
  9420. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  9421. Warn(0, "Unused attributes", attributeState->mSrc);
  9422. }
  9423. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  9424. {
  9425. if (mCurTypeInstance->mCustomAttributes != NULL)
  9426. {
  9427. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  9428. {
  9429. String typeName = TypeToString(customAttribute.mType);
  9430. if (typeName == "System.PackedAttribute")
  9431. {
  9432. isPacked = true;
  9433. }
  9434. else if (typeName == "System.UnionAttribute")
  9435. {
  9436. isUnion = true;
  9437. }
  9438. else if (typeName == "System.CReprAttribute")
  9439. {
  9440. isCRepr = true;
  9441. isOrdered = true;
  9442. }
  9443. else if (typeName == "System.OrderedAttribute")
  9444. {
  9445. isOrdered = true;
  9446. }
  9447. else if (typeName == "System.AlwaysIncludeAttribute")
  9448. {
  9449. for (auto setProp : customAttribute.mSetProperties)
  9450. {
  9451. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  9452. if (propertyDef->mName == "AssumeInstantiated")
  9453. {
  9454. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9455. if ((constant != NULL) && (constant->mBool))
  9456. mCurTypeInstance->mHasBeenInstantiated = true;
  9457. }
  9458. else if (propertyDef->mName == "IncludeAllMethods")
  9459. {
  9460. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9461. if ((constant != NULL) && (constant->mBool))
  9462. mCurTypeInstance->mIncludeAllMethods = true;
  9463. }
  9464. }
  9465. }
  9466. else if (typeName == "System.AlignAttribute")
  9467. {
  9468. if (customAttribute.mCtorArgs.size() >= 1)
  9469. {
  9470. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  9471. alignOverride = alignConstant->mInt32;
  9472. }
  9473. }
  9474. else if (typeName == "System.UnderlyingArrayAttribute")
  9475. {
  9476. if (customAttribute.mCtorArgs.size() >= 2)
  9477. {
  9478. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  9479. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  9480. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  9481. {
  9482. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  9483. underlyingArraySize = sizeConstant->mInt32;
  9484. }
  9485. }
  9486. }
  9487. }
  9488. }
  9489. }
  9490. // Checking to see if we're an attribute or not
  9491. void BfModule::ProcessCustomAttributeData()
  9492. {
  9493. bool isAttribute = false;
  9494. auto checkTypeInst = mCurTypeInstance->mBaseType;
  9495. while (checkTypeInst != NULL)
  9496. {
  9497. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  9498. isAttribute = true;
  9499. checkTypeInst = checkTypeInst->mBaseType;
  9500. }
  9501. if (!isAttribute)
  9502. return;
  9503. auto attributeData = new BfAttributeData();
  9504. bool hasCustomAttribute = false;
  9505. if (mCurTypeInstance->mCustomAttributes != NULL)
  9506. {
  9507. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  9508. {
  9509. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  9510. {
  9511. if (customAttribute.mCtorArgs.size() > 0)
  9512. {
  9513. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  9514. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  9515. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  9516. }
  9517. for (auto& setProp : customAttribute.mSetProperties)
  9518. {
  9519. BfPropertyDef* propDef = setProp.mPropertyRef;
  9520. if (propDef->mName == "AllowMultiple")
  9521. {
  9522. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9523. if (constant != NULL)
  9524. attributeData->mAllowMultiple = constant->mBool;
  9525. }
  9526. else if (propDef->mName == "Inherited")
  9527. {
  9528. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9529. if (constant != NULL)
  9530. attributeData->mInherited = constant->mBool;
  9531. }
  9532. else if (propDef->mName == "ValidOn")
  9533. {
  9534. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9535. if (constant != NULL)
  9536. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  9537. }
  9538. }
  9539. hasCustomAttribute = true;
  9540. }
  9541. }
  9542. }
  9543. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  9544. {
  9545. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  9546. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  9547. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  9548. }
  9549. mCurTypeInstance->mAttributeData = attributeData;
  9550. }
  9551. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  9552. {
  9553. auto constant = constHolder->GetConstant(irValue);
  9554. if (constant == NULL)
  9555. return false;
  9556. if (constant->mTypeCode != BfTypeCode_StringId)
  9557. return false;
  9558. int stringId = constant->mInt32;
  9559. BfStringPoolEntry* entry = NULL;
  9560. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  9561. {
  9562. str = entry->mString;
  9563. }
  9564. else
  9565. {
  9566. BF_DBG_FATAL("Failed to find string by id");
  9567. }
  9568. return true;
  9569. }
  9570. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  9571. {
  9572. BfVariant variant;
  9573. variant.mTypeCode = BfTypeCode_None;
  9574. BfType* primType = NULL;
  9575. if (value.mType->IsPrimitiveType())
  9576. primType = (BfPrimitiveType*)value.mType;
  9577. else if (value.mType->IsTypedPrimitive())
  9578. primType = value.mType->GetUnderlyingType();
  9579. if (primType)
  9580. {
  9581. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  9582. if (constant != NULL)
  9583. {
  9584. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  9585. {
  9586. variant.mUInt64 = 0;
  9587. variant.mTypeCode = BfTypeCode_Let;
  9588. return variant;
  9589. }
  9590. switch (constant->mTypeCode)
  9591. {
  9592. case BfTypeCode_Int8:
  9593. case BfTypeCode_UInt8:
  9594. case BfTypeCode_Int16:
  9595. case BfTypeCode_UInt16:
  9596. case BfTypeCode_Int32:
  9597. case BfTypeCode_UInt32:
  9598. case BfTypeCode_Int64:
  9599. case BfTypeCode_UInt64:
  9600. case BfTypeCode_IntPtr:
  9601. case BfTypeCode_UIntPtr:
  9602. case BfTypeCode_IntUnknown:
  9603. case BfTypeCode_UIntUnknown:
  9604. case BfTypeCode_Float:
  9605. case BfTypeCode_Double:
  9606. case BfTypeCode_Char8:
  9607. case BfTypeCode_Char16:
  9608. case BfTypeCode_Char32:
  9609. variant.mTypeCode = constant->mTypeCode;
  9610. variant.mInt64 = constant->mInt64;
  9611. break;
  9612. default:
  9613. if (refNode != NULL)
  9614. Fail("Invalid const expression type", refNode);
  9615. break;
  9616. }
  9617. }
  9618. }
  9619. return variant;
  9620. }
  9621. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  9622. {
  9623. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  9624. {
  9625. auto elementType = typedValue.mType->GetUnderlyingType();
  9626. if (typedValue.IsAddr())
  9627. {
  9628. if (elementType->IsValuelessType())
  9629. {
  9630. BF_ASSERT(!typedValue.mValue);
  9631. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  9632. }
  9633. else
  9634. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  9635. }
  9636. else
  9637. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  9638. if (typedValue.mType->IsValuelessType())
  9639. {
  9640. BF_ASSERT(typedValue.mValue.IsFake());
  9641. }
  9642. }
  9643. return typedValue;
  9644. }
  9645. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  9646. {
  9647. if (!typedValue.IsAddr())
  9648. return typedValue;
  9649. PopulateType(typedValue.mType);
  9650. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  9651. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  9652. if (typedValue.mValue.IsConst())
  9653. {
  9654. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  9655. if (constantValue != NULL)
  9656. {
  9657. if (constantValue->mConstType == BfConstType_GlobalVar)
  9658. {
  9659. auto globalVar = (BfGlobalVar*)constantValue;
  9660. if (globalVar->mName[0] == '#')
  9661. {
  9662. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  9663. if (result)
  9664. return result;
  9665. return GetDefaultTypedValue(typedValue.mType);
  9666. }
  9667. }
  9668. }
  9669. }
  9670. BfIRValue loadedVal = typedValue.mValue;
  9671. if (loadedVal)
  9672. {
  9673. if (typedValue.mType->IsVar())
  9674. {
  9675. return BfTypedValue(loadedVal, typedValue.mType, false);
  9676. }
  9677. /*if (isVolatile)
  9678. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  9679. PopulateType(typedValue.mType, BfPopulateType_Data);
  9680. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  9681. }
  9682. return BfTypedValue(loadedVal, typedValue.mType, false);
  9683. }
  9684. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  9685. {
  9686. if (typedValue.IsSplat())
  9687. return AggregateSplat(typedValue);
  9688. if (typedValue.IsAddr())
  9689. return LoadValue(typedValue);
  9690. return typedValue;
  9691. }
  9692. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  9693. {
  9694. if (!typedValue.IsSplat())
  9695. return typedValue;
  9696. if (typedValue.mType->IsValuelessType())
  9697. return typedValue;
  9698. int elementIdx = 0;
  9699. auto _ExtractValue = [&](BfType* checkType)
  9700. {
  9701. if (valueArrPtr != NULL)
  9702. return valueArrPtr[elementIdx++];
  9703. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  9704. };
  9705. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  9706. {
  9707. if (checkType->IsStruct())
  9708. {
  9709. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  9710. auto checkTypeInstance = checkType->ToTypeInstance();
  9711. if (checkTypeInstance->mBaseType != NULL)
  9712. {
  9713. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  9714. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  9715. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  9716. }
  9717. if (checkTypeInstance->mIsUnion)
  9718. {
  9719. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  9720. if (!unionInnerType->IsValuelessType())
  9721. {
  9722. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  9723. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  9724. }
  9725. if (checkTypeInstance->IsEnum())
  9726. {
  9727. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  9728. BfIRValue fieldValue = checkTypeLambda(dscrType);
  9729. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  9730. }
  9731. }
  9732. else
  9733. {
  9734. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  9735. {
  9736. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  9737. if (fieldInstance->mDataIdx >= 0)
  9738. {
  9739. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  9740. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  9741. }
  9742. }
  9743. }
  9744. return curValue;
  9745. }
  9746. else if (checkType->IsMethodRef())
  9747. {
  9748. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  9749. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  9750. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  9751. {
  9752. BfIRValue fieldValue;
  9753. auto checkType = methodRefType->GetCaptureType(dataIdx);
  9754. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  9755. {
  9756. fieldValue = checkTypeLambda(checkType);
  9757. }
  9758. else
  9759. {
  9760. fieldValue = _ExtractValue(checkType);
  9761. }
  9762. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  9763. }
  9764. return curValue;
  9765. }
  9766. else if (!checkType->IsValuelessType())
  9767. {
  9768. return _ExtractValue(checkType);
  9769. }
  9770. return BfIRValue();
  9771. };
  9772. BfIRValue value = checkTypeLambda(typedValue.mType);
  9773. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  9774. }
  9775. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  9776. {
  9777. if (!typedValue.IsSplat())
  9778. return;
  9779. if (typedValue.mType->IsValuelessType())
  9780. return;
  9781. /*static int sCallIdx = 0;
  9782. if (!mCompiler->mIsResolveOnly)
  9783. sCallIdx++;
  9784. int callIdx = sCallIdx;*/
  9785. int elementIdx = 0;
  9786. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  9787. {
  9788. if (checkType->IsStruct())
  9789. {
  9790. auto checkTypeInstance = checkType->ToTypeInstance();
  9791. if (checkTypeInstance->mBaseType != NULL)
  9792. {
  9793. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  9794. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  9795. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  9796. }
  9797. if (checkTypeInstance->mIsUnion)
  9798. {
  9799. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  9800. if (!unionInnerType->IsValuelessType())
  9801. {
  9802. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  9803. checkTypeLambda(unionInnerType, fieldAddrVal);
  9804. }
  9805. if (checkTypeInstance->IsEnum())
  9806. {
  9807. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  9808. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  9809. checkTypeLambda(dscrType, fieldAddrVal);
  9810. }
  9811. }
  9812. else
  9813. {
  9814. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  9815. {
  9816. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  9817. if (fieldInstance->mDataIdx >= 0)
  9818. {
  9819. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  9820. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  9821. }
  9822. }
  9823. }
  9824. }
  9825. else if (checkType->IsMethodRef())
  9826. {
  9827. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  9828. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  9829. {
  9830. auto dataType = methodRefType->GetCaptureType(dataIdx);
  9831. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  9832. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  9833. {
  9834. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  9835. }
  9836. else
  9837. {
  9838. // static int sItrCount = 0;
  9839. // sItrCount++;
  9840. // int curItr = sItrCount;
  9841. // if (curItr == 1)
  9842. // {
  9843. // NOP;
  9844. // }
  9845. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  9846. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  9847. }
  9848. }
  9849. }
  9850. else if (!checkType->IsValuelessType())
  9851. {
  9852. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  9853. mBfIRBuilder->CreateStore(val, curAddrVal);
  9854. }
  9855. };
  9856. checkTypeLambda(typedValue.mType, addrVal);
  9857. }
  9858. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  9859. {
  9860. bool wasReadOnly = typedVal.IsReadOnly();
  9861. if ((typedVal.mType->IsValueType()) &&
  9862. (!typedVal.mType->IsValuelessType()))
  9863. {
  9864. wasReadOnly = true; // Any non-addr is implicitly read-only
  9865. //static int gCallIdx = 0;
  9866. if (typedVal.IsAddr())
  9867. return typedVal;
  9868. BfType* type = typedVal.mType;
  9869. PopulateType(type);
  9870. auto tempVar = CreateAlloca(type);
  9871. if (typedVal.IsSplat())
  9872. AggregateSplatIntoAddr(typedVal, tempVar);
  9873. else
  9874. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  9875. return BfTypedValue(tempVar, type,
  9876. typedVal.IsThis() ?
  9877. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  9878. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  9879. }
  9880. return LoadValue(typedVal);
  9881. }
  9882. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  9883. {
  9884. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  9885. typedValue.mKind = BfTypedValueKind_Addr;
  9886. return typedValue;
  9887. }
  9888. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  9889. {
  9890. BfIRValue val;
  9891. if (typedValue.mValue.IsArg())
  9892. {
  9893. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  9894. if (isAddr != NULL)
  9895. {
  9896. if (wantType != NULL)
  9897. *isAddr = wantType->IsComposite();
  9898. else
  9899. *isAddr = false;
  9900. }
  9901. else if (wantType->IsComposite())
  9902. val = mBfIRBuilder->CreateLoad(val);
  9903. }
  9904. if (!val)
  9905. {
  9906. auto checkMethodState = mCurMethodState;
  9907. while (checkMethodState != NULL)
  9908. {
  9909. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  9910. {
  9911. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  9912. if (decompAddr == typedValue.mValue)
  9913. {
  9914. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  9915. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  9916. {
  9917. // This is really backing for a POINTER to a composite inside a methodRef
  9918. val = mBfIRBuilder->CreateLoad(val);
  9919. }
  9920. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  9921. {
  9922. *isAddr = true;
  9923. return val;
  9924. }
  9925. else
  9926. {
  9927. val = mBfIRBuilder->CreateLoad(val);
  9928. break;
  9929. }
  9930. }
  9931. }
  9932. if (val)
  9933. break;
  9934. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  9935. {
  9936. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  9937. return mBfIRBuilder->GetFakeVal();
  9938. }
  9939. checkMethodState = checkMethodState->mPrevMethodState;
  9940. }
  9941. }
  9942. if (val)
  9943. {
  9944. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  9945. {
  9946. BF_ASSERT(wantType != NULL);
  9947. if (wantType != NULL)
  9948. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  9949. }
  9950. return val;
  9951. }
  9952. BFMODULE_FATAL(this, "Splat not found");
  9953. return BfIRValue();
  9954. }
  9955. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  9956. {
  9957. int useFieldIdx = fieldIdx;
  9958. BfType* fieldType = NULL;
  9959. if (fieldInstance != NULL)
  9960. {
  9961. fieldType = fieldInstance->mResolvedType;
  9962. if (typedValue.mType->IsUnion())
  9963. {
  9964. if (fieldIdx == 1)
  9965. {
  9966. if (typedValue.IsSplat())
  9967. {
  9968. BfTypedValue innerVal = typedValue;
  9969. innerVal.mType = fieldType;
  9970. return innerVal;
  9971. }
  9972. }
  9973. }
  9974. }
  9975. else
  9976. {
  9977. if (typedValue.mType->IsPayloadEnum())
  9978. {
  9979. auto typeInst = typedValue.mType->ToTypeInstance();
  9980. if (fieldIdx == 1)
  9981. fieldType = typeInst->GetUnionInnerType();
  9982. else if (fieldIdx == 2)
  9983. {
  9984. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  9985. }
  9986. }
  9987. else if (typedValue.mType->IsUnion())
  9988. {
  9989. if (fieldIdx == 1)
  9990. {
  9991. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  9992. if (typedValue.IsSplat())
  9993. {
  9994. BfTypedValue innerVal = typedValue;
  9995. innerVal.mType = fieldType;
  9996. return innerVal;
  9997. }
  9998. }
  9999. }
  10000. }
  10001. BF_ASSERT(typedValue.mType->IsStruct());
  10002. if (typedValue.IsSplat())
  10003. {
  10004. if (typedValue.mType->IsPayloadEnum())
  10005. {
  10006. if (fieldIdx == 1)
  10007. {
  10008. // Payload
  10009. auto typeInst = typedValue.mType->ToTypeInstance();
  10010. auto unionInnerType = typeInst->GetUnionInnerType();
  10011. bool isAddr = false;
  10012. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  10013. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  10014. }
  10015. if (fieldIdx == 2)
  10016. {
  10017. // Discriminator
  10018. auto typeInst = typedValue.mType->ToTypeInstance();
  10019. auto unionInnerType = typeInst->GetUnionInnerType();
  10020. auto dscrType = typeInst->GetDiscriminatorType();
  10021. int argIdx = typedValue.mValue.mId;
  10022. int componentIdx = 0;
  10023. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  10024. bool isAddr;
  10025. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  10026. return BfTypedValue(irVal, dscrType, isAddr);
  10027. }
  10028. }
  10029. int componentIdx = 0;
  10030. BfTypedValue retVal;
  10031. BfFieldInstance* wantFieldInstance = fieldInstance;
  10032. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  10033. {
  10034. if (checkType->IsStruct())
  10035. {
  10036. auto checkTypeInstance = checkType->ToTypeInstance();
  10037. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  10038. {
  10039. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  10040. fieldType = checkTypeInstance->GetUnionInnerType();
  10041. checkTypeLambda(fieldType);
  10042. if (checkType->IsEnum())
  10043. {
  10044. // Past discriminator...
  10045. componentIdx++;
  10046. }
  10047. return;
  10048. }
  10049. if (checkTypeInstance->mBaseType != NULL)
  10050. checkTypeLambda(checkTypeInstance->mBaseType);
  10051. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  10052. {
  10053. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  10054. if (fieldInstance == wantFieldInstance)
  10055. {
  10056. bool isAddr = false;
  10057. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  10058. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  10059. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  10060. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  10061. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  10062. {
  10063. retVal = LoadValue(retVal);
  10064. }
  10065. break;
  10066. }
  10067. if (fieldInstance->mDataIdx >= 0)
  10068. checkTypeLambda(fieldInstance->GetResolvedType());
  10069. }
  10070. }
  10071. else if (!checkType->IsValuelessType())
  10072. {
  10073. componentIdx++;
  10074. //argIdx++;
  10075. }
  10076. };
  10077. checkTypeLambda(typedValue.mType);
  10078. BF_ASSERT(retVal);
  10079. return retVal;
  10080. }
  10081. if (typedValue.IsAddr())
  10082. {
  10083. BF_ASSERT(fieldType != NULL);
  10084. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  10085. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  10086. }
  10087. else
  10088. {
  10089. BF_ASSERT(fieldType != NULL);
  10090. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  10091. }
  10092. }
  10093. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  10094. {
  10095. if (typedValue.IsAddr())
  10096. {
  10097. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  10098. return mBfIRBuilder->CreateLoad(addrVal);
  10099. }
  10100. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  10101. }
  10102. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  10103. {
  10104. if (elementType->IsSizeAligned())
  10105. {
  10106. if (isElementIndex)
  10107. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  10108. else
  10109. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  10110. }
  10111. auto ptrType = CreatePointerType(elementType);
  10112. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  10113. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  10114. auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  10115. BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  10116. BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  10117. return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  10118. }
  10119. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  10120. {
  10121. if (elementType->IsSizeAligned())
  10122. {
  10123. if (isElementIndex)
  10124. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  10125. else
  10126. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  10127. }
  10128. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  10129. }
  10130. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  10131. {
  10132. if (modifyType == NULL)
  10133. modifyType = "modify";
  10134. if (typedValue.mType->IsVar())
  10135. return true;
  10136. if (typedValue.IsReadOnly())
  10137. {
  10138. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  10139. return false;
  10140. }
  10141. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  10142. {
  10143. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  10144. return false;
  10145. }
  10146. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  10147. {
  10148. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  10149. return false;
  10150. }
  10151. return true;
  10152. }
  10153. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  10154. {
  10155. // If one is an interface and the other is an impl, B is the impl
  10156. auto implOwner = methodB->GetOwner();
  10157. if (methodA->mMethodDef->mIsLocalMethod)
  10158. {
  10159. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  10160. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  10161. if (sepPosA != sepPosB)
  10162. return false;
  10163. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  10164. return false;
  10165. }
  10166. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  10167. return false;
  10168. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  10169. return false;
  10170. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  10171. return false;
  10172. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  10173. {
  10174. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  10175. return false;
  10176. }
  10177. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  10178. {
  10179. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  10180. return false;
  10181. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  10182. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  10183. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  10184. return false;
  10185. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  10186. return false;
  10187. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  10188. return false;
  10189. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  10190. {
  10191. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  10192. return false;
  10193. }
  10194. }
  10195. int implicitParamCountA = methodA->GetImplicitParamCount();
  10196. int implicitParamCountB = methodB->GetImplicitParamCount();
  10197. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  10198. return false;
  10199. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  10200. return false;
  10201. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  10202. {
  10203. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  10204. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  10205. return false;
  10206. }
  10207. // Compare generic params. Generic params are part of the method signature here
  10208. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  10209. return false;
  10210. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  10211. {
  10212. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  10213. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  10214. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  10215. return false;
  10216. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  10217. return false;
  10218. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  10219. return false;
  10220. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  10221. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  10222. return false;
  10223. }
  10224. return true;
  10225. }
  10226. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  10227. {
  10228. if (!CompareMethodSignatures(methodA, methodB))
  10229. return false;
  10230. if (methodA->mReturnType != methodB->mReturnType)
  10231. return false;
  10232. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  10233. return false;
  10234. return true;
  10235. }
  10236. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  10237. {
  10238. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  10239. return false;
  10240. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  10241. return false;
  10242. if (iMethodInst->mMethodDef->mIsOperator)
  10243. {
  10244. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  10245. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  10246. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  10247. return false;
  10248. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  10249. return false;
  10250. }
  10251. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  10252. return false;
  10253. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  10254. {
  10255. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  10256. return false;
  10257. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  10258. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  10259. if (iParamType->IsSelf())
  10260. {
  10261. if (methodParamType != methodInstance->GetOwner())
  10262. return false;
  10263. }
  10264. else if (!iParamType->IsGenericParam())
  10265. {
  10266. if (methodParamType != iParamType)
  10267. return false;
  10268. }
  10269. else
  10270. {
  10271. if (!methodParamType->IsGenericParam())
  10272. return false;
  10273. auto genericParamType = (BfGenericParamType*)methodParamType;
  10274. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  10275. return false;
  10276. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  10277. bool hadInterface = false;
  10278. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  10279. if (interfaceConstraint == iParamType)
  10280. hadInterface = true;
  10281. if (!hadInterface)
  10282. return false;
  10283. }
  10284. }
  10285. return true;
  10286. }
  10287. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  10288. {
  10289. BfMethodInstance* methodInstance = methodRef;
  10290. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  10291. {
  10292. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  10293. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  10294. {
  10295. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  10296. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  10297. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  10298. BfMethodRef methodRef = methodInstance;
  10299. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  10300. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  10301. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  10302. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  10303. (mIsReified))
  10304. {
  10305. specializedMethodRefInfo->mHasReifiedRef = true;
  10306. }
  10307. }
  10308. }
  10309. }
  10310. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  10311. {
  10312. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  10313. return BfModuleMethodInstance(methodInstance, BfIRValue());
  10314. if (mBfIRBuilder == NULL)
  10315. return BfModuleMethodInstance(methodInstance, BfIRValue());
  10316. if (methodInstance->GetOwner()->IsFunction())
  10317. {
  10318. // No actual ref needed- not an actual generated function
  10319. return BfModuleMethodInstance(methodInstance, BfIRValue());
  10320. }
  10321. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  10322. if (!isGenFunction)
  10323. AddMethodReference(methodInstance, flags);
  10324. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  10325. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  10326. if (mCompiler->IsSkippingExtraResolveChecks())
  10327. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10328. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  10329. {
  10330. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10331. }
  10332. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  10333. BfMethodRef methodRef = methodInstance;
  10334. if (isInlined)
  10335. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  10336. else
  10337. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  10338. if (!isGenFunction)
  10339. {
  10340. BfIRValue* irFuncPtr = NULL;
  10341. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  10342. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  10343. }
  10344. if (mAwaitingInitFinish)
  10345. FinishInit();
  10346. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  10347. if (!isGenFunction)
  10348. mFuncReferences[methodRef] = func;
  10349. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  10350. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  10351. {
  10352. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  10353. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  10354. // type instance
  10355. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  10356. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  10357. for (auto ownedTypeInst : mOwnedTypeInstances)
  10358. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  10359. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  10360. {
  10361. mIncompleteMethodCount++;
  10362. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  10363. inlineMethodRequest->mType = methodInstance->GetOwner();
  10364. inlineMethodRequest->mFromModule = this;
  10365. inlineMethodRequest->mFunc = func;
  10366. inlineMethodRequest->mFromModuleRevision = mRevision;
  10367. inlineMethodRequest->mMethodInstance = methodInstance;
  10368. BF_ASSERT(mIsModuleMutable);
  10369. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  10370. }
  10371. }
  10372. return BfModuleMethodInstance(methodInstance, func);
  10373. }
  10374. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  10375. {
  10376. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  10377. if (mBfIRBuilder == NULL)
  10378. {
  10379. // To allow for custom attribute data
  10380. PrepareForIRWriting(typeInst);
  10381. }
  10382. BfModule* declareModule = this;
  10383. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  10384. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  10385. declareModule = declareModule->mParentModule;
  10386. // Check for attributes
  10387. if (typeInst == mContext->mBfObjectType)
  10388. {
  10389. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  10390. if (methodDecl != NULL)
  10391. {
  10392. auto attributesDirective = methodDecl->mAttributes;
  10393. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  10394. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  10395. {
  10396. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  10397. }
  10398. }
  10399. }
  10400. else
  10401. {
  10402. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  10403. GetMethodCustomAttributes(methodInstance);
  10404. }
  10405. BF_ASSERT(mModuleOptions == NULL);
  10406. if (methodInstance->GetCustomAttributes() != NULL)
  10407. {
  10408. auto project = typeInst->mTypeDef->mProject;
  10409. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  10410. BfModuleOptions wantOptions = moduleOptions;
  10411. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  10412. if (typeOptions != NULL)
  10413. {
  10414. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  10415. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  10416. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  10417. }
  10418. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  10419. {
  10420. StringT<128> attrName;
  10421. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  10422. {
  10423. attrName.Clear();
  10424. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  10425. Array<int>* arrPtr;
  10426. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  10427. {
  10428. for (auto optionsIdx : *arrPtr)
  10429. {
  10430. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  10431. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  10432. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  10433. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  10434. }
  10435. }
  10436. }
  10437. }
  10438. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  10439. {
  10440. auto lastCheckModule = this;
  10441. auto checkModule = this->mNextAltModule;
  10442. while (checkModule != NULL)
  10443. {
  10444. if (*checkModule->mModuleOptions == wantOptions)
  10445. {
  10446. declareModule = checkModule;
  10447. break;
  10448. }
  10449. lastCheckModule = checkModule;
  10450. checkModule = checkModule->mNextAltModule;
  10451. }
  10452. // Not found?
  10453. if (declareModule == this)
  10454. {
  10455. String specModuleName = mModuleName + "@@";
  10456. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  10457. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  10458. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  10459. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  10460. declareModule = new BfModule(mContext, specModuleName);
  10461. declareModule->mProject = project;
  10462. declareModule->mModuleOptions = new BfModuleOptions();
  10463. *declareModule->mModuleOptions = wantOptions;
  10464. declareModule->mParentModule = lastCheckModule;
  10465. declareModule->Init();
  10466. lastCheckModule->mNextAltModule = declareModule;
  10467. }
  10468. }
  10469. }
  10470. declareModule->PrepareForIRWriting(typeInst);
  10471. return declareModule;
  10472. }
  10473. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  10474. {
  10475. if (methodDef->mMethodType == BfMethodType_Init)
  10476. return BfModuleMethodInstance();
  10477. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  10478. {
  10479. // Don't bother inlining for resolve-only
  10480. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  10481. }
  10482. bool processNow = false;
  10483. bool keepInCurrentModule = false;
  10484. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  10485. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  10486. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  10487. {
  10488. return BfModuleMethodInstance();
  10489. }
  10490. if (methodDef->mIsLocalMethod)
  10491. {
  10492. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10493. BfLocalMethod* localMethod;
  10494. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  10495. {
  10496. // Handle the def in the correct method state
  10497. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  10498. }
  10499. BFMODULE_FATAL(this, "Cannot find local method");
  10500. return BfModuleMethodInstance();
  10501. }
  10502. #ifdef _DEBUG
  10503. for (auto arg : methodGenericArguments)
  10504. BF_ASSERT(!arg->IsVar());
  10505. #endif
  10506. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  10507. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  10508. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  10509. // a FinishInit
  10510. if ((typeInst->IsIncomplete()) &&
  10511. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  10512. {
  10513. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  10514. // for resolve-only because we don't differentiate between reified/unreified there
  10515. PopulateType(typeInst, BfPopulateType_Full);
  10516. }
  10517. bool tryModuleMethodLookup = false;
  10518. BfModuleMethodInstance moduleMethodInst;
  10519. BfModule* instModule = typeInst->mModule;
  10520. if (keepInCurrentModule)
  10521. {
  10522. // Stay here
  10523. instModule = this;
  10524. }
  10525. if (this == mContext->mUnreifiedModule)
  10526. {
  10527. // Stay in this 'resolve only' module here
  10528. }
  10529. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  10530. {
  10531. BF_ASSERT(this == mContext->mUnreifiedModule);
  10532. }
  10533. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  10534. {
  10535. BF_ASSERT(instModule == mParentModule);
  10536. }
  10537. else if (instModule != this)
  10538. {
  10539. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  10540. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  10541. if ((!mIsReified) && (instModule->mIsReified))
  10542. {
  10543. BF_ASSERT(!mCompiler->mIsResolveOnly);
  10544. // A resolve-only module is specializing a method from a type in a reified module,
  10545. // we need to take care that this doesn't cause anything new to become reified
  10546. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  10547. if (!moduleMethodInstance)
  10548. return moduleMethodInstance;
  10549. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  10550. return moduleMethodInstance;
  10551. }
  10552. else
  10553. {
  10554. if ((mIsReified) && (!instModule->mIsReified))
  10555. {
  10556. if (!typeInst->IsUnspecializedTypeVariation())
  10557. {
  10558. if (!instModule->mReifyQueued)
  10559. {
  10560. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  10561. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  10562. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  10563. mContext->mReifyModuleWorkList.Add(instModule);
  10564. instModule->mReifyQueued = true;
  10565. }
  10566. // This ensures that the method will actually be created when it gets reified
  10567. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  10568. specializationRequest->mFromModule = typeInst->mModule;
  10569. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  10570. specializationRequest->mMethodDef = methodDef;
  10571. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  10572. specializationRequest->mType = typeInst;
  10573. specializationRequest->mFlags = flags;
  10574. specializationRequest->mForeignType = foreignType;
  10575. }
  10576. }
  10577. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  10578. // Not extern
  10579. // Create the instance in the proper module and then create a reference in this one
  10580. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  10581. if (!moduleMethodInst)
  10582. return moduleMethodInst;
  10583. tryModuleMethodLookup = true;
  10584. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  10585. {
  10586. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  10587. }
  10588. }
  10589. }
  10590. if (tryModuleMethodLookup)
  10591. {
  10592. SetMethodDependency(moduleMethodInst.mMethodInstance);
  10593. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  10594. }
  10595. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  10596. {
  10597. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  10598. if (moduleMethodInstance)
  10599. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  10600. return moduleMethodInst;
  10601. }
  10602. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  10603. bool hadConcreteInterfaceGenericArgument = false;
  10604. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  10605. isReified = false;
  10606. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  10607. {
  10608. isReified = false;
  10609. }
  10610. BfTypeVector sanitizedMethodGenericArguments;
  10611. SizedArray<BfProject*, 4> projectList;
  10612. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  10613. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  10614. isUnspecializedPass = false;
  10615. // 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
  10616. bool isExternalExtensionMethod = false;
  10617. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  10618. {
  10619. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  10620. {
  10621. auto specProject = methodDef->mDeclaringType->mProject;
  10622. isExternalExtensionMethod = true;
  10623. if (typeInst->IsGenericTypeInstance())
  10624. {
  10625. auto genericTypeInst = (BfTypeInstance*)typeInst;
  10626. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  10627. genericTypeInst->GenerateProjectsReferenced();
  10628. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  10629. {
  10630. // This is a generic type where a generic param is already confined to the project in question
  10631. isExternalExtensionMethod = false;
  10632. }
  10633. }
  10634. if (isExternalExtensionMethod)
  10635. {
  10636. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  10637. projectList.push_back(methodDef->mDeclaringType->mProject);
  10638. }
  10639. }
  10640. }
  10641. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  10642. {
  10643. int typeProjectsCounts = 0;
  10644. if (typeInst->IsGenericTypeInstance())
  10645. {
  10646. auto genericTypeInst = (BfTypeInstance*)typeInst;
  10647. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  10648. genericTypeInst->GenerateProjectsReferenced();
  10649. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  10650. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  10651. }
  10652. else
  10653. {
  10654. typeProjectsCounts = 1;
  10655. projectList.Insert(0, typeInst->mTypeDef->mProject);
  10656. }
  10657. isUnspecializedPass = true;
  10658. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  10659. {
  10660. auto genericArgType = methodGenericArguments[genericArgIdx];
  10661. //BF_ASSERT(!genericArgType->IsRef());
  10662. if (genericArgType->IsConcreteInterfaceType())
  10663. {
  10664. hadConcreteInterfaceGenericArgument = true;
  10665. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  10666. genericArgType = concreteInterfaceType->mInterface;
  10667. }
  10668. if (genericArgType->IsGenericParam())
  10669. {
  10670. auto genericParam = (BfGenericParamType*) genericArgType;
  10671. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  10672. isUnspecializedPass = false;
  10673. }
  10674. else
  10675. {
  10676. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  10677. isUnspecializedPass = false;
  10678. }
  10679. sanitizedMethodGenericArguments.push_back(genericArgType);
  10680. }
  10681. if ((int)projectList.size() > typeProjectsCounts)
  10682. {
  10683. // Just leave the new items
  10684. projectList.RemoveRange(0, typeProjectsCounts);
  10685. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  10686. {
  10687. return lhs->mName < rhs->mName;
  10688. });
  10689. }
  10690. else
  10691. {
  10692. projectList.Clear();
  10693. }
  10694. }
  10695. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  10696. BfMethodInstanceGroup* methodInstGroup = NULL;
  10697. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  10698. {
  10699. BF_ASSERT(!typeInst->IsInterface());
  10700. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  10701. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  10702. {
  10703. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  10704. // if (checkGroup.mDefault == NULL)
  10705. // {
  10706. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  10707. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  10708. // methodInstGroup = &checkGroup;
  10709. // break;
  10710. // }
  10711. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  10712. {
  10713. methodInstGroup = &checkGroup;
  10714. break;
  10715. }
  10716. }
  10717. if (methodInstGroup == NULL)
  10718. {
  10719. // Allocate a new entry
  10720. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  10721. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  10722. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  10723. methodInstGroup->mOwner = typeInst;
  10724. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  10725. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  10726. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  10727. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  10728. else
  10729. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  10730. }
  10731. }
  10732. else
  10733. {
  10734. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  10735. }
  10736. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  10737. {
  10738. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  10739. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  10740. }
  10741. BfIRFunction prevIRFunc;
  10742. bool doingRedeclare = false;
  10743. BfMethodInstance* methodInstance = NULL;
  10744. auto _SetReified = [&]()
  10745. {
  10746. methodInstance->mIsReified = true;
  10747. };
  10748. if (lookupMethodGenericArguments.size() == 0)
  10749. {
  10750. methodInstance = methodInstGroup->mDefault;
  10751. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  10752. {
  10753. MarkDerivedDirty(typeInst);
  10754. if (mIsScratchModule)
  10755. {
  10756. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  10757. _SetReified();
  10758. CheckHotMethod(methodInstance, "");
  10759. }
  10760. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  10761. {
  10762. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  10763. // the specializations to handle that for us
  10764. return BfModuleMethodInstance(methodInstance);
  10765. }
  10766. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  10767. {
  10768. if (methodDef->mIsAbstract)
  10769. {
  10770. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  10771. _SetReified();
  10772. }
  10773. else
  10774. {
  10775. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  10776. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  10777. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  10778. doingRedeclare = true;
  10779. mOnDemandMethodCount++;
  10780. }
  10781. }
  10782. else
  10783. {
  10784. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  10785. // We haven't processed it yet
  10786. _SetReified();
  10787. CheckHotMethod(methodInstance, "");
  10788. if (methodInstance->mDeclModule == this)
  10789. {
  10790. if (methodInstance->mMethodProcessRequest != NULL)
  10791. {
  10792. // Disconnect method process request
  10793. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  10794. }
  10795. }
  10796. else
  10797. {
  10798. if (methodInstance->mMethodProcessRequest != NULL)
  10799. {
  10800. // Disconnect method process request
  10801. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  10802. methodInstance->mMethodProcessRequest = NULL;
  10803. }
  10804. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  10805. {
  10806. // Add new request in proper module
  10807. methodInstance->mDeclModule = this;
  10808. }
  10809. else
  10810. {
  10811. if (methodInstance->mDeclModule == NULL)
  10812. {
  10813. //
  10814. }
  10815. else if (methodInstance->mDeclModule != this)
  10816. {
  10817. // Is from specialized module?
  10818. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  10819. }
  10820. }
  10821. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  10822. {
  10823. methodInstance->mIRFunction = BfIRFunction();
  10824. if (!mIsModuleMutable)
  10825. StartExtension();
  10826. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  10827. {
  10828. StringT<128> mangledName;
  10829. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  10830. bool isIntrinsic = false;
  10831. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  10832. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  10833. }
  10834. }
  10835. AddMethodToWorkList(methodInstance);
  10836. }
  10837. }
  10838. }
  10839. }
  10840. else
  10841. {
  10842. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  10843. if (methodInstGroup->mMethodSpecializationMap == NULL)
  10844. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  10845. BfMethodInstance** methodInstancePtr = NULL;
  10846. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  10847. {
  10848. methodInstance = *methodInstancePtr;
  10849. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  10850. {
  10851. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  10852. AddMethodToWorkList(methodInstance);
  10853. methodInstance->mRequestedByAutocomplete = false;
  10854. }
  10855. if ((isReified) && (!methodInstance->mIsReified))
  10856. {
  10857. MarkDerivedDirty(typeInst);
  10858. if (methodInstance->mHasBeenProcessed)
  10859. {
  10860. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  10861. delete methodInstance;
  10862. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  10863. methodInstance = NULL;
  10864. }
  10865. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  10866. {
  10867. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  10868. delete methodInstance;
  10869. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  10870. methodInstance = NULL;
  10871. }
  10872. else
  10873. {
  10874. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  10875. // We haven't processed it yet
  10876. _SetReified();
  10877. CheckHotMethod(methodInstance, "");
  10878. }
  10879. }
  10880. }
  10881. }
  10882. if ((methodInstance != NULL) && (!doingRedeclare))
  10883. {
  10884. SetMethodDependency(methodInstance);
  10885. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  10886. {
  10887. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  10888. BF_ASSERT(!methodInstance->mIsReified);*/
  10889. if (methodInstance->mIsReified != isReified)
  10890. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  10891. if ((!isReified) &&
  10892. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  10893. {
  10894. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  10895. methodInstance->mIRFunction = BfIRFunction();
  10896. }
  10897. methodInstance->mIsReified = isReified;
  10898. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  10899. {
  10900. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  10901. }
  10902. if (!methodInstance->mMethodDef->mIsAbstract)
  10903. {
  10904. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  10905. {
  10906. // Wait until unreified
  10907. }
  10908. else
  10909. AddMethodToWorkList(methodInstance);
  10910. }
  10911. else
  10912. {
  10913. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  10914. }
  10915. }
  10916. if (mExtensionCount > 0)
  10917. {
  10918. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  10919. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  10920. {
  10921. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  10922. if (mAwaitingInitFinish)
  10923. FinishInit();
  10924. // We need to refer to a function that was defined in a prior module
  10925. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  10926. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  10927. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  10928. methodInstance->mDeclModule = this;
  10929. // Add this inlined def to ourselves
  10930. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  10931. {
  10932. mIncompleteMethodCount++;
  10933. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  10934. inlineMethodRequest->mType = typeInst;
  10935. inlineMethodRequest->mFromModule = this;
  10936. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  10937. inlineMethodRequest->mFromModuleRevision = mRevision;
  10938. inlineMethodRequest->mMethodInstance = methodInstance;
  10939. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  10940. BF_ASSERT(mIsModuleMutable);
  10941. }
  10942. }
  10943. }
  10944. if (mCompiler->IsSkippingExtraResolveChecks())
  10945. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10946. else
  10947. {
  10948. if (methodInstance->mDeclModule != this)
  10949. return ReferenceExternalMethodInstance(methodInstance, flags);
  10950. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  10951. {
  10952. auto importKind = methodInstance->GetImportCallKind();
  10953. if (importKind != BfImportCallKind_None)
  10954. {
  10955. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  10956. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  10957. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  10958. }
  10959. }
  10960. return BfModuleMethodInstance(methodInstance);
  10961. }
  10962. }
  10963. if (!doingRedeclare)
  10964. {
  10965. BfModule* specModule = NULL;
  10966. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  10967. {
  10968. specModule = GetSpecializedMethodModule(projectList);
  10969. }
  10970. if ((specModule != NULL) && (specModule != this))
  10971. {
  10972. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  10973. if (mAwaitingInitFinish)
  10974. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  10975. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  10976. }
  10977. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  10978. {
  10979. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  10980. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  10981. }
  10982. }
  10983. if (methodInstance == NULL)
  10984. {
  10985. if (lookupMethodGenericArguments.size() == 0)
  10986. {
  10987. BF_ASSERT(methodInstGroup->mDefault == NULL);
  10988. methodInstance = new BfMethodInstance();
  10989. methodInstGroup->mDefault = methodInstance;
  10990. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  10991. }
  10992. else
  10993. {
  10994. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  10995. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  10996. depthExceeded = true;
  10997. if (depthExceeded)
  10998. {
  10999. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  11000. return BfModuleMethodInstance();
  11001. }
  11002. BfMethodInstance** methodInstancePtr = NULL;
  11003. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  11004. BF_ASSERT(added);
  11005. methodInstance = new BfMethodInstance();
  11006. *methodInstancePtr = methodInstance;
  11007. if (mCompiler->IsAutocomplete())
  11008. methodInstance->mRequestedByAutocomplete = true;
  11009. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  11010. }
  11011. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  11012. methodInstance->mIRFunction = prevIRFunc; // Take it over
  11013. }
  11014. methodInstance->mMethodDef = methodDef;
  11015. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  11016. methodInstance->mMethodInstanceGroup = methodInstGroup;
  11017. methodInstance->mIsReified = isReified;
  11018. SetupMethodIdHash(methodInstance);
  11019. if (hadConcreteInterfaceGenericArgument)
  11020. methodInstance->mIgnoreBody = true;
  11021. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  11022. {
  11023. methodInstance->mIsForeignMethodDef = true;
  11024. BF_ASSERT(foreignType != NULL);
  11025. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  11026. }
  11027. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  11028. {
  11029. if (!lookupMethodGenericArguments.empty())
  11030. {
  11031. auto compareType = lookupMethodGenericArguments[0];
  11032. PopulateType(compareType, BfPopulateType_Data);
  11033. if (compareType->IsSplattable())
  11034. methodInstance->mAlwaysInline = true;
  11035. }
  11036. }
  11037. if (methodDef->mMethodType == BfMethodType_Init)
  11038. {
  11039. methodInstance->mMangleWithIdx = true;
  11040. }
  11041. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  11042. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  11043. declareModule = methodInstance->mDeclModule;
  11044. BF_ASSERT(typeInst == methodInstance->GetOwner());
  11045. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11046. if (isUnspecializedPass)
  11047. {
  11048. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  11049. {
  11050. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  11051. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  11052. }
  11053. }
  11054. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  11055. {
  11056. if (!sanitizedMethodGenericArguments.IsEmpty())
  11057. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  11058. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  11059. {
  11060. Fail("Internal error");
  11061. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  11062. return NULL;
  11063. }
  11064. for (auto genericArg : sanitizedMethodGenericArguments)
  11065. {
  11066. if (genericArg->IsPrimitiveType())
  11067. genericArg = GetWrappedStructType(genericArg);
  11068. if (genericArg != NULL)
  11069. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  11070. }
  11071. }
  11072. // Generic constraints
  11073. if (!methodDef->mGenericParams.IsEmpty())
  11074. {
  11075. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  11076. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  11077. {
  11078. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  11079. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  11080. }
  11081. }
  11082. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  11083. {
  11084. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  11085. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  11086. }
  11087. bool addToWorkList = !processNow;
  11088. if (mCompiler->GetAutoComplete() != NULL)
  11089. {
  11090. if (typeInst->IsSpecializedByAutoCompleteMethod())
  11091. addToWorkList = false;
  11092. if (methodInstance->mRequestedByAutocomplete)
  11093. addToWorkList = false;
  11094. }
  11095. BF_ASSERT(declareModule != NULL);
  11096. methodInstance->mDeclModule = declareModule;
  11097. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  11098. {
  11099. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  11100. // of a reified module -
  11101. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  11102. // BUT if we don't reify it then we have to remove the body after processing.
  11103. // 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
  11104. // the proper reified module.
  11105. declareModule = mContext->mUnreifiedModule;
  11106. }
  11107. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  11108. {
  11109. BF_ASSERT(!methodInstance->mIsReified);
  11110. declareModule = mContext->mUnreifiedModule;
  11111. }
  11112. SetMethodDependency(methodInstance);
  11113. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  11114. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  11115. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  11116. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  11117. {
  11118. // For mixins we only process the unspecialized version
  11119. addToWorkList = false;
  11120. }
  11121. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  11122. if (processNow)
  11123. {
  11124. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  11125. ProcessMethod(methodInstance);
  11126. }
  11127. if (mCompiler->IsSkippingExtraResolveChecks())
  11128. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  11129. if (methodInstance->mDeclModule != this)
  11130. return ReferenceExternalMethodInstance(methodInstance, flags);
  11131. return BfModuleMethodInstance(methodInstance);
  11132. }
  11133. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  11134. {
  11135. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  11136. if (methodInstance->mIsForeignMethodDef)
  11137. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  11138. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  11139. }
  11140. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  11141. {
  11142. if (!methodInstance->mMethodDef->mIsLocalMethod)
  11143. return NULL;
  11144. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  11145. if (outerLocal == NULL)
  11146. return NULL;
  11147. BfTypeVector genericArgs;
  11148. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  11149. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  11150. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  11151. }
  11152. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  11153. {
  11154. HashContext hashCtx;
  11155. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  11156. {
  11157. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  11158. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  11159. if (methodInstance->GetNumGenericArguments() != 0)
  11160. {
  11161. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  11162. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  11163. hashCtx.Mixin(methodGenericArg->mTypeId);
  11164. }
  11165. };
  11166. _MixinMethodInstance(methodInstance);
  11167. if (methodInstance->mMethodDef->mIsLocalMethod)
  11168. {
  11169. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  11170. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  11171. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  11172. }
  11173. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  11174. }
  11175. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  11176. {
  11177. BfIRValue globalValue;
  11178. BfIRValue* globalValuePtr = NULL;
  11179. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  11180. {
  11181. globalValue = *globalValuePtr;
  11182. }
  11183. if (!globalValue)
  11184. {
  11185. // This is necessary to reify the interface type
  11186. PopulateType(ifaceType);
  11187. StringT<128> slotVarName;
  11188. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  11189. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  11190. BfIRValue value;
  11191. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  11192. {
  11193. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  11194. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  11195. int virtSlotIdx = ifaceType->mSlotNum + 1;
  11196. value = GetConstValue32(virtSlotIdx);*/
  11197. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  11198. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  11199. }
  11200. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  11201. mInterfaceSlotRefs[ifaceType] = globalValue;
  11202. }
  11203. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  11204. }
  11205. void BfModule::HadSlotCountDependency()
  11206. {
  11207. if (mCompiler->mIsResolveOnly)
  11208. return;
  11209. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  11210. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  11211. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  11212. }
  11213. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  11214. {
  11215. if (str == "#TimeLocal")
  11216. {
  11217. time_t rawtime;
  11218. time(&rawtime);
  11219. tm* timeinfo = localtime(&rawtime);
  11220. char result[32];
  11221. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  11222. 1900 + timeinfo->tm_year,
  11223. timeinfo->tm_mon,
  11224. timeinfo->tm_mday,
  11225. timeinfo->tm_hour,
  11226. timeinfo->tm_min,
  11227. timeinfo->tm_sec);
  11228. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  11229. }
  11230. return BfTypedValue();
  11231. }
  11232. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  11233. {
  11234. BfIRValue globalValue;
  11235. auto fieldDef = fieldInstance->GetFieldDef();
  11236. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  11237. {
  11238. if (fieldInstance->mConstIdx != -1)
  11239. {
  11240. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  11241. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  11242. }
  11243. else
  11244. {
  11245. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  11246. }
  11247. }
  11248. if (mIsScratchModule)
  11249. {
  11250. // Just fake it for the extern and unspecialized modules
  11251. return BfTypedValue(mBfIRBuilder->CreateConstNull(), fieldInstance->GetResolvedType(), true);
  11252. }
  11253. BfIRValue* globalValuePtr = NULL;
  11254. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  11255. {
  11256. globalValue = *globalValuePtr;
  11257. BF_ASSERT(globalValue);
  11258. }
  11259. else
  11260. {
  11261. StringT<128> staticVarName;
  11262. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  11263. auto typeType = fieldInstance->GetResolvedType();
  11264. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  11265. {
  11266. typeType = typeType->GetUnderlyingType();
  11267. }
  11268. PopulateType(typeType);
  11269. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  11270. {
  11271. BfIRType irType = mBfIRBuilder->MapType(typeType);
  11272. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  11273. globalValue = mBfIRBuilder->CreateGlobalVariable(
  11274. irType,
  11275. false,
  11276. BfIRLinkageType_External,
  11277. BfIRValue(),
  11278. staticVarName,
  11279. IsThreadLocal(fieldInstance));
  11280. if (!mBfIRBuilder->mIgnoreWrites)
  11281. {
  11282. // Only store this if we actually did the creation
  11283. BF_ASSERT(globalValue);
  11284. mStaticFieldRefs[fieldInstance] = globalValue;
  11285. }
  11286. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  11287. }
  11288. }
  11289. auto type = fieldInstance->GetResolvedType();
  11290. if (type->IsValuelessType())
  11291. return BfTypedValue(globalValue, type);
  11292. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  11293. }
  11294. BfTypedValue BfModule::GetThis()
  11295. {
  11296. auto useMethodState = mCurMethodState;
  11297. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  11298. {
  11299. useMethodState = useMethodState->mPrevMethodState;
  11300. }
  11301. if (useMethodState != NULL)
  11302. {
  11303. // Fake a 'this' for var field resolution
  11304. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  11305. {
  11306. auto thisType = mCurTypeInstance;
  11307. if (thisType->IsValueType())
  11308. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  11309. else
  11310. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  11311. }
  11312. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  11313. {
  11314. return BfTypedValue();
  11315. }
  11316. }
  11317. else
  11318. {
  11319. //TODO: Do we allow useMethodState to be NULL anymore?
  11320. return BfTypedValue();
  11321. }
  11322. // if (useMethodState->HasNonStaticMixin())
  11323. // {
  11324. // auto checkMethodState = useMethodState;
  11325. // while (checkMethodState != NULL)
  11326. // {
  11327. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  11328. // {
  11329. // auto varDecl = checkMethodState->mLocals[localIdx];
  11330. // if (varDecl->mName == "this")
  11331. // {
  11332. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  11333. // if (varDecl->mIsSplat)
  11334. // {
  11335. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  11336. // }
  11337. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  11338. // {
  11339. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  11340. // }
  11341. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  11342. // }
  11343. // }
  11344. //
  11345. // checkMethodState = checkMethodState->mPrevMethodState;
  11346. // }
  11347. // }
  11348. // Check mixin state for 'this'
  11349. {
  11350. auto checkMethodState = useMethodState;
  11351. while (checkMethodState != NULL)
  11352. {
  11353. if (checkMethodState->mMixinState != NULL)
  11354. {
  11355. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  11356. if (thisValue.HasType())
  11357. {
  11358. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  11359. if (!thisValue.mType->IsValueType())
  11360. thisValue = LoadValue(thisValue);
  11361. return thisValue;
  11362. }
  11363. }
  11364. checkMethodState = checkMethodState->mPrevMethodState;
  11365. }
  11366. }
  11367. auto curMethodInstance = mCurMethodInstance;
  11368. if (useMethodState->mMethodInstance != NULL)
  11369. curMethodInstance = useMethodState->mMethodInstance;
  11370. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  11371. {
  11372. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  11373. {
  11374. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  11375. if (constLocal.mIsThis)
  11376. {
  11377. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  11378. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  11379. }
  11380. }
  11381. return BfTypedValue();
  11382. }
  11383. if (useMethodState->mLocals.IsEmpty())
  11384. {
  11385. // 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
  11386. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  11387. return BfTypedValue();
  11388. }
  11389. auto thisLocal = useMethodState->mLocals[0];
  11390. BF_ASSERT(thisLocal->mIsThis);
  11391. bool preferValue = !IsTargetingBeefBackend();
  11392. if (!thisLocal->mAddr)
  11393. preferValue = true;
  11394. bool usedVal = false;
  11395. BfIRValue thisValue;
  11396. if ((preferValue) && (!thisLocal->mIsLowered))
  11397. {
  11398. thisValue = thisLocal->mValue;
  11399. usedVal = true;
  11400. }
  11401. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  11402. thisValue = thisLocal->mAddr;
  11403. else
  11404. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  11405. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  11406. if (useMethodState->mClosureState != NULL)
  11407. {
  11408. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  11409. if (closureTypeInst != NULL)
  11410. {
  11411. if (closureTypeInst->mFieldInstances.size() > 0)
  11412. {
  11413. auto& field = closureTypeInst->mFieldInstances[0];
  11414. auto fieldDef = field.GetFieldDef();
  11415. if (fieldDef->mName == "__this")
  11416. {
  11417. if (mCurMethodState->mClosureState->mCapturing)
  11418. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  11419. // This is a captured 'this'
  11420. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  11421. if (field.mResolvedType->IsRef())
  11422. {
  11423. auto refType = (BfRefType*)field.mResolvedType;
  11424. auto underlyingType = refType->GetUnderlyingType();
  11425. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  11426. }
  11427. if (field.mResolvedType->IsObject())
  11428. {
  11429. result = LoadValue(result);
  11430. result.mKind = BfTypedValueKind_ThisValue;
  11431. }
  11432. else
  11433. {
  11434. if (fieldDef->mIsReadOnly)
  11435. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  11436. else
  11437. result.mKind = BfTypedValueKind_ThisAddr;
  11438. }
  11439. return result;
  11440. }
  11441. }
  11442. return BfTypedValue();
  11443. }
  11444. if (useMethodState->mClosureState->mCapturing)
  11445. {
  11446. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  11447. if (thisType->IsValueType())
  11448. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  11449. else
  11450. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  11451. }
  11452. }
  11453. auto localDef = useMethodState->mLocals[0];
  11454. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  11455. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  11456. {
  11457. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  11458. {
  11459. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  11460. }
  11461. if (localDef->mIsSplat)
  11462. {
  11463. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  11464. }
  11465. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  11466. }
  11467. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  11468. }
  11469. BfLocalVariable* BfModule::GetThisVariable()
  11470. {
  11471. if (mCurMethodState == NULL)
  11472. return NULL;
  11473. auto methodState = mCurMethodState->GetNonCaptureState();
  11474. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  11475. return methodState->mLocals[0];
  11476. return NULL;
  11477. }
  11478. bool BfModule::IsInGeneric()
  11479. {
  11480. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  11481. }
  11482. bool BfModule::InDefinitionSection()
  11483. {
  11484. if (mCurTypeInstance != NULL)
  11485. {
  11486. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  11487. return false;
  11488. }
  11489. return !IsInSpecializedSection();
  11490. }
  11491. bool BfModule::IsInSpecializedGeneric()
  11492. {
  11493. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  11494. return true;
  11495. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  11496. return false;
  11497. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  11498. }
  11499. bool BfModule::IsInSpecializedSection()
  11500. {
  11501. return IsInSpecializedGeneric() ||
  11502. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  11503. }
  11504. bool BfModule::IsInUnspecializedGeneric()
  11505. {
  11506. if (mCurMethodInstance != NULL)
  11507. return mCurMethodInstance->mIsUnspecialized;
  11508. return false;
  11509. }
  11510. //////////////////////////////////////////////////////////////////////////
  11511. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  11512. {
  11513. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  11514. if (type->IsValuelessType())
  11515. return mBfIRBuilder->GetFakeVal();
  11516. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  11517. if ((!doLifetimeEnd) && (WantsLifetimes()))
  11518. {
  11519. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  11520. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  11521. }
  11522. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  11523. auto typeOptions = GetTypeOptions();
  11524. if (typeOptions != NULL)
  11525. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  11526. // Local variable inits are implicitly handled in the Beef Backend
  11527. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  11528. {
  11529. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11530. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  11531. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  11532. mBfIRBuilder->ClearDebugLocation(storeInst);
  11533. mBfIRBuilder->SetInsertPoint(prevBlock);
  11534. }
  11535. return allocaInst;
  11536. }
  11537. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  11538. {
  11539. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  11540. mCurMethodState->mLocals.push_back(localVar);
  11541. BfLocalVarEntry* localVarEntryPtr;
  11542. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  11543. {
  11544. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  11545. localVarEntryPtr->mLocalVar = localVar;
  11546. }
  11547. }
  11548. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  11549. {
  11550. if ((mBfIRBuilder->DbgHasInfo()) &&
  11551. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  11552. (mHasFullDebugInfo) &&
  11553. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  11554. {
  11555. auto varType = localVarDef->mResolvedType;
  11556. if (localVarDef->mResolvedType->IsValuelessType())
  11557. {
  11558. }
  11559. else
  11560. {
  11561. bool isByAddr = false;
  11562. auto diValue = localVarDef->mValue;
  11563. if (localVarDef->mConstValue)
  11564. diValue = localVarDef->mConstValue;
  11565. else if (localVarDef->mAddr)
  11566. {
  11567. diValue = localVarDef->mAddr;
  11568. isByAddr = true;
  11569. }
  11570. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  11571. bool didConstToMem = false;
  11572. bool isConstant = false;
  11573. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  11574. diType = mBfIRBuilder->DbgCreateConstType(diType);
  11575. else if (localVarDef->mConstValue)
  11576. {
  11577. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  11578. isConstant =
  11579. (constant->mConstType < BfConstType_GlobalVar) ||
  11580. (constant->mConstType == BfConstType_AggZero) ||
  11581. (constant->mConstType == BfConstType_Array);
  11582. if (isConstant)
  11583. {
  11584. if (localVarDef->mResolvedType->IsComposite())
  11585. {
  11586. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  11587. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  11588. if (IsTargetingBeefBackend())
  11589. {
  11590. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  11591. didConstToMem = true;
  11592. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  11593. }
  11594. else
  11595. {
  11596. isByAddr = true;
  11597. mBfIRBuilder->SaveDebugLocation();
  11598. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11599. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  11600. mBfIRBuilder->ClearDebugLocation();
  11601. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  11602. auto addrVal = CreateAlloca(ptrType);
  11603. mBfIRBuilder->CreateStore(constMem, addrVal);
  11604. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  11605. diValue = addrVal;
  11606. didConstToMem = true;
  11607. mBfIRBuilder->SetInsertPoint(prevBlock);
  11608. mBfIRBuilder->RestoreDebugLocation();
  11609. }
  11610. }
  11611. if (mCompiler->mOptions.IsCodeView())
  11612. diType = mBfIRBuilder->DbgCreateConstType(diType);
  11613. }
  11614. }
  11615. if (!mBfIRBuilder->mIgnoreWrites)
  11616. {
  11617. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  11618. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  11619. localVarDef->mDbgVarInst = diVariable;
  11620. if (mBfIRBuilder->HasDebugLocation())
  11621. {
  11622. if ((isConstant) && (!didConstToMem))
  11623. {
  11624. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  11625. }
  11626. else
  11627. {
  11628. if ((IsTargetingBeefBackend()) && (doAliasValue))
  11629. {
  11630. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  11631. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  11632. }
  11633. if (isByAddr)
  11634. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  11635. else if (diValue)
  11636. {
  11637. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  11638. }
  11639. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  11640. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  11641. }
  11642. }
  11643. }
  11644. }
  11645. }
  11646. }
  11647. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  11648. {
  11649. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  11650. {
  11651. if ((!localVarDef->mValue.IsConst()) &&
  11652. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  11653. {
  11654. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  11655. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  11656. }
  11657. }
  11658. if (addDebugInfo)
  11659. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  11660. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  11661. DoAddLocalVariable(localVarDef);
  11662. auto rootMethodState = mCurMethodState->GetRootMethodState();
  11663. if (localVarDef->mLocalVarId == -1)
  11664. {
  11665. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  11666. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  11667. }
  11668. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  11669. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  11670. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  11671. {
  11672. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  11673. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  11674. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  11675. }
  11676. return localVarDef;
  11677. }
  11678. void BfModule::CreateDIRetVal()
  11679. {
  11680. if (!WantsDebugInfo())
  11681. return;
  11682. /*if (!mCurMethodState->mRetVal)
  11683. {
  11684. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  11685. return;
  11686. }*/
  11687. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  11688. {
  11689. BfType* dbgType = mCurMethodInstance->mReturnType;
  11690. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  11691. if (mCurMethodInstance->GetStructRetIdx() != -1)
  11692. {
  11693. BF_ASSERT(mCurMethodState->mRetValAddr);
  11694. dbgType = CreatePointerType(dbgType);
  11695. dbgValue = mCurMethodState->mRetValAddr;
  11696. }
  11697. else
  11698. {
  11699. BF_ASSERT(!mCurMethodState->mRetValAddr);
  11700. }
  11701. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  11702. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  11703. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  11704. }
  11705. }
  11706. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  11707. {
  11708. if (variableDef->mName.IsEmpty())
  11709. return;
  11710. BfLocalVarEntry* localVarEntryPtr = NULL;
  11711. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  11712. {
  11713. auto checkLocal = localVarEntryPtr->mLocalVar;
  11714. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  11715. {
  11716. BfError* error;
  11717. if (checkLocal->mIsImplicitParam)
  11718. return; // Ignore 'redefinition'
  11719. if (checkLocal->IsParam())
  11720. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  11721. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  11722. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  11723. else
  11724. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  11725. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  11726. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  11727. return;
  11728. }
  11729. }
  11730. }
  11731. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  11732. {
  11733. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  11734. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  11735. {
  11736. if (tokenNode->GetToken() == BfToken_Colon)
  11737. {
  11738. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  11739. {
  11740. Fail("Cannot access method scope across deferred block boundary", scopeName);
  11741. return NULL;
  11742. }
  11743. return &mCurMethodState->mHeadScope;
  11744. }
  11745. else if (tokenNode->GetToken() == BfToken_Mixin)
  11746. {
  11747. if (fromMixinState == NULL)
  11748. {
  11749. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  11750. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  11751. return mCurMethodState->mCurScope;
  11752. }
  11753. fromMixinState->mUsedInvocationScope = true;
  11754. return fromMixinState->mTargetScope;
  11755. }
  11756. else if (tokenNode->GetToken() == BfToken_New)
  11757. return NULL;
  11758. }
  11759. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  11760. {
  11761. auto findLabel = scopeName->ToString();
  11762. bool crossedDeferredBlock = false;
  11763. auto checkScope = mCurMethodState->mCurScope;
  11764. while (checkScope != NULL)
  11765. {
  11766. if (checkScope->mIsDeferredBlock)
  11767. crossedDeferredBlock = true;
  11768. if (checkScope->mLabel == findLabel)
  11769. {
  11770. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  11771. {
  11772. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  11773. return NULL;
  11774. }
  11775. return checkScope;
  11776. }
  11777. checkScope = checkScope->mPrevScope;
  11778. }
  11779. if (!inMixinDecl)
  11780. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  11781. }
  11782. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  11783. {
  11784. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  11785. }
  11786. return mCurMethodState->mCurScope;
  11787. }
  11788. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  11789. {
  11790. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  11791. }
  11792. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  11793. {
  11794. auto scopeData = FindScope(scopeName, false);
  11795. if (scopeData == NULL)
  11796. return NULL;
  11797. int scopeDepth = scopeData->GetDepth();
  11798. // Find the first break data that is at or below the depth of our requested scope
  11799. auto breakData = mCurMethodState->mBreakData;
  11800. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  11801. {
  11802. if (breakData->mScope->mIsConditional)
  11803. return NULL;
  11804. breakData = breakData->mPrevBreakData;
  11805. }
  11806. return breakData;
  11807. }
  11808. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  11809. {
  11810. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  11811. if (!IsTargetingBeefBackend())
  11812. return;
  11813. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  11814. {
  11815. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  11816. }
  11817. }
  11818. void BfModule::ClearLifetimeEnds()
  11819. {
  11820. auto scopeData = mCurMethodState->mCurScope;
  11821. while (scopeData != NULL)
  11822. {
  11823. scopeData->mDeferredLifetimeEnds.Clear();
  11824. scopeData = scopeData->mPrevScope;
  11825. }
  11826. }
  11827. bool BfModule::WantsDebugInfo()
  11828. {
  11829. if ((mCurMethodInstance != NULL) &&
  11830. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  11831. return false;
  11832. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  11833. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  11834. }
  11835. BfTypeOptions* BfModule::GetTypeOptions()
  11836. {
  11837. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  11838. return mCurMethodState->mMethodTypeOptions;
  11839. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  11840. }
  11841. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  11842. {
  11843. BfReflectKind reflectKind = BfReflectKind_None;
  11844. if (attrType->mCustomAttributes != NULL)
  11845. {
  11846. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  11847. {
  11848. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  11849. {
  11850. for (auto& prop : customAttr.mSetProperties)
  11851. {
  11852. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  11853. if (propDef->mName == "ReflectUser")
  11854. {
  11855. if (prop.mParam.mValue.IsConst())
  11856. {
  11857. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  11858. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  11859. }
  11860. }
  11861. }
  11862. // Check for Flags arg
  11863. if (customAttr.mCtorArgs.size() < 2)
  11864. continue;
  11865. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  11866. if (constant == NULL)
  11867. continue;
  11868. if (constant->mTypeCode == BfTypeCode_Boolean)
  11869. continue;
  11870. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  11871. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  11872. }
  11873. }
  11874. }
  11875. return reflectKind;
  11876. }
  11877. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  11878. {
  11879. auto checkTypeInstance = typeInstance;
  11880. while (checkTypeInstance != NULL)
  11881. {
  11882. if (checkTypeInstance->mCustomAttributes != NULL)
  11883. {
  11884. auto checkReflectKind = BfReflectKind_None;
  11885. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  11886. {
  11887. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  11888. {
  11889. if (customAttr.mCtorArgs.size() > 0)
  11890. {
  11891. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  11892. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  11893. }
  11894. else
  11895. {
  11896. checkReflectKind = BfReflectKind_All;
  11897. }
  11898. }
  11899. else
  11900. {
  11901. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  11902. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  11903. }
  11904. }
  11905. if ((checkTypeInstance == typeInstance) ||
  11906. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  11907. {
  11908. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  11909. }
  11910. }
  11911. for (auto ifaceEntry : typeInstance->mInterfaces)
  11912. {
  11913. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  11914. {
  11915. auto iface = ifaceEntry.mInterfaceType;
  11916. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  11917. if (customAttr != NULL)
  11918. {
  11919. for (auto& prop : customAttr->mSetProperties)
  11920. {
  11921. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  11922. if (propDef->mName == "ReflectImplementer")
  11923. {
  11924. if (prop.mParam.mValue.IsConst())
  11925. {
  11926. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  11927. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  11928. }
  11929. }
  11930. }
  11931. }
  11932. }
  11933. }
  11934. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  11935. }
  11936. return reflectKind;
  11937. }
  11938. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  11939. {
  11940. BfScopeData* checkScope = mCurMethodState->mCurScope;
  11941. while (checkScope != NULL)
  11942. {
  11943. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  11944. return true;
  11945. if (checkScope == scope)
  11946. break;
  11947. checkScope = checkScope->mPrevScope;
  11948. }
  11949. return false;
  11950. }
  11951. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  11952. {
  11953. // Is there anything we need to do here?
  11954. if (mBfIRBuilder->mIgnoreWrites)
  11955. {
  11956. // Just visit deferred blocks
  11957. BfScopeData* checkScope = mCurMethodState->mCurScope;
  11958. while (checkScope != NULL)
  11959. {
  11960. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  11961. while (deferredCallEntry != NULL)
  11962. {
  11963. if (deferredCallEntry->mDeferredBlock != NULL)
  11964. {
  11965. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  11966. }
  11967. deferredCallEntry = deferredCallEntry->mNext;
  11968. }
  11969. if (checkScope == scopeData)
  11970. break;
  11971. checkScope = checkScope->mPrevScope;
  11972. }
  11973. return;
  11974. }
  11975. // Why did we want to do SetIllegalSrcPos here?
  11976. // Don't we always want to step onto these instances?
  11977. // Find a case where we don't and perhaps only do it there.
  11978. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  11979. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  11980. //SetIllegalSrcPos();
  11981. bool setSrcPos = false;
  11982. bool wantsNop = true;
  11983. BfAstNode* deferCloseNode = NULL;
  11984. if (mCurMethodState->mInPostReturn)
  11985. {
  11986. // These won't get used, they are post-return
  11987. return;
  11988. }
  11989. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  11990. BfScopeData* scopeJumpBlock = NULL;
  11991. bool hadExtraDeferredLifetimeEnds = false;
  11992. auto _FlushLifetimeEnds = [&]()
  11993. {
  11994. for (auto lifetimeEnd : deferredLifetimeEnds)
  11995. {
  11996. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  11997. mBfIRBuilder->ClearDebugLocation_Last();
  11998. }
  11999. deferredLifetimeEnds.clear();
  12000. };
  12001. BfScopeData* checkScope = mCurMethodState->mCurScope;
  12002. while (checkScope != NULL)
  12003. {
  12004. if (checkScope->mCloseNode != NULL)
  12005. deferCloseNode = checkScope->mCloseNode;
  12006. if (doneBlock)
  12007. {
  12008. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  12009. for (auto& checkHandler : checkScope->mDeferredHandlers)
  12010. {
  12011. if (checkHandler.mDoneBlock == doneBlock)
  12012. {
  12013. scopeJumpBlock = checkScope;
  12014. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  12015. mBfIRBuilder->ClearDebugLocation_Last();
  12016. _FlushLifetimeEnds();
  12017. break;
  12018. }
  12019. }
  12020. if (scopeJumpBlock != NULL)
  12021. break;
  12022. }
  12023. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  12024. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  12025. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  12026. if (hasWork)
  12027. {
  12028. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  12029. if (deferCloseNode != NULL)
  12030. {
  12031. UpdateSrcPos(deferCloseNode);
  12032. }
  12033. if (doneBlock)
  12034. {
  12035. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  12036. String blockName = "deferredCalls";
  12037. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  12038. BfDeferredHandler deferredHandler;
  12039. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  12040. {
  12041. mBfIRBuilder->SaveDebugLocation();
  12042. mBfIRBuilder->ClearDebugLocation();
  12043. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  12044. mBfIRBuilder->RestoreDebugLocation();
  12045. }
  12046. else
  12047. {
  12048. // Definitely chain
  12049. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  12050. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  12051. mBfIRBuilder->ClearDebugLocation_Last();
  12052. _FlushLifetimeEnds();
  12053. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  12054. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  12055. }
  12056. deferredHandler.mDoneBlock = doneBlock;
  12057. if (!mBfIRBuilder->mIgnoreWrites)
  12058. checkScope->mDeferredHandlers.push_back(deferredHandler);
  12059. if (checkScope == &mCurMethodState->mHeadScope)
  12060. {
  12061. if (!mCurMethodState->mDIRetVal)
  12062. {
  12063. // 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
  12064. // be scoped to the physical method
  12065. /*if (deferCloseNode != NULL)
  12066. {
  12067. UpdateSrcPos(deferCloseNode);
  12068. }*/
  12069. CreateDIRetVal();
  12070. }
  12071. }
  12072. if (checkScope != mCurMethodState->mTailScope)
  12073. {
  12074. if (deferredHandler.mHandlerBlock.IsFake())
  12075. {
  12076. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  12077. }
  12078. if (!mBfIRBuilder->mIgnoreWrites)
  12079. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  12080. }
  12081. }
  12082. std::unordered_set<BfDeferredCallEntry*> handledSet;
  12083. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  12084. while (deferredCallEntry != NULL)
  12085. {
  12086. BfDeferredCallEmitState deferredCallEmitState;
  12087. deferredCallEmitState.mCloseNode = deferCloseNode;
  12088. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  12089. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  12090. if (deferCloseNode != NULL)
  12091. {
  12092. UpdateSrcPos(deferCloseNode);
  12093. }
  12094. if (wantsNop)
  12095. EmitEnsureInstructionAt();
  12096. wantsNop = false;
  12097. if (deferredCallEntry->mDeferredBlock != NULL)
  12098. {
  12099. auto itr = handledSet.insert(deferredCallEntry);
  12100. if (!itr.second)
  12101. {
  12102. // Already handled, can happen if we defer again within the block
  12103. deferredCallEntry = deferredCallEntry->mNext;
  12104. continue;
  12105. }
  12106. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  12107. EmitDeferredCall(*deferredCallEntry, true);
  12108. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  12109. {
  12110. // The list changed, start over and ignore anything we've already handled
  12111. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  12112. }
  12113. else
  12114. deferredCallEntry = deferredCallEntry->mNext;
  12115. }
  12116. else
  12117. {
  12118. EmitDeferredCall(*deferredCallEntry, true);
  12119. deferredCallEntry = deferredCallEntry->mNext;
  12120. }
  12121. }
  12122. if (checkScope->mSavedStack)
  12123. {
  12124. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  12125. if (mCurMethodState->mDynStackRevIdx)
  12126. {
  12127. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  12128. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  12129. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  12130. }
  12131. }
  12132. }
  12133. if (!checkScope->mIsScopeHead)
  12134. {
  12135. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  12136. if (!IsTargetingBeefBackend())
  12137. {
  12138. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  12139. {
  12140. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  12141. }
  12142. }
  12143. else
  12144. {
  12145. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  12146. {
  12147. deferredLifetimeEnds.Add(lifetimeEnd);
  12148. }
  12149. }
  12150. }
  12151. if (checkScope == scopeData)
  12152. break;
  12153. checkScope = checkScope->mPrevScope;
  12154. }
  12155. if ((doneBlock) && (scopeJumpBlock == NULL))
  12156. {
  12157. mBfIRBuilder->CreateBr(doneBlock);
  12158. mBfIRBuilder->ClearDebugLocation_Last();
  12159. }
  12160. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  12161. // may have been created when other scope lifetimes were available
  12162. _FlushLifetimeEnds();
  12163. // Emit lifetimeEnds after the branch for Beef
  12164. /*if (IsTargetingBeefBackend())
  12165. {
  12166. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  12167. BfScopeData* checkScope = mCurMethodState->mCurScope;
  12168. while (checkScope != NULL)
  12169. {
  12170. if (checkScope == scopeJumpBlock)
  12171. break;
  12172. if (!checkScope->mIsScopeHead)
  12173. {
  12174. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  12175. {
  12176. if (needsEnsureInst)
  12177. {
  12178. needsEnsureInst = false;
  12179. }
  12180. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  12181. }
  12182. }
  12183. if (checkScope == scopeData)
  12184. break;
  12185. checkScope = checkScope->mPrevScope;
  12186. }
  12187. }*/
  12188. }
  12189. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  12190. {
  12191. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  12192. {
  12193. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  12194. while (deferredLocalAssignData != NULL)
  12195. {
  12196. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  12197. break;
  12198. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  12199. deferredLocalAssignData->mIsUnconditional = false;
  12200. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  12201. }
  12202. }
  12203. // When we leave a scope, mark those as assigned for deferred assignment purposes
  12204. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  12205. {
  12206. auto localDef = mCurMethodState->mLocals[localIdx];
  12207. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  12208. {
  12209. bool hadAssignment = false;
  12210. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  12211. {
  12212. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  12213. if (entry.mLocalVar == localDef)
  12214. hadAssignment = true;
  12215. }
  12216. if (!hadAssignment)
  12217. {
  12218. localDef->mHadExitBeforeAssign = true;
  12219. mCurMethodState->LocalDefined(localDef);
  12220. }
  12221. }
  12222. }
  12223. }
  12224. void BfModule::CreateReturn(BfIRValue val)
  12225. {
  12226. if (mCurMethodInstance->GetStructRetIdx() != -1)
  12227. {
  12228. // Store to sret
  12229. BF_ASSERT(val);
  12230. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  12231. mBfIRBuilder->CreateRetVoid();
  12232. return;
  12233. }
  12234. if (mCurMethodInstance->mReturnType->IsValuelessType())
  12235. {
  12236. mBfIRBuilder->CreateRetVoid();
  12237. return;
  12238. }
  12239. if (mCurMethodInstance->mReturnType->IsStruct())
  12240. {
  12241. BfTypeCode loweredReturnType = BfTypeCode_None;
  12242. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  12243. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  12244. if (loweredReturnType != BfTypeCode_None)
  12245. {
  12246. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  12247. mBfIRBuilder->CreateStore(val, retVal);
  12248. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  12249. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  12250. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  12251. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  12252. mBfIRBuilder->CreateRet(loadedReturnValue);
  12253. return;
  12254. }
  12255. }
  12256. BF_ASSERT(val);
  12257. mBfIRBuilder->CreateRet(val);
  12258. }
  12259. void BfModule::EmitReturn(BfIRValue val)
  12260. {
  12261. if (mCurMethodState->mIRExitBlock)
  12262. {
  12263. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  12264. {
  12265. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  12266. {
  12267. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  12268. if (!mCurMethodState->mRetVal)
  12269. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  12270. mBfIRBuilder->CreateStore(val, retVal);
  12271. }
  12272. }
  12273. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  12274. }
  12275. else
  12276. {
  12277. EmitDeferredScopeCalls(false, NULL);
  12278. if (val)
  12279. {
  12280. if (mCurMethodInstance->mReturnType->IsValuelessType())
  12281. mBfIRBuilder->CreateRetVoid();
  12282. else
  12283. mBfIRBuilder->CreateRet(val);
  12284. }
  12285. }
  12286. mCurMethodState->SetHadReturn(true);
  12287. mCurMethodState->mLeftBlockUncond = true;
  12288. }
  12289. void BfModule::EmitDefaultReturn()
  12290. {
  12291. if (mCurMethodState->mInDeferredBlock)
  12292. return;
  12293. if (mCurMethodState->mIRExitBlock)
  12294. {
  12295. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  12296. }
  12297. else
  12298. {
  12299. if (mCurMethodInstance->mReturnType->IsVoid())
  12300. mBfIRBuilder->CreateRetVoid();
  12301. else if (mCurMethodInstance->GetStructRetIdx() == -1)
  12302. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  12303. }
  12304. mCurMethodState->SetHadReturn(true);
  12305. mCurMethodState->mLeftBlockUncond = true;
  12306. }
  12307. void BfModule::AssertErrorState()
  12308. {
  12309. if (mIgnoreErrors)
  12310. return;
  12311. if (mHadBuildError)
  12312. return;
  12313. if (mCurTypeInstance != NULL)
  12314. {
  12315. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  12316. return;
  12317. }
  12318. if (mCurMethodInstance != NULL)
  12319. {
  12320. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  12321. return;
  12322. if (mCurMethodInstance->mHasFailed)
  12323. return;
  12324. }
  12325. // We want the module to be marked as failed even if it's just an error in the parser
  12326. if (mCurMethodInstance != NULL)
  12327. mCurMethodInstance->mHasFailed = true;
  12328. mHadBuildError = true;
  12329. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  12330. if (mCurTypeInstance != NULL)
  12331. {
  12332. if (mCurTypeInstance->mTypeFailed)
  12333. return;
  12334. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  12335. return;
  12336. }
  12337. if (mCurMethodInstance != NULL)
  12338. {
  12339. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  12340. return;
  12341. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  12342. return;
  12343. }
  12344. if (mCompiler->IsAutocomplete())
  12345. return;
  12346. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  12347. }
  12348. void BfModule::AssertParseErrorState()
  12349. {
  12350. if (mCompiler->mRevision == 1)
  12351. AssertErrorState();
  12352. }
  12353. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  12354. {
  12355. BF_ASSERT(delegateType->IsDelegate());
  12356. auto typeInst = delegateType->ToTypeInstance();
  12357. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  12358. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  12359. return invokeMethodInstance->mReturnType;
  12360. }
  12361. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  12362. {
  12363. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  12364. }
  12365. void BfModule::CreateDelegateInvokeMethod()
  12366. {
  12367. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  12368. //mBfIRBuilder->ClearDebugLocation();
  12369. SetIllegalSrcPos();
  12370. auto typeInstance = mCurTypeInstance;
  12371. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  12372. SizedArray<BfIRType, 4> staticParamTypes;
  12373. SizedArray<BfIRValue, 4> staticFuncArgs;
  12374. SizedArray<BfIRValue, 4> memberFuncArgs;
  12375. auto multicastDelegateType = typeInstance->mBaseType;
  12376. if (multicastDelegateType->mFieldInstances.size() != 2)
  12377. {
  12378. AssertErrorState();
  12379. return;
  12380. }
  12381. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  12382. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  12383. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  12384. BfExprEvaluator exprEvaluator(this);
  12385. SizedArray<BfIRType, 8> origParamTypes;
  12386. BfIRType origReturnType;
  12387. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  12388. if (mCurMethodInstance->mReturnType->IsValueType())
  12389. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  12390. if (mCurMethodInstance->GetStructRetIdx() != 0)
  12391. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  12392. int thisIdx = 0;
  12393. if (mCurMethodInstance->GetStructRetIdx() != -1)
  12394. {
  12395. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  12396. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  12397. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  12398. }
  12399. if (mCurMethodInstance->GetStructRetIdx() == 0)
  12400. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  12401. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  12402. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  12403. {
  12404. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  12405. exprEvaluator.PushArg(localVal, staticFuncArgs);
  12406. exprEvaluator.PushArg(localVal, memberFuncArgs);
  12407. }
  12408. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  12409. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  12410. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  12411. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  12412. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  12413. auto doneBB = mBfIRBuilder->CreateBlock("done");
  12414. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  12415. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  12416. BfIRValue nonStaticResult;
  12417. BfIRValue staticResult;
  12418. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  12419. /// Non-static invocation
  12420. {
  12421. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  12422. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  12423. mBfIRBuilder->SetInsertPoint(trueBB);
  12424. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  12425. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  12426. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  12427. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  12428. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  12429. if (mCurMethodInstance->GetStructRetIdx() != -1)
  12430. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  12431. if (callingConv != BfIRCallingConv_CDecl)
  12432. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  12433. mCurMethodState->SetHadReturn(false);
  12434. mCurMethodState->mLeftBlockUncond = false;
  12435. mCurMethodState->mLeftBlockCond = false;
  12436. mBfIRBuilder->CreateBr(doneBB);
  12437. }
  12438. // Static invocation
  12439. {
  12440. mBfIRBuilder->AddBlock(falseBB);
  12441. mBfIRBuilder->SetInsertPoint(falseBB);
  12442. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  12443. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  12444. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  12445. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  12446. if (mCurMethodInstance->GetStructRetIdx() != -1)
  12447. {
  12448. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  12449. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  12450. }
  12451. if (callingConv == BfIRCallingConv_ThisCall)
  12452. callingConv = BfIRCallingConv_CDecl;
  12453. if (callingConv != BfIRCallingConv_CDecl)
  12454. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  12455. mCurMethodState->SetHadReturn(false);
  12456. mCurMethodState->mLeftBlockUncond = false;
  12457. mCurMethodState->mLeftBlockCond = false;
  12458. mBfIRBuilder->CreateBr(doneBB);
  12459. }
  12460. mBfIRBuilder->AddBlock(doneBB);
  12461. mBfIRBuilder->SetInsertPoint(doneBB);
  12462. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->GetStructRetIdx() != -1))
  12463. {
  12464. mBfIRBuilder->CreateRetVoid();
  12465. }
  12466. else
  12467. {
  12468. BfIRType loweredIRReturnType;
  12469. BfTypeCode loweredTypeCode = BfTypeCode_None;
  12470. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  12471. if (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2))
  12472. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  12473. else
  12474. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  12475. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  12476. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  12477. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  12478. mBfIRBuilder->CreateRet(phi);
  12479. }
  12480. }
  12481. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  12482. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  12483. {
  12484. auto typeDef = typeInstance->mTypeDef;
  12485. auto methodDeclaration = methodDef->mMethodDeclaration;
  12486. if (!mCompiler->mIsResolveOnly)
  12487. return true;
  12488. if (typeInstance->IsGenericTypeInstance())
  12489. {
  12490. // We only really want to process the unspecialized type for autocompletion
  12491. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  12492. return false;
  12493. }
  12494. BfAstNode* checkNode = methodDeclaration;
  12495. if (methodDeclaration == NULL)
  12496. checkNode = methodDef->mBody;
  12497. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  12498. {
  12499. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  12500. return true;
  12501. }
  12502. return false;
  12503. }
  12504. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  12505. {
  12506. methodInst->mAppendAllocAlign = 1;
  12507. }
  12508. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  12509. {
  12510. BP_ZONE("BfModule::TryConstCalcAppend");
  12511. if (mCompiler->mIsResolveOnly)
  12512. return BfTypedValue();
  12513. // We want to regenerate all ctor calls when the method internals change
  12514. {
  12515. auto checkTypeInst = methodInst->GetOwner();
  12516. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  12517. {
  12518. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  12519. checkTypeInst = GetBaseType(checkTypeInst);
  12520. }
  12521. }
  12522. if (!methodInst->mMayBeConst)
  12523. return BfTypedValue();
  12524. // Do we need to iterate in order to resolve mAppendAllocAlign?
  12525. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  12526. bool wasAllConst = true;
  12527. int argIdx = 0;
  12528. int paramIdx = 0;
  12529. while (true)
  12530. {
  12531. if (argIdx >= (int)args.size())
  12532. break;
  12533. auto paramType = methodInst->GetParamType(paramIdx);
  12534. PopulateType(paramType);
  12535. int argCount = 0;
  12536. if (!paramType->IsValuelessType())
  12537. {
  12538. if (methodInst->GetParamIsSplat(paramIdx))
  12539. argCount = paramType->GetSplatCount();
  12540. else
  12541. argCount = 1;
  12542. for (int argOfs = 0; argOfs < argCount; argOfs++)
  12543. {
  12544. auto arg = args[argIdx + argOfs];
  12545. if (!arg.IsConst())
  12546. {
  12547. wasAllConst = false;
  12548. if (!isFirstRun)
  12549. {
  12550. auto& param = methodInst->mParams[argIdx];
  12551. if (param.mReferencedInConstPass)
  12552. {
  12553. // If this param is required as part of the const calculation then
  12554. // we require that it be const...
  12555. return BfTypedValue();
  12556. }
  12557. }
  12558. }
  12559. }
  12560. }
  12561. paramIdx++;
  12562. argIdx += argCount;
  12563. }
  12564. auto methodDef = methodInst->mMethodDef;
  12565. auto methodDecl = methodDef->GetMethodDeclaration();
  12566. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  12567. if (methodDeclBlock == NULL)
  12568. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  12569. BfTypedValue constValue;
  12570. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  12571. auto checkState = mCurMethodState->mConstResolveState;
  12572. while (checkState != NULL)
  12573. {
  12574. if (checkState->mMethodInstance == methodInst)
  12575. {
  12576. return BfTypedValue();
  12577. }
  12578. checkState = checkState->mPrevConstResolveState;
  12579. }
  12580. //auto accumValue = GetConstValue(0);
  12581. bool failed = false;
  12582. //
  12583. {
  12584. BfConstResolveState constResolveState;
  12585. constResolveState.mMethodInstance = methodInst;
  12586. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  12587. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  12588. BfMethodState methodState;
  12589. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  12590. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  12591. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  12592. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  12593. methodState.mConstResolveState = &constResolveState;
  12594. int argIdx = 0;
  12595. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  12596. {
  12597. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  12598. continue;
  12599. auto paramType = methodInst->GetParamType(paramIdx);
  12600. // Fix this after we allow structs to be consts
  12601. //BF_ASSERT(!paramType->IsSplattable());
  12602. BfLocalVariable* localVar = new BfLocalVariable();
  12603. localVar->mName = methodInst->GetParamName(paramIdx);
  12604. localVar->mResolvedType = paramType;
  12605. localVar->mConstValue = args[argIdx];
  12606. localVar->mParamIdx = paramIdx;
  12607. AddLocalVariableDef(localVar);
  12608. argIdx++;
  12609. }
  12610. AppendAllocVisitor appendAllocVisitor;
  12611. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  12612. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  12613. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  12614. if (baseCtorAppendValue)
  12615. {
  12616. if (baseCtorAppendValue.mValue.IsFake())
  12617. appendAllocVisitor.mFailed = true;
  12618. else
  12619. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  12620. }
  12621. appendAllocVisitor.mModule = this;
  12622. appendAllocVisitor.VisitChild(methodDecl->mBody);
  12623. if (!appendAllocVisitor.mFailed)
  12624. constValue = appendAllocVisitor.mConstAccum;
  12625. if (isFirstRun)
  12626. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  12627. if (isFirstRun)
  12628. {
  12629. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  12630. {
  12631. auto localVar = mCurMethodState->mLocals[paramIdx];
  12632. if (localVar->mReadFromId != -1)
  12633. {
  12634. auto& param = methodInst->mParams[paramIdx];
  12635. param.mReferencedInConstPass = true;
  12636. }
  12637. }
  12638. }
  12639. }
  12640. mBfIRBuilder->SetInsertPoint(prevBlock);
  12641. if (!constValue)
  12642. {
  12643. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  12644. // all-const args
  12645. if (wasAllConst)
  12646. {
  12647. methodInst->mMayBeConst = false;
  12648. }
  12649. }
  12650. return constValue;
  12651. }
  12652. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  12653. {
  12654. // Any errors should only be shown in the actual CTOR call
  12655. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  12656. auto methodDef = mCurMethodInstance->mMethodDef;
  12657. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  12658. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  12659. BfCustomAttributes* customAttributes = NULL;
  12660. defer(delete customAttributes);
  12661. BfInvocationExpression* ctorInvocation = NULL;
  12662. if (ctorDeclaration != NULL)
  12663. {
  12664. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  12665. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  12666. {
  12667. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  12668. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  12669. }
  12670. }
  12671. BfTypeInstance* targetType = NULL;
  12672. if (ctorInvocation != NULL)
  12673. {
  12674. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  12675. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12676. }
  12677. else
  12678. targetType = mCurTypeInstance->mBaseType;
  12679. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  12680. return NULL;
  12681. auto targetRefNode = methodDef->GetRefNode();
  12682. BfType* targetThisType = targetType;
  12683. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  12684. BfExprEvaluator exprEvaluator(this);
  12685. BfResolvedArgs argValues;
  12686. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  12687. {
  12688. argValues.Init(&ctorInvocation->mArguments);
  12689. }
  12690. //
  12691. {
  12692. }
  12693. BfFunctionBindResult bindResult;
  12694. bindResult.mSkipThis = true;
  12695. bindResult.mWantsArgs = true;
  12696. {
  12697. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  12698. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12699. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  12700. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  12701. }
  12702. if (bindResult.mMethodInstance == NULL)
  12703. {
  12704. AssertErrorState();
  12705. return BfTypedValue();
  12706. }
  12707. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  12708. {
  12709. return BfTypedValue();
  12710. }
  12711. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  12712. bindResult.mIRArgs.RemoveAt(0);
  12713. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  12714. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  12715. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  12716. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  12717. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  12718. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  12719. if (appendSizeTypedValue)
  12720. return appendSizeTypedValue;
  12721. if (constOnly)
  12722. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  12723. bool needsRecalc = false;
  12724. for (auto irArg : bindResult.mIRArgs)
  12725. {
  12726. if (irArg.IsFake())
  12727. needsRecalc = true;
  12728. }
  12729. auto calcAppendArgs = bindResult.mIRArgs;
  12730. if (needsRecalc)
  12731. {
  12732. // Do it again, but without mIgnoreWrites set
  12733. BfResolvedArgs argValues;
  12734. argValues.Init(&ctorInvocation->mArguments);
  12735. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12736. BfFunctionBindResult bindResult;
  12737. bindResult.mSkipThis = true;
  12738. bindResult.mWantsArgs = true;
  12739. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  12740. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  12741. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  12742. bindResult.mIRArgs.RemoveAt(0);
  12743. calcAppendArgs = bindResult.mIRArgs;
  12744. }
  12745. BF_ASSERT(calcAppendMethodModule.mFunc);
  12746. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  12747. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  12748. return appendSizeTypedValue;
  12749. }
  12750. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  12751. void BfModule::EmitCtorCalcAppend()
  12752. {
  12753. if (mCompiler->mIsResolveOnly)
  12754. return;
  12755. auto methodDef = mCurMethodInstance->mMethodDef;
  12756. auto methodDecl = methodDef->GetMethodDeclaration();
  12757. Array<BfAstNode*> deferredNodeList;
  12758. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  12759. if (methodDeclBlock == NULL)
  12760. return;
  12761. AppendAllocVisitor appendAllocVisitor;
  12762. auto baseCalcAppend = CallBaseCtorCalc(false);
  12763. if (baseCalcAppend)
  12764. {
  12765. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  12766. }
  12767. appendAllocVisitor.mModule = this;
  12768. appendAllocVisitor.VisitChild(methodDecl->mBody);
  12769. }
  12770. void BfModule::CreateStaticCtor()
  12771. {
  12772. auto typeDef = mCurTypeInstance->mTypeDef;
  12773. auto methodDef = mCurMethodInstance->mMethodDef;
  12774. BfIRBlock exitBB;
  12775. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  12776. {
  12777. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  12778. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  12779. mBfIRBuilder->MapType(boolType),
  12780. false,
  12781. BfIRLinkageType_Internal,
  12782. GetDefaultValue(boolType),
  12783. "didStaticInit");
  12784. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  12785. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  12786. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  12787. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  12788. mBfIRBuilder->SetInsertPoint(initBB);
  12789. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  12790. }
  12791. // Do DLL imports
  12792. if (!mDllImportEntries.empty())
  12793. {
  12794. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  12795. PopulateType(internalType);
  12796. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  12797. if (!getSharedProcAddressInstance)
  12798. {
  12799. if (!mCompiler->mPassInstance->HasFailed())
  12800. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  12801. }
  12802. }
  12803. // Fill in initializer values
  12804. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  12805. {
  12806. for (auto fieldDef : typeDef->mFields)
  12807. {
  12808. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12809. {
  12810. // For extensions, only handle these fields in the appropriate extension
  12811. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12812. continue;
  12813. UpdateSrcPos(fieldDef->mInitializer);
  12814. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12815. if (!fieldInst->mFieldIncluded)
  12816. continue;
  12817. if (fieldInst->mResolvedType->IsVar())
  12818. {
  12819. continue;
  12820. }
  12821. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  12822. }
  12823. }
  12824. }
  12825. else
  12826. {
  12827. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12828. {
  12829. if (tempTypeDef->mFullName == typeDef->mFullName)
  12830. {
  12831. for (auto fieldDef : tempTypeDef->mFields)
  12832. {
  12833. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  12834. {
  12835. if (fieldDef->mInitializer != NULL)
  12836. {
  12837. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  12838. {
  12839. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12840. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12841. }
  12842. BfType* wantType = NULL;
  12843. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  12844. {
  12845. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12846. }
  12847. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12848. }
  12849. }
  12850. }
  12851. }
  12852. }
  12853. }
  12854. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  12855. CallChainedMethods(mCurMethodInstance, false);
  12856. }
  12857. void BfModule::EmitDtorBody()
  12858. {
  12859. if (mCurTypeInstance->IsClosure())
  12860. {
  12861. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  12862. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  12863. auto thisVal = GetThis();
  12864. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  12865. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  12866. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  12867. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  12868. SizedArray<BfIRValue, 1> args;
  12869. args.push_back(thisVal.mValue);
  12870. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  12871. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  12872. // Fall through to Object::~this call
  12873. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  12874. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  12875. SizedArray<BfIRValue, 1> vals = { basePtr };
  12876. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  12877. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  12878. mBfIRBuilder->SetTailCall(result);
  12879. return;
  12880. }
  12881. auto typeDef = mCurTypeInstance->mTypeDef;
  12882. auto methodDef = mCurMethodInstance->mMethodDef;
  12883. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12884. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  12885. CallChainedMethods(mCurMethodInstance, true);
  12886. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  12887. {
  12888. VisitEmbeddedStatement(bodyBlock);
  12889. if (bodyBlock->mCloseBrace != NULL)
  12890. {
  12891. UpdateSrcPos(bodyBlock->mCloseBrace);
  12892. }
  12893. }
  12894. else
  12895. {
  12896. if (methodDeclaration != NULL)
  12897. UpdateSrcPos(methodDeclaration);
  12898. else if (typeDef->mTypeDeclaration != NULL)
  12899. UpdateSrcPos(typeDef->mTypeDeclaration);
  12900. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  12901. {
  12902. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  12903. }
  12904. }
  12905. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  12906. {
  12907. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  12908. {
  12909. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  12910. auto fieldDef = fieldInst->GetFieldDef();
  12911. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  12912. {
  12913. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  12914. {
  12915. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  12916. continue;
  12917. }
  12918. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  12919. {
  12920. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken, true);
  12921. }
  12922. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  12923. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  12924. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  12925. continue;
  12926. UpdateSrcPos(fieldDtor);
  12927. BfScopeData scopeData;
  12928. mCurMethodState->AddScope(&scopeData);
  12929. NewScopeState();
  12930. UpdateSrcPos(fieldDtor);
  12931. bool hasDbgInfo = (!fieldDef->mIsConst);
  12932. if (hasDbgInfo)
  12933. {
  12934. mBfIRBuilder->SaveDebugLocation();
  12935. mBfIRBuilder->ClearDebugLocation();
  12936. }
  12937. BfIRValue value;
  12938. if (fieldDef->mIsStatic)
  12939. {
  12940. value = ReferenceStaticField(fieldInst).mValue;
  12941. }
  12942. else
  12943. {
  12944. if (!mCurTypeInstance->IsValueType())
  12945. {
  12946. auto thisValue = GetThis();
  12947. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  12948. }
  12949. else
  12950. {
  12951. AssertErrorState();
  12952. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  12953. }
  12954. }
  12955. BfIRValue staticVal;
  12956. if (hasDbgInfo)
  12957. {
  12958. BfIRValue dbgShowValue = value;
  12959. BfLocalVariable* localDef = new BfLocalVariable();
  12960. localDef->mName = "_";
  12961. localDef->mResolvedType = fieldInst->mResolvedType;
  12962. localDef->mAddr = value;
  12963. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  12964. {
  12965. // Create another pointer indirection, a ref to the gep
  12966. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  12967. auto allocaInst = CreateAlloca(refFieldType);
  12968. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  12969. localDef->mResolvedType = refFieldType;
  12970. localDef->mAddr = allocaInst;
  12971. }
  12972. mBfIRBuilder->RestoreDebugLocation();
  12973. auto defLocalVar = AddLocalVariableDef(localDef, true);
  12974. // Put back so we actually modify the correct value*/
  12975. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  12976. defLocalVar->mAddr = value;
  12977. }
  12978. while (fieldDtor != NULL)
  12979. {
  12980. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12981. {
  12982. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  12983. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  12984. }
  12985. UpdateSrcPos(fieldDtor);
  12986. VisitEmbeddedStatement(fieldDtor->mBody);
  12987. fieldDtor = fieldDtor->mNextFieldDtor;
  12988. }
  12989. RestoreScopeState();
  12990. }
  12991. }
  12992. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  12993. {
  12994. auto checkBaseType = mCurTypeInstance->mBaseType;
  12995. while (checkBaseType != NULL)
  12996. {
  12997. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  12998. {
  12999. if (bodyBlock->mCloseBrace != NULL)
  13000. UpdateSrcPos(bodyBlock->mCloseBrace);
  13001. }
  13002. else
  13003. {
  13004. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  13005. }
  13006. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  13007. {
  13008. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  13009. if (mCompiler->IsSkippingExtraResolveChecks())
  13010. {
  13011. // Nothing
  13012. }
  13013. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  13014. {
  13015. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  13016. {
  13017. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  13018. SizedArray<BfIRValue, 1> vals = { basePtr };
  13019. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  13020. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  13021. }
  13022. }
  13023. else
  13024. {
  13025. // Invalid base dtor declaration
  13026. AssertErrorState();
  13027. }
  13028. break;
  13029. }
  13030. checkBaseType = checkBaseType->mBaseType;
  13031. }
  13032. }
  13033. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  13034. }
  13035. else
  13036. {
  13037. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  13038. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  13039. // resolve pass, NOT the autocomplete expression
  13040. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  13041. {
  13042. if (tempTypeDef->mFullName == typeDef->mFullName)
  13043. {
  13044. for (auto fieldDef : tempTypeDef->mFields)
  13045. {
  13046. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  13047. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13048. {
  13049. BfType* fieldType = NULL;
  13050. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  13051. {
  13052. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  13053. auto curFieldDef = curFieldInstance->GetFieldDef();
  13054. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  13055. fieldType = curFieldInstance->GetResolvedType();
  13056. }
  13057. if (fieldType == NULL)
  13058. fieldType = GetPrimitiveType(BfTypeCode_Var);
  13059. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  13060. BfScopeData scopeData;
  13061. mCurMethodState->AddScope(&scopeData);
  13062. NewScopeState();
  13063. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  13064. if (fieldType != NULL)
  13065. {
  13066. BfLocalVariable* localDef = new BfLocalVariable();
  13067. localDef->mName = "_";
  13068. localDef->mResolvedType = fieldType;
  13069. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  13070. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  13071. AddLocalVariableDef(localDef);
  13072. }
  13073. while (fieldDtor != NULL)
  13074. {
  13075. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  13076. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  13077. UpdateSrcPos(fieldDtor);
  13078. VisitEmbeddedStatement(fieldDtor->mBody);
  13079. fieldDtor = fieldDtor->mNextFieldDtor;
  13080. }
  13081. RestoreScopeState();
  13082. }
  13083. }
  13084. }
  13085. }
  13086. }
  13087. }
  13088. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  13089. {
  13090. auto typeInstance = methodInstance->GetOwner();
  13091. bool foundDllImportAttr = false;
  13092. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  13093. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  13094. {
  13095. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  13096. {
  13097. foundDllImportAttr = true;
  13098. }
  13099. }
  13100. if (!foundDllImportAttr)
  13101. {
  13102. AssertErrorState();
  13103. return BfIRValue();
  13104. }
  13105. String name = "bf_hs_preserve@";
  13106. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  13107. name += "__imp";
  13108. BfIRType returnType;
  13109. SizedArray<BfIRType, 8> paramTypes;
  13110. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  13111. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  13112. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  13113. BfIRValue initVal;
  13114. if (define)
  13115. {
  13116. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13117. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  13118. }
  13119. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  13120. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  13121. {
  13122. auto voidType = GetPrimitiveType(BfTypeCode_None);
  13123. auto ptrType = CreatePointerType(voidType);
  13124. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  13125. }
  13126. return globalVar;
  13127. }
  13128. void BfModule::CreateDllImportMethod()
  13129. {
  13130. if (mBfIRBuilder->mIgnoreWrites)
  13131. return;
  13132. auto globalVar = mFuncReferences[mCurMethodInstance];
  13133. if (!globalVar)
  13134. return;
  13135. bool allowTailCall = true;
  13136. mBfIRBuilder->ClearDebugLocation();
  13137. bool isHotCompile = mCompiler->IsHotCompile();
  13138. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  13139. if (isHotCompile)
  13140. {
  13141. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  13142. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  13143. }
  13144. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  13145. BfIRType returnType;
  13146. SizedArray<BfIRType, 8> paramTypes;
  13147. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  13148. SizedArray<BfIRValue, 8> args;
  13149. for (int i = 0; i < (int)paramTypes.size(); i++)
  13150. args.push_back(mBfIRBuilder->GetArgument(i));
  13151. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  13152. if (isHotCompile)
  13153. {
  13154. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  13155. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  13156. if (callingConvention == BfIRCallingConv_StdCall)
  13157. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  13158. else if (callingConvention == BfIRCallingConv_FastCall)
  13159. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  13160. else
  13161. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  13162. if (allowTailCall)
  13163. mBfIRBuilder->SetTailCall(result);
  13164. CreateReturn(result);
  13165. mCurMethodState->mHadReturn = true;
  13166. }
  13167. if (HasCompiledOutput())
  13168. {
  13169. BfDllImportEntry dllImportEntry;
  13170. dllImportEntry.mFuncVar = globalVar;
  13171. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13172. mDllImportEntries.push_back(dllImportEntry);
  13173. }
  13174. }
  13175. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  13176. {
  13177. auto methodDef = methodInstance->mMethodDef;
  13178. BfTypeInstance* owner = NULL;
  13179. if (!methodDef->mIsStatic)
  13180. owner = methodInstance->GetThisType()->ToTypeInstance();
  13181. if (owner == NULL)
  13182. owner = methodInstance->GetOwner();
  13183. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  13184. return BfIRCallingConv_CDecl;
  13185. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  13186. return BfIRCallingConv_StdCall;
  13187. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  13188. return BfIRCallingConv_FastCall;
  13189. if ((!methodDef->mIsStatic) && (!owner->IsValuelessType()) &&
  13190. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  13191. return BfIRCallingConv_ThisCall;
  13192. return BfIRCallingConv_CDecl;
  13193. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  13194. }
  13195. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  13196. {
  13197. BfMethodDef* methodDef = NULL;
  13198. if (methodInstance != NULL)
  13199. methodDef = methodInstance->mMethodDef;
  13200. if (!func)
  13201. return;
  13202. if (mCompiler->mOptions.mNoFramePointerElim)
  13203. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  13204. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  13205. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  13206. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  13207. if (methodInstance == NULL)
  13208. return;
  13209. if (methodDef->mImportKind == BfImportKind_Export)
  13210. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  13211. if (methodDef->mIsNoReturn)
  13212. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  13213. auto callingConv = GetIRCallingConvention(methodInstance);
  13214. if (callingConv != BfIRCallingConv_CDecl)
  13215. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  13216. if (isInlined)
  13217. {
  13218. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  13219. }
  13220. int argIdx = 0;
  13221. int paramIdx = 0;
  13222. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  13223. paramIdx = -1;
  13224. int argCount = methodInstance->GetIRFunctionParamCount(this);
  13225. while (argIdx < argCount)
  13226. {
  13227. if (argIdx == methodInstance->GetStructRetIdx())
  13228. {
  13229. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  13230. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  13231. argIdx++;
  13232. continue;
  13233. }
  13234. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  13235. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  13236. paramIdx++;
  13237. BfType* resolvedTypeRef = NULL;
  13238. BfType* resolvedTypeRef2 = NULL;
  13239. String paramName;
  13240. bool isSplattable = false;
  13241. bool tryLowering = true;
  13242. if (isThis)
  13243. {
  13244. paramName = "this";
  13245. if (methodInstance->mIsClosure)
  13246. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  13247. else
  13248. resolvedTypeRef = methodInstance->GetThisType();
  13249. isSplattable = (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsThisSplatting());
  13250. tryLowering = methodInstance->AllowsThisSplatting();
  13251. }
  13252. else
  13253. {
  13254. paramName = methodInstance->GetParamName(paramIdx);
  13255. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  13256. if (resolvedTypeRef->IsMethodRef())
  13257. isSplattable = true;
  13258. else if ((resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting()))
  13259. {
  13260. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  13261. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  13262. {
  13263. // crepr splat is always splattable
  13264. isSplattable = true;
  13265. }
  13266. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  13267. isSplattable = true;
  13268. }
  13269. }
  13270. if (tryLowering)
  13271. {
  13272. BfTypeCode loweredTypeCode = BfTypeCode_None;
  13273. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  13274. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  13275. {
  13276. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  13277. argIdx++;
  13278. if (loweredTypeCode2 != BfTypeCode_None)
  13279. {
  13280. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  13281. argIdx++;
  13282. }
  13283. paramIdx++;
  13284. continue;
  13285. }
  13286. }
  13287. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  13288. {
  13289. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  13290. int addDeref = -1;
  13291. if (resolvedTypeRef->IsRef())
  13292. {
  13293. auto refType = (BfRefType*)resolvedTypeRef;
  13294. auto elementType = refType->mElementType;
  13295. PopulateType(elementType, BfPopulateType_Data);
  13296. addDeref = elementType->mSize;
  13297. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  13298. AssertErrorState();
  13299. }
  13300. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  13301. {
  13302. if (isThis)
  13303. {
  13304. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  13305. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  13306. addDeref = resolvedTypeRef->mSize;
  13307. }
  13308. else if (methodInstance->WantsStructsAttribByVal())
  13309. {
  13310. mBfIRBuilder->PopulateType(resolvedTypeRef);
  13311. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  13312. }
  13313. }
  13314. else if (resolvedTypeRef->IsPrimitiveType())
  13315. {
  13316. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  13317. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  13318. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  13319. }
  13320. if (addDeref >= 0)
  13321. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  13322. argIdx++;
  13323. };
  13324. if (isSplattable)
  13325. {
  13326. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  13327. {
  13328. if (checkType->IsStruct())
  13329. {
  13330. auto checkTypeInstance = checkType->ToTypeInstance();
  13331. if (checkTypeInstance->mBaseType != NULL)
  13332. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  13333. if (checkTypeInstance->mIsUnion)
  13334. {
  13335. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  13336. checkTypeLambda(unionInnerType, curName + "_data");
  13337. }
  13338. else
  13339. {
  13340. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13341. {
  13342. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13343. auto fieldDef = fieldInstance->GetFieldDef();
  13344. if (fieldInstance->mDataIdx >= 0)
  13345. {
  13346. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  13347. }
  13348. }
  13349. }
  13350. if (checkTypeInstance->IsEnum())
  13351. {
  13352. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  13353. argIdx++;
  13354. }
  13355. }
  13356. else if (checkType->IsMethodRef())
  13357. {
  13358. auto methodRefType = (BfMethodRefType*)checkType;
  13359. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  13360. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  13361. {
  13362. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  13363. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  13364. {
  13365. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  13366. }
  13367. else
  13368. {
  13369. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  13370. }
  13371. }
  13372. }
  13373. else if (!checkType->IsValuelessType())
  13374. {
  13375. _SetupParam(curName, checkType);
  13376. }
  13377. };
  13378. checkTypeLambda(resolvedTypeRef, paramName);
  13379. paramIdx++;
  13380. continue;
  13381. }
  13382. _SetupParam(paramName, resolvedTypeRef);
  13383. if (resolvedTypeRef2 != NULL)
  13384. _SetupParam(paramName, resolvedTypeRef2);
  13385. paramIdx++;
  13386. }
  13387. }
  13388. void BfModule::EmitCtorBody(bool& skipBody)
  13389. {
  13390. auto methodInstance = mCurMethodInstance;
  13391. auto methodDef = methodInstance->mMethodDef;
  13392. auto methodDeclaration = methodDef->mMethodDeclaration;
  13393. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  13394. auto typeDef = mCurTypeInstance->mTypeDef;
  13395. BfCustomAttributes* customAttributes = NULL;
  13396. defer(delete customAttributes);
  13397. BfInvocationExpression* ctorInvocation = NULL;
  13398. BfAttributeState attributeState;
  13399. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  13400. if (ctorDeclaration != NULL)
  13401. {
  13402. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  13403. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  13404. {
  13405. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  13406. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  13407. }
  13408. }
  13409. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  13410. // Prologue
  13411. mBfIRBuilder->ClearDebugLocation();
  13412. bool hadThisInitializer = false;
  13413. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  13414. {
  13415. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  13416. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  13417. if (targetToken->GetToken() == BfToken_This)
  13418. {
  13419. hadThisInitializer = true;
  13420. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  13421. mCurMethodState->LocalDefined(GetThisVariable());
  13422. }
  13423. }
  13424. // Zero out memory for default ctor
  13425. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  13426. {
  13427. if (mCurTypeInstance->IsTypedPrimitive())
  13428. {
  13429. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  13430. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  13431. }
  13432. else if (mCurTypeInstance->mInstSize > 0)
  13433. {
  13434. BfIRValue fillValue = GetConstValue8(0);
  13435. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  13436. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  13437. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  13438. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  13439. }
  13440. }
  13441. BfAstNode* baseCtorNode = NULL;
  13442. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  13443. baseCtorNode = ctorInvocation->mTarget;
  13444. else if (methodDef->mBody != NULL)
  13445. baseCtorNode = methodDef->mBody;
  13446. else if (ctorDeclaration != NULL)
  13447. baseCtorNode = ctorDeclaration;
  13448. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13449. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  13450. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  13451. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  13452. else
  13453. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  13454. bool calledCtorNoBody = false;
  13455. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  13456. {
  13457. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  13458. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  13459. {
  13460. BfMethodDef* defaultCtor = NULL;
  13461. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  13462. {
  13463. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  13464. {
  13465. defaultCtor = methodDef;
  13466. }
  13467. }
  13468. if (defaultCtor != NULL)
  13469. {
  13470. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  13471. SetIllegalSrcPos();
  13472. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  13473. BfExprEvaluator exprEvaluator(this);
  13474. SizedArray<BfIRValue, 1> irArgs;
  13475. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  13476. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  13477. calledCtorNoBody = true;
  13478. }
  13479. }
  13480. }
  13481. // Initialize fields (if applicable)
  13482. if (mCurTypeInstance->IsBoxed())
  13483. {
  13484. skipBody = true;
  13485. }
  13486. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  13487. {
  13488. // Field initializers occur in CtorNoBody methods for extensions
  13489. }
  13490. else if (!hadThisInitializer)
  13491. {
  13492. // If we had a 'this' initializer, that other ctor will have initialized our fields
  13493. //auto
  13494. if ((!mCompiler->mIsResolveOnly) ||
  13495. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  13496. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  13497. {
  13498. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  13499. // to properly set the assigned flags
  13500. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  13501. bool hadInlineInitBlock = false;
  13502. BfScopeData scopeData;
  13503. auto _CheckInitBlock = [&](BfAstNode* node)
  13504. {
  13505. if (!hadInlineInitBlock)
  13506. {
  13507. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  13508. {
  13509. UpdateSrcPos(baseCtorNode);
  13510. if (methodDef->mBody == NULL)
  13511. SetIllegalSrcPos();
  13512. // 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
  13513. EmitEnsureInstructionAt();
  13514. BfType* thisType = mCurTypeInstance;
  13515. if (thisType->IsValueType())
  13516. thisType = CreateRefType(thisType);
  13517. SizedArray<BfIRMDNode, 1> diParamTypes;
  13518. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  13519. mCurMethodState->AddScope(&scopeData);
  13520. NewScopeState();
  13521. int flags = 0;
  13522. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  13523. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  13524. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  13525. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  13526. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  13527. UpdateSrcPos(node);
  13528. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13529. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  13530. //
  13531. {
  13532. auto loadedThis = GetThis();
  13533. // LLVM can't handle two variables pointing to the same value
  13534. BfIRValue copiedThisPtr;
  13535. copiedThisPtr = CreateAlloca(thisType);
  13536. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  13537. mBfIRBuilder->ClearDebugLocation(storeInst);
  13538. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  13539. }
  13540. hadInlineInitBlock = true;
  13541. }
  13542. }
  13543. UpdateSrcPos(node);
  13544. };
  13545. for (auto fieldDef : typeDef->mFields)
  13546. {
  13547. // For extensions, only handle these fields in the appropriate extension
  13548. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13549. continue;
  13550. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  13551. {
  13552. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  13553. if (!fieldInst->mFieldIncluded)
  13554. continue;
  13555. if (fieldInst->mDataIdx < 0)
  13556. continue;
  13557. if (fieldDef->mInitializer == NULL)
  13558. {
  13559. continue;
  13560. // if (fieldDef->mProtection != BfProtection_Hidden)
  13561. // continue;
  13562. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  13563. // continue;
  13564. }
  13565. if (fieldInst->mResolvedType == NULL)
  13566. {
  13567. BF_ASSERT(mHadBuildError);
  13568. continue;
  13569. }
  13570. if (fieldDef->mInitializer != NULL)
  13571. {
  13572. _CheckInitBlock(fieldDef->mInitializer);
  13573. }
  13574. BfIRValue fieldAddr;
  13575. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  13576. {
  13577. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  13578. }
  13579. else
  13580. {
  13581. // Failed
  13582. }
  13583. auto assignValue = GetFieldInitializerValue(fieldInst);
  13584. if (mCurTypeInstance->IsUnion())
  13585. {
  13586. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  13587. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  13588. }
  13589. if ((fieldAddr) && (assignValue))
  13590. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  13591. }
  13592. }
  13593. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  13594. BfMemberSetEntry* entry = NULL;
  13595. BfMethodDef* initMethodDef = NULL;
  13596. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  13597. if (entry != NULL)
  13598. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  13599. SizedArray<BfAstNode*, 8> initBodies;
  13600. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  13601. {
  13602. if (initMethodDef->mDeclaringType != methodDef->mDeclaringType)
  13603. continue;
  13604. if (initMethodDef->mMethodType != BfMethodType_Init)
  13605. continue;
  13606. initBodies.Insert(0, initMethodDef->mBody);
  13607. }
  13608. for (auto body : initBodies)
  13609. {
  13610. _CheckInitBlock(body);
  13611. VisitEmbeddedStatement(body);
  13612. }
  13613. if (hadInlineInitBlock)
  13614. {
  13615. RestoreScopeState();
  13616. // This gets set to false because of AddScope but we actually are still in the head block
  13617. mCurMethodState->mInHeadScope = true;
  13618. }
  13619. }
  13620. else // Autocomplete case
  13621. {
  13622. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  13623. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  13624. // resolve pass, NOT the autocomplete expression
  13625. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  13626. {
  13627. if (tempTypeDef->mFullName == typeDef->mFullName)
  13628. {
  13629. for (auto fieldDef : tempTypeDef->mFields)
  13630. {
  13631. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13632. {
  13633. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  13634. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  13635. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  13636. if ((wantType != NULL) &&
  13637. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  13638. wantType = NULL;
  13639. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  13640. }
  13641. }
  13642. tempTypeDef->PopulateMemberSets();
  13643. BfMemberSetEntry* entry = NULL;
  13644. BfMethodDef* initMethodDef = NULL;
  13645. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  13646. if (entry != NULL)
  13647. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  13648. SizedArray<BfAstNode*, 8> initBodies;
  13649. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  13650. {
  13651. if (initMethodDef->mMethodType != BfMethodType_Init)
  13652. continue;
  13653. initBodies.Insert(0, initMethodDef->mBody);
  13654. }
  13655. for (auto body : initBodies)
  13656. VisitEmbeddedStatement(body);
  13657. }
  13658. }
  13659. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  13660. for (auto fieldDef : typeDef->mFields)
  13661. {
  13662. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  13663. {
  13664. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  13665. if (fieldDef->mInitializer != NULL)
  13666. MarkFieldInitialized(fieldInst);
  13667. }
  13668. }
  13669. }
  13670. }
  13671. // Call base ctor (if applicable)
  13672. BfTypeInstance* targetType = NULL;
  13673. BfAstNode* targetRefNode = NULL;
  13674. if (ctorDeclaration != NULL)
  13675. targetRefNode = ctorDeclaration->mInitializer;
  13676. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  13677. targetRefNode = invocationExpr->mTarget;
  13678. if (baseCtorNode != NULL)
  13679. {
  13680. UpdateSrcPos(baseCtorNode);
  13681. if (methodDef->mBody == NULL)
  13682. SetIllegalSrcPos();
  13683. }
  13684. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  13685. {
  13686. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  13687. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  13688. }
  13689. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  13690. {
  13691. auto baseType = mCurTypeInstance->mBaseType;
  13692. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  13693. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  13694. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  13695. {
  13696. // Try to find a ctor without any params first
  13697. BfMethodDef* matchedMethod = NULL;
  13698. bool hadCtorWithAllDefaults = false;
  13699. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  13700. for (int pass = 0; pass < 2; pass++)
  13701. {
  13702. baseType->mTypeDef->PopulateMemberSets();
  13703. BfMemberSetEntry* entry = NULL;
  13704. BfMethodDef* checkMethodDef = NULL;
  13705. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  13706. if (entry != NULL)
  13707. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  13708. while (checkMethodDef != NULL)
  13709. {
  13710. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  13711. if (isHiddenGenerated)
  13712. {
  13713. // Allow calling of the default base ctor if it is implicitly defined
  13714. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  13715. allowMethod = true;
  13716. }
  13717. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  13718. {
  13719. if (checkMethodDef->mParams.size() == 0)
  13720. {
  13721. matchedMethod = checkMethodDef;
  13722. }
  13723. else if (isHiddenGenerated)
  13724. {
  13725. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  13726. hadCtorWithAllDefaults = true;
  13727. }
  13728. }
  13729. checkMethodDef = checkMethodDef->mNextWithSameName;
  13730. }
  13731. if (matchedMethod != NULL)
  13732. break;
  13733. }
  13734. if ((HasCompiledOutput()) && (matchedMethod != NULL))
  13735. {
  13736. SizedArray<BfIRValue, 1> args;
  13737. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  13738. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  13739. {
  13740. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  13741. args.push_back(basePtr);
  13742. }
  13743. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  13744. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  13745. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  13746. if (callingConv != BfIRCallingConv_CDecl)
  13747. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  13748. }
  13749. if (matchedMethod == NULL)
  13750. {
  13751. targetType = mCurTypeInstance->mBaseType;
  13752. if (ctorDeclaration != NULL)
  13753. targetRefNode = ctorDeclaration->mThisToken;
  13754. else if (typeDef->mTypeDeclaration != NULL)
  13755. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  13756. }
  13757. }
  13758. }
  13759. if (methodDef->mHasAppend)
  13760. {
  13761. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  13762. }
  13763. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  13764. {
  13765. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  13766. {
  13767. if (targetType == mCurTypeInstance)
  13768. {
  13769. auto thisVariable = GetThisVariable();
  13770. if (thisVariable != NULL)
  13771. {
  13772. thisVariable->mUnassignedFieldFlags = 0;
  13773. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  13774. }
  13775. }
  13776. targetType = NULL;
  13777. }
  13778. }
  13779. if (targetType != NULL)
  13780. {
  13781. BfAstNode* refNode = methodDeclaration;
  13782. if (refNode == NULL)
  13783. refNode = typeDef->mTypeDeclaration;
  13784. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  13785. auto autoComplete = mCompiler->GetAutoComplete();
  13786. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  13787. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  13788. {
  13789. auto invocationExpr = ctorInvocation;
  13790. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  13791. }
  13792. BfType* targetThisType = targetType;
  13793. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  13794. BfExprEvaluator exprEvaluator(this);
  13795. BfResolvedArgs argValues;
  13796. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  13797. {
  13798. argValues.Init(&ctorInvocation->mArguments);
  13799. if (gDebugStuff)
  13800. {
  13801. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  13802. }
  13803. }
  13804. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  13805. BfTypedValue appendIdxVal;
  13806. if (methodDef->mHasAppend)
  13807. {
  13808. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  13809. BF_ASSERT(localVar->mName == "appendIdx");
  13810. auto intRefType = localVar->mResolvedType;
  13811. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  13812. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  13813. }
  13814. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  13815. if (autoComplete != NULL)
  13816. {
  13817. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  13818. {
  13819. if (autoComplete->mMethodMatchInfo != NULL)
  13820. autoComplete->mIsCapturingMethodMatchInfo = true;
  13821. else
  13822. autoComplete->mIsCapturingMethodMatchInfo = false;
  13823. }
  13824. else
  13825. autoComplete->mIsCapturingMethodMatchInfo = false;
  13826. }
  13827. }
  13828. }
  13829. void BfModule::EmitEnumToStringBody()
  13830. {
  13831. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  13832. auto strVal = CreateAlloca(stringType);
  13833. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  13834. BfExprEvaluator exprEvaluator(this);
  13835. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  13836. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  13837. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  13838. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  13839. BfType* discriminatorType = NULL;
  13840. BfTypedValue rawPayload;
  13841. BfIRValue enumVal;
  13842. if (mCurTypeInstance->IsPayloadEnum())
  13843. {
  13844. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  13845. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  13846. enumTypedValue = LoadValue(enumTypedValue);
  13847. enumVal = enumTypedValue.mValue;
  13848. rawPayload = ExtractValue(GetThis(), NULL, 1);
  13849. }
  13850. else
  13851. enumVal = mBfIRBuilder->GetArgument(0);
  13852. Array<BfType*> paramTypes;
  13853. paramTypes.Add(stringType);
  13854. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  13855. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  13856. HashSet<int64> handledCases;
  13857. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  13858. {
  13859. if (fieldInstance.mIsEnumPayloadCase)
  13860. {
  13861. int tagId = -fieldInstance.mDataIdx - 1;
  13862. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  13863. mBfIRBuilder->AddBlock(caseBlock);
  13864. mBfIRBuilder->SetInsertPoint(caseBlock);
  13865. BF_ASSERT(discriminatorType->IsPrimitiveType());
  13866. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  13867. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  13868. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  13869. auto stringDestVal = LoadValue(stringDestAddr);
  13870. SizedArray<BfIRValue, 2> args;
  13871. args.Add(stringDestVal.mValue);
  13872. args.Add(caseStr);
  13873. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  13874. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  13875. BF_ASSERT(payloadType->IsTuple());
  13876. if (payloadType->mFieldInstances.size() != 0)
  13877. {
  13878. auto payload = rawPayload;
  13879. if (payload.mType != payloadType)
  13880. {
  13881. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  13882. }
  13883. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  13884. SizedArray<BfIRValue, 2> irArgs;
  13885. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  13886. stringDestVal = LoadValue(stringDestAddr);
  13887. irArgs.Add(stringDestVal.mValue);
  13888. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  13889. }
  13890. mBfIRBuilder->CreateBr(endBlock);
  13891. continue;
  13892. }
  13893. if (fieldInstance.mConstIdx == -1)
  13894. continue;
  13895. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  13896. if (!handledCases.TryAdd(constant->mInt64, NULL))
  13897. {
  13898. // Duplicate
  13899. continue;
  13900. }
  13901. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  13902. mBfIRBuilder->AddBlock(caseBlock);
  13903. mBfIRBuilder->SetInsertPoint(caseBlock);
  13904. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  13905. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  13906. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  13907. mBfIRBuilder->CreateStore(caseStr, strVal);
  13908. mBfIRBuilder->CreateBr(appendBlock);
  13909. }
  13910. mBfIRBuilder->AddBlock(appendBlock);
  13911. mBfIRBuilder->SetInsertPoint(appendBlock);
  13912. SizedArray<BfIRValue, 2> args;
  13913. auto stringDestVal = LoadValue(stringDestAddr);
  13914. args.Add(stringDestVal.mValue);
  13915. args.Add(mBfIRBuilder->CreateLoad(strVal));
  13916. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  13917. mBfIRBuilder->CreateBr(endBlock);
  13918. mBfIRBuilder->AddBlock(noMatchBlock);
  13919. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  13920. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  13921. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  13922. args.clear();
  13923. args.Add(int64Val);
  13924. stringDestVal = LoadValue(stringDestAddr);
  13925. args.Add(stringDestVal.mValue);
  13926. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  13927. mBfIRBuilder->CreateBr(endBlock);
  13928. mBfIRBuilder->AddBlock(endBlock);
  13929. mBfIRBuilder->SetInsertPoint(endBlock);
  13930. }
  13931. void BfModule::EmitTupleToStringBody()
  13932. {
  13933. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  13934. BfExprEvaluator exprEvaluator(this);
  13935. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  13936. Array<BfType*> paramTypes;
  13937. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  13938. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  13939. paramTypes.Clear();
  13940. paramTypes.Add(stringType);
  13941. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  13942. auto _AppendChar = [&](char c)
  13943. {
  13944. SizedArray<BfIRValue, 2> args;
  13945. auto stringDestVal = LoadValue(stringDestRef);
  13946. args.Add(stringDestVal.mValue);
  13947. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  13948. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  13949. };
  13950. int fieldIdx = 0;
  13951. auto thisValue = GetThis();
  13952. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  13953. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  13954. BfIRValue commaStr;
  13955. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  13956. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  13957. _AppendChar('(');
  13958. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  13959. {
  13960. if (fieldInstance.mDataIdx == -1)
  13961. continue;
  13962. if (fieldIdx > 0)
  13963. {
  13964. if (!commaStr)
  13965. commaStr = GetStringObjectValue(", ");
  13966. SizedArray<BfIRValue, 2> args;
  13967. auto stringDestVal = LoadValue(stringDestRef);
  13968. args.Add(stringDestVal.mValue);
  13969. args.Add(commaStr);
  13970. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  13971. }
  13972. fieldIdx++;
  13973. if (fieldInstance.mResolvedType->IsValuelessType())
  13974. continue;
  13975. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  13976. if (fieldValue.mType->IsPrimitiveType())
  13977. {
  13978. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  13979. }
  13980. auto typeInstance = fieldValue.mType->ToTypeInstance();
  13981. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  13982. {
  13983. BfExprEvaluator exprEvaluator(this);
  13984. SizedArray<BfResolvedArg, 0> resolvedArgs;
  13985. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  13986. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  13987. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  13988. methodMatcher.TryDevirtualizeCall(fieldValue);
  13989. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  13990. BfResolvedArg resolvedArg;
  13991. auto stringDestVal = LoadValue(stringDestRef);
  13992. resolvedArg.mTypedValue = stringDestVal;
  13993. resolvedArg.mResolvedType = stringDestVal.mType;
  13994. resolvedArgs.Add(resolvedArg);
  13995. exprEvaluator.CreateCall(&methodMatcher, callVal);
  13996. continue;
  13997. }
  13998. if (fieldValue.mType->IsObjectOrInterface())
  13999. {
  14000. fieldValue = LoadValue(fieldValue);
  14001. BF_ASSERT(!fieldValue.IsAddr());
  14002. SizedArray<BfIRValue, 2> args;
  14003. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  14004. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  14005. stringDestVal = LoadValue(stringDestVal);
  14006. args.Add(stringDestVal.mValue);
  14007. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  14008. continue;
  14009. }
  14010. BfExprEvaluator exprEvaluator(this);
  14011. SizedArray<BfResolvedArg, 0> resolvedArgs;
  14012. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  14013. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  14014. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  14015. methodMatcher.TryDevirtualizeCall(fieldValue);
  14016. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  14017. {
  14018. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  14019. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  14020. // Just append the type name
  14021. String typeName = TypeToString(fieldInstance.mResolvedType);
  14022. auto strVal = GetStringObjectValue(typeName);
  14023. SizedArray<BfIRValue, 2> args;
  14024. auto stringDestVal = LoadValue(stringDestRef);
  14025. args.Add(stringDestVal.mValue);
  14026. args.Add(strVal);
  14027. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  14028. continue;
  14029. }
  14030. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  14031. BfResolvedArg resolvedArg;
  14032. auto stringDestVal = LoadValue(stringDestRef);
  14033. resolvedArg.mTypedValue = stringDestVal;
  14034. resolvedArg.mResolvedType = stringDestVal.mType;
  14035. resolvedArgs.Add(resolvedArg);
  14036. exprEvaluator.CreateCall(&methodMatcher, callVal);
  14037. }
  14038. _AppendChar(')');
  14039. }
  14040. void BfModule::EmitIteratorBlock(bool& skipBody)
  14041. {
  14042. auto methodInstance = mCurMethodInstance;
  14043. auto methodDef = methodInstance->mMethodDef;
  14044. auto methodDeclaration = methodDef->GetMethodDeclaration();
  14045. auto typeDef = mCurTypeInstance->mTypeDef;
  14046. BfType* innerRetType = NULL;
  14047. BfTypeInstance* usingInterface = NULL;
  14048. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  14049. if (retTypeInst != NULL)
  14050. {
  14051. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  14052. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  14053. {
  14054. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  14055. }
  14056. }
  14057. if (innerRetType == NULL)
  14058. {
  14059. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  14060. return;
  14061. }
  14062. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  14063. if (blockBody == NULL)
  14064. return;
  14065. }
  14066. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  14067. {
  14068. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  14069. if (fieldTypeInst == NULL)
  14070. return;
  14071. if (!markVal.mType->IsComposite())
  14072. markVal = LoadValue(markVal);
  14073. BfExprEvaluator exprEvaluator(this);
  14074. PopulateType(markVal.mType, BfPopulateType_Data);
  14075. if (markVal.mType->IsObjectOrInterface())
  14076. {
  14077. BfIRValue val = markVal.mValue;
  14078. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  14079. SizedArray<BfIRValue, 1> args;
  14080. args.push_back(val);
  14081. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  14082. }
  14083. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  14084. {
  14085. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  14086. if (markMemberMethodInstance)
  14087. {
  14088. SizedArray<BfIRValue, 1> args;
  14089. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  14090. if (markVal.mType != methodOwner)
  14091. markVal = Cast(NULL, markVal, methodOwner);
  14092. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  14093. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  14094. }
  14095. }
  14096. }
  14097. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  14098. {
  14099. Array<BfMethodInstance*> methodInstances;
  14100. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  14101. {
  14102. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  14103. auto chainedMethodInst = methodInstGroup.mDefault;
  14104. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  14105. {
  14106. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  14107. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  14108. {
  14109. methodInstances.push_back(chainedMethodInst);
  14110. }
  14111. }
  14112. }
  14113. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  14114. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  14115. {
  14116. bool isBetter;
  14117. bool isWorse;
  14118. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  14119. if (isBetter == isWorse)
  14120. {
  14121. return false;
  14122. }
  14123. return isWorse;
  14124. });
  14125. if (reverse)
  14126. std::reverse(methodInstances.begin(), methodInstances.end());
  14127. for (auto chainedMethodInst : methodInstances)
  14128. {
  14129. auto declModule = this;
  14130. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14131. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  14132. BfExprEvaluator exprEvaluator(this);
  14133. SizedArray<BfIRValue, 1> args;
  14134. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  14135. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  14136. }
  14137. }
  14138. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  14139. {
  14140. BF_ASSERT(mCurMethodInstance->mIsReified);
  14141. if (mCurTypeInstance->mHotTypeData == NULL)
  14142. {
  14143. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  14144. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  14145. }
  14146. auto hotMethod = mCurMethodInstance->mHotMethod;
  14147. for (auto depData : hotMethod->mReferences)
  14148. {
  14149. // Only virtual decls are allowed to already be there
  14150. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  14151. }
  14152. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  14153. int prevSize = (int)hotMethod->mReferences.size();
  14154. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  14155. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  14156. refCount++;
  14157. hotMethod->mReferences.Reserve(refCount);
  14158. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  14159. {
  14160. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  14161. hotThis->mRefCount++;
  14162. hotMethod->mReferences.Insert(0, hotThis);
  14163. prevSize++;
  14164. }
  14165. for (auto val : builder->mAllocatedData)
  14166. {
  14167. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  14168. hotMethod->mReferences.Add(hotAllocation);
  14169. }
  14170. for (auto val : builder->mUsedData)
  14171. hotMethod->mReferences.Add(val);
  14172. for (auto val : builder->mCalledMethods)
  14173. hotMethod->mReferences.Add(val);
  14174. for (auto val : builder->mDevirtualizedCalledMethods)
  14175. {
  14176. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  14177. hotMethod->mReferences.Add(devirtualizedMethod);
  14178. }
  14179. for (auto val : builder->mFunctionPtrs)
  14180. {
  14181. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  14182. hotMethod->mReferences.Add(funcRef);
  14183. }
  14184. for (auto val : builder->mInnerMethods)
  14185. {
  14186. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  14187. hotMethod->mReferences.Add(innerMethod);
  14188. }
  14189. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  14190. {
  14191. auto depData = hotMethod->mReferences[refIdx];
  14192. BF_ASSERT(depData != NULL);
  14193. depData->mRefCount++;
  14194. }
  14195. }
  14196. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  14197. {
  14198. auto methodDef = methodInstance->mMethodDef;
  14199. auto methodDeclaration = methodDef->mMethodDeclaration;
  14200. bool isThisStruct = false;
  14201. if (thisType != NULL)
  14202. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  14203. int argIdx = 0;
  14204. if (argIdx == methodInstance->GetStructRetIdx())
  14205. argIdx++;
  14206. if (!methodDef->mIsStatic)
  14207. {
  14208. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14209. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14210. BfLocalVariable* paramVar = new BfLocalVariable();
  14211. paramVar->mResolvedType = thisType;
  14212. paramVar->mName = "this";
  14213. if (!thisType->IsValuelessType())
  14214. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  14215. else
  14216. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  14217. if ((thisType->IsSplattable()) && (methodInstance->AllowsThisSplatting()))
  14218. {
  14219. if (!thisType->IsTypedPrimitive())
  14220. paramVar->mIsSplat = true;
  14221. }
  14222. else if ((!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  14223. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  14224. auto thisTypeInst = thisType->ToTypeInstance();
  14225. paramVar->mIsStruct = isThisStruct;
  14226. paramVar->mAddr = BfIRValue();
  14227. paramVar->mIsThis = true;
  14228. paramVar->mParamIdx = -1;
  14229. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  14230. {
  14231. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  14232. }
  14233. else
  14234. {
  14235. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14236. }
  14237. paramVar->mReadFromId = -1;
  14238. paramVar->Init();
  14239. if (methodDeclaration == NULL)
  14240. UseDefaultSrcPos();
  14241. AddLocalVariableDef(paramVar);
  14242. if (!thisType->IsValuelessType())
  14243. {
  14244. if (wantsDIData)
  14245. {
  14246. BfType* thisPtrType = thisType;
  14247. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  14248. if (!thisType->IsValueType())
  14249. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  14250. else if (!paramVar->mIsSplat)
  14251. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  14252. diParams->push_back(diType);
  14253. }
  14254. if (paramVar->mIsSplat)
  14255. {
  14256. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14257. }
  14258. else
  14259. {
  14260. argIdx++;
  14261. if (loweredTypeCode2 != BfTypeCode_None)
  14262. argIdx++;
  14263. }
  14264. }
  14265. }
  14266. if (argIdx == methodInstance->GetStructRetIdx())
  14267. argIdx++;
  14268. bool hadParams = false;
  14269. bool hasDefault = false;
  14270. int compositeVariableIdx = -1;
  14271. int paramIdx = 0;
  14272. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  14273. {
  14274. // We already issues a type error for this param if we had one in declaration processing
  14275. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  14276. BfLocalVariable* paramVar = new BfLocalVariable();
  14277. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14278. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14279. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  14280. auto resolvedType = methodInstance->GetParamType(paramIdx);
  14281. if (resolvedType == NULL)
  14282. {
  14283. AssertErrorState();
  14284. paramVar->mParamFailed = true;
  14285. }
  14286. prevIgnoreErrors.Restore();
  14287. PopulateType(resolvedType, BfPopulateType_Declaration);
  14288. paramVar->mResolvedType = resolvedType;
  14289. paramVar->mName = methodInstance->GetParamName(paramIdx);
  14290. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  14291. if (!isParamSkipped)
  14292. {
  14293. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  14294. if (resolvedType->IsMethodRef())
  14295. {
  14296. paramVar->mIsSplat = true;
  14297. }
  14298. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  14299. {
  14300. if (methodInstance->AllowsSplatting())
  14301. {
  14302. int splatCount = resolvedType->GetSplatCount();
  14303. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  14304. paramVar->mIsSplat = true;
  14305. }
  14306. }
  14307. }
  14308. else
  14309. {
  14310. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  14311. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  14312. }
  14313. paramVar->mIsLowered = resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  14314. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  14315. paramVar->mParamIdx = paramIdx;
  14316. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  14317. paramVar->mReadFromId = 0;
  14318. if (resolvedType->IsRef())
  14319. {
  14320. auto refType = (BfRefType*)resolvedType;
  14321. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  14322. }
  14323. else
  14324. {
  14325. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14326. if (methodDef->mMethodType != BfMethodType_Mixin)
  14327. paramVar->mIsReadOnly = true;
  14328. }
  14329. if (paramVar->mResolvedType->IsGenericParam())
  14330. {
  14331. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  14332. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  14333. {
  14334. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  14335. paramVar->mResolvedType = typedVal.mType;
  14336. paramVar->mConstValue = typedVal.mValue;
  14337. }
  14338. }
  14339. if (paramVar->mResolvedType->IsConstExprValue())
  14340. {
  14341. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  14342. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  14343. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  14344. BF_ASSERT(unspecParamType->IsGenericParam());
  14345. if (unspecParamType->IsGenericParam())
  14346. {
  14347. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  14348. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  14349. {
  14350. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  14351. if (genericParamInst->mTypeConstraint != NULL)
  14352. {
  14353. BfExprEvaluator exprEvaluator(this);
  14354. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  14355. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  14356. auto checkType = genericParamInst->mTypeConstraint;
  14357. if (checkType->IsTypedPrimitive())
  14358. checkType = checkType->GetUnderlyingType();
  14359. if (exprEvaluator.mResult.mType == checkType)
  14360. {
  14361. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  14362. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  14363. BF_ASSERT(paramVar->mConstValue.IsConst());
  14364. }
  14365. else
  14366. {
  14367. AssertErrorState();
  14368. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  14369. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  14370. }
  14371. }
  14372. }
  14373. }
  14374. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  14375. if (paramVar->mResolvedType->IsConstExprValue())
  14376. {
  14377. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  14378. //AssertErrorState();
  14379. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  14380. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  14381. }
  14382. }
  14383. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  14384. {
  14385. if (compositeVariableIdx == -1)
  14386. {
  14387. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  14388. BfLocalVariable* localVar = new BfLocalVariable();
  14389. auto paramInst = &methodInstance->mParams[paramIdx];
  14390. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  14391. localVar->mName = paramDef->mName;
  14392. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  14393. localVar->mCompositeCount = 0;
  14394. DoAddLocalVariable(localVar);
  14395. }
  14396. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  14397. }
  14398. CheckVariableDef(paramVar);
  14399. paramVar->Init();
  14400. AddLocalVariableDef(paramVar);
  14401. if (!isParamSkipped)
  14402. {
  14403. if (wantsDIData)
  14404. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  14405. if (paramVar->mIsSplat)
  14406. {
  14407. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14408. }
  14409. else
  14410. {
  14411. argIdx++;
  14412. }
  14413. if (loweredTypeCode2 != BfTypeCode_None)
  14414. argIdx++;
  14415. }
  14416. }
  14417. // Try to find an ending delegate params composite
  14418. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  14419. {
  14420. auto paramDef = methodDef->mParams.back();
  14421. if (paramDef->mParamKind == BfParamKind_Params)
  14422. {
  14423. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  14424. if (paramsType == NULL)
  14425. {
  14426. AssertErrorState();
  14427. }
  14428. else if (paramsType->IsGenericParam())
  14429. {
  14430. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  14431. if (genericParamInstance->mTypeConstraint != NULL)
  14432. {
  14433. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  14434. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  14435. ((typeInstConstraint != NULL) &&
  14436. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  14437. {
  14438. BfLocalVariable* localVar = new BfLocalVariable();
  14439. localVar->mName = paramDef->mName;
  14440. localVar->mResolvedType = paramsType;
  14441. localVar->mCompositeCount = 0;
  14442. DoAddLocalVariable(localVar);
  14443. }
  14444. }
  14445. }
  14446. else if (paramsType->IsDelegate())
  14447. {
  14448. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  14449. if (invokeMethodInstance != NULL)
  14450. {
  14451. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  14452. // and wasn't cleared by the preceding loop
  14453. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  14454. BfLocalVariable* localVar = new BfLocalVariable();
  14455. localVar->mName = paramDef->mName;
  14456. localVar->mResolvedType = paramsType;
  14457. localVar->mCompositeCount = 0;
  14458. DoAddLocalVariable(localVar);
  14459. }
  14460. }
  14461. }
  14462. }
  14463. }
  14464. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  14465. {
  14466. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  14467. // return;
  14468. auto _ClearState = [&]()
  14469. {
  14470. mCurMethodState->mLocalMethods.Clear();
  14471. for (auto& local : mCurMethodState->mLocals)
  14472. delete local;
  14473. mCurMethodState->mLocals.Clear();
  14474. mCurMethodState->mLocalVarSet.Clear();
  14475. };
  14476. // 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
  14477. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  14478. // however (compiler bug), so this is the safest way
  14479. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  14480. {
  14481. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  14482. {
  14483. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  14484. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  14485. if (!mHadBuildError)
  14486. {
  14487. // Process as a closure - that allows us to look back and see the const locals and stuff
  14488. BfClosureState closureState;
  14489. mCurMethodState->mClosureState = &closureState;
  14490. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  14491. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  14492. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  14493. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  14494. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  14495. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  14496. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  14497. _ClearState();
  14498. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  14499. {
  14500. auto localVar = new BfLocalVariable();
  14501. *localVar = constLocal;
  14502. DoAddLocalVariable(localVar);
  14503. }
  14504. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  14505. bool doProcess = !mCompiler->mCanceling;
  14506. if (doProcess)
  14507. {
  14508. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  14509. ProcessMethod(deferredLocalMethod->mMethodInstance);
  14510. }
  14511. }
  14512. delete deferredLocalMethod;
  14513. mSystem->CheckLockYield();
  14514. }
  14515. }
  14516. for (auto& kv : mCurMethodState->mLocalMethodCache)
  14517. {
  14518. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  14519. }
  14520. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  14521. {
  14522. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  14523. {
  14524. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  14525. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  14526. BfClosureState closureState;
  14527. mCurMethodState->mClosureState = &closureState;
  14528. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  14529. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  14530. if (lambdaInstance->mClosureTypeInstance != NULL)
  14531. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  14532. else
  14533. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  14534. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  14535. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  14536. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  14537. _ClearState();
  14538. for (auto& constLocal : lambdaInstance->mConstLocals)
  14539. {
  14540. //if (constLocal.mIsThis)
  14541. {
  14542. // Valueless 'this'
  14543. closureState.mConstLocals.Add(constLocal);
  14544. }
  14545. /*else
  14546. {
  14547. auto localVar = new BfLocalVariable();
  14548. *localVar = constLocal;
  14549. DoAddLocalVariable(localVar);
  14550. }*/
  14551. }
  14552. BfMethodInstanceGroup methodInstanceGroup;
  14553. methodInstanceGroup.mOwner = mCurTypeInstance;
  14554. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  14555. bool doProcess = !mCompiler->mCanceling;
  14556. if (doProcess)
  14557. {
  14558. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  14559. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  14560. ProcessMethod(lambdaInstance->mMethodInstance);
  14561. if (lambdaInstance->mDtorMethodInstance != NULL)
  14562. {
  14563. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  14564. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  14565. }
  14566. }
  14567. }
  14568. mSystem->CheckLockYield();
  14569. }
  14570. }
  14571. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  14572. {
  14573. if (checkType->IsComposite())
  14574. PopulateType(checkType, BfPopulateType_Data);
  14575. if (!checkType->WantsGCMarking())
  14576. return;
  14577. auto typeInstance = checkType->ToTypeInstance();
  14578. bool callMarkMethod = false;
  14579. // Call the actual marking method
  14580. if (memberDepth == 0)
  14581. {
  14582. // Don't call marking method on self
  14583. }
  14584. else if (checkType->IsObjectOrInterface())
  14585. {
  14586. if (!objectOffsets.Add(curOffset))
  14587. {
  14588. return;
  14589. }
  14590. callMarkMethod = true;
  14591. }
  14592. else if (checkType->IsSizedArray())
  14593. {
  14594. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  14595. if (sizedArrayType->mElementType->WantsGCMarking())
  14596. {
  14597. BfTypedValue arrayValue = thisValue;
  14598. if (thisValue.mType != checkType)
  14599. {
  14600. BfIRValue srcValue = thisValue.mValue;
  14601. if (curOffset != 0)
  14602. {
  14603. if (!thisValue.mType->IsPointer())
  14604. {
  14605. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  14606. auto int8PtrType = CreatePointerType(int8Type);
  14607. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  14608. }
  14609. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  14610. }
  14611. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  14612. }
  14613. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  14614. {
  14615. if (sizedArrayType->mElementType->IsSizeAligned())
  14616. {
  14617. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  14618. auto ptrValue = mBfIRBuilder->CreateBitCast(target, mBfIRBuilder->MapType(ptrType));
  14619. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, index);
  14620. return BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  14621. }
  14622. else
  14623. {
  14624. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index);
  14625. return BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  14626. }
  14627. };
  14628. if (sizedArrayType->mElementCount > 6)
  14629. {
  14630. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  14631. auto itr = CreateAlloca(intPtrType);
  14632. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  14633. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  14634. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  14635. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  14636. mBfIRBuilder->CreateBr(loopBB);
  14637. mBfIRBuilder->SetInsertPoint(loopBB);
  14638. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  14639. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  14640. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  14641. mBfIRBuilder->SetInsertPoint(bodyBB);
  14642. BfTypedValue value = _SizedIndex(arrayValue.mValue, loadedItr);
  14643. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  14644. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  14645. mBfIRBuilder->CreateStore(incValue, itr);
  14646. mBfIRBuilder->CreateBr(loopBB);
  14647. mBfIRBuilder->SetInsertPoint(doneBB);
  14648. }
  14649. else
  14650. {
  14651. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  14652. {
  14653. BfTypedValue value = _SizedIndex(arrayValue.mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  14654. HashSet<int> objectOffsets;
  14655. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  14656. }
  14657. }
  14658. }
  14659. }
  14660. else if (typeInstance != NULL)
  14661. {
  14662. typeInstance->mTypeDef->PopulateMemberSets();
  14663. BfMemberSetEntry* entry = NULL;
  14664. BfMethodDef* methodDef = NULL;
  14665. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  14666. {
  14667. methodDef = (BfMethodDef*)entry->mMemberDef;
  14668. if (methodDef->HasBody())
  14669. {
  14670. callMarkMethod = true;
  14671. }
  14672. }
  14673. }
  14674. if (callMarkMethod)
  14675. {
  14676. BfTypedValue markValue;
  14677. auto memberType = checkType;
  14678. if (memberType->IsObjectOrInterface())
  14679. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  14680. auto memberPtrType = CreatePointerType(memberType);
  14681. if (curOffset == 0)
  14682. {
  14683. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  14684. }
  14685. else
  14686. {
  14687. if (!thisValue.mType->IsPointer())
  14688. {
  14689. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  14690. auto int8PtrType = CreatePointerType(int8Type);
  14691. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  14692. }
  14693. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  14694. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  14695. }
  14696. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  14697. return;
  14698. }
  14699. auto methodDef = mCurMethodInstance->mMethodDef;
  14700. if (checkType->IsPayloadEnum())
  14701. {
  14702. for (auto& fieldInst : typeInstance->mFieldInstances)
  14703. {
  14704. if (!fieldInst.mIsEnumPayloadCase)
  14705. continue;
  14706. auto fieldDef = fieldInst.GetFieldDef();
  14707. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  14708. }
  14709. return;
  14710. }
  14711. if (typeInstance == NULL)
  14712. return;
  14713. for (auto& fieldInst : typeInstance->mFieldInstances)
  14714. {
  14715. auto fieldDef = fieldInst.GetFieldDef();
  14716. if (fieldDef == NULL)
  14717. continue;
  14718. if (fieldDef->mIsStatic)
  14719. continue;
  14720. if (typeInstance == mCurTypeInstance)
  14721. {
  14722. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  14723. // we may be marking member values that can never contain a value anyway, but this is benign
  14724. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14725. continue;
  14726. }
  14727. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  14728. }
  14729. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  14730. {
  14731. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  14732. }
  14733. }
  14734. void BfModule::EmitGCMarkMembers()
  14735. {
  14736. auto methodDef = mCurMethodInstance->mMethodDef;
  14737. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  14738. BfModuleMethodInstance markFromGCThreadMethodInstance;
  14739. if (gcType != NULL)
  14740. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  14741. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  14742. {
  14743. if (mCurTypeInstance->IsBoxed())
  14744. {
  14745. // This already gets filled in by the normal boxed forwarding
  14746. }
  14747. else
  14748. {
  14749. auto thisValue = GetThis();
  14750. if (thisValue.IsSplat())
  14751. {
  14752. BfIRFunction func = mCurMethodInstance->mIRFunction;
  14753. int argIdx = 0;
  14754. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  14755. {
  14756. if (checkType->IsStruct())
  14757. {
  14758. auto checkTypeInstance = checkType->ToTypeInstance();
  14759. if (checkTypeInstance->mBaseType != NULL)
  14760. checkTypeLambda(checkTypeInstance->mBaseType);
  14761. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14762. {
  14763. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14764. if (fieldInstance->mDataIdx >= 0)
  14765. checkTypeLambda(fieldInstance->GetResolvedType());
  14766. }
  14767. }
  14768. else if (checkType->IsMethodRef())
  14769. {
  14770. BFMODULE_FATAL(this, "Not handled");
  14771. }
  14772. else if (checkType->WantsGCMarking())
  14773. {
  14774. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  14775. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  14776. argIdx++;
  14777. }
  14778. };
  14779. checkTypeLambda(thisValue.mType);
  14780. }
  14781. else if (!methodDef->mIsStatic)
  14782. {
  14783. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  14784. {
  14785. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  14786. if (moduleMethodInst)
  14787. {
  14788. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  14789. if (methodBaseType != mContext->mBfObjectType)
  14790. {
  14791. auto thisValue = GetThis();
  14792. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  14793. SizedArray<BfIRValue, 1> args;
  14794. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  14795. {
  14796. BfExprEvaluator exprEvaluator(this);
  14797. exprEvaluator.SplatArgs(baseValue, args);
  14798. }
  14799. else
  14800. {
  14801. args.push_back(baseValue.mValue);
  14802. }
  14803. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  14804. }
  14805. }
  14806. }
  14807. }
  14808. if (!methodDef->mIsStatic)
  14809. {
  14810. HashSet<int> objectOffsets;
  14811. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  14812. }
  14813. else
  14814. {
  14815. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  14816. {
  14817. if (thisValue.IsSplat())
  14818. break;
  14819. auto fieldDef = fieldInst.GetFieldDef();
  14820. if (fieldDef == NULL)
  14821. continue;
  14822. if (fieldInst.mIsThreadLocal)
  14823. continue;
  14824. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  14825. {
  14826. // For extensions, only handle these fields in the appropriate extension
  14827. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14828. continue;
  14829. if (!fieldInst.mFieldIncluded)
  14830. continue;
  14831. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  14832. if (fieldTypeInst != NULL)
  14833. {
  14834. auto fieldDef = fieldInst.GetFieldDef();
  14835. BfTypedValue markVal;
  14836. if (fieldDef->mIsConst)
  14837. continue;
  14838. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  14839. continue;
  14840. mBfIRBuilder->PopulateType(fieldTypeInst);
  14841. if (fieldTypeInst->IsValuelessType())
  14842. continue;
  14843. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  14844. {
  14845. StringT<128> staticVarName;
  14846. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  14847. if (staticVarName.StartsWith('#'))
  14848. continue;
  14849. markVal = ReferenceStaticField(&fieldInst);
  14850. }
  14851. else if (!fieldDef->mIsStatic)
  14852. {
  14853. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  14854. }
  14855. if (markVal)
  14856. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  14857. }
  14858. }
  14859. }
  14860. }
  14861. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14862. CallChainedMethods(mCurMethodInstance, false);
  14863. }
  14864. }
  14865. }
  14866. void BfModule::EmitGCFindTLSMembers()
  14867. {
  14868. auto methodDef = mCurMethodInstance->mMethodDef;
  14869. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  14870. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  14871. BF_ASSERT(reportTLSMark);
  14872. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  14873. {
  14874. auto fieldDef = fieldInst.GetFieldDef();
  14875. if (fieldDef == NULL)
  14876. continue;
  14877. if (!fieldInst.mIsThreadLocal)
  14878. continue;
  14879. // For extensions, only handle these fields in the appropriate extension
  14880. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14881. continue;
  14882. if (!fieldInst.mFieldIncluded)
  14883. continue;
  14884. if (fieldDef->mIsConst)
  14885. continue;
  14886. auto fieldType = fieldInst.mResolvedType;
  14887. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  14888. continue;
  14889. if (fieldType->IsValuelessType())
  14890. continue;
  14891. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  14892. if (markVal)
  14893. {
  14894. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  14895. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  14896. SizedArray<BfIRValue, 2> llvmArgs;
  14897. llvmArgs.push_back(fieldRefPtr);
  14898. llvmArgs.push_back(markFuncPtr);
  14899. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  14900. }
  14901. }
  14902. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14903. CallChainedMethods(mCurMethodInstance, false);
  14904. }
  14905. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  14906. {
  14907. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  14908. if (mAwaitingInitFinish)
  14909. FinishInit();
  14910. if (!methodInstance->mIsReified)
  14911. BF_ASSERT(!mIsReified);
  14912. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedTypeVariation());
  14913. if (methodInstance->mMethodInfoEx != NULL)
  14914. {
  14915. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  14916. {
  14917. if (methodGenericArg->IsMethodRef())
  14918. {
  14919. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  14920. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  14921. }
  14922. }
  14923. }
  14924. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  14925. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  14926. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  14927. {
  14928. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  14929. }
  14930. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  14931. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  14932. (mCompiler->mResolvePassData != NULL))
  14933. {
  14934. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  14935. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  14936. }
  14937. if (methodInstance->mHasBeenProcessed)
  14938. {
  14939. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  14940. return;
  14941. }
  14942. if (methodInstance->mFailedConstraints)
  14943. {
  14944. // The only way this should be able to happen is if we fail our generic param check
  14945. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  14946. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  14947. methodInstance->mHasBeenProcessed = true;
  14948. return;
  14949. }
  14950. if (HasCompiledOutput())
  14951. {
  14952. BF_ASSERT(mIsModuleMutable);
  14953. }
  14954. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  14955. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  14956. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  14957. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  14958. {
  14959. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  14960. auto owningModule = methodInstance->GetOwner()->mModule;
  14961. if (owningModule->mIsScratchModule)
  14962. {
  14963. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  14964. }
  14965. else
  14966. {
  14967. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  14968. if (owningModule->mOnDemandMethodCount > 0)
  14969. owningModule->mOnDemandMethodCount--;
  14970. }
  14971. }
  14972. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  14973. // self-referencing append allocations in ctor@calcAppend
  14974. methodInstance->mHasBeenProcessed = true;
  14975. mIncompleteMethodCount--;
  14976. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  14977. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  14978. auto methodDef = methodInstance->mMethodDef;
  14979. auto methodDeclaration = methodDef->GetMethodDeclaration();
  14980. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  14981. {
  14982. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  14983. // so we get the new vdata for it
  14984. methodInstance->GetOwner()->mDirty = true;
  14985. }
  14986. int dependentGenericStartIdx = 0;
  14987. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  14988. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  14989. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  14990. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  14991. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  14992. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  14993. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  14994. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  14995. if ((methodInstance->mIsReified) &&
  14996. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  14997. {
  14998. mCurTypeInstance->mHasBeenInstantiated = true;
  14999. }
  15000. // Warnings are shown in the capture phase
  15001. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  15002. mIgnoreWarnings = true;
  15003. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  15004. UseDefaultSrcPos();
  15005. // We may not actually be populated in relatively rare autocompelte cases
  15006. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  15007. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  15008. BfAstNode* nameNode = NULL;
  15009. if (methodDeclaration != NULL)
  15010. {
  15011. nameNode = methodDeclaration->mNameNode;
  15012. if (nameNode == NULL)
  15013. {
  15014. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  15015. nameNode = ctorDeclaration->mThisToken;
  15016. }
  15017. }
  15018. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  15019. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  15020. {
  15021. if (methodInstance->GetExplicitInterface() == NULL)
  15022. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  15023. else
  15024. {
  15025. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  15026. {
  15027. auto ifaceInst = ifaceEntry.mInterfaceType;
  15028. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  15029. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  15030. if (methodInstance->GetExplicitInterface() != ifaceInst)
  15031. continue;
  15032. ifaceInst->mTypeDef->PopulateMemberSets();
  15033. BfMethodDef* nextMethod = NULL;
  15034. BfMemberSetEntry* entry = NULL;
  15035. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  15036. nextMethod = (BfMethodDef*)entry->mMemberDef;
  15037. while (nextMethod != NULL)
  15038. {
  15039. auto checkMethod = nextMethod;
  15040. nextMethod = nextMethod->mNextWithSameName;
  15041. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  15042. if (implMethodInst == methodInstance)
  15043. {
  15044. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  15045. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  15046. }
  15047. }
  15048. }
  15049. }
  15050. if (methodDef->mIsOverride)
  15051. {
  15052. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  15053. {
  15054. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  15055. if (ventry.mDeclaringMethod.mMethodNum == -1)
  15056. continue;
  15057. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  15058. if (virtMethod != NULL)
  15059. {
  15060. if (virtMethod == methodInstance)
  15061. {
  15062. // Is matching method
  15063. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  15064. {
  15065. auto baseType = mCurTypeInstance->mBaseType;
  15066. if (baseType != NULL)
  15067. {
  15068. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  15069. baseType = baseType->mBaseType;
  15070. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  15071. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  15072. }
  15073. }
  15074. break;
  15075. }
  15076. }
  15077. }
  15078. }
  15079. }
  15080. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  15081. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  15082. {
  15083. if (mBfIRBuilder->mIgnoreWrites)
  15084. return;
  15085. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  15086. if (!methodInstance->mIRFunction)
  15087. {
  15088. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  15089. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  15090. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  15091. }
  15092. if (HasCompiledOutput())
  15093. {
  15094. BfDllImportEntry dllImportEntry;
  15095. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  15096. dllImportEntry.mMethodInstance = mCurMethodInstance;
  15097. mDllImportEntries.push_back(dllImportEntry);
  15098. }
  15099. return;
  15100. }
  15101. StringT<128> mangledName;
  15102. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  15103. if (!methodInstance->mIRFunction)
  15104. {
  15105. bool isIntrinsic = false;
  15106. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  15107. }
  15108. if (methodInstance->mIsIntrinsic)
  15109. return;
  15110. if (mCurTypeInstance->IsFunction())
  15111. return;
  15112. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15113. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  15114. if (methodDef->mBody != NULL)
  15115. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  15116. else if (methodDeclaration != NULL)
  15117. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  15118. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15119. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  15120. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  15121. {
  15122. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  15123. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  15124. {
  15125. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  15126. }
  15127. }
  15128. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  15129. BfMethodState methodState;
  15130. if (mCurMethodState != NULL)
  15131. methodState.mClosureState = mCurMethodState->mClosureState;
  15132. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  15133. {
  15134. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  15135. if (methodInstance->mHotMethod == NULL)
  15136. CheckHotMethod(methodInstance, mangledName);
  15137. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  15138. }
  15139. methodState.mPrevMethodState = mCurMethodState;
  15140. methodState.mMethodInstance = methodInstance;
  15141. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15142. if (methodInstance->GetCustomAttributes() != NULL)
  15143. {
  15144. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  15145. if (typeOptionsIdx != -1)
  15146. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  15147. }
  15148. BfTypeState typeState(mCurTypeInstance);
  15149. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  15150. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  15151. BfMethodInstance* unspecializedMethodInstance = NULL;
  15152. if ((prevMethodState.mPrevVal != NULL) &&
  15153. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  15154. {
  15155. // This is 'inner' (probably a closure) - use binding from outer function
  15156. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  15157. }
  15158. else if ((methodInstance->mIsUnspecialized) ||
  15159. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  15160. {
  15161. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  15162. }
  15163. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  15164. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation) && (!methodInstance->mMethodDef->mIsLocalMethod))))
  15165. {
  15166. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  15167. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  15168. if (!unspecializedMethodInstance->mHasBeenProcessed)
  15169. {
  15170. // Make sure the unspecialized method is processed so we can take its bindings
  15171. // Clear mCurMethodState so we don't think we're in a local method
  15172. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  15173. mContext->ProcessMethod(unspecializedMethodInstance);
  15174. }
  15175. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  15176. }
  15177. if (methodDef->mMethodType == BfMethodType_Operator)
  15178. {
  15179. auto operatorDef = (BfOperatorDef*) methodDef;
  15180. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  15181. auto paramErrorRefNode = refNode;
  15182. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  15183. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  15184. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  15185. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  15186. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  15187. {
  15188. if (methodDef->mParams.size() != 2)
  15189. {
  15190. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  15191. }
  15192. else
  15193. {
  15194. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  15195. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  15196. {
  15197. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  15198. }
  15199. }
  15200. BfType* wantType = NULL;
  15201. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  15202. {
  15203. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  15204. }
  15205. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  15206. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  15207. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  15208. }
  15209. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  15210. {
  15211. if (methodDef->mIsStatic)
  15212. {
  15213. if (methodDef->mParams.size() != 1)
  15214. {
  15215. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  15216. }
  15217. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  15218. {
  15219. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  15220. }
  15221. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  15222. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  15223. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  15224. {
  15225. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  15226. }
  15227. }
  15228. else
  15229. {
  15230. if (methodDef->mParams.size() != 0)
  15231. {
  15232. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  15233. }
  15234. if (!mCurMethodInstance->mReturnType->IsVoid())
  15235. {
  15236. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  15237. }
  15238. }
  15239. }
  15240. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  15241. {
  15242. if (methodDef->mParams.size() != 1)
  15243. {
  15244. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  15245. }
  15246. if (!mCurMethodInstance->mReturnType->IsVoid())
  15247. {
  15248. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  15249. }
  15250. }
  15251. else // Conversion
  15252. {
  15253. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  15254. {
  15255. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  15256. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  15257. }
  15258. if (methodDef->mParams.size() != 1)
  15259. {
  15260. auto refNode = paramErrorRefNode;
  15261. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  15262. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  15263. Fail("Conversion operators must declare one parameter", refNode);
  15264. }
  15265. else
  15266. {
  15267. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  15268. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  15269. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  15270. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  15271. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  15272. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  15273. // happened here
  15274. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  15275. {
  15276. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  15277. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  15278. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  15279. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  15280. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  15281. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  15282. }
  15283. }
  15284. }
  15285. }
  15286. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  15287. if (methodDef->mMethodType == BfMethodType_Mixin)
  15288. wantsDIData = false;
  15289. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  15290. wantsDIData = false;
  15291. bool wantsDIVariables = wantsDIData;
  15292. if (methodDef->mIsExtern)
  15293. wantsDIVariables = false;
  15294. SizedArray<BfIRMDNode, 8> diParams;
  15295. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  15296. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  15297. BfType* thisType = NULL;
  15298. if (!methodDef->mIsStatic)
  15299. {
  15300. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  15301. thisType = methodState.mClosureState->mClosureType;
  15302. else
  15303. thisType = mCurTypeInstance;
  15304. }
  15305. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  15306. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  15307. //////////////////////////////////////////////////////////////////////////
  15308. //
  15309. {
  15310. if (methodDeclaration != NULL)
  15311. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  15312. else if (methodDef->mBody != NULL)
  15313. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  15314. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15315. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  15316. }
  15317. BfIRMDNode diFunction;
  15318. if (wantsDIData)
  15319. {
  15320. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  15321. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  15322. int defLine = mCurFilePosition.mCurLine;
  15323. if (mDICompileUnit)
  15324. {
  15325. int flags = 0;
  15326. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  15327. if (methodDef->mProtection == BfProtection_Public)
  15328. flags = llvm::DINode::FlagPublic;
  15329. else if (methodDef->mProtection == BfProtection_Protected)
  15330. flags = llvm::DINode::FlagProtected;
  15331. else
  15332. flags = llvm::DINode::FlagPrivate;
  15333. if (methodDef->mIsOverride)
  15334. {
  15335. //flags |= llvm::DINode::FlagVirtual;
  15336. }
  15337. else if (methodDef->mIsVirtual)
  15338. flags |= llvm::DINode::FlagIntroducedVirtual;
  15339. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  15340. flags |= llvm::DINode::FlagStaticMember;
  15341. else
  15342. {
  15343. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  15344. flags |= llvm::DINode::FlagStaticMember;
  15345. }
  15346. flags |= llvm::DINode::FlagPrototyped;
  15347. if (methodDef->mMethodType == BfMethodType_Ctor)
  15348. {
  15349. flags |= llvm::DINode::FlagArtificial;
  15350. }
  15351. auto llvmFunction = methodInstance->mIRFunction;
  15352. SizedArray<BfIRMDNode, 1> genericArgs;
  15353. SizedArray<BfIRValue, 1> genericConstValueArgs;
  15354. String methodName;
  15355. if (methodInstance->GetForeignType() != NULL)
  15356. {
  15357. methodName += TypeToString(methodInstance->GetForeignType());
  15358. methodName += ".";
  15359. }
  15360. if (methodInstance->GetExplicitInterface() != NULL)
  15361. {
  15362. methodName += TypeToString(methodInstance->GetExplicitInterface());
  15363. methodName += ".";
  15364. }
  15365. methodName += methodDef->mName;
  15366. if (methodInstance->GetNumGenericArguments() != 0)
  15367. {
  15368. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  15369. {
  15370. if (genericArg->IsConstExprValue())
  15371. {
  15372. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  15373. while (genericConstValueArgs.size() < genericArgs.size())
  15374. genericConstValueArgs.push_back(BfIRValue());
  15375. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  15376. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  15377. }
  15378. else
  15379. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  15380. }
  15381. methodName += "<";
  15382. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  15383. {
  15384. if (i > 0)
  15385. methodName += ", ";
  15386. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  15387. methodName += TypeToString(type);
  15388. }
  15389. methodName += ">";
  15390. }
  15391. if ((methodName.empty()) && (methodDeclaration != NULL))
  15392. {
  15393. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  15394. {
  15395. methodName += "operator";
  15396. if (operatorDecl->mIsConvOperator)
  15397. {
  15398. methodName += " ";
  15399. methodName += TypeToString(methodInstance->mReturnType);
  15400. }
  15401. else if (operatorDecl->mOpTypeToken != NULL)
  15402. methodName += operatorDecl->mOpTypeToken->ToString();
  15403. }
  15404. }
  15405. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  15406. methodName += "$CHK";
  15407. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  15408. methodName += "$UCHK";
  15409. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  15410. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  15411. // defLine + 1, diFuncType, false, true,
  15412. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  15413. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  15414. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  15415. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  15416. defLine + 1, diFuncType, false, true,
  15417. llvm::dwarf::DW_VIRTUALITY_none,
  15418. 0,
  15419. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  15420. }
  15421. }
  15422. //////////////////////////////////////////////////////////////////////////
  15423. // Head and Init get rolled into Entry afterwards.
  15424. methodState.mIRFunction = methodInstance->mIRFunction;
  15425. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  15426. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  15427. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  15428. methodState.mCurScope->mDIScope = diFunction;
  15429. auto llvmEntryBlock = methodState.mIREntryBlock;
  15430. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  15431. if (methodDef->mName == "__MALFORMED")
  15432. {
  15433. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  15434. mBfIRBuilder->SetInsertPoint(newBlock);
  15435. }
  15436. if (methodDef->mBody != NULL)
  15437. {
  15438. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  15439. }
  15440. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  15441. {
  15442. // We want to be able to step into delegate invokes -- we actually step over them
  15443. if (methodDef->mName != "Invoke")
  15444. {
  15445. UpdateSrcPos(typeDef->mTypeDeclaration);
  15446. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  15447. }
  15448. }
  15449. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  15450. mBfIRBuilder->ClearDebugLocation();
  15451. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  15452. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  15453. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  15454. {
  15455. int localIdx = 0;
  15456. int argIdx = 0;
  15457. Array<BfIRValue> splatAddrValues;
  15458. for ( ; argIdx < irParamCount; localIdx++)
  15459. {
  15460. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  15461. if ((isThis) && (thisType->IsValuelessType()))
  15462. isThis = false;
  15463. if (methodInstance->GetStructRetIdx() == argIdx)
  15464. {
  15465. argIdx++;
  15466. if (argIdx == irParamCount)
  15467. break;
  15468. }
  15469. BfLocalVariable* paramVar = NULL;
  15470. while (true)
  15471. {
  15472. BF_ASSERT(localIdx < methodState.mLocals.size());
  15473. paramVar = methodState.mLocals[localIdx];
  15474. if ((paramVar->mCompositeCount == -1) &&
  15475. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  15476. break;
  15477. localIdx++;
  15478. }
  15479. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  15480. {
  15481. paramVar->mIsReadOnly = true;
  15482. }
  15483. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter));
  15484. if (paramVar->mResolvedType->IsMethodRef())
  15485. wantsAddr = false;
  15486. // if ((methodDef->mHasAppend) && (argIdx == 1))
  15487. // {
  15488. // BF_ASSERT(paramVar->mName == "appendIdx");
  15489. // wantsAddr = true;
  15490. // }
  15491. if (paramVar->mIsSplat)
  15492. {
  15493. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  15494. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  15495. BfTypeUtils::SplatIterate([&](BfType* checkType)
  15496. {
  15497. BfIRType splatIRType;
  15498. if (checkType->IsComposite())
  15499. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  15500. else
  15501. splatIRType = mBfIRBuilder->MapType(checkType);
  15502. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  15503. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  15504. if (!paramVar->mAddr)
  15505. paramVar->mAddr = allocaInst;
  15506. if (WantsLifetimes())
  15507. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  15508. splatAddrValues.push_back(allocaInst);
  15509. }, paramVar->mResolvedType);
  15510. mBfIRBuilder->SetInsertPoint(prevInsert);
  15511. }
  15512. else if (isThis)
  15513. {
  15514. if (wantsAddr)
  15515. {
  15516. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  15517. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  15518. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  15519. if (paramVar->mIsSplat)
  15520. {
  15521. //
  15522. }
  15523. else
  15524. {
  15525. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  15526. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  15527. wantPtr = true;
  15528. if (wantPtr)
  15529. {
  15530. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  15531. }
  15532. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  15533. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  15534. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  15535. paramVar->mAddr = allocaInst;
  15536. if (WantsLifetimes())
  15537. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  15538. }
  15539. mBfIRBuilder->SetInsertPoint(prevInsert);
  15540. }
  15541. }
  15542. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  15543. {
  15544. // Address doesn't change so we don't have to alloca it
  15545. BfIRType allocType;
  15546. int alignSize = mSystem->mPtrSize;
  15547. if (paramVar->mResolvedType->IsRef())
  15548. {
  15549. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  15550. }
  15551. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  15552. {
  15553. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  15554. alignSize = paramVar->mResolvedType->mAlign;
  15555. }
  15556. else
  15557. {
  15558. paramVar->mHasLocalStructBacking = true;
  15559. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  15560. if (typeInst != NULL)
  15561. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  15562. else
  15563. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  15564. }
  15565. if (wantsAddr)
  15566. {
  15567. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  15568. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  15569. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  15570. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  15571. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  15572. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  15573. paramVar->mAddr = allocaInst;
  15574. mBfIRBuilder->SetInsertPoint(prevInsert);
  15575. if (WantsLifetimes())
  15576. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  15577. }
  15578. }
  15579. else if (wantsAddr)
  15580. {
  15581. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  15582. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  15583. paramVar->mAddr = allocaInst;
  15584. }
  15585. if (paramVar->mIsSplat)
  15586. {
  15587. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  15588. }
  15589. else if (paramVar->mIsLowered)
  15590. {
  15591. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15592. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15593. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  15594. argIdx++;
  15595. if (loweredTypeCode2 != BfTypeCode_None)
  15596. argIdx++;
  15597. }
  15598. else
  15599. {
  15600. argIdx++;
  15601. }
  15602. }
  15603. if (methodDef->mBody != NULL)
  15604. UpdateSrcPos(methodDef->mBody);
  15605. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15606. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  15607. localIdx = 0;
  15608. argIdx = 0;
  15609. int splatAddrIdx = 0;
  15610. while (localIdx < (int)methodState.mLocals.size())
  15611. {
  15612. if (argIdx == methodInstance->GetStructRetIdx())
  15613. argIdx++;
  15614. int curLocalIdx = localIdx++;
  15615. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  15616. if (!paramVar->IsParam())
  15617. continue;
  15618. if (paramVar->mCompositeCount != -1)
  15619. continue;
  15620. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  15621. if ((isThis) && (thisType->IsValuelessType()))
  15622. isThis = false;
  15623. if (paramVar->mValue.IsArg())
  15624. BF_ASSERT(paramVar->mValue.mId == argIdx);
  15625. BfIRMDNode diVariable;
  15626. if (wantsDIData)
  15627. {
  15628. String paramName = paramVar->mName;
  15629. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  15630. if (isThis)
  15631. {
  15632. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  15633. paramName = "__closure";
  15634. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  15635. {
  15636. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  15637. bool wantRef = paramVar->mResolvedType->IsComposite();
  15638. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  15639. wantRef = true;
  15640. if (wantRef)
  15641. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  15642. }
  15643. else if (!paramVar->mResolvedType->IsValueType())
  15644. {
  15645. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  15646. }
  15647. }
  15648. else
  15649. {
  15650. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  15651. {
  15652. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  15653. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  15654. diType = mBfIRBuilder->DbgCreateConstType(diType);
  15655. }
  15656. }
  15657. if (!paramVar->mIsSplat)
  15658. {
  15659. if (paramVar->mResolvedType->IsValuelessType())
  15660. {
  15661. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  15662. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  15663. }
  15664. else if (paramVar->mIsImplicitParam)
  15665. {
  15666. // Annotate this specially?
  15667. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  15668. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  15669. }
  15670. else
  15671. {
  15672. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  15673. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  15674. }
  15675. paramVar->mDbgVarInst = diVariable;
  15676. }
  15677. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  15678. {
  15679. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  15680. // {
  15681. // // Only add this placeholder if we don't have any values
  15682. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  15683. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  15684. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  15685. // }
  15686. }
  15687. }
  15688. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  15689. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  15690. {
  15691. // Write our argument value into the .addr
  15692. mBfIRBuilder->ClearDebugLocation();
  15693. if (paramVar->mIsSplat)
  15694. {
  15695. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  15696. //
  15697. }
  15698. else
  15699. {
  15700. bool handled = false;
  15701. if (paramVar->mIsLowered)
  15702. {
  15703. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15704. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15705. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  15706. {
  15707. // We have a lowered type coming in, so we have to cast the .addr before storing
  15708. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  15709. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  15710. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, primPtrType);
  15711. mBfIRBuilder->CreateStore(paramVar->mValue, primPtrVal);
  15712. if (loweredTypeCode2 != BfTypeCode_None)
  15713. {
  15714. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  15715. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  15716. BfIRValue primPtrVal2;
  15717. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  15718. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  15719. else
  15720. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  15721. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  15722. }
  15723. // We don't want to allow directly using value
  15724. paramVar->mValue = BfIRValue();
  15725. handled = true;
  15726. }
  15727. else
  15728. {
  15729. BF_ASSERT("Expected lowered");
  15730. }
  15731. }
  15732. if (!handled)
  15733. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  15734. }
  15735. }
  15736. if (methodDef->mBody != NULL)
  15737. UpdateSrcPos(methodDef->mBody);
  15738. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  15739. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  15740. else if (methodDeclaration == NULL)
  15741. UseDefaultSrcPos();
  15742. // Write our argument value into the .addr
  15743. if (paramVar->mIsSplat)
  15744. {
  15745. int splatComponentIdx = 0;
  15746. auto curArgIdx = argIdx;
  15747. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  15748. {
  15749. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  15750. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  15751. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  15752. mBfIRBuilder->ClearDebugLocation(storeInst);
  15753. if (wantsDIData)
  15754. {
  15755. BfIRMDNode diType;
  15756. if (checkType->IsComposite())
  15757. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  15758. else
  15759. diType = mBfIRBuilder->DbgGetType(checkType);
  15760. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  15761. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  15762. if (wantsDIVariables)
  15763. {
  15764. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  15765. }
  15766. }
  15767. curArgIdx++;
  15768. splatComponentIdx++;
  15769. };
  15770. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  15771. {
  15772. if (checkType->IsStruct())
  15773. {
  15774. auto checkTypeInstance = checkType->ToTypeInstance();
  15775. if (checkTypeInstance->mBaseType != NULL)
  15776. {
  15777. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  15778. }
  15779. if (checkTypeInstance->mIsUnion)
  15780. {
  15781. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  15782. if (!unionInnerType->IsValuelessType())
  15783. {
  15784. _FinishSplatsIterate(unionInnerType, name + "$u");
  15785. }
  15786. if (checkTypeInstance->IsEnum())
  15787. {
  15788. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  15789. _FinishSplatsIterate(dscrType, name + "$d");
  15790. }
  15791. }
  15792. else
  15793. {
  15794. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  15795. {
  15796. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  15797. auto fieldDef = fieldInstance->GetFieldDef();
  15798. if (fieldInstance->mDataIdx >= 0)
  15799. {
  15800. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  15801. }
  15802. }
  15803. }
  15804. }
  15805. else if (checkType->IsMethodRef())
  15806. {
  15807. auto methodRefType = (BfMethodRefType*)checkType;
  15808. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  15809. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  15810. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  15811. // {
  15812. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  15813. // if (!paramType->IsValuelessType())
  15814. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  15815. // }
  15816. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  15817. {
  15818. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  15819. String paramName = methodInstance->GetParamName(paramIdx);
  15820. if (paramName == "this")
  15821. paramName = "__this";
  15822. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  15823. {
  15824. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  15825. }
  15826. else
  15827. {
  15828. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  15829. }
  15830. }
  15831. }
  15832. else if (!checkType->IsValuelessType())
  15833. {
  15834. _FinishSplats(checkType, name);
  15835. }
  15836. };
  15837. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  15838. if (!paramVar->mConstValue)
  15839. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  15840. }
  15841. BfIRValue declareCall;
  15842. if (diVariable)
  15843. {
  15844. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  15845. {
  15846. if (!paramVar->mAddr)
  15847. {
  15848. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  15849. {
  15850. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  15851. {
  15852. // We don't need to set the location for this
  15853. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  15854. }
  15855. }
  15856. else
  15857. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  15858. }
  15859. else
  15860. {
  15861. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  15862. }
  15863. }
  15864. }
  15865. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  15866. {
  15867. // We don't allow actually assignment to "this", so we just do a single load
  15868. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  15869. // we need to store it in the stack frame for debugging purposes
  15870. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  15871. mBfIRBuilder->ClearDebugLocation(loadedThis);
  15872. paramVar->mValue = loadedThis;
  15873. }
  15874. if ((wantsDIData) && (declareCall))
  15875. mBfIRBuilder->UpdateDebugLocation(declareCall);
  15876. if (paramVar->mIsSplat)
  15877. {
  15878. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  15879. }
  15880. else if (paramVar->mIsLowered)
  15881. {
  15882. argIdx++;
  15883. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15884. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15885. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  15886. if (loweredTypeCode2 != BfTypeCode_None)
  15887. argIdx++;
  15888. }
  15889. else if (!paramVar->mResolvedType->IsValuelessType())
  15890. {
  15891. argIdx++;
  15892. }
  15893. }
  15894. if (wantsDIData)
  15895. {
  15896. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  15897. }
  15898. }
  15899. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  15900. {
  15901. auto paramVar = mCurMethodState->mLocals[varIdx];
  15902. // 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
  15903. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  15904. // if (paramVar->mIsSplat)
  15905. // {
  15906. // if (wantsDIVariables)
  15907. // {
  15908. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  15909. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  15910. // }
  15911. // }
  15912. if (paramVar->mResolvedType->IsValuelessType())
  15913. {
  15914. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  15915. {
  15916. // Only add this placeholder if we don't have any values
  15917. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  15918. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  15919. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  15920. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  15921. }
  15922. }
  15923. }
  15924. if (IsTargetingBeefBackend())
  15925. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  15926. if (methodState.mClosureState != NULL)
  15927. {
  15928. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  15929. {
  15930. BfLocalVariable* localVar = new BfLocalVariable();
  15931. *localVar = constLocal;
  15932. AddLocalVariableDef(localVar, true);
  15933. }
  15934. }
  15935. bool wantsRemoveBody = false;
  15936. bool skipBody = false;
  15937. bool skipUpdateSrcPos = false;
  15938. bool skipEndChecks = false;
  15939. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  15940. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  15941. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  15942. hasExternSpecifier = true;
  15943. // Allocate, clear, set classVData
  15944. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  15945. {
  15946. CreateStaticCtor();
  15947. }
  15948. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  15949. {
  15950. skipBody = true;
  15951. skipEndChecks = true;
  15952. if (HasCompiledOutput())
  15953. {
  15954. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  15955. mBfIRBuilder->ClearDebugLocation();
  15956. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  15957. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  15958. PopulateType(innerType, BfPopulateType_DataAndMethods);
  15959. mBfIRBuilder->PopulateType(mCurTypeInstance);
  15960. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  15961. if (methodInstance->mIsForeignMethodDef)
  15962. {
  15963. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  15964. }
  15965. BfTypeVector methodGenericArguments;
  15966. if (methodInstance->mMethodInfoEx != NULL)
  15967. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  15968. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  15969. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  15970. {
  15971. if (!methodInstance->mReturnType->IsValuelessType())
  15972. {
  15973. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  15974. CreateReturn(retVal);
  15975. }
  15976. else
  15977. mBfIRBuilder->CreateRetVoid();
  15978. }
  15979. else
  15980. {
  15981. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  15982. SizedArray<BfIRValue, 8> innerParams;
  15983. BfExprEvaluator exprEvaluator(this);
  15984. if (!innerType->IsValuelessType())
  15985. {
  15986. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  15987. BfTypedValue innerVal(thisValue, innerType, true);
  15988. if (boxedType->IsBoxedStructPtr())
  15989. {
  15990. innerVal = LoadValue(innerVal);
  15991. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  15992. }
  15993. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  15994. }
  15995. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  15996. {
  15997. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  15998. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  15999. exprEvaluator.PushArg(localVal, innerParams);
  16000. }
  16001. if (!innerMethodInstance.mFunc)
  16002. {
  16003. BF_ASSERT(innerType->IsUnspecializedType());
  16004. }
  16005. else if (methodInstance->GetStructRetIdx() != -1)
  16006. {
  16007. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  16008. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  16009. exprEvaluator.mReceivingValue = &returnType;
  16010. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  16011. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  16012. mBfIRBuilder->CreateRetVoid();
  16013. }
  16014. else
  16015. {
  16016. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  16017. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  16018. if (mCurMethodInstance->mReturnType->IsValueType())
  16019. retVal = LoadValue(retVal);
  16020. CreateReturn(retVal.mValue);
  16021. }
  16022. }
  16023. }
  16024. mCurMethodState->SetHadReturn(true);
  16025. mCurMethodState->mLeftBlockUncond = true;
  16026. }
  16027. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  16028. {
  16029. SetIllegalSrcPos();
  16030. mBfIRBuilder->ClearDebugLocation();
  16031. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  16032. auto thisVal = GetThis();
  16033. int prevSize = mContext->mBfObjectType->mInstSize;
  16034. int curSize = mCurTypeInstance->mInstSize;
  16035. if (curSize > prevSize)
  16036. {
  16037. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  16038. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  16039. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  16040. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  16041. }
  16042. skipUpdateSrcPos = true;
  16043. }
  16044. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  16045. {
  16046. EmitCtorBody(skipBody);
  16047. }
  16048. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  16049. {
  16050. EmitDtorBody();
  16051. skipBody = true;
  16052. }
  16053. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  16054. {
  16055. EmitIteratorBlock(skipBody);
  16056. }
  16057. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  16058. {
  16059. // We need to be able to mark deleted objects
  16060. mCurMethodState->mIgnoreObjectAccessCheck = true;
  16061. }
  16062. auto customAttributes = methodInstance->GetCustomAttributes();
  16063. if (customAttributes != NULL)
  16064. {
  16065. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  16066. mCurMethodState->mIgnoreObjectAccessCheck = true;
  16067. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  16068. mCurMethodState->mDisableChecks = true;
  16069. }
  16070. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  16071. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  16072. {
  16073. // We chain even non-default ctors to the default ctors
  16074. auto defaultCtor = methodInstance;
  16075. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  16076. CallChainedMethods(defaultCtor, false);
  16077. }
  16078. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  16079. if (methodDef->mBody == NULL)
  16080. {
  16081. if (methodDeclaration != NULL)
  16082. {
  16083. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16084. {
  16085. if (operatorDeclaration->mIsConvOperator)
  16086. wantsRemoveBody = true;
  16087. }
  16088. }
  16089. bool isDllImport = false;
  16090. if (methodInstance->GetImportKind() == BfImportKind_Import_Static)
  16091. {
  16092. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  16093. {
  16094. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  16095. {
  16096. if (customAttr.mCtorArgs.size() == 1)
  16097. {
  16098. auto fileNameArg = customAttr.mCtorArgs[0];
  16099. int strNum = 0;
  16100. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  16101. if (constant != NULL)
  16102. {
  16103. if (constant->IsNull())
  16104. continue; // Invalid
  16105. strNum = constant->mInt32;
  16106. }
  16107. else
  16108. {
  16109. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  16110. }
  16111. if (!mImportFileNames.Contains(strNum))
  16112. mImportFileNames.Add(strNum);
  16113. }
  16114. }
  16115. }
  16116. //mImportFileNames
  16117. }
  16118. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  16119. {
  16120. CreateDllImportMethod();
  16121. }
  16122. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  16123. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  16124. {
  16125. if (mCurTypeInstance->mTypeDef->mIsFunction)
  16126. {
  16127. // Emit nothing
  16128. }
  16129. else
  16130. {
  16131. CreateDelegateInvokeMethod();
  16132. mCurMethodState->SetHadReturn(true);
  16133. mCurMethodState->mLeftBlockUncond = true;
  16134. }
  16135. }
  16136. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  16137. {
  16138. if (mCurTypeInstance->IsObject())
  16139. {
  16140. CreateDynamicCastMethod();
  16141. }
  16142. else
  16143. {
  16144. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  16145. mCurMethodState->mHadReturn = true;
  16146. }
  16147. }
  16148. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  16149. {
  16150. BfIRValue ret;
  16151. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  16152. {
  16153. // This can happen if we provide an invalid name
  16154. AssertErrorState();
  16155. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  16156. }
  16157. else
  16158. {
  16159. // Unfortunate DebugLoc shenanigans-
  16160. // 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,
  16161. // so we only set the loc on the CreateRet which gets inlined out
  16162. mBfIRBuilder->SaveDebugLocation();
  16163. mBfIRBuilder->ClearDebugLocation();
  16164. BfIRValue fromBool;
  16165. if (!mCurTypeInstance->IsTypedPrimitive())
  16166. {
  16167. fromBool = GetDefaultValue(methodInstance->mReturnType);
  16168. }
  16169. else
  16170. {
  16171. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  16172. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  16173. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  16174. }
  16175. mBfIRBuilder->RestoreDebugLocation();
  16176. ret = mBfIRBuilder->CreateRet(fromBool);
  16177. //ExtendLocalLifetimes(0);
  16178. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16179. }
  16180. mCurMethodState->SetHadReturn(true);
  16181. mCurMethodState->mLeftBlockUncond = true;
  16182. }
  16183. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  16184. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  16185. {
  16186. BfIRValue ret;
  16187. // Unfortunate DebugLoc shenanigans-
  16188. // 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,
  16189. // so we only set the loc on the CreateRet which gets inlined out
  16190. mBfIRBuilder->SaveDebugLocation();
  16191. mBfIRBuilder->ClearDebugLocation();
  16192. BfIRValue fromBool;
  16193. mBfIRBuilder->RestoreDebugLocation();
  16194. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  16195. //ExtendLocalLifetimes(0);
  16196. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16197. mCurMethodState->SetHadReturn(true);
  16198. mCurMethodState->mLeftBlockUncond = true;
  16199. }
  16200. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  16201. {
  16202. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  16203. if (HasCompiledOutput())
  16204. {
  16205. EmitEnumToStringBody();
  16206. }
  16207. mBfIRBuilder->CreateRetVoid();
  16208. mCurMethodState->SetHadReturn(true);
  16209. mCurMethodState->mLeftBlockUncond = true;
  16210. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16211. }
  16212. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  16213. {
  16214. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  16215. if (HasCompiledOutput())
  16216. {
  16217. EmitTupleToStringBody();
  16218. }
  16219. mBfIRBuilder->CreateRetVoid();
  16220. mCurMethodState->SetHadReturn(true);
  16221. mCurMethodState->mLeftBlockUncond = true;
  16222. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16223. }
  16224. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  16225. {
  16226. CreateValueTypeEqualsMethod(false);
  16227. skipBody = true;
  16228. skipEndChecks = true;
  16229. }
  16230. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  16231. {
  16232. CreateValueTypeEqualsMethod(true);
  16233. skipBody = true;
  16234. skipEndChecks = true;
  16235. }
  16236. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  16237. {
  16238. CreateValueTypeEqualsMethod(false);
  16239. skipBody = true;
  16240. skipEndChecks = true;
  16241. }
  16242. else
  16243. {
  16244. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  16245. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  16246. {
  16247. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  16248. Fail("Body expected", methodDef->mBody);
  16249. }
  16250. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  16251. {
  16252. if (methodInstance->mReturnType->IsValuelessType())
  16253. {
  16254. mBfIRBuilder->CreateRetVoid();
  16255. }
  16256. else if (HasCompiledOutput())
  16257. {
  16258. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  16259. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  16260. BfFieldDef* fieldDef = NULL;
  16261. if (fieldInstance != NULL)
  16262. fieldDef = fieldInstance->GetFieldDef();
  16263. BfType* retType = methodInstance->mReturnType;
  16264. if (retType->IsRef())
  16265. retType = retType->GetUnderlyingType();
  16266. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  16267. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  16268. {
  16269. BfTypedValue lookupValue;
  16270. if (fieldDef->IsNonConstStatic())
  16271. lookupValue = ReferenceStaticField(fieldInstance);
  16272. else if (mCurTypeInstance->IsObject())
  16273. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  16274. else
  16275. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  16276. lookupValue = LoadOrAggregateValue(lookupValue);
  16277. CreateReturn(lookupValue.mValue);
  16278. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16279. }
  16280. else
  16281. {
  16282. // This can happen if we have two properties with the same name but different types
  16283. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  16284. EmitDefaultReturn();
  16285. }
  16286. }
  16287. else
  16288. {
  16289. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  16290. EmitDefaultReturn();
  16291. }
  16292. mCurMethodState->SetHadReturn(true);
  16293. }
  16294. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  16295. {
  16296. if ((!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  16297. {
  16298. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  16299. }
  16300. else if (!mCompiler->IsAutocomplete())
  16301. {
  16302. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  16303. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  16304. auto fieldDef = fieldInstance->GetFieldDef();
  16305. auto& lastParam = mCurMethodState->mLocals.back();
  16306. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  16307. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  16308. {
  16309. BfIRValue lookupAddr;
  16310. if (fieldDef->IsNonConstStatic())
  16311. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  16312. else
  16313. {
  16314. auto thisValue = GetThis();
  16315. if (thisValue.IsSplat())
  16316. {
  16317. BFMODULE_FATAL(this, "Should not happen");
  16318. }
  16319. if (mCurTypeInstance->IsObject())
  16320. thisValue = LoadValue(thisValue);
  16321. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  16322. }
  16323. BfExprEvaluator exprEvaluator(this);
  16324. auto localVal = exprEvaluator.LoadLocal(lastParam);
  16325. localVal = LoadOrAggregateValue(localVal);
  16326. mBfIRBuilder->CreateStore(localVal.mValue, lookupAddr);
  16327. }
  16328. else if (!fieldInstance->mResolvedType->IsValuelessType())
  16329. {
  16330. // This can happen if we have two properties with the same name but different types
  16331. AssertErrorState();
  16332. }
  16333. }
  16334. }
  16335. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  16336. {
  16337. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  16338. {
  16339. if (HasCompiledOutput())
  16340. EmitGCMarkMembers();
  16341. }
  16342. else if (!mCurTypeInstance->IsObject())
  16343. {
  16344. }
  16345. }
  16346. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  16347. {
  16348. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  16349. {
  16350. if (HasCompiledOutput())
  16351. EmitGCFindTLSMembers();
  16352. }
  16353. }
  16354. }
  16355. }
  16356. else if (!skipBody)
  16357. {
  16358. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  16359. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  16360. {
  16361. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  16362. if (mCurMethodInstance->GetStructRetIdx() != -1)
  16363. {
  16364. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  16365. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  16366. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst);
  16367. mBfIRBuilder->ClearDebugLocation(storeInst);
  16368. mCurMethodState->mRetValAddr = allocaInst;
  16369. }
  16370. else
  16371. {
  16372. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  16373. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  16374. }
  16375. }
  16376. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  16377. {
  16378. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  16379. BfGetSymbolReferenceKind prevSymbolKind;
  16380. BfAutoComplete* prevAutoComplete;
  16381. if (mCompiler->mResolvePassData != NULL)
  16382. {
  16383. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  16384. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16385. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  16386. }
  16387. EmitCtorCalcAppend();
  16388. if (mCompiler->mResolvePassData != NULL)
  16389. {
  16390. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  16391. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  16392. }
  16393. }
  16394. else if (!isEmptyBodied)
  16395. {
  16396. if (!mCurMethodState->mIRExitBlock)
  16397. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  16398. bool isExpressionBody = false;
  16399. if (methodDeclaration != NULL)
  16400. {
  16401. if (methodDeclaration->mFatArrowToken != NULL)
  16402. isExpressionBody = true;
  16403. }
  16404. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  16405. {
  16406. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  16407. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  16408. isExpressionBody = true;
  16409. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  16410. {
  16411. isExpressionBody = true;
  16412. }
  16413. }
  16414. else
  16415. {
  16416. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  16417. {
  16418. if (!block->mChildArr.IsEmpty())
  16419. {
  16420. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  16421. {
  16422. if (exprStmt->mTrailingSemicolon == NULL)
  16423. isExpressionBody = true;
  16424. }
  16425. }
  16426. }
  16427. else
  16428. isExpressionBody = true;
  16429. }
  16430. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  16431. {
  16432. while (fieldDtorBody != NULL)
  16433. {
  16434. VisitEmbeddedStatement(fieldDtorBody->mBody);
  16435. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  16436. }
  16437. }
  16438. else if (!isExpressionBody)
  16439. {
  16440. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  16441. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  16442. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  16443. VisitCodeBlock(bodyBlock);
  16444. }
  16445. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  16446. {
  16447. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  16448. // {
  16449. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  16450. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  16451. // }
  16452. auto expectingType = mCurMethodInstance->mReturnType;
  16453. // What was this error for?
  16454. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  16455. // {
  16456. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  16457. // }
  16458. BfEvalExprFlags exprEvalFlags = BfEvalExprFlags_AllowRefExpr;
  16459. if (expectingType->IsVoid())
  16460. {
  16461. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  16462. bool wasReturnGenericParam = false;
  16463. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  16464. {
  16465. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  16466. }
  16467. else
  16468. {
  16469. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  16470. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  16471. wasReturnGenericParam = true;
  16472. }
  16473. // If we the void return was from a generic specialization, allow us to return a void result,
  16474. // otherwise treat expression as though it must be a statement
  16475. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  16476. if (isStatement)
  16477. expectingType = NULL;
  16478. }
  16479. UpdateSrcPos(expressionBody);
  16480. auto retVal = CreateValueFromExpression(expressionBody, expectingType, exprEvalFlags);
  16481. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  16482. {
  16483. mCurMethodState->mHadReturn = true;
  16484. retVal = LoadOrAggregateValue(retVal);
  16485. EmitReturn(retVal.mValue);
  16486. }
  16487. }
  16488. }
  16489. }
  16490. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  16491. if (skipUpdateSrcPos)
  16492. {
  16493. // Skip
  16494. }
  16495. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  16496. UpdateSrcPos(bodyBlock->mCloseBrace);
  16497. else if (methodDef->mBody != NULL)
  16498. UpdateSrcPos(methodDef->mBody);
  16499. else if (methodDeclaration != NULL)
  16500. UpdateSrcPos(methodDeclaration);
  16501. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  16502. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  16503. else
  16504. UseDefaultSrcPos();
  16505. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  16506. {
  16507. if (mCurMethodState->mRetVal)
  16508. {
  16509. mCurMethodState->SetHadReturn(true);
  16510. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  16511. mBfIRBuilder->CreateRet(retVal);
  16512. }
  16513. else
  16514. AssertErrorState();
  16515. }
  16516. if (!mCurMethodState->mHadReturn)
  16517. {
  16518. // Clear off the stackallocs that have occurred after a scopeData break
  16519. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  16520. }
  16521. if (mCurMethodState->mIRExitBlock)
  16522. {
  16523. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  16524. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  16525. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  16526. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  16527. if (!mCurMethodState->mDIRetVal)
  16528. CreateDIRetVal();
  16529. }
  16530. for (auto localVar : mCurMethodState->mLocals)
  16531. {
  16532. if ((skipEndChecks) || (methodDef->mBody == NULL))
  16533. break;
  16534. LocalVariableDone(localVar, true);
  16535. }
  16536. if (mCurMethodState->mIRExitBlock)
  16537. {
  16538. if ((mCurMethodState->mRetVal) && (mCurMethodInstance->GetStructRetIdx() == -1))
  16539. {
  16540. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  16541. CreateReturn(loadedVal);
  16542. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16543. if (mCurMethodState->mDIRetVal)
  16544. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  16545. }
  16546. else
  16547. {
  16548. // Have something on the last line to step onto
  16549. if (mHasFullDebugInfo)
  16550. {
  16551. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  16552. UpdateSrcPos(bodyBlock->mCloseBrace);
  16553. EmitEnsureInstructionAt();
  16554. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  16555. {
  16556. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  16557. mBfIRBuilder->EnsureFunctionPatchable();
  16558. }
  16559. }
  16560. mBfIRBuilder->CreateRetVoid();
  16561. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16562. if (mCurMethodState->mDIRetVal)
  16563. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  16564. }
  16565. }
  16566. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  16567. {
  16568. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  16569. {
  16570. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  16571. {
  16572. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  16573. mBfIRBuilder->EnsureFunctionPatchable();
  16574. }
  16575. mBfIRBuilder->CreateRetVoid();
  16576. }
  16577. }
  16578. else
  16579. {
  16580. if (!mCurMethodState->mHadReturn)
  16581. {
  16582. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  16583. if (bodyBlock != NULL)
  16584. {
  16585. if (bodyBlock->mCloseBrace != NULL)
  16586. {
  16587. BfAstNode* target = bodyBlock->mCloseBrace;
  16588. Fail("Method must return value", target);
  16589. }
  16590. else
  16591. {
  16592. // It's possible to not have a closing brace if the method ends in an EOF
  16593. AssertErrorState();
  16594. }
  16595. }
  16596. }
  16597. }
  16598. // Move 'init' into 'entry'
  16599. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  16600. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  16601. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  16602. {
  16603. // Don't keep instructions for unspecialized types
  16604. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  16605. }
  16606. if ((hasExternSpecifier) && (!skipBody))
  16607. {
  16608. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  16609. // incase it gets called later by some hot-loaded coded
  16610. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()))
  16611. CreateFakeCallerMethod(mangledName);
  16612. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  16613. }
  16614. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  16615. {
  16616. // We only need the DLL stub when we may be hot swapping
  16617. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  16618. }
  16619. else if (wantsRemoveBody)
  16620. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  16621. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  16622. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  16623. // unspecialized types
  16624. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  16625. {
  16626. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  16627. methodInstance->mIRFunction = BfIRFunction();
  16628. }
  16629. CheckAddFailType();
  16630. if (mHadBuildError)
  16631. prevHadBuildError.CancelRestore();
  16632. if (mHadBuildWarning)
  16633. prevHadWarning.CancelRestore();
  16634. if (!methodDef->mIsLocalMethod)
  16635. ProcessMethod_ProcessDeferredLocals();
  16636. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  16637. if (methodState.mHotDataReferenceBuilder != NULL)
  16638. {
  16639. AddHotDataReferences(&hotDataReferenceBuilder);
  16640. }
  16641. else
  16642. {
  16643. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  16644. {
  16645. // Remove the hot method data
  16646. auto hotMethod = methodInstance->mHotMethod;
  16647. auto prevMethod = hotMethod->mPrevVersion;
  16648. if (prevMethod != NULL)
  16649. {
  16650. // If there's a prev method then pull its data into the main HotMethod.
  16651. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  16652. // over to the main HotMethod definition to keep the HotMethod address
  16653. // invariant
  16654. for (auto ref : hotMethod->mReferences)
  16655. ref->Deref();
  16656. hotMethod->mReferences.Clear();
  16657. BF_ASSERT(prevMethod->mRefCount == 1);
  16658. hotMethod->mReferences = prevMethod->mReferences;
  16659. if (hotMethod->mSrcTypeVersion != NULL)
  16660. hotMethod->mSrcTypeVersion->Deref();
  16661. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  16662. prevMethod->mSrcTypeVersion = NULL;
  16663. prevMethod->mReferences.Clear();
  16664. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  16665. prevMethod->mPrevVersion = NULL;
  16666. prevMethod->Deref();
  16667. }
  16668. hotMethod->Deref();
  16669. methodInstance->mHotMethod = NULL;
  16670. }
  16671. }
  16672. }
  16673. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  16674. {
  16675. String name;
  16676. bool found = false;
  16677. auto checkMethodState = mCurMethodState;
  16678. while (checkMethodState != NULL)
  16679. {
  16680. if (checkMethodState->mClosureState == NULL)
  16681. break;
  16682. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  16683. {
  16684. found = true;
  16685. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  16686. break;
  16687. }
  16688. checkMethodState = checkMethodState->mPrevMethodState;
  16689. }
  16690. if (!found)
  16691. name += mCurMethodInstance->mMethodDef->mName;
  16692. int prevSepPos = (int)name.LastIndexOf('$');
  16693. if (prevSepPos != -1)
  16694. {
  16695. name.RemoveToEnd(prevSepPos);
  16696. }
  16697. name += "@";
  16698. name += baseName;
  16699. HashContext hashCtx;
  16700. if (anchorNode != NULL)
  16701. {
  16702. hashCtx.Mixin(anchorNode->GetStartCharId());
  16703. }
  16704. //
  16705. {
  16706. auto checkMethodState = declMethodState;
  16707. auto checkMixinState = declMixinState;
  16708. while (checkMethodState != NULL)
  16709. {
  16710. if (checkMixinState != NULL)
  16711. {
  16712. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  16713. }
  16714. checkMethodState = checkMethodState->mPrevMethodState;
  16715. if (checkMethodState != NULL)
  16716. checkMixinState = checkMethodState->mMixinState;
  16717. }
  16718. }
  16719. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16720. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  16721. {
  16722. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  16723. {
  16724. StringT<128> genericTypeName;
  16725. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  16726. hashCtx.MixinStr(genericTypeName);
  16727. }
  16728. }
  16729. uint64 hashVal = hashCtx.Finish64();
  16730. name += "$";
  16731. name += BfTypeUtils::HashEncode64(hashVal);
  16732. return name;
  16733. }
  16734. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  16735. {
  16736. if (localMethod->mMethodDef != NULL)
  16737. return localMethod->mMethodDef;
  16738. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16739. auto declMethodState = localMethod->mDeclMethodState;
  16740. auto declMixinState = localMethod->mDeclMixinState;
  16741. auto typeInst = mCurTypeInstance;
  16742. BfAstNode* body = NULL;
  16743. BfAstNode* anchorNode = NULL;
  16744. auto _AllocDirectTypeRef = [&](BfType* type)
  16745. {
  16746. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  16747. directTypeRef->Init(type);
  16748. return directTypeRef;
  16749. };
  16750. auto methodDeclaration = localMethod->mMethodDeclaration;
  16751. if (methodDeclaration != NULL)
  16752. {
  16753. body = methodDeclaration->mBody;
  16754. anchorNode = methodDeclaration->mOpenParen;
  16755. }
  16756. else
  16757. {
  16758. body = localMethod->mLambdaBindExpr->mBody;
  16759. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  16760. }
  16761. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  16762. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  16763. BfMethodDef* methodDef;
  16764. BfMethodDef* outerMethodDef = NULL;
  16765. if (localMethod->mOuterLocalMethod != NULL)
  16766. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  16767. else
  16768. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  16769. if (methodDeclaration != NULL)
  16770. {
  16771. BfDefBuilder defBuilder(mCompiler->mSystem);
  16772. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  16773. defBuilder.mPassInstance = mCompiler->mPassInstance;
  16774. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  16775. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  16776. }
  16777. else
  16778. {
  16779. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  16780. methodDef = new BfMethodDef();
  16781. methodDef->mName = localMethod->mMethodName;
  16782. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  16783. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  16784. methodDef->mBody = body;
  16785. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  16786. {
  16787. auto paramType = invokeMethod->GetParamType(paramIdx);
  16788. String paramName;
  16789. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  16790. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  16791. else
  16792. paramName = invokeMethod->GetParamName(paramIdx);
  16793. auto paramDef = new BfParameterDef();
  16794. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  16795. paramDef->mName = paramName;
  16796. methodDef->mParams.Add(paramDef);
  16797. }
  16798. if (outerMethodDef != NULL)
  16799. {
  16800. for (auto genericParam : outerMethodDef->mGenericParams)
  16801. {
  16802. auto* copiedGenericParamDef = new BfGenericParamDef();
  16803. *copiedGenericParamDef = *genericParam;
  16804. methodDef->mGenericParams.Add(copiedGenericParamDef);
  16805. }
  16806. }
  16807. }
  16808. methodDef->mIdx = ~methodLocalIdx;
  16809. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  16810. methodDef->mName = localMethod->mExpectedFullName;
  16811. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  16812. //
  16813. // if (!localMethod->mExpectedFullName.IsEmpty())
  16814. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  16815. methodDef->mIsStatic = true;
  16816. methodDef->mIsLocalMethod = true;
  16817. methodDef->mIsVirtual = false;
  16818. localMethod->mMethodDef = methodDef;
  16819. auto methodInstanceGroup = new BfMethodInstanceGroup();
  16820. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  16821. methodInstanceGroup->mMethodIdx = -1;
  16822. methodInstanceGroup->mOwner = mCurTypeInstance;
  16823. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  16824. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  16825. {
  16826. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  16827. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  16828. }
  16829. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  16830. {
  16831. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  16832. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16833. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  16834. {
  16835. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  16836. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  16837. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  16838. autoComplete->mDefType = typeInst->mTypeDef;
  16839. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  16840. autoComplete->mReplaceLocalId = methodLocalIdx;
  16841. }
  16842. }
  16843. return localMethod->mMethodDef;
  16844. }
  16845. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  16846. {
  16847. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  16848. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  16849. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16850. auto declMethodState = localMethod->mDeclMethodState;
  16851. auto declMixinState = localMethod->mDeclMixinState;
  16852. auto callerMethodState = mCurMethodState;
  16853. auto typeInst = mCurTypeInstance;
  16854. if (mCurMethodState->mMixinState != NULL)
  16855. {
  16856. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  16857. }
  16858. auto methodDef = GetLocalMethodDef(localMethod);
  16859. BfAstNode* body = NULL;
  16860. auto methodDeclaration = localMethod->mMethodDeclaration;
  16861. if (methodDeclaration != NULL)
  16862. {
  16863. body = methodDeclaration->mBody;
  16864. }
  16865. else
  16866. {
  16867. body = localMethod->mLambdaBindExpr->mBody;
  16868. }
  16869. bool hadConcreteInterfaceGenericArgument = false;
  16870. BfTypeVector sanitizedMethodGenericArguments;
  16871. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  16872. // version of this method for this pass through the outermost method
  16873. int dependentGenericStartIdx = 0;
  16874. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  16875. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16876. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  16877. if (methodGenericArguments.size() == 0)
  16878. {
  16879. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  16880. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  16881. }
  16882. else
  16883. {
  16884. int genericArgIdx = 0;
  16885. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  16886. // {
  16887. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  16888. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  16889. // }
  16890. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  16891. {
  16892. auto genericArgType = methodGenericArguments[genericArgIdx];
  16893. BF_ASSERT(!genericArgType->IsRef());
  16894. if (genericArgType->IsConcreteInterfaceType())
  16895. {
  16896. hadConcreteInterfaceGenericArgument = true;
  16897. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  16898. genericArgType = concreteInterfaceType->mInterface;
  16899. }
  16900. sanitizedMethodGenericArguments.push_back(genericArgType);
  16901. }
  16902. }
  16903. bool wantPrematureMethodInstance = false;
  16904. if (!force)
  16905. {
  16906. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  16907. }
  16908. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  16909. bool isDefaultPass = true;
  16910. BfTypeVector lookupMethodGenericArguments;
  16911. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  16912. {
  16913. auto genericArgType = methodGenericArguments[genericArgIdx];
  16914. BF_ASSERT(!genericArgType->IsRef());
  16915. lookupMethodGenericArguments.Add(genericArgType);
  16916. if (genericArgType->IsGenericParam())
  16917. {
  16918. auto genericParam = (BfGenericParamType*)genericArgType;
  16919. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  16920. isDefaultPass = false;
  16921. }
  16922. else
  16923. {
  16924. isDefaultPass = false;
  16925. }
  16926. }
  16927. bool hadExistingMethodInstance = false;
  16928. if (methodInstance != NULL)
  16929. {
  16930. hadExistingMethodInstance = true;
  16931. }
  16932. else
  16933. {
  16934. if (isDefaultPass)
  16935. {
  16936. methodInstance = methodInstGroup->mDefault;
  16937. if (methodInstance != NULL)
  16938. {
  16939. hadExistingMethodInstance = true;
  16940. }
  16941. else
  16942. {
  16943. methodInstance = new BfMethodInstance();
  16944. methodInstGroup->mDefault = methodInstance;
  16945. }
  16946. }
  16947. else
  16948. {
  16949. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  16950. if (methodInstGroup->mMethodSpecializationMap == NULL)
  16951. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  16952. BfMethodInstance** methodInstancePtr = NULL;
  16953. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  16954. {
  16955. methodInstance = *methodInstancePtr;
  16956. hadExistingMethodInstance = true;
  16957. }
  16958. else
  16959. {
  16960. methodInstance = new BfMethodInstance();
  16961. *methodInstancePtr = methodInstance;
  16962. }
  16963. }
  16964. }
  16965. if (hadExistingMethodInstance)
  16966. {
  16967. if ((!methodInstance->mDisallowCalling) ||
  16968. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  16969. return BfModuleMethodInstance(methodInstance);
  16970. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  16971. }
  16972. else
  16973. {
  16974. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  16975. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  16976. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  16977. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  16978. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  16979. methodInstance->mMethodDef = methodDef;
  16980. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  16981. if (hadConcreteInterfaceGenericArgument)
  16982. methodInstance->mIgnoreBody = true;
  16983. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  16984. for (auto genericArg : sanitizedMethodGenericArguments)
  16985. {
  16986. if (genericArg->IsPrimitiveType())
  16987. genericArg = GetWrappedStructType(genericArg);
  16988. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  16989. }
  16990. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  16991. {
  16992. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  16993. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  16994. }
  16995. SetupMethodIdHash(methodInstance);
  16996. }
  16997. auto _SetupMethodInstance = [&]()
  16998. {
  16999. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  17000. // Generic constraints
  17001. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  17002. {
  17003. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  17004. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  17005. }
  17006. };
  17007. //////////////////////////////////////////////////////////////////////////
  17008. auto _VisitLambdaBody = [&]()
  17009. {
  17010. if (localMethod->mDeclOnly)
  17011. return;
  17012. if (mCompiler->mCanceling)
  17013. return;
  17014. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  17015. {
  17016. VisitCodeBlock(blockBody);
  17017. }
  17018. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  17019. CreateValueFromExpression(bodyExpr);
  17020. };
  17021. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  17022. {
  17023. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  17024. auto result = ResolveTypeRef(typeRef);
  17025. if (result == NULL)
  17026. result = mContext->mBfObjectType;
  17027. return result;
  17028. };
  17029. BfTypeInstance* outerClosure = NULL;
  17030. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  17031. outerClosure = declMethodState->mClosureState->mClosureType;
  17032. BfMethodState methodState;
  17033. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  17034. BfIRFunctionType funcType;
  17035. auto voidType = GetPrimitiveType(BfTypeCode_None);
  17036. SizedArray<BfIRType, 0> paramTypes;
  17037. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  17038. mBfIRBuilder->SaveDebugLocation();
  17039. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  17040. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  17041. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  17042. BfDeferredLocalAssignData deferredLocalAssignData;
  17043. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  17044. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  17045. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  17046. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17047. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  17048. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  17049. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  17050. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  17051. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  17052. methodState.mIRFunction = declMethodState->mIRFunction;
  17053. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  17054. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  17055. {
  17056. methodState.mCurScope->mAstBlock = blockBody;
  17057. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  17058. }
  17059. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  17060. BfClosureState closureState;
  17061. if (methodDef->mMethodType == BfMethodType_Mixin)
  17062. {
  17063. if (declMethodState != NULL)
  17064. {
  17065. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  17066. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  17067. else if (declMethodState->mMethodInstance != NULL)
  17068. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  17069. }
  17070. }
  17071. if (closureState.mReturnType == NULL)
  17072. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  17073. closureState.mCapturing = true;
  17074. closureState.mLocalMethod = localMethod;
  17075. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17076. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  17077. methodState.mClosureState = &closureState;
  17078. closureState.mClosureType = outerClosure;
  17079. int outerLocalsCount = (int)methodState.mLocals.size();
  17080. if (!hadExistingMethodInstance)
  17081. {
  17082. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  17083. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  17084. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  17085. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  17086. auto declareModule = this;
  17087. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  17088. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  17089. BF_ASSERT(declareModule != NULL);
  17090. methodInstance->mDeclModule = declareModule;
  17091. _SetupMethodInstance();
  17092. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  17093. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  17094. }
  17095. if (wantPrematureMethodInstance)
  17096. {
  17097. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  17098. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  17099. // its true method instance
  17100. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  17101. //BF_ASSERT(moduleMethodInstance);
  17102. return BfModuleMethodInstance(methodInstance);
  17103. }
  17104. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  17105. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  17106. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  17107. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  17108. closureState.mClosureMethodDef = methodDef;
  17109. bool wantsVisitBody = true;
  17110. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  17111. wantsVisitBody = false;
  17112. if (methodInstance->IsOrInUnspecializedVariation())
  17113. wantsVisitBody = false;
  17114. if (wantsVisitBody)
  17115. {
  17116. BP_ZONE("VisitLambdaBody");
  17117. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  17118. // this capture stage for each of those times
  17119. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  17120. /*
  17121. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  17122. // that will not occur during the actual lambda method generation, for example: returning a value
  17123. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  17124. // our AST nodes will still be visited
  17125. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  17126. */
  17127. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  17128. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  17129. mBfIRBuilder->SaveDebugLocation();
  17130. closureState.mCaptureVisitingBody = true;
  17131. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  17132. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  17133. methodState.mMethodInstance = methodInstance;
  17134. NewScopeState();
  17135. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  17136. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  17137. {
  17138. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  17139. for (auto localDef : methodState.mLocals)
  17140. {
  17141. if (localDef->mResolvedType->IsVar())
  17142. continue;
  17143. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  17144. }
  17145. }
  17146. // Keep outs for being marked as assigned
  17147. auto rootMethodState = mCurMethodState->GetRootMethodState();
  17148. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  17149. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  17150. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  17151. if (!mIgnoreErrors)
  17152. localMethod->mDidBodyErrorPass = true;
  17153. _VisitLambdaBody();
  17154. RestoreScopeState();
  17155. closureState.mCaptureVisitingBody = false;
  17156. mBfIRBuilder->RestoreDebugLocation();
  17157. }
  17158. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  17159. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  17160. {
  17161. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  17162. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  17163. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  17164. }
  17165. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  17166. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  17167. closureState.mClosureMethodDef = NULL;
  17168. for (auto methodInstance : closureState.mLocalMethodRefs)
  17169. {
  17170. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  17171. }
  17172. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  17173. prevIgnoreWrites.Restore();
  17174. std::multiset<BfClosureCapturedEntry> capturedEntries;
  17175. //
  17176. {
  17177. auto varMethodState = declMethodState;
  17178. while (varMethodState != NULL)
  17179. {
  17180. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  17181. {
  17182. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  17183. methodDef->mIsStatic = false;
  17184. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  17185. methodDef->mIsMutating = true;
  17186. }
  17187. bool copyOuterCaptures = false;
  17188. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  17189. {
  17190. auto localVar = varMethodState->mLocals[localIdx];
  17191. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  17192. {
  17193. if (localVar->mIsThis)
  17194. {
  17195. // We can only set mutating if our owning type is mutating
  17196. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  17197. {
  17198. if (typeInst->IsValueType())
  17199. {
  17200. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  17201. methodDef->mIsMutating = true;
  17202. }
  17203. }
  17204. methodDef->mIsStatic = false;
  17205. continue;
  17206. }
  17207. if ((localVar->mIsThis) && (outerClosure != NULL))
  17208. {
  17209. continue;
  17210. }
  17211. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  17212. {
  17213. closureState.mConstLocals.push_back(*localVar);
  17214. continue;
  17215. }
  17216. BfClosureCapturedEntry capturedEntry;
  17217. auto capturedType = localVar->mResolvedType;
  17218. bool captureByRef = false;
  17219. if (!capturedType->IsRef())
  17220. {
  17221. if (localVar->mIsThis)
  17222. {
  17223. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  17224. captureByRef = true;
  17225. }
  17226. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  17227. captureByRef = true;
  17228. }
  17229. else
  17230. {
  17231. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  17232. {
  17233. capturedType = ((BfRefType*)capturedType)->mElementType;
  17234. }
  17235. }
  17236. if (captureByRef)
  17237. {
  17238. //capturedEntry.mIsByReference = true;
  17239. capturedType = CreateRefType(capturedType);
  17240. }
  17241. else
  17242. {
  17243. //capturedEntry.mIsByReference = false;
  17244. }
  17245. capturedEntry.mNameNode = localVar->mNameNode;
  17246. capturedEntry.mType = capturedType;
  17247. capturedEntry.mName = localVar->mName;
  17248. //capturedEntry.mLocalVarDef = localVar;
  17249. capturedEntries.insert(capturedEntry);
  17250. }
  17251. }
  17252. varMethodState = varMethodState->mPrevMethodState;
  17253. if ((varMethodState == NULL) ||
  17254. (varMethodState->mMixinState != NULL) ||
  17255. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  17256. break;
  17257. }
  17258. }
  17259. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  17260. {
  17261. auto fieldDef = copyField->GetFieldDef();
  17262. BfClosureCapturedEntry capturedEntry;
  17263. capturedEntry.mName = copyField->GetFieldDef()->mName;
  17264. capturedEntry.mType = copyField->mResolvedType;
  17265. if (capturedEntry.mType->IsRef())
  17266. {
  17267. // Keep by ref
  17268. }
  17269. else if (!fieldDef->mIsReadOnly)
  17270. {
  17271. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  17272. }
  17273. capturedEntries.insert(capturedEntry);
  17274. }
  17275. int captureIdx = 0;
  17276. for (auto& capturedEntry : capturedEntries)
  17277. {
  17278. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  17279. }
  17280. /*if (isDefaultPass)
  17281. {
  17282. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  17283. int captureIdx = 0;
  17284. for (auto& capturedEntry : capturedEntries)
  17285. {
  17286. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  17287. BfParameterDef* paramDef = new BfParameterDef();
  17288. paramDef->mName = capturedEntry.mName;
  17289. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  17290. directTypeRef->mType = capturedEntry.mType;
  17291. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  17292. paramDef->mTypeRef = directTypeRef;
  17293. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  17294. methodDef->mParams.Insert(captureIdx, paramDef);
  17295. captureIdx++;
  17296. }
  17297. }
  17298. else
  17299. {
  17300. auto defaultMethodInstance = methodInstGroup->mDefault;
  17301. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  17302. }*/
  17303. methodState.Reset();
  17304. closureState.mCapturing = false;
  17305. //////////////////////////////////////////////////////////////////////////
  17306. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  17307. if (methodInstance->mReturnType != NULL)
  17308. {
  17309. BF_ASSERT(methodInstance->mDisallowCalling);
  17310. // We did a premature declaration (without captures)
  17311. methodInstance->UndoDeclaration();
  17312. methodInstance->mDisallowCalling = false;
  17313. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  17314. }
  17315. auto declareModule = this;
  17316. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  17317. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  17318. BF_ASSERT(declareModule != NULL);
  17319. methodInstance->mDeclModule = declareModule;
  17320. _SetupMethodInstance();
  17321. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  17322. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  17323. closureState.mReturnType = methodInstance->mReturnType;
  17324. mCompiler->mStats.mMethodsQueued++;
  17325. mCompiler->UpdateCompletion();
  17326. declareModule->mIncompleteMethodCount++;
  17327. mCompiler->mStats.mMethodsProcessed++;
  17328. if (!methodInstance->mIsReified)
  17329. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  17330. auto deferMethodState = rootMethodState;
  17331. // 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)
  17332. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  17333. (methodDef->mMethodType != BfMethodType_Mixin) &&
  17334. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)))
  17335. {
  17336. BP_ZONE("BfDeferredLocalMethod:create");
  17337. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  17338. deferredLocalMethod->mLocalMethod = localMethod;
  17339. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  17340. deferredLocalMethod->mMethodInstance = methodInstance;
  17341. auto checkMethodState = declMethodState;
  17342. while (checkMethodState != NULL)
  17343. {
  17344. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  17345. {
  17346. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  17347. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  17348. }
  17349. if (checkMethodState->mMixinState != NULL)
  17350. {
  17351. BfMixinRecord mixinRecord;
  17352. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  17353. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  17354. }
  17355. checkMethodState = checkMethodState->mPrevMethodState;
  17356. }
  17357. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  17358. }
  17359. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  17360. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  17361. mBfIRBuilder->RestoreDebugLocation();
  17362. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  17363. {
  17364. auto checkMethodState = mCurMethodState;
  17365. while (checkMethodState != NULL)
  17366. {
  17367. BfLocalMethod* nextLocalMethod = NULL;
  17368. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  17369. {
  17370. while (nextLocalMethod != NULL)
  17371. {
  17372. auto checkLocalMethod = nextLocalMethod;
  17373. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  17374. if (checkLocalMethod == localMethod)
  17375. continue;
  17376. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  17377. continue;
  17378. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  17379. if (checkMethodInstance == NULL)
  17380. continue; // Not generated yet
  17381. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  17382. {
  17383. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  17384. if (bfError != NULL)
  17385. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  17386. }
  17387. }
  17388. }
  17389. checkMethodState = checkMethodState->mPrevMethodState;
  17390. }
  17391. }
  17392. return BfModuleMethodInstance(methodInstance);
  17393. }
  17394. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  17395. {
  17396. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  17397. return 0;
  17398. auto rootMethodState = mCurMethodState->GetRootMethodState();
  17399. int rootMethodGenericParamCount = 0;
  17400. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  17401. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  17402. if (mCurMethodInstance == NULL)
  17403. return rootMethodGenericParamCount;
  17404. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  17405. return rootMethodGenericParamCount;
  17406. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  17407. if (callerLocalMethod == NULL)
  17408. return rootMethodGenericParamCount;
  17409. BfLocalMethod* calledLocalMethod = NULL;
  17410. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  17411. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  17412. {
  17413. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  17414. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  17415. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  17416. }
  17417. return rootMethodGenericParamCount;
  17418. }
  17419. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  17420. {
  17421. auto methodDef = methodInstance->mMethodDef;
  17422. auto customAttributes = methodInstance->GetCustomAttributes();
  17423. if (customAttributes != NULL)
  17424. return;
  17425. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17426. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  17427. auto typeInstance = methodInstance->GetOwner();
  17428. BfTypeState typeState(typeInstance);
  17429. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  17430. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  17431. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  17432. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  17433. BfAttributeDirective* attributeDirective = NULL;
  17434. if (methodDeclaration != NULL)
  17435. attributeDirective = methodDeclaration->mAttributes;
  17436. else if (propertyMethodDeclaration != NULL)
  17437. {
  17438. attributeDirective = propertyMethodDeclaration->mAttributes;
  17439. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  17440. {
  17441. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  17442. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  17443. }
  17444. }
  17445. if (attributeDirective != NULL)
  17446. {
  17447. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  17448. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  17449. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  17450. }
  17451. customAttributes = methodInstance->GetCustomAttributes();
  17452. if (customAttributes == NULL)
  17453. {
  17454. auto owner = methodInstance->GetOwner();
  17455. if ((owner->IsDelegate()) || (owner->IsFunction()))
  17456. customAttributes = owner->mCustomAttributes;
  17457. }
  17458. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  17459. if (customAttributes != NULL)
  17460. {
  17461. auto linkNameAttr = customAttributes->Get(typeInstance->mModule->mCompiler->mCallingConventionAttributeTypeDef);
  17462. if (linkNameAttr != NULL)
  17463. {
  17464. if (linkNameAttr->mCtorArgs.size() == 1)
  17465. {
  17466. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  17467. if (constant != NULL)
  17468. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  17469. }
  17470. }
  17471. }
  17472. }
  17473. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  17474. {
  17475. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  17476. {
  17477. // Don't create a func
  17478. return;
  17479. }
  17480. auto typeInstance = methodInstance->GetOwner();
  17481. auto methodDef = methodInstance->mMethodDef;
  17482. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  17483. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  17484. if (mCompiler->mResolvePassData == NULL)
  17485. {
  17486. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  17487. {
  17488. typeInstance->mHasStaticInitMethod = true;
  17489. }
  17490. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  17491. {
  17492. typeInstance->mHasStaticDtorMethod = true;
  17493. }
  17494. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  17495. {
  17496. typeInstance->mHasStaticMarkMethod = true;
  17497. }
  17498. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  17499. {
  17500. typeInstance->mHasTLSFindMethod = true;
  17501. }
  17502. }
  17503. if (isTemporaryFunc)
  17504. {
  17505. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  17506. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  17507. mangledName = "autocomplete_tmp";
  17508. }
  17509. if (!mBfIRBuilder->mIgnoreWrites)
  17510. {
  17511. BfIRFunction prevFunc;
  17512. // Remove old version (if we have one)
  17513. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  17514. if (prevFunc)
  17515. {
  17516. if ((methodDef->mIsOverride) && (mCurTypeInstance->mTypeDef->mIsCombinedPartial))
  17517. {
  17518. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  17519. mBfIRBuilder->Func_SafeRename(prevFunc);
  17520. }
  17521. else if (methodDef->mIsExtern)
  17522. {
  17523. // Allow this
  17524. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  17525. }
  17526. else if (typeInstance->IsIRFuncUsed(prevFunc))
  17527. {
  17528. // We can have a collision of names when we have generic methods that differ only in
  17529. // their constraints, but they should only collide in their unspecialized form
  17530. // since only one will be chosen for a given concrete type
  17531. mCurMethodInstance->mMangleWithIdx = true;
  17532. mangledName.Clear();
  17533. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  17534. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  17535. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  17536. }
  17537. else
  17538. {
  17539. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  17540. mBfIRBuilder->Func_SafeRename(prevFunc);
  17541. }
  17542. }
  17543. }
  17544. if (typeInstance != mContext->mBfObjectType)
  17545. {
  17546. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  17547. GetMethodCustomAttributes(methodInstance);
  17548. }
  17549. // if (prevFunc)
  17550. // {
  17551. // if (methodDef->mIsExtern)
  17552. // {
  17553. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  17554. // methodInstance->mIRFunction = prevFunc;
  17555. // }
  17556. // else
  17557. // {
  17558. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  17559. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  17560. // {
  17561. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  17562. // BfLogSysM("Ignoring function name collision\n");
  17563. // }
  17564. // else
  17565. // {
  17566. // if (methodDef->mMethodDeclaration == NULL)
  17567. // {
  17568. // AssertErrorState();
  17569. // }
  17570. // else
  17571. // {
  17572. // BF_ASSERT(mIsSpecialModule);
  17573. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  17574. // {
  17575. // // We shouldn't have name collisions on the first run!
  17576. // AssertErrorState();
  17577. // }
  17578. // }
  17579. // }
  17580. // BfLogSysM("Before erase\n");
  17581. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  17582. // }
  17583. // }
  17584. bool isIntrinsic = false;
  17585. if (!methodInstance->mIRFunction)
  17586. {
  17587. BfIRFunction func;
  17588. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  17589. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  17590. {
  17591. if (!mIsReified)
  17592. wantsLLVMFunc = false;
  17593. }*/
  17594. if (wantsLLVMFunc)
  17595. {
  17596. func = GetIntrinsic(methodInstance, true);
  17597. if (func)
  17598. {
  17599. isIntrinsic = true;
  17600. }
  17601. else
  17602. {
  17603. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  17604. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  17605. if (methodInstance->mAlwaysInline)
  17606. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  17607. // if (prevFunc)
  17608. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  17609. }
  17610. methodInstance->mIRFunction = func;
  17611. //if (!ignoreWrites)
  17612. //BF_ASSERT(!func.IsFake());
  17613. }
  17614. }
  17615. if (outIsIntrinsic != NULL)
  17616. *outIsIntrinsic = isIntrinsic;
  17617. if (!isIntrinsic)
  17618. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  17619. }
  17620. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  17621. {
  17622. if (methodInstance->mHotMethod != NULL)
  17623. return;
  17624. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  17625. {
  17626. auto srcTypeInst = methodInstance->GetOwner();
  17627. StringT<128> mangledName = inMangledName;
  17628. if (mangledName.IsEmpty())
  17629. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  17630. // We always keep the current primary method at the same address
  17631. BfHotMethod* hotMethod;
  17632. BfHotMethod** hotMethodPtr;
  17633. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  17634. {
  17635. hotMethod = new BfHotMethod();
  17636. *hotMethodPtr = hotMethod;
  17637. hotMethod->mRefCount = 1;
  17638. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  17639. #ifdef BF_DBG_HOTMETHOD_IDX
  17640. static int sMethodIdx = 0;
  17641. hotMethod->mMethodIdx = sMethodIdx++;
  17642. #endif
  17643. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  17644. }
  17645. else
  17646. {
  17647. hotMethod = *hotMethodPtr;
  17648. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  17649. {
  17650. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  17651. auto prevHotMethod = *hotMethodPtr;
  17652. hotMethod = new BfHotMethod();
  17653. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  17654. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  17655. hotDupMethod->mRefCount++;
  17656. prevHotMethod->mReferences.Add(hotDupMethod);
  17657. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  17658. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  17659. }
  17660. else if (mCompiler->IsHotCompile())
  17661. {
  17662. // Link the previous version into the mPrevVersion
  17663. BfHotMethod* prevMethod = new BfHotMethod();
  17664. prevMethod->mRefCount = 1;
  17665. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  17666. hotMethod->mPrevVersion = prevMethod;
  17667. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  17668. hotMethod->mSrcTypeVersion = NULL;
  17669. prevMethod->mFlags = hotMethod->mFlags;
  17670. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  17671. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  17672. #ifdef BF_DBG_HOTMETHOD_NAME
  17673. prevMethod->mMangledName = hotMethod->mMangledName;
  17674. #endif
  17675. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  17676. }
  17677. else
  17678. {
  17679. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  17680. hotMethod->Clear(true);
  17681. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  17682. }
  17683. }
  17684. if (methodInstance->mIsClosure)
  17685. {
  17686. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  17687. }
  17688. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  17689. hotMethod->mSrcTypeVersion->mRefCount++;
  17690. hotMethod->mRefCount++;
  17691. #ifdef BF_DBG_HOTMETHOD_NAME
  17692. hotMethod->mMangledName = mangledName;
  17693. #endif
  17694. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!mCompiler->IsHotCompile()))
  17695. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  17696. methodInstance->mHotMethod = hotMethod;
  17697. }
  17698. }
  17699. static void StackOverflow()
  17700. {
  17701. int i = 0;
  17702. if (i == 0)
  17703. StackOverflow();
  17704. }
  17705. // methodDeclaration is NULL for default constructors
  17706. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  17707. {
  17708. BP_ZONE("BfModule::BfMethodDeclaration");
  17709. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  17710. // to effectively make mIgnoreWrites method-scoped
  17711. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  17712. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  17713. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  17714. if (mCompiler->IsAutocomplete())
  17715. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  17716. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  17717. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  17718. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  17719. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  17720. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  17721. if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  17722. {
  17723. BF_ASSERT(mContext->mResolvingVarField);
  17724. isTemporaryFunc = true;
  17725. }
  17726. if (mAwaitingInitFinish)
  17727. FinishInit();
  17728. auto typeInstance = mCurTypeInstance;
  17729. auto typeDef = typeInstance->mTypeDef;
  17730. auto methodDef = mCurMethodInstance->mMethodDef;
  17731. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  17732. if (methodDef->mName == "__FATALERRORNAME")
  17733. BFMODULE_FATAL(this, "__FATALERRORNAME");
  17734. if (methodDef->mName == "__STACKOVERFLOW")
  17735. StackOverflow();
  17736. if (typeInstance->IsClosure())
  17737. {
  17738. if (methodDef->mName == "Invoke")
  17739. return;
  17740. }
  17741. auto methodInstance = mCurMethodInstance;
  17742. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  17743. addToWorkList = false;
  17744. bool hasNonGenericParams = false;
  17745. bool hasGenericParams = false;
  17746. int dependentGenericStartIdx = 0;
  17747. if (methodDef->mIsLocalMethod)
  17748. {
  17749. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  17750. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  17751. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  17752. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  17753. // over the local method each time
  17754. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  17755. dependentGenericStartIdx = 0;
  17756. if (rootMethodInstance->mMethodInfoEx != NULL)
  17757. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  17758. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  17759. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  17760. }
  17761. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  17762. {
  17763. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  17764. if (genericArgType->IsGenericParam())
  17765. {
  17766. hasGenericParams = true;
  17767. auto genericParam = (BfGenericParamType*)genericArgType;
  17768. methodInstance->mIsUnspecialized = true;
  17769. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  17770. methodInstance->mIsUnspecializedVariation = true;
  17771. }
  17772. else
  17773. {
  17774. hasNonGenericParams = true;
  17775. if (genericArgType->IsUnspecializedType())
  17776. {
  17777. methodInstance->mIsUnspecialized = true;
  17778. methodInstance->mIsUnspecializedVariation = true;
  17779. }
  17780. }
  17781. }
  17782. if ((hasGenericParams) && (hasNonGenericParams))
  17783. {
  17784. methodInstance->mIsUnspecializedVariation = true;
  17785. }
  17786. if (typeInstance->IsUnspecializedType())
  17787. {
  17788. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  17789. // actually want to do method processing on it
  17790. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  17791. methodInstance->mIsUnspecializedVariation = true;
  17792. methodInstance->mIsUnspecialized = true;
  17793. }
  17794. //methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  17795. for (auto genericParamDef : methodDef->mGenericParams)
  17796. {
  17797. if (mCompiler->IsAutocomplete())
  17798. {
  17799. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  17800. //autoComplete->CheckTypeRef()
  17801. }
  17802. }
  17803. if (methodInstance->mIsUnspecializedVariation)
  17804. {
  17805. }
  17806. if (methodInstance->mIsUnspecializedVariation)
  17807. BF_ASSERT(methodInstance->mIsUnspecialized);
  17808. if (methodDef->mMethodType == BfMethodType_Mixin)
  17809. methodInstance->mIsUnspecialized = true;
  17810. if (methodInstance->mIsUnspecialized)
  17811. {
  17812. //BF_ASSERT(methodInstance->mDeclModule == methodInstance->GetOwner()->mModule);
  17813. }
  17814. BfAutoComplete* bfAutocomplete = NULL;
  17815. if (mCompiler->mResolvePassData != NULL)
  17816. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  17817. if (methodInstance->mMethodInfoEx != NULL)
  17818. {
  17819. BfTypeInstance* unspecializedTypeInstance = NULL;
  17820. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  17821. {
  17822. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  17823. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  17824. {
  17825. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  17826. }
  17827. else
  17828. {
  17829. auto externConstraintDef = genericParam->GetExternConstraintDef();
  17830. // if (unspecializedTypeInstance == NULL)
  17831. // unspecializedTypeInstance = GetUnspecializedTypeInstance(mCurTypeInstance);
  17832. //
  17833. // // Resolve in the unspecialized type, then resolve the generic later. This fixes ambiguity where the type is specialized by a method generic arg
  17834. // {
  17835. // SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, unspecializedTypeInstance);
  17836. // genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  17837. // }
  17838. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  17839. auto autoComplete = mCompiler->GetAutoComplete();
  17840. if (autoComplete != NULL)
  17841. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  17842. if (genericParam->mExternType != NULL)
  17843. {
  17844. //
  17845. }
  17846. else
  17847. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  17848. }
  17849. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized);
  17850. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  17851. {
  17852. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  17853. if (bfAutocomplete != NULL)
  17854. {
  17855. for (auto nameNode : genericParamDef->mNameNodes)
  17856. {
  17857. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  17858. }
  17859. }
  17860. }
  17861. }
  17862. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  17863. {
  17864. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  17865. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  17866. if (genericParam->mTypeConstraint != NULL)
  17867. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  17868. }
  17869. }
  17870. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  17871. {
  17872. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  17873. BfAstNode* nameNode = methodDeclaration->mNameNode;
  17874. if (nameNode == NULL)
  17875. {
  17876. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  17877. nameNode = ctorDeclaration->mThisToken;
  17878. }
  17879. if (autoComplete->IsAutocompleteNode(nameNode))
  17880. {
  17881. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  17882. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  17883. autoComplete->mDefType = typeDef;
  17884. autoComplete->mDefMethod = methodDef;
  17885. autoComplete->SetDefinitionLocation(nameNode);
  17886. if (methodDef->mIsOverride)
  17887. {
  17888. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  17889. {
  17890. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  17891. if (ventry.mDeclaringMethod.mMethodNum == -1)
  17892. continue;
  17893. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  17894. if (virtMethod != NULL)
  17895. {
  17896. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  17897. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  17898. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  17899. {
  17900. // Is matching method
  17901. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  17902. {
  17903. auto baseType = typeInstance->mBaseType;
  17904. if (baseType != NULL)
  17905. {
  17906. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  17907. baseType = baseType->mBaseType;
  17908. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  17909. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  17910. autoComplete->mDefType = baseType->mTypeDef;
  17911. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  17912. }
  17913. }
  17914. break;
  17915. }
  17916. }
  17917. }
  17918. }
  17919. }
  17920. }
  17921. bool reportErrors = true;
  17922. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  17923. reportErrors = true;
  17924. // Only the defining contexts needs to report errors here
  17925. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  17926. if (methodDef->mMethodType == BfMethodType_Dtor)
  17927. {
  17928. if (methodDef->mIsStatic)
  17929. {
  17930. }
  17931. else
  17932. {
  17933. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  17934. {
  17935. BfAstNode* refNode = methodDeclaration;
  17936. if (refNode == NULL)
  17937. {
  17938. // Whatever caused this ctor to be generated should have caused another failure
  17939. // But that failure might not be generated until the ctor is generated
  17940. }
  17941. else
  17942. {
  17943. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  17944. if (dtorDecl != NULL)
  17945. refNode = dtorDecl->mThisToken;
  17946. Fail("Structs cannot have destructors", refNode);
  17947. }
  17948. }
  17949. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17950. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  17951. (mCurTypeInstance != mContext->mBfObjectType))
  17952. {
  17953. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  17954. }
  17955. }
  17956. }
  17957. BfType* resolvedReturnType = NULL;
  17958. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  17959. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  17960. (methodDef->mReturnTypeRef != NULL))
  17961. {
  17962. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  17963. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  17964. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  17965. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  17966. {
  17967. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  17968. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  17969. }
  17970. if (resolvedReturnType == NULL)
  17971. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  17972. }
  17973. else
  17974. {
  17975. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  17976. }
  17977. BF_ASSERT(resolvedReturnType != NULL);
  17978. mCurMethodInstance->mReturnType = resolvedReturnType;
  17979. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  17980. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  17981. //if (!methodInstance->IsSpecializedGenericMethod())
  17982. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  17983. if (methodDef->mExplicitInterface != NULL)
  17984. {
  17985. auto autoComplete = mCompiler->GetAutoComplete();
  17986. if (autoComplete != NULL)
  17987. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  17988. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  17989. BfTypeInstance* explicitInterface = NULL;
  17990. if (explicitType != NULL)
  17991. explicitInterface = explicitType->ToTypeInstance();
  17992. if (explicitInterface != NULL)
  17993. {
  17994. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  17995. if (autoComplete != NULL)
  17996. {
  17997. BfTokenNode* dotToken = NULL;
  17998. BfAstNode* nameNode = NULL;
  17999. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  18000. {
  18001. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  18002. nameNode = methodDeclaration->mNameNode;
  18003. }
  18004. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  18005. }
  18006. }
  18007. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  18008. {
  18009. bool interfaceFound = false;
  18010. for (auto ifaceInst : typeInstance->mInterfaces)
  18011. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  18012. if (!interfaceFound)
  18013. {
  18014. if (methodDef->mMethodDeclaration != NULL)
  18015. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  18016. else
  18017. {
  18018. // For property decls, we should have already given the error during type population
  18019. if (mCompiler->mRevision == 1)
  18020. AssertErrorState();
  18021. }
  18022. }
  18023. }
  18024. }
  18025. bool isThisStruct = mCurTypeInstance->IsStruct();
  18026. BfType* thisType = NULL;
  18027. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  18028. {
  18029. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  18030. {
  18031. thisType = mCurTypeInstance;
  18032. if (thisType == NULL)
  18033. return;
  18034. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  18035. {
  18036. BfTypeUtils::SplatIterate([&](BfType* checkType)
  18037. {
  18038. PopulateType(checkType, BfPopulateType_Data);
  18039. }, thisType);
  18040. }
  18041. }
  18042. else
  18043. {
  18044. thisType = mCurTypeInstance;
  18045. PopulateType(thisType, BfPopulateType_Declaration);
  18046. }
  18047. }
  18048. int implicitParamCount = 0;
  18049. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  18050. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  18051. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  18052. bool hadDelegateParams = false;
  18053. bool hadParams = false;
  18054. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  18055. {
  18056. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  18057. BfParameterDef* paramDef = NULL;
  18058. int paramDefIdx = -1;
  18059. if (paramIdx < implicitParamCount)
  18060. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  18061. else
  18062. {
  18063. paramDefIdx = paramIdx - implicitParamCount;
  18064. paramDef = methodDef->mParams[paramDefIdx];
  18065. }
  18066. if (hadParams)
  18067. break;
  18068. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  18069. continue;
  18070. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  18071. (paramDef->mParamKind != BfParamKind_AppendIdx))
  18072. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  18073. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  18074. {
  18075. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  18076. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  18077. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  18078. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  18079. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  18080. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  18081. }
  18082. BfType* resolvedParamType = NULL;
  18083. if (closureCaptureEntry != NULL)
  18084. resolvedParamType = closureCaptureEntry->mType;
  18085. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  18086. {
  18087. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  18088. resolvedParamType = mContext->mBfObjectType;
  18089. }
  18090. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  18091. {
  18092. if (methodDef->mMethodType != BfMethodType_Mixin)
  18093. {
  18094. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  18095. resolvedParamType = mContext->mBfObjectType;
  18096. }
  18097. else
  18098. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  18099. }
  18100. BfType* unresolvedParamType = resolvedParamType;
  18101. bool wasGenericParam = false;
  18102. if (resolvedParamType == NULL)
  18103. {
  18104. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  18105. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  18106. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  18107. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  18108. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  18109. resolvedParamType = resolvedParamType->GetUnderlyingType();
  18110. }
  18111. if (resolvedParamType == NULL)
  18112. {
  18113. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  18114. unresolvedParamType = resolvedParamType;
  18115. if (mCurTypeInstance->IsBoxed())
  18116. {
  18117. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  18118. // If we failed a lookup here then we better have also failed it in the original type
  18119. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType->ToTypeInstance()));
  18120. }
  18121. }
  18122. if (!methodInstance->IsSpecializedGenericMethod())
  18123. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  18124. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  18125. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  18126. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  18127. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  18128. {
  18129. if (paramDef->mParamKind == BfParamKind_Params)
  18130. {
  18131. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  18132. if (refNode != NULL)
  18133. refNode = paramDef->mParamDeclaration->mModToken;
  18134. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  18135. }
  18136. BfMethodState methodState;
  18137. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  18138. methodState.mTempKind = BfMethodState::TempKind_Static;
  18139. BfTypedValue defaultValue;
  18140. if (resolvedParamType->IsConstExprValue())
  18141. {
  18142. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  18143. BfExprEvaluator exprEvaluator(this);
  18144. exprEvaluator.mExpectingType = constExprType->mType;
  18145. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  18146. defaultValue = exprEvaluator.GetResult();
  18147. }
  18148. else
  18149. {
  18150. BfConstResolver constResolver(this);
  18151. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  18152. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  18153. {
  18154. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  18155. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  18156. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  18157. {
  18158. defaultValue = castedDefaultValue; // Good!
  18159. }
  18160. else if (!CanCast(defaultValue, resolvedParamType))
  18161. {
  18162. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  18163. // a conversion operator.
  18164. // This should throw an error
  18165. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  18166. AssertErrorState();
  18167. if (!defaultValue.mValue.IsConst())
  18168. defaultValue = BfTypedValue();
  18169. }
  18170. }
  18171. }
  18172. if (!defaultValue)
  18173. {
  18174. defaultValue = GetDefaultTypedValue(resolvedParamType);
  18175. if (!defaultValue.mValue.IsConst())
  18176. defaultValue = BfTypedValue();
  18177. }
  18178. if (defaultValue)
  18179. {
  18180. if (defaultValue.mType->IsVar())
  18181. {
  18182. AssertErrorState();
  18183. }
  18184. else
  18185. {
  18186. BF_ASSERT(defaultValue.mValue.IsConst());
  18187. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  18188. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  18189. CurrentAddToConstHolder(defaultValue.mValue);
  18190. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  18191. }
  18192. }
  18193. }
  18194. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  18195. {
  18196. bool addParams = true;
  18197. bool isValid = false;
  18198. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  18199. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  18200. {
  18201. // Span<T>
  18202. isValid = true;
  18203. }
  18204. else if (resolvedParamType->IsArray())
  18205. {
  18206. // Array is the 'normal' params type
  18207. isValid = true;
  18208. }
  18209. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  18210. {
  18211. hadDelegateParams = true;
  18212. // This means we copy the params from a delegate
  18213. BfMethodParam methodParam;
  18214. methodParam.mResolvedType = resolvedParamType;
  18215. methodParam.mParamDefIdx = paramDefIdx;
  18216. methodParam.mDelegateParamIdx = 0;
  18217. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  18218. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  18219. {
  18220. methodParam.mDelegateParamIdx = delegateParamIdx;
  18221. mCurMethodInstance->mParams.Add(methodParam);
  18222. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  18223. if (!methodInstance->IsSpecializedGenericMethod())
  18224. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  18225. }
  18226. isValid = true;
  18227. addParams = false;
  18228. }
  18229. else if (resolvedParamType->IsGenericParam())
  18230. {
  18231. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  18232. if (genericParamInstance->mTypeConstraint != NULL)
  18233. {
  18234. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  18235. if (genericParamInstance->mTypeConstraint->IsArray())
  18236. {
  18237. BfMethodParam methodParam;
  18238. methodParam.mResolvedType = resolvedParamType;
  18239. methodParam.mParamDefIdx = paramDefIdx;
  18240. mCurMethodInstance->mParams.Add(methodParam);
  18241. isValid = true;
  18242. }
  18243. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  18244. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  18245. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  18246. {
  18247. mCurMethodInstance->mHadGenericDelegateParams = true;
  18248. isValid = true;
  18249. addParams = false;
  18250. }
  18251. }
  18252. }
  18253. else
  18254. {
  18255. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  18256. if ((paramTypeInst != NULL) &&
  18257. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  18258. {
  18259. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  18260. isValid = true;
  18261. addParams = false;
  18262. }
  18263. }
  18264. if (!isValid)
  18265. {
  18266. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  18267. // Failure case, make it an Object[]
  18268. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  18269. }
  18270. if (addParams)
  18271. {
  18272. BfMethodParam methodParam;
  18273. methodParam.mResolvedType = resolvedParamType;
  18274. methodParam.mParamDefIdx = paramDefIdx;
  18275. mCurMethodInstance->mParams.push_back(methodParam);
  18276. }
  18277. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  18278. {
  18279. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  18280. }
  18281. }
  18282. else
  18283. {
  18284. BfMethodParam methodParam;
  18285. methodParam.mResolvedType = resolvedParamType;
  18286. methodParam.mParamDefIdx = paramDefIdx;
  18287. mCurMethodInstance->mParams.Add(methodParam);
  18288. }
  18289. }
  18290. if (hadDelegateParams)
  18291. {
  18292. HashSet<String> usedNames;
  18293. Dictionary<int, int> usedParamDefIdx;
  18294. for (auto methodParam : methodDef->mParams)
  18295. {
  18296. usedNames.Add(methodParam->mName);
  18297. }
  18298. for (auto& methodParam : mCurMethodInstance->mParams)
  18299. {
  18300. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  18301. {
  18302. int* refCount = NULL;
  18303. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  18304. (*refCount)++;
  18305. }
  18306. }
  18307. for (auto& methodParam : mCurMethodInstance->mParams)
  18308. {
  18309. if (methodParam.mDelegateParamIdx != -1)
  18310. {
  18311. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  18312. methodParam.mDelegateParamNameCombine = true;
  18313. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  18314. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  18315. if (usedNames.Contains(paramName))
  18316. methodParam.mDelegateParamNameCombine = true;
  18317. }
  18318. }
  18319. }
  18320. int argIdx = 0;
  18321. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  18322. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  18323. {
  18324. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  18325. auto thisType = methodInstance->GetOwner();
  18326. if (methodInstance->GetParamIsSplat(thisIdx))
  18327. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  18328. else if (!thisType->IsValuelessType())
  18329. {
  18330. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18331. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18332. if (!methodDef->mIsMutating)
  18333. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18334. argIdx++;
  18335. if (loweredTypeCode2 != BfTypeCode_None)
  18336. argIdx++;
  18337. }
  18338. }
  18339. if (methodInstance->GetStructRetIdx() != -1)
  18340. argIdx++;
  18341. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  18342. {
  18343. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  18344. BfType* checkType = methodParam.mResolvedType;
  18345. int checkArgIdx = argIdx;
  18346. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  18347. {
  18348. checkArgIdx = 0;
  18349. checkType = methodInstance->GetThisType();
  18350. }
  18351. if (checkType->IsMethodRef())
  18352. {
  18353. methodParam.mIsSplat = true;
  18354. }
  18355. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting()))
  18356. {
  18357. PopulateType(checkType, BfPopulateType_Data);
  18358. if (checkType->IsSplattable())
  18359. {
  18360. int splatCount = checkType->GetSplatCount();
  18361. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  18362. {
  18363. methodParam.mIsSplat = true;
  18364. argIdx += splatCount;
  18365. continue;
  18366. }
  18367. }
  18368. else if (!checkType->IsValuelessType())
  18369. {
  18370. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18371. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18372. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18373. argIdx++;
  18374. if (loweredTypeCode2 != BfTypeCode_None)
  18375. argIdx++;
  18376. continue;
  18377. }
  18378. }
  18379. argIdx++;
  18380. }
  18381. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  18382. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  18383. {
  18384. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  18385. }
  18386. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  18387. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  18388. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  18389. (!methodDef->mIsSkipCall))
  18390. {
  18391. if (methodDeclaration->mEndSemicolon == NULL)
  18392. {
  18393. AssertParseErrorState();
  18394. }
  18395. else
  18396. {
  18397. bool isError = true;
  18398. if (typeInstance->IsTypedPrimitive())
  18399. {
  18400. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18401. {
  18402. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  18403. {
  18404. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  18405. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  18406. {
  18407. isError = false;
  18408. }
  18409. }
  18410. }
  18411. }
  18412. if (isError)
  18413. {
  18414. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  18415. MethodToString(methodInstance).c_str()),
  18416. methodDef->GetRefNode());
  18417. }
  18418. }
  18419. }
  18420. if (methodDef->IsEmptyPartial())
  18421. hasExternSpecifier = true;
  18422. if (!methodInstance->IsAutocompleteMethod())
  18423. {
  18424. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  18425. int implicitParamCount = methodInstance->GetImplicitParamCount();
  18426. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  18427. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  18428. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  18429. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  18430. int paramIdx = 0;
  18431. int defaultParamIdx = 0;
  18432. while (true)
  18433. {
  18434. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  18435. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  18436. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  18437. {
  18438. paramIdx++;
  18439. continue;
  18440. }
  18441. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  18442. {
  18443. defaultParamIdx++;
  18444. continue;
  18445. }
  18446. if ((isDone) || (isDefaultDone))
  18447. {
  18448. // 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
  18449. // to cause us to throw an assertion in the declaration here
  18450. if (!defaultMethodInstance->mHadGenericDelegateParams)
  18451. BF_ASSERT((isDone) && (isDefaultDone));
  18452. break;
  18453. }
  18454. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  18455. if (paramType->IsRef())
  18456. paramType = paramType->GetUnderlyingType();
  18457. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  18458. paramIdx++;
  18459. defaultParamIdx++;
  18460. }
  18461. }
  18462. StringT<128> mangledName;
  18463. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  18464. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  18465. {
  18466. auto paramType = methodInstance->GetParamType(paramIdx);
  18467. if (paramType->IsComposite())
  18468. PopulateType(paramType, BfPopulateType_Data);
  18469. if (!methodInstance->IsParamSkipped(paramIdx))
  18470. {
  18471. if (paramType->IsStruct())
  18472. {
  18473. //
  18474. }
  18475. else
  18476. {
  18477. PopulateType(paramType, BfPopulateType_Declaration);
  18478. }
  18479. }
  18480. }
  18481. // Only process method in default unspecialized mode, not in variations
  18482. if (methodInstance->mIsUnspecializedVariation)
  18483. return;
  18484. PopulateType(resolvedReturnType, BfPopulateType_Data);
  18485. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  18486. if (resolvedReturnType->IsValuelessType())
  18487. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  18488. if (!mBfIRBuilder->mIgnoreWrites)
  18489. {
  18490. bool isIntrinsic = false;
  18491. if (!methodInstance->mIRFunction)
  18492. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  18493. if (isIntrinsic)
  18494. {
  18495. addToWorkList = false;
  18496. }
  18497. }
  18498. auto func = methodInstance->mIRFunction;
  18499. // if (methodInstance->mIsReified)
  18500. // CheckHotMethod(methodInstance, mangledName);
  18501. 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);
  18502. SizedArray<BfIRMDNode, 8> diParams;
  18503. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  18504. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  18505. {
  18506. //CS0708
  18507. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  18508. }
  18509. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  18510. {
  18511. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  18512. methodDef->mIsVirtual = false;
  18513. }
  18514. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  18515. {
  18516. if (methodDef->mIsStatic)
  18517. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  18518. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  18519. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  18520. else if (methodDef->mMethodType == BfMethodType_Ctor)
  18521. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  18522. else if (methodDef->mMethodType == BfMethodType_Dtor)
  18523. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  18524. }
  18525. if (isTemporaryFunc)
  18526. {
  18527. // This handles temporary methods for autocomplete types
  18528. //BF_ASSERT(mIsScratchModule);
  18529. //BF_ASSERT(mCompiler->IsAutocomplete());
  18530. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  18531. return; // Bail out early for autocomplete pass
  18532. }
  18533. if ((methodInstance->GetImportCallKind() != BfImportCallKind_None) && (!mBfIRBuilder->mIgnoreWrites) && (!methodInstance->mIRFunction))
  18534. {
  18535. BfLogSysM("DllImportGlobalVar DoMethodDeclaration processing %p\n", methodInstance);
  18536. // If this is in an extension then we did create the global variable already in the original obj
  18537. bool doDefine = mExtensionCount == 0;
  18538. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, doDefine);
  18539. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  18540. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  18541. }
  18542. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  18543. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  18544. // autocompleter. Why did we have this check anyway?
  18545. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  18546. {
  18547. AddMethodReference(methodInstance);
  18548. mFuncReferences[methodInstance] = func;
  18549. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  18550. }*/
  18551. if (mParentModule != NULL)
  18552. {
  18553. // For extension modules we need to keep track of our own methods so we can know which methods
  18554. // we have defined ourselves and which are from the parent module or other extensions
  18555. if (!func.IsFake())
  18556. mFuncReferences[methodInstance] = func;
  18557. }
  18558. if (addToWorkList)
  18559. {
  18560. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  18561. if (wasAwaitingDecl)
  18562. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  18563. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  18564. {
  18565. if (!wasAwaitingDecl)
  18566. AddMethodToWorkList(methodInstance);
  18567. }
  18568. else
  18569. {
  18570. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  18571. methodInstance->mIgnoreBody = true;
  18572. if (typeInstance->IsUnspecializedType())
  18573. {
  18574. // Don't hold on to actual Function for unspecialized types
  18575. methodInstance->mIRFunction = BfIRFunction();
  18576. }
  18577. }
  18578. }
  18579. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  18580. (!methodDef->mIsLocalMethod) &&
  18581. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  18582. (!methodDef->mReturnTypeRef->IsTemporary()))
  18583. {
  18584. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  18585. {
  18586. //TODO:
  18587. //CS0053
  18588. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  18589. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  18590. methodDef->mReturnTypeRef, true);
  18591. }
  18592. else
  18593. {
  18594. //CS0050
  18595. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  18596. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  18597. methodDef->mReturnTypeRef, true);
  18598. }
  18599. }
  18600. if (typeInstance->IsInterface())
  18601. {
  18602. if (methodDef->mMethodType == BfMethodType_Ctor)
  18603. Fail("Interfaces cannot contain constructors", methodDeclaration);
  18604. if (methodDeclaration != NULL)
  18605. {
  18606. if (methodDef->mBody == NULL)
  18607. {
  18608. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  18609. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  18610. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  18611. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  18612. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  18613. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  18614. }
  18615. }
  18616. }
  18617. bool foundHiddenMethod = false;
  18618. // Don't compare specialized generic methods against normal methods
  18619. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  18620. (!methodDef->mIsLocalMethod))
  18621. {
  18622. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  18623. {
  18624. typeDef->PopulateMemberSets();
  18625. BfMethodDef* nextMethod = NULL;
  18626. BfMemberSetEntry* entry = NULL;
  18627. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  18628. nextMethod = (BfMethodDef*)entry->mMemberDef;
  18629. while (nextMethod != NULL)
  18630. {
  18631. auto checkMethod = nextMethod;
  18632. nextMethod = nextMethod->mNextWithSameName;
  18633. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  18634. {
  18635. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  18636. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  18637. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  18638. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  18639. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  18640. {
  18641. bool canChain = false;
  18642. if ((methodDef->mParams.empty()) &&
  18643. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  18644. {
  18645. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  18646. canChain = true;
  18647. else if (methodDef->mMethodType == BfMethodType_Normal)
  18648. {
  18649. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  18650. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  18651. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  18652. canChain = true;
  18653. }
  18654. }
  18655. if (canChain)
  18656. {
  18657. bool isBetter;
  18658. bool isWorse;
  18659. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  18660. if (isBetter && !isWorse)
  18661. {
  18662. methodInstance->mChainType = BfMethodChainType_ChainHead;
  18663. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  18664. }
  18665. else
  18666. {
  18667. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  18668. methodInstance->mChainType = BfMethodChainType_ChainMember;
  18669. }
  18670. }
  18671. else
  18672. {
  18673. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  18674. continue;
  18675. bool silentlyAllow = false;
  18676. bool extensionWarn = false;
  18677. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  18678. {
  18679. if (typeInstance->IsInterface())
  18680. {
  18681. if (methodDef->mIsOverride)
  18682. silentlyAllow = true;
  18683. }
  18684. else
  18685. {
  18686. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  18687. {
  18688. silentlyAllow = true;
  18689. methodInstance->mIsInnerOverride = true;
  18690. CheckOverridenMethod(methodInstance, checkMethodInstance);
  18691. }
  18692. else if ((methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject) &&
  18693. (!checkMethod->mDeclaringType->IsExtension()))
  18694. {
  18695. foundHiddenMethod = true;
  18696. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  18697. silentlyAllow = true;
  18698. else if (methodDef->mIsNew)
  18699. silentlyAllow = true;
  18700. else
  18701. extensionWarn = true;
  18702. }
  18703. else
  18704. silentlyAllow = true;
  18705. }
  18706. }
  18707. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  18708. silentlyAllow = true;
  18709. if (!silentlyAllow)
  18710. {
  18711. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  18712. {
  18713. auto refNode = methodDef->GetRefNode();
  18714. BfError* bfError;
  18715. if (extensionWarn)
  18716. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  18717. 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'.",
  18718. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  18719. else
  18720. bfError = Fail("Method already declared with the same parameter types", refNode, true);
  18721. if (bfError != NULL)
  18722. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  18723. }
  18724. }
  18725. }
  18726. }
  18727. }
  18728. }
  18729. }
  18730. // Virtual methods give their error while slotting
  18731. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  18732. (!methodDef->mIsLocalMethod) &&
  18733. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  18734. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  18735. {
  18736. auto baseType = typeInstance->mBaseType;
  18737. while (baseType != NULL)
  18738. {
  18739. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  18740. auto baseTypeDef = baseType->mTypeDef;
  18741. baseTypeDef->PopulateMemberSets();
  18742. BfMethodDef* checkMethod = NULL;
  18743. BfMemberSetEntry* entry = NULL;
  18744. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  18745. checkMethod = (BfMethodDef*)entry->mMemberDef;
  18746. while (checkMethod != NULL)
  18747. {
  18748. if (checkMethod->mMethodDeclaration == NULL)
  18749. continue;
  18750. if (baseType->mMethodInstanceGroups.size() == 0)
  18751. {
  18752. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  18753. break;
  18754. }
  18755. if (checkMethod == methodDef)
  18756. continue;
  18757. if (checkMethod->mName != methodDef->mName)
  18758. continue;
  18759. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  18760. if (checkMethodInstance != NULL)
  18761. {
  18762. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  18763. (checkMethod->mProtection != BfProtection_Private) &&
  18764. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  18765. {
  18766. if (!methodDef->mIsNew)
  18767. {
  18768. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  18769. if (refNode != NULL)
  18770. {
  18771. 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?
  18772. if (bfError != NULL)
  18773. bfError->mIsPersistent = true;
  18774. }
  18775. }
  18776. foundHiddenMethod = true;
  18777. break;
  18778. }
  18779. }
  18780. checkMethod = checkMethod->mNextWithSameName;
  18781. }
  18782. if (foundHiddenMethod)
  18783. break;
  18784. baseType = baseType->mBaseType;
  18785. }
  18786. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  18787. {
  18788. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18789. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  18790. methodDeclaration->mNewSpecifier;
  18791. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  18792. }
  18793. }
  18794. }
  18795. mCompiler->mStats.mMethodDeclarations++;
  18796. mCompiler->UpdateCompletion();
  18797. }
  18798. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  18799. {
  18800. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  18801. auto typeInstance = mCurTypeInstance;
  18802. auto methodDef = methodInstance->mMethodDef;
  18803. int virtualMethodMatchIdx = -1;
  18804. if (typeInstance->mHotTypeData != NULL)
  18805. {
  18806. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  18807. {
  18808. BF_ASSERT(mCompiler->IsHotCompile());
  18809. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  18810. // may slot this override anyway (?)
  18811. int vTableStart = 0;
  18812. auto implBaseType = typeInstance->GetImplBaseType();
  18813. if (implBaseType != NULL)
  18814. vTableStart = implBaseType->mVirtualMethodTableSize;
  18815. StringT<128> mangledName;
  18816. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  18817. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  18818. {
  18819. // O(1) checking when virtual methods haven't changed
  18820. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  18821. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  18822. if (mangledName == entry.mFuncName)
  18823. {
  18824. virtualMethodMatchIdx = vTableStart + checkIdx;
  18825. break;
  18826. }
  18827. }
  18828. if (virtualMethodMatchIdx != -1)
  18829. {
  18830. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  18831. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  18832. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  18833. }
  18834. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  18835. }
  18836. }
  18837. if (virtualMethodMatchIdx == -1)
  18838. {
  18839. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  18840. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  18841. typeInstance->mVirtualMethodTable.push_back(entry);
  18842. }
  18843. }
  18844. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  18845. {
  18846. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  18847. {
  18848. // When we provide an extension override in the same project a root type override
  18849. isBetter = true;
  18850. isWorse = false;
  18851. }
  18852. else
  18853. {
  18854. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  18855. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  18856. }
  18857. }
  18858. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  18859. {
  18860. BP_ZONE("BfModule::SlotVirtualMethod");
  18861. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  18862. return false;
  18863. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  18864. {
  18865. if (!mCompiler->mOptions.mAllowHotSwapping)
  18866. return;
  18867. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  18868. return;
  18869. if (methodInstance->mHotMethod == NULL)
  18870. CheckHotMethod(methodInstance, "");
  18871. if (methodInstance->mHotMethod == NULL)
  18872. return;
  18873. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  18874. if (declMethodInstance->mHotMethod == NULL)
  18875. CheckHotMethod(declMethodInstance, "");
  18876. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  18877. virtualDecl->mRefCount++;
  18878. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  18879. };
  18880. auto typeInstance = mCurTypeInstance;
  18881. auto typeDef = typeInstance->mTypeDef;
  18882. auto methodDef = methodInstance->mMethodDef;
  18883. auto methodDeclaration = methodDef->GetMethodDeclaration();
  18884. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18885. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  18886. if (methodInstance->mIsInnerOverride)
  18887. return false;
  18888. BfAstNode* declaringNode = methodDeclaration;
  18889. if (propertyMethodDeclaration != NULL)
  18890. declaringNode = propertyMethodDeclaration->mNameNode;
  18891. BfMethodInstance* methodOverriden = NULL;
  18892. bool usedMethod = false;
  18893. BfTokenNode* virtualToken = NULL;
  18894. if (propertyDeclaration != NULL)
  18895. virtualToken = propertyDeclaration->mVirtualSpecifier;
  18896. else if (methodDeclaration != NULL)
  18897. virtualToken = methodDeclaration->mVirtualSpecifier;
  18898. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  18899. {
  18900. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  18901. }
  18902. else if (methodDef->mIsVirtual)
  18903. {
  18904. if (mCompiler->IsHotCompile())
  18905. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  18906. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  18907. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  18908. BfTypeInstance* checkBase = typeInstance;
  18909. // If we are in an extension, look in ourselves first
  18910. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  18911. checkBase = checkBase->mBaseType;
  18912. if (typeInstance->IsValueType())
  18913. {
  18914. if (typeInstance->mBaseType == NULL)
  18915. return false; // It's actually ValueType
  18916. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  18917. if (!methodDef->mIsOverride)
  18918. {
  18919. Fail("Structs cannot have virtual methods", virtualToken, true);
  18920. return false;
  18921. }
  18922. checkBase = mContext->mBfObjectType;
  18923. if (checkBase->mVirtualMethodTableSize == 0)
  18924. PopulateType(checkBase, BfPopulateType_Full);
  18925. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  18926. return false; // System circular ref, don't do struct checking on those
  18927. }
  18928. int virtualMethodMatchIdx = -1;
  18929. bool hadHidingError = false;
  18930. BfMethodInstance* bestOverrideMethodInstance = NULL;
  18931. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  18932. int bestOverrideMethodIdx = -1;
  18933. int ambiguousOverrideMethodIdx = -1;
  18934. if (checkBase != NULL)
  18935. {
  18936. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  18937. auto lookupType = checkBase;
  18938. while (lookupType != NULL)
  18939. {
  18940. lookupType->mTypeDef->PopulateMemberSets();
  18941. BfMethodDef* nextMethodDef = NULL;
  18942. BfMemberSetEntry* entry;
  18943. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  18944. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  18945. while (nextMethodDef != NULL)
  18946. {
  18947. auto checkMethodDef = nextMethodDef;
  18948. nextMethodDef = nextMethodDef->mNextWithSameName;
  18949. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  18950. continue;
  18951. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  18952. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  18953. continue;
  18954. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  18955. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  18956. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  18957. {
  18958. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  18959. continue;
  18960. }
  18961. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18962. if (baseMethodInstance == NULL)
  18963. {
  18964. AssertErrorState();
  18965. continue;
  18966. }
  18967. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  18968. {
  18969. if (methodDef->mIsOverride)
  18970. {
  18971. BfMethodInstance* checkMethodInstance;
  18972. if (typeInstance->IsValueType())
  18973. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18974. else
  18975. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18976. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  18977. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  18978. continue;
  18979. if (bestOverrideMethodInstance != NULL)
  18980. {
  18981. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  18982. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  18983. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  18984. if (isBetter == isWorse)
  18985. {
  18986. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  18987. }
  18988. else
  18989. {
  18990. if (isWorse)
  18991. continue;
  18992. ambiguousOverrideMethodInstance = NULL;
  18993. }
  18994. }
  18995. bestOverrideMethodInstance = checkMethodInstance;
  18996. bestOverrideMethodIdx = checkMethodIdx;
  18997. }
  18998. else
  18999. {
  19000. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  19001. {
  19002. if (!hadHidingError)
  19003. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  19004. hadHidingError = true;
  19005. }
  19006. }
  19007. }
  19008. }
  19009. lookupType = lookupType->mBaseType;
  19010. }
  19011. }
  19012. //TODO:
  19013. if ((checkBase != NULL)
  19014. && (false)
  19015. )
  19016. {
  19017. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  19018. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  19019. {
  19020. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  19021. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  19022. {
  19023. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  19024. continue;
  19025. }
  19026. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  19027. if (baseMethodInstance == NULL)
  19028. {
  19029. AssertErrorState();
  19030. continue;
  19031. }
  19032. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  19033. {
  19034. if (methodDef->mIsOverride)
  19035. {
  19036. BfMethodInstance* checkMethodInstance;
  19037. if (typeInstance->IsValueType())
  19038. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  19039. else
  19040. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  19041. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  19042. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  19043. continue;
  19044. if (bestOverrideMethodInstance != NULL)
  19045. {
  19046. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  19047. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  19048. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  19049. if (isBetter == isWorse)
  19050. {
  19051. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  19052. }
  19053. else
  19054. {
  19055. if (isWorse)
  19056. continue;
  19057. ambiguousOverrideMethodInstance = NULL;
  19058. }
  19059. }
  19060. bestOverrideMethodInstance = checkMethodInstance;
  19061. bestOverrideMethodIdx = checkMethodIdx;
  19062. }
  19063. else
  19064. {
  19065. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  19066. {
  19067. if (!hadHidingError)
  19068. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  19069. hadHidingError = true;
  19070. }
  19071. }
  19072. }
  19073. }
  19074. }
  19075. if (bestOverrideMethodInstance != NULL)
  19076. {
  19077. if (ambiguousOverrideMethodInstance != NULL)
  19078. {
  19079. bool allow = false;
  19080. // 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.
  19081. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  19082. bool canSeeEachOther = false;
  19083. //
  19084. {
  19085. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  19086. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  19087. canSeeEachOther = true;
  19088. }
  19089. //
  19090. {
  19091. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  19092. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  19093. canSeeEachOther = true;
  19094. }
  19095. if (!canSeeEachOther)
  19096. {
  19097. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  19098. }
  19099. else
  19100. {
  19101. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  19102. if (error != NULL)
  19103. {
  19104. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  19105. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  19106. }
  19107. }
  19108. }
  19109. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  19110. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  19111. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  19112. {
  19113. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  19114. {
  19115. BfTypeReference* returnTypeRef;
  19116. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  19117. {
  19118. returnTypeRef = propertyDeclaration->mTypeRef;
  19119. Fail("Property differs from overridden property by type", returnTypeRef, true);
  19120. }
  19121. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  19122. {
  19123. returnTypeRef = methodDeclaration->mReturnType;
  19124. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  19125. }
  19126. else
  19127. {
  19128. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  19129. }
  19130. return usedMethod;
  19131. }
  19132. }
  19133. if (methodDef->mIsOverride)
  19134. {
  19135. // We can have multiple matches when a virtual method is used to implement interface methods
  19136. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  19137. // vtable entries for this method signature
  19138. virtualMethodMatchIdx = bestOverrideMethodIdx;
  19139. if (!typeInstance->IsValueType())
  19140. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  19141. if (typeInstance->IsValueType())
  19142. {
  19143. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  19144. }
  19145. else
  19146. {
  19147. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  19148. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  19149. BfMethodInstance* setMethodInstance = methodInstance;
  19150. bool doOverride = false;
  19151. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  19152. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  19153. {
  19154. methodOverriden = overridenRef;
  19155. doOverride = true;
  19156. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  19157. {
  19158. bool isBetter = false;
  19159. bool isWorse = false;
  19160. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  19161. if (isBetter == isWorse)
  19162. {
  19163. // We have to resolve later per-project
  19164. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  19165. {
  19166. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  19167. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  19168. }
  19169. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  19170. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  19171. doOverride = false;
  19172. }
  19173. else
  19174. {
  19175. if ((isBetter) && (ambiguityContext != NULL))
  19176. {
  19177. ambiguityContext->Remove(virtualMethodMatchIdx);
  19178. }
  19179. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  19180. {
  19181. if (preferRootDefinition)
  19182. {
  19183. // Leave the master GCMarkMember
  19184. isBetter = false;
  19185. isWorse = true;
  19186. }
  19187. }
  19188. doOverride = isBetter;
  19189. }
  19190. }
  19191. }
  19192. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  19193. {
  19194. methodOverriden = overridenRef;
  19195. doOverride = true;
  19196. }
  19197. if (doOverride)
  19198. {
  19199. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  19200. _AddVirtualDecl(declMethodInstance);
  19201. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  19202. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  19203. }
  19204. }
  19205. if (methodOverriden != NULL)
  19206. {
  19207. CheckOverridenMethod(methodInstance, methodOverriden);
  19208. }
  19209. }
  19210. }
  19211. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  19212. {
  19213. if (methodDef->mIsOverride)
  19214. {
  19215. BfTokenNode* overrideToken = NULL;
  19216. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  19217. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  19218. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  19219. overrideToken = methodDeclaration->mVirtualSpecifier;
  19220. if (overrideToken != NULL)
  19221. {
  19222. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  19223. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  19224. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  19225. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  19226. else
  19227. Fail("No suitable method found to override", overrideToken, true);
  19228. }
  19229. return usedMethod;
  19230. }
  19231. UniqueSlotVirtualMethod(methodInstance);
  19232. }
  19233. else
  19234. usedMethod = true;
  19235. if (typeInstance->IsValueType())
  19236. return usedMethod;
  19237. }
  19238. bool foundInterface = false;
  19239. bool hadAnyMatch = false;
  19240. // See if this method matches interfaces
  19241. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  19242. {
  19243. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  19244. if (ifaceInst->IsIncomplete())
  19245. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  19246. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  19247. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  19248. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  19249. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  19250. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  19251. continue;
  19252. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  19253. continue;
  19254. bool hadMatch = false;
  19255. BfMethodInstance* hadNameMatch = NULL;
  19256. BfType* expectedReturnType = NULL;
  19257. bool showedError = false;
  19258. // We go through our VTable looking for NULL entries within the interface sections
  19259. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  19260. // because a normal method declared in this type could have matched earlier
  19261. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  19262. ifaceInst->mTypeDef->PopulateMemberSets();
  19263. BfMethodDef* checkMethodDef = NULL;
  19264. BfMemberSetEntry* entry;
  19265. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  19266. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  19267. while (checkMethodDef != NULL)
  19268. {
  19269. int iMethodIdx = checkMethodDef->mIdx;
  19270. int iTableIdx = iMethodIdx + startIdx;
  19271. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  19272. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  19273. bool storeIFaceMethod = false;
  19274. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  19275. {
  19276. checkMethodDef = checkMethodDef->mNextWithSameName;
  19277. continue;
  19278. }
  19279. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  19280. auto iMethodInst = iMethodGroup.mDefault;
  19281. if (iMethodInst == NULL)
  19282. {
  19283. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  19284. AssertErrorState();
  19285. checkMethodDef = checkMethodDef->mNextWithSameName;
  19286. continue;
  19287. }
  19288. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  19289. hadNameMatch = iMethodInst;
  19290. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  19291. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  19292. {
  19293. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  19294. }
  19295. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  19296. {
  19297. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  19298. {
  19299. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  19300. {
  19301. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  19302. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  19303. if (error != NULL)
  19304. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  19305. showedError = true;
  19306. }
  19307. }
  19308. }
  19309. if (doesMethodSignatureMatch)
  19310. {
  19311. usedMethod = true;
  19312. hadMatch = true;
  19313. hadAnyMatch = true;
  19314. storeIFaceMethod = true;
  19315. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  19316. {
  19317. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  19318. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  19319. {
  19320. // When autocompletion regenerates a single method body but not the whole type then
  19321. // we will see ourselves in the vtable already
  19322. return usedMethod;
  19323. }
  19324. bool isBetter = false;
  19325. bool isWorse = false;
  19326. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  19327. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  19328. if (isBetter == isWorse)
  19329. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  19330. if (isBetter == isWorse)
  19331. {
  19332. if (ambiguityContext != NULL)
  19333. {
  19334. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  19335. }
  19336. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  19337. storeIFaceMethod = true;
  19338. }
  19339. else
  19340. {
  19341. if ((isBetter) && (ambiguityContext != NULL))
  19342. ambiguityContext->Remove(~iTableIdx);
  19343. storeIFaceMethod = isBetter;
  19344. }
  19345. }
  19346. }
  19347. if (storeIFaceMethod)
  19348. {
  19349. if (methodInstance->GetNumGenericParams() != 0)
  19350. _AddVirtualDecl(iMethodInst);
  19351. *iMethodPtr = methodInstance;
  19352. }
  19353. checkMethodDef = checkMethodDef->mNextWithSameName;
  19354. }
  19355. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  19356. {
  19357. if (expectedReturnType != NULL)
  19358. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  19359. else if (hadNameMatch != NULL)
  19360. {
  19361. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  19362. if (error != NULL)
  19363. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  19364. }
  19365. else
  19366. {
  19367. auto propertyDecl = methodDef->GetPropertyDeclaration();
  19368. if (propertyDecl != NULL)
  19369. {
  19370. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  19371. String name;
  19372. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  19373. name = "this[]";
  19374. else if (propertyDecl->mNameNode != NULL)
  19375. propertyDecl->mNameNode->ToString(name);
  19376. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  19377. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  19378. }
  19379. else
  19380. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  19381. }
  19382. }
  19383. }
  19384. // Any overriden virtual methods that were used in interfaces also need to be replaced
  19385. if (methodOverriden != NULL)
  19386. {
  19387. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  19388. {
  19389. if (methodEntry.mMethodRef == methodOverriden)
  19390. methodEntry.mMethodRef = methodInstance;
  19391. }
  19392. }
  19393. return usedMethod;
  19394. }
  19395. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  19396. {
  19397. auto methodDef = methodInstance->mMethodDef;
  19398. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  19399. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  19400. {
  19401. const char* protectionNames[] = { "hidden", "private", "internal", "protected", "public" };
  19402. BfAstNode* protectionRefNode = NULL;
  19403. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  19404. {
  19405. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  19406. if (protectionRefNode == NULL)
  19407. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  19408. if (protectionRefNode == NULL)
  19409. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  19410. }
  19411. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  19412. {
  19413. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  19414. if (protectionRefNode == NULL)
  19415. protectionRefNode = methodDeclaration->mNameNode;
  19416. }
  19417. if (protectionRefNode != NULL)
  19418. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  19419. }
  19420. }
  19421. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  19422. {
  19423. auto typeInstance = mCurTypeInstance;
  19424. auto methodDef = methodInstance->mMethodDef;
  19425. if (methodDef->mMethodType == BfMethodType_Ctor)
  19426. return true;
  19427. bool foundOverride = false;
  19428. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  19429. {
  19430. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  19431. }
  19432. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  19433. {
  19434. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  19435. }
  19436. BfAstNode* declaringNode = methodDef->GetRefNode();
  19437. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  19438. {
  19439. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  19440. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  19441. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  19442. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  19443. continue;
  19444. ifaceInst->mTypeDef->PopulateMemberSets();
  19445. BfMethodDef* nextMethod = NULL;
  19446. BfMemberSetEntry* entry = NULL;
  19447. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  19448. nextMethod = (BfMethodDef*)entry->mMemberDef;
  19449. while (nextMethod != NULL)
  19450. {
  19451. auto checkMethod = nextMethod;
  19452. nextMethod = nextMethod->mNextWithSameName;
  19453. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  19454. if (ifaceMethod == NULL)
  19455. continue;
  19456. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  19457. {
  19458. if (methodDef->mIsOverride)
  19459. {
  19460. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  19461. {
  19462. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  19463. if (error != NULL)
  19464. {
  19465. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  19466. }
  19467. }
  19468. foundOverride = true;
  19469. }
  19470. else if (!methodDef->mIsNew)
  19471. {
  19472. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  19473. }
  19474. }
  19475. }
  19476. }
  19477. if ((methodDef->mIsOverride) && (!foundOverride))
  19478. {
  19479. // This allows us to declare a method in the base definition or in an extension and then provide
  19480. // an implementation in a more-specific extension
  19481. typeInstance->mTypeDef->PopulateMemberSets();
  19482. BfMethodDef* nextMethod = NULL;
  19483. BfMemberSetEntry* entry = NULL;
  19484. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  19485. nextMethod = (BfMethodDef*)entry->mMemberDef;
  19486. while (nextMethod != NULL)
  19487. {
  19488. auto checkMethod = nextMethod;
  19489. nextMethod = nextMethod->mNextWithSameName;
  19490. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  19491. if (ifaceMethod == NULL)
  19492. continue;
  19493. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  19494. continue;
  19495. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  19496. {
  19497. foundOverride = true;
  19498. }
  19499. }
  19500. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  19501. // {
  19502. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  19503. // if (ifaceMethod == NULL)
  19504. // continue;
  19505. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  19506. // continue;
  19507. //
  19508. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  19509. // {
  19510. // foundOverride = true;
  19511. // }
  19512. // }
  19513. }
  19514. if (methodDef->mIsOverride)
  19515. {
  19516. if (!foundOverride)
  19517. {
  19518. BfTokenNode* overrideToken = NULL;
  19519. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  19520. overrideToken = propertyDeclaration->mVirtualSpecifier;
  19521. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  19522. overrideToken = methodDeclaration->mVirtualSpecifier;
  19523. if (overrideToken != NULL)
  19524. {
  19525. Fail("No suitable method found to override", overrideToken, true);
  19526. }
  19527. else
  19528. {
  19529. // Possible cause - DTOR with params
  19530. AssertErrorState();
  19531. }
  19532. }
  19533. return true;
  19534. }
  19535. // Generic methods can't be called virtually
  19536. if (methodInstance->GetNumGenericParams() != 0)
  19537. return true;
  19538. // Only public methods can be called virtually
  19539. if (methodDef->mProtection != BfProtection_Public)
  19540. return true;
  19541. UniqueSlotVirtualMethod(methodInstance);
  19542. return true;
  19543. }
  19544. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  19545. {
  19546. if (methodInstance->mMethodInfoEx == NULL)
  19547. return;
  19548. int wantMinDepth = -1;
  19549. if (mCurTypeInstance != NULL)
  19550. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  19551. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  19552. {
  19553. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  19554. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  19555. wantMinDepth = wantTypeMinDepth;
  19556. }
  19557. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  19558. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  19559. }
  19560. void BfModule::DbgFinish()
  19561. {
  19562. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  19563. return;
  19564. if (mAwaitingInitFinish)
  19565. FinishInit();
  19566. if (mHasForceLinkMarker)
  19567. return;
  19568. String markerName;
  19569. BfIRValue linkMarker;
  19570. if (mBfIRBuilder->DbgHasInfo())
  19571. {
  19572. bool needForceLinking = false;
  19573. for (auto& ownedType : mOwnedTypeInstances)
  19574. {
  19575. bool hasConfirmedReference = false;
  19576. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  19577. {
  19578. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  19579. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  19580. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  19581. {
  19582. hasConfirmedReference = true;
  19583. }
  19584. }
  19585. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  19586. needForceLinking = true;
  19587. }
  19588. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  19589. {
  19590. BfMethodState methodState;
  19591. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  19592. methodState.mTempKind = BfMethodState::TempKind_Static;
  19593. mHasForceLinkMarker = true;
  19594. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  19595. SizedArray<BfIRType, 0> paramTypes;
  19596. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  19597. String linkName = "FORCELINKMOD_" + mModuleName;
  19598. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  19599. mBfIRBuilder->SetActiveFunction(func);
  19600. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  19601. mBfIRBuilder->SetInsertPoint(entryBlock);
  19602. auto firstType = mOwnedTypeInstances[0];
  19603. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  19604. SizedArray<BfIRMDNode, 1> diParamTypes;
  19605. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  19606. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  19607. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  19608. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  19609. methodState.mCurScope->mDIScope = diScope;
  19610. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  19611. SizedArray<BfIRValue, 8> args;
  19612. BfExprEvaluator exprEvaluator(this);
  19613. for (auto& ownedType : mOwnedTypeInstances)
  19614. {
  19615. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  19616. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  19617. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  19618. }
  19619. mBfIRBuilder->CreateRetVoid();
  19620. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  19621. }
  19622. }
  19623. }
  19624. bool BfModule::Finish()
  19625. {
  19626. BP_ZONE("BfModule::Finish");
  19627. BfLogSysM("BfModule finish: %p\n", this);
  19628. if (mHadBuildError)
  19629. {
  19630. // Don't AssertErrorState here, this current pass may not have failed but
  19631. // the module was still queued in mFinishedModuleWorkList
  19632. ClearModule();
  19633. return true;
  19634. }
  19635. if (mUsedSlotCount != -1)
  19636. {
  19637. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  19638. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  19639. }
  19640. BF_ASSERT(mAddedToCount);
  19641. mAddedToCount = false;
  19642. mAwaitingFinish = false;
  19643. mCompiler->mStats.mModulesFinished++;
  19644. if (HasCompiledOutput())
  19645. {
  19646. DbgFinish();
  19647. if (mAwaitingInitFinish)
  19648. FinishInit();
  19649. for (auto ownedTypeInst : mOwnedTypeInstances)
  19650. {
  19651. // Generate dbg info and add global variables if we haven't already
  19652. mBfIRBuilder->PopulateType(ownedTypeInst);
  19653. }
  19654. if (mBfIRBuilder->DbgHasInfo())
  19655. {
  19656. mBfIRBuilder->DbgFinalize();
  19657. }
  19658. String objOutputPath;
  19659. String irOutputPath;
  19660. mIsModuleMutable = false;
  19661. //mOutFileNames.Clear();
  19662. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  19663. bool writeModule = mBfIRBuilder->HasExports();
  19664. String outputPath;
  19665. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  19666. auto& compilerOpts = mCompiler->mOptions;
  19667. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  19668. auto moduleOptions = GetModuleOptions();
  19669. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  19670. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  19671. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  19672. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  19673. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  19674. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  19675. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  19676. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  19677. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  19678. bool allowWriteToLib = true;
  19679. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  19680. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  19681. {
  19682. codeGenOptions.mWriteToLib = true;
  19683. mWroteToLib = true;
  19684. }
  19685. else
  19686. {
  19687. mWroteToLib = false;
  19688. }
  19689. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  19690. {
  19691. outputPath = mModuleName;
  19692. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  19693. BfModuleFileName moduleFileName;
  19694. if (mParentModule != NULL)
  19695. {
  19696. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  19697. {
  19698. if (checkPair.mValue == this)
  19699. moduleFileName.mProjects = checkPair.mKey;
  19700. }
  19701. }
  19702. moduleFileName.mProjects.Add(mProject);
  19703. if (fileIdx > 0)
  19704. outputPath += StrFormat("@%d", fileIdx + 1);
  19705. if (mCompiler->mOptions.mWriteIR)
  19706. irOutputPath = outputPath + ".ll";
  19707. if (mCompiler->mOptions.mGenerateObj)
  19708. {
  19709. objOutputPath = outputPath + BF_OBJ_EXT;
  19710. moduleFileName.mFileName = objOutputPath;
  19711. }
  19712. else if (mCompiler->mOptions.mWriteIR)
  19713. {
  19714. moduleFileName.mFileName = irOutputPath;
  19715. }
  19716. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  19717. {
  19718. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  19719. }
  19720. moduleFileName.mModuleWritten = writeModule;
  19721. moduleFileName.mWroteToLib = mWroteToLib;
  19722. if (!mOutFileNames.Contains(moduleFileName))
  19723. mOutFileNames.Add(moduleFileName);
  19724. }
  19725. if (mCompiler->IsHotCompile())
  19726. {
  19727. codeGenOptions.mIsHotCompile = true;
  19728. if (mParentModule != NULL)
  19729. mParentModule->mHadHotObjectWrites = true;
  19730. mHadHotObjectWrites = true;
  19731. }
  19732. //TODO: Testing VDATA
  19733. /*if (mModuleName == "vdata")
  19734. {
  19735. codeGenOptions.mOptLevel = 4;
  19736. }*/
  19737. codeGenOptions.GenerateHash();
  19738. BP_ZONE("BfModule::Finish.WriteObjectFile");
  19739. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  19740. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  19741. mLastModuleWrittenRevision = mCompiler->mRevision;
  19742. }
  19743. else
  19744. {
  19745. for (auto type : mOwnedTypeInstances)
  19746. {
  19747. BF_ASSERT(!type->IsIncomplete());
  19748. }
  19749. }
  19750. for (auto& specModulePair : mSpecializedMethodModules)
  19751. {
  19752. auto specModule = specModulePair.mValue;
  19753. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  19754. {
  19755. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  19756. }
  19757. }
  19758. CleanupFileInstances();
  19759. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  19760. return true;
  19761. }
  19762. void BfModule::ReportMemory(MemReporter* memReporter)
  19763. {
  19764. memReporter->Add(sizeof(BfModule));
  19765. if (mBfIRBuilder != NULL)
  19766. {
  19767. memReporter->BeginSection("IRBuilder_ConstData");
  19768. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  19769. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  19770. memReporter->EndSection();
  19771. memReporter->BeginSection("IRBuilder_BFIR");
  19772. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  19773. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  19774. memReporter->EndSection();
  19775. memReporter->Add(sizeof(BfIRBuilder));
  19776. }
  19777. memReporter->BeginSection("FileInstanceMap");
  19778. memReporter->AddMap(mFileInstanceMap);
  19779. memReporter->AddMap(mNamedFileInstanceMap);
  19780. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  19781. memReporter->EndSection();
  19782. memReporter->AddVec(mOwnedTypeInstances, false);
  19783. memReporter->AddVec(mSpecializedMethodModules, false);
  19784. memReporter->AddVec(mOutFileNames, false);
  19785. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  19786. memReporter->AddMap(mInterfaceSlotRefs, false);
  19787. memReporter->AddMap(mStaticFieldRefs, false);
  19788. memReporter->AddMap(mClassVDataRefs, false);
  19789. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  19790. memReporter->AddMap(mTypeDataRefs, false);
  19791. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  19792. memReporter->AddMap(mDeferredMethodCallData, false);
  19793. memReporter->AddHashSet(mDeferredMethodIds, false);
  19794. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  19795. }
  19796. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  19797. // be transient through the next compile
  19798. void BfModule::ClearModuleData(bool clearTransientData)
  19799. {
  19800. BfLogSysM("ClearModuleData %p\n", this);
  19801. if (mAddedToCount)
  19802. {
  19803. mCompiler->mStats.mModulesFinished++;
  19804. mAddedToCount = false;
  19805. }
  19806. mDICompileUnit = BfIRMDNode();
  19807. mIsModuleMutable = false;
  19808. if (clearTransientData)
  19809. mIncompleteMethodCount = 0;
  19810. mHasGenericMethods = false;
  19811. // We don't want to clear these because we want it to persist through module extensions-
  19812. // otherwise we may think an extension succeeds even though the base module failed
  19813. //mHadBuildError = false;
  19814. //mHadBuildWarning = false;
  19815. mClassVDataRefs.Clear();
  19816. mClassVDataExtRefs.Clear();
  19817. for (auto& kv : mTypeDataRefs)
  19818. kv.mValue = BfIRValue();
  19819. mStringCharPtrPool.Clear();
  19820. mStringObjectPool.Clear();
  19821. mStaticFieldRefs.Clear();
  19822. BF_ASSERT(!mIgnoreErrors);
  19823. for (auto prevIRBuilder : mPrevIRBuilders)
  19824. delete prevIRBuilder;
  19825. mPrevIRBuilders.Clear();
  19826. for (auto& specPair : mSpecializedMethodModules)
  19827. {
  19828. auto specModule = specPair.mValue;
  19829. specModule->ClearModuleData();
  19830. }
  19831. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  19832. mBuiltInFuncs[i] = BfIRFunction();
  19833. if (mNextAltModule != NULL)
  19834. mNextAltModule->ClearModuleData();
  19835. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  19836. delete mBfIRBuilder;
  19837. mBfIRBuilder = NULL;
  19838. mWantsIRIgnoreWrites = false;
  19839. }
  19840. void BfModule::DisownMethods()
  19841. {
  19842. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  19843. mBuiltInFuncs[i] = BfIRFunction();
  19844. BfModule* methodModule = this;
  19845. if (mParentModule != NULL)
  19846. methodModule = mParentModule;
  19847. for (auto typeInst : methodModule->mOwnedTypeInstances)
  19848. {
  19849. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  19850. {
  19851. if (methodGroup.mDefault != NULL)
  19852. {
  19853. if (methodGroup.mDefault->mIRFunction)
  19854. {
  19855. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  19856. if (methodGroup.mDefault->mDeclModule == this)
  19857. {
  19858. methodGroup.mDefault->mIRFunction = BfIRFunction();
  19859. }
  19860. }
  19861. }
  19862. if (methodGroup.mMethodSpecializationMap != NULL)
  19863. {
  19864. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  19865. {
  19866. auto methodInstance = mapPair.mValue;
  19867. if (methodInstance->mDeclModule == this)
  19868. {
  19869. methodInstance->mIRFunction = BfIRFunction();
  19870. }
  19871. }
  19872. }
  19873. }
  19874. }
  19875. }
  19876. void BfModule::ClearModule()
  19877. {
  19878. ClearModuleData();
  19879. DisownMethods();
  19880. for (auto& specPair : mSpecializedMethodModules)
  19881. {
  19882. auto specModule = specPair.mValue;
  19883. specModule->ClearModule();
  19884. }
  19885. if (mNextAltModule != NULL)
  19886. mNextAltModule->ClearModule();
  19887. }