BfModule.cpp 700 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(push) // 6
  4. #pragma warning(disable:4996)
  5. #include "BfCompiler.h"
  6. #include "BfSystem.h"
  7. #include "BfParser.h"
  8. #include "BfCodeGen.h"
  9. #include "BfExprEvaluator.h"
  10. #include "../Backend/BeLibManger.h"
  11. #include <fcntl.h>
  12. #include "BfConstResolver.h"
  13. #include "BfMangler.h"
  14. #include "BeefySysLib/util/PerfTimer.h"
  15. #include "BeefySysLib/util/BeefPerf.h"
  16. #include "BeefySysLib/util/StackHelper.h"
  17. #include "BfSourceClassifier.h"
  18. #include "BfAutoComplete.h"
  19. #include "BfDemangler.h"
  20. #include "BfResolvePass.h"
  21. #include "BfFixits.h"
  22. #include "BfIRCodeGen.h"
  23. #include "BfDefBuilder.h"
  24. #include "BfDeferEvalChecker.h"
  25. #pragma warning(pop)
  26. //////////////////////////////////////////////////////////////////////////
  27. static bool gDebugStuff = false;
  28. USING_NS_BF;
  29. //////////////////////////////////////////////////////////////////////////
  30. void BfLocalVariable::Init()
  31. {
  32. if (mResolvedType->IsValuelessType())
  33. {
  34. mIsAssigned = true;
  35. return;
  36. }
  37. if (mIsAssigned)
  38. return;
  39. bool isStruct = mResolvedType->IsStruct();
  40. if (mResolvedType->IsRef())
  41. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  42. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  43. {
  44. auto resolvedTypeRef = mResolvedType;
  45. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  46. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  47. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  48. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  49. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  50. {
  51. // Base ctor is responsible for initializing its own fields
  52. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  53. }
  54. if (mUnassignedFieldFlags == 0)
  55. mIsAssigned = true;
  56. }
  57. else
  58. {
  59. mUnassignedFieldFlags = 1;
  60. }
  61. }
  62. BfLocalMethod::~BfLocalMethod()
  63. {
  64. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  65. if (mMethodDeclaration != NULL)
  66. {
  67. mSource->mRefCount--;
  68. BF_ASSERT(mSource->mRefCount >= 0);
  69. }
  70. delete mMethodDef;
  71. delete mMethodInstanceGroup;
  72. }
  73. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  74. {
  75. mIsChained = doChain;
  76. if (outerLocalAssignData == NULL)
  77. return;
  78. mChainedAssignData = outerLocalAssignData;
  79. if (!doChain)
  80. {
  81. outerLocalAssignData->BreakExtendChain();
  82. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  83. }
  84. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  85. }
  86. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  87. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  88. // if ((GetValue(out a)) && (GetValue(out b)) {}
  89. void BfDeferredLocalAssignData::BreakExtendChain()
  90. {
  91. if (!mIsChained)
  92. return;
  93. mIsChained = false;
  94. if (mChainedAssignData == NULL)
  95. return;
  96. mChainedAssignData->BreakExtendChain();
  97. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  98. }
  99. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  100. {
  101. BreakExtendChain();
  102. //TODO: We got rid of this case because we now set the proper assigned data when we do a return
  103. // If one of these had a return then treat that case as if it did have an assign -- because it doesn't
  104. // cause an UNASSIGNED value to be used
  105. // if (mHadReturn || otherLocalAssignData.mHadReturn)
  106. // {
  107. // SetUnion(otherLocalAssignData);
  108. // mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  109. // return;
  110. // }
  111. for (int i = 0; i < (int)mAssignedLocals.size(); )
  112. {
  113. auto& local = mAssignedLocals[i];
  114. if (!otherLocalAssignData.mAssignedLocals.Contains(local))
  115. {
  116. mAssignedLocals.RemoveAt(i);
  117. }
  118. else
  119. i++;
  120. }
  121. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  122. }
  123. void BfDeferredLocalAssignData::Validate() const
  124. {
  125. for (auto var : mAssignedLocals)
  126. {
  127. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  128. }
  129. }
  130. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  131. {
  132. BreakExtendChain();
  133. Validate();
  134. otherLocalAssignData.Validate();
  135. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  136. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  137. {
  138. if (!mAssignedLocals.Contains(*otherItr))
  139. mAssignedLocals.push_back(*otherItr);
  140. ++otherItr;
  141. }
  142. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  143. }
  144. BfMethodState::~BfMethodState()
  145. {
  146. BF_ASSERT(mPendingNullConditional == NULL);
  147. if (mPrevMethodState != NULL)
  148. {
  149. BF_ASSERT(mCurAccessId == 1);
  150. BF_ASSERT(mCurLocalVarId <= 0);
  151. }
  152. for (auto local : mLocals)
  153. delete local;
  154. for (auto& kv : mLambdaCache)
  155. delete kv.mValue;
  156. }
  157. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  158. {
  159. auto checkMethodState = this;
  160. while (checkMethodState != NULL)
  161. {
  162. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  163. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  164. return checkMethodState;
  165. checkMethodState = checkMethodState->mPrevMethodState;
  166. }
  167. BF_FATAL("Failed to find method state for localvar");
  168. return NULL;
  169. }
  170. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx)
  171. {
  172. auto localVarMethodState = GetMethodStateForLocal(localVar);
  173. if (localVarMethodState != this)
  174. {
  175. return;
  176. }
  177. //BF_ASSERT(localVarMethodState == this);
  178. if (!localVar->mIsAssigned)
  179. {
  180. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  181. // 'a' is always defined, but 'b' isn't:
  182. // if (Check(out a) || Check(out b)) { } int z = a;
  183. auto deferredLocalAssignData = mDeferredLocalAssignData;
  184. if ((deferredLocalAssignData != NULL) &&
  185. (deferredLocalAssignData->mIsIfCondition) &&
  186. (!deferredLocalAssignData->mIfMayBeSkipped))
  187. {
  188. ifDeferredLocalAssignData = deferredLocalAssignData;
  189. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  190. }
  191. while ((deferredLocalAssignData != NULL) &&
  192. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  193. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  194. if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  195. {
  196. if (fieldIdx >= 0)
  197. {
  198. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  199. /*if ((localVar->mResolvedTypeRef != NULL) && (localVar->mResolvedTypeRef->IsUnion()))
  200. {
  201. }*/
  202. if (localVar->mUnassignedFieldFlags == 0)
  203. localVar->mIsAssigned = true;
  204. }
  205. else
  206. {
  207. localVar->mIsAssigned = true;
  208. }
  209. }
  210. else
  211. {
  212. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  213. BfAssignedLocal defineVal = {localVar, fieldIdx + 1};
  214. auto& assignedLocals = deferredLocalAssignData->mAssignedLocals;
  215. if (!assignedLocals.Contains(defineVal))
  216. assignedLocals.push_back(defineVal);
  217. if (ifDeferredLocalAssignData != NULL)
  218. {
  219. auto& assignedLocals = ifDeferredLocalAssignData->mAssignedLocals;
  220. if (!assignedLocals.Contains(defineVal))
  221. assignedLocals.push_back(defineVal);
  222. }
  223. }
  224. }
  225. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  226. }
  227. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  228. {
  229. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  230. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  231. {
  232. LocalDefined(assignedLocal.mLocalVar);
  233. }
  234. }
  235. void BfMethodState::Reset()
  236. {
  237. mHeadScope.mDeferredCallEntries.DeleteAll();
  238. }
  239. //////////////////////////////////////////////////////////////////////////
  240. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  241. {
  242. Entry* entry = NULL;
  243. if (mEntries.TryAdd(id, NULL, &entry))
  244. {
  245. entry->mInterfaceEntry = interfaceEntry;
  246. entry->mMethodIdx = methodIdx;
  247. }
  248. if (!entry->mCandidates.Contains(candidateA))
  249. entry->mCandidates.push_back(candidateA);
  250. if (!entry->mCandidates.Contains(candidateB))
  251. entry->mCandidates.push_back(candidateB);
  252. }
  253. void BfAmbiguityContext::Remove(int id)
  254. {
  255. mEntries.Remove(id);
  256. }
  257. void BfAmbiguityContext::Finish()
  258. {
  259. for (auto& entryPair : mEntries)
  260. {
  261. int id = entryPair.mKey;
  262. auto entry = &entryPair.mValue;
  263. if (id >= 0)
  264. {
  265. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  266. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  267. for (auto candidate : entry->mCandidates)
  268. {
  269. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  270. }
  271. }
  272. else
  273. {
  274. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  275. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  276. for (auto candidate : entry->mCandidates)
  277. {
  278. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  279. }
  280. }
  281. }
  282. }
  283. //////////////////////////////////////////////////////////////////////////
  284. class HasAppendAllocVisitor : BfElementVisitor
  285. {
  286. public:
  287. bool mHas;
  288. public:
  289. HasAppendAllocVisitor()
  290. {
  291. mHas = false;
  292. }
  293. void Visit(BfObjectCreateExpression* objCreateExpr)
  294. {
  295. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  296. {
  297. if (newToken->GetToken() == BfToken_Append)
  298. {
  299. mHas = true;
  300. }
  301. }
  302. }
  303. bool HasAppendAlloc(BfAstNode* node)
  304. {
  305. mHas = false;
  306. VisitChild(node);
  307. return mHas;
  308. }
  309. };
  310. class AppendAllocVisitor : public BfStructuralVisitor
  311. {
  312. public:
  313. BfModule* mModule;
  314. HasAppendAllocVisitor mHasAppendAllocVisitor;
  315. BfTypedValue mConstAccum;
  316. bool mFailed;
  317. bool mIsFirstConstPass;
  318. int mCurAppendAlign;
  319. public:
  320. AppendAllocVisitor()
  321. {
  322. mFailed = false;
  323. mIsFirstConstPass = false;
  324. mCurAppendAlign = 0;
  325. }
  326. void EmitAppendAlign(int align, int sizeMultiple = 0)
  327. {
  328. if (mIsFirstConstPass)
  329. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  330. if (sizeMultiple == 0)
  331. sizeMultiple = align;
  332. if (mCurAppendAlign == 0)
  333. mCurAppendAlign = sizeMultiple;
  334. else
  335. {
  336. if (sizeMultiple % align == 0)
  337. mCurAppendAlign = align;
  338. else
  339. mCurAppendAlign = sizeMultiple % align;
  340. }
  341. if (mConstAccum)
  342. {
  343. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  344. if (constant != NULL)
  345. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  346. else
  347. BF_ASSERT(mIsFirstConstPass);
  348. return;
  349. }
  350. mModule->EmitAppendAlign(align, sizeMultiple);
  351. }
  352. void Visit(BfAstNode* astNode) override
  353. {
  354. mModule->VisitChild(astNode);
  355. }
  356. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  357. {
  358. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  359. {
  360. if (newToken->GetToken() == BfToken_Append)
  361. {
  362. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  363. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  364. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  365. BfArrayType* arrayType = NULL;
  366. bool isArrayAlloc = false;
  367. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  368. SizedArray<BfIRValue, 2> dimLengthVals;
  369. BfType* origResolvedTypeRef = NULL;
  370. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  371. {
  372. if (variableDecl != NULL)
  373. {
  374. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  375. if (origResolvedTypeRef->IsObject())
  376. {
  377. if (origResolvedTypeRef->IsArray())
  378. {
  379. arrayType = (BfArrayType*)origResolvedTypeRef;
  380. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  381. isArrayAlloc = true;
  382. }
  383. }
  384. else if (origResolvedTypeRef->IsPointer())
  385. {
  386. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  387. }
  388. }
  389. }
  390. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  391. {
  392. isArrayAlloc = true;
  393. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  394. int dimensions = 1;
  395. if (arrayTypeRef->mParams.size() != 0)
  396. {
  397. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  398. for (auto arg : arrayTypeRef->mParams)
  399. {
  400. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  401. {
  402. if (tokenNode->GetToken() == BfToken_Comma)
  403. {
  404. if (isRawArrayAlloc)
  405. {
  406. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  407. continue;
  408. }
  409. dimensions++;
  410. continue;
  411. }
  412. }
  413. auto expr = BfNodeDynCast<BfExpression>(arg);
  414. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  415. {
  416. mModule->CreateValueFromExpression(expr, intType);
  417. continue;
  418. }
  419. BfTypedValue dimLength;
  420. if (expr == NULL)
  421. {
  422. // Not specified
  423. dimLengthVals.push_back(BfIRValue());
  424. continue;
  425. }
  426. if (arg != NULL)
  427. dimLength = mModule->CreateValueFromExpression(expr, intType);
  428. if (!dimLength)
  429. {
  430. dimLength = mModule->GetDefaultTypedValue(intType);
  431. }
  432. dimLengthVals.push_back(dimLength.mValue);
  433. }
  434. }
  435. if (!isRawArrayAlloc)
  436. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  437. }
  438. if (origResolvedTypeRef == NULL)
  439. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  440. if (origResolvedTypeRef == NULL)
  441. {
  442. mModule->AssertErrorState();
  443. return;
  444. }
  445. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  446. auto resolvedTypeRef = origResolvedTypeRef;
  447. auto resultType = resolvedTypeRef;
  448. BfIRValue sizeValue;
  449. int curAlign = 0;
  450. if (isArrayAlloc)
  451. {
  452. int dimensions = 1;
  453. if (arrayType != NULL)
  454. dimensions = arrayType->mDimensions;
  455. bool sizeFailed = false;
  456. //
  457. {
  458. BfAstNode* initNode = objCreateExpr;
  459. for (int dim = 0; dim < dimensions; dim++)
  460. {
  461. BfAstNode* nextInitNode = NULL;
  462. int dimSize = -1;
  463. if (initNode == objCreateExpr)
  464. {
  465. dimSize = objCreateExpr->mArguments.size();
  466. if (!objCreateExpr->mArguments.IsEmpty())
  467. nextInitNode = objCreateExpr->mArguments[0];
  468. }
  469. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  470. {
  471. dimSize = (int)tupleNode->mCommas.size() + 1;
  472. }
  473. if (dimSize >= 0)
  474. {
  475. if (dim >= dimLengthVals.size())
  476. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  477. }
  478. else
  479. {
  480. sizeFailed = true;
  481. }
  482. }
  483. }
  484. BfIRValue allocCount;
  485. if (!sizeFailed)
  486. {
  487. if (!dimLengthVals.IsEmpty())
  488. {
  489. allocCount = dimLengthVals[0];
  490. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  491. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  492. }
  493. }
  494. if (!allocCount)
  495. {
  496. mFailed = true;
  497. if (!mIsFirstConstPass)
  498. {
  499. if (!mConstAccum)
  500. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  501. return;
  502. }
  503. }
  504. if (isRawArrayAlloc)
  505. {
  506. curAlign = resultType->mAlign;
  507. EmitAppendAlign(resultType->mAlign);
  508. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  509. }
  510. else
  511. {
  512. if (arrayType == NULL)
  513. arrayType = mModule->CreateArrayType(resultType, 1);
  514. // Array is a special case where the total size isn't aligned with mAlign
  515. // since we add arbitrary elements to the end without padding the end to align
  516. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  517. curAlign = arrayType->mAlign;
  518. auto firstElementField = &arrayType->mFieldInstances.back();
  519. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  520. sizeValue = mModule->GetConstValue(arrayClassSize);
  521. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  522. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  523. }
  524. }
  525. else
  526. {
  527. auto typeInst = resultType->ToTypeInstance();
  528. if (typeInst != NULL)
  529. {
  530. curAlign = typeInst->mInstAlign;
  531. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  532. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  533. }
  534. else
  535. {
  536. curAlign = resultType->mAlign;
  537. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  538. sizeValue = mModule->GetConstValue(resultType->mSize);
  539. }
  540. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  541. BfExprEvaluator exprEvaluator(mModule);
  542. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  543. BfFunctionBindResult bindResult;
  544. bindResult.mWantsArgs = true;
  545. exprEvaluator.mFunctionBindResult = &bindResult;
  546. SizedArray<BfExpression*, 8> copiedArgs;
  547. for (BfExpression* arg : objCreateExpr->mArguments)
  548. copiedArgs.push_back(arg);
  549. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  550. BfResolvedArgs argValues(&sizedArgExprs);
  551. if (typeInst != NULL)
  552. {
  553. exprEvaluator.ResolveArgValues(argValues);
  554. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  555. }
  556. exprEvaluator.mFunctionBindResult = NULL;
  557. if (bindResult.mMethodInstance != NULL)
  558. {
  559. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  560. {
  561. auto calcAppendArgs = bindResult.mIRArgs;
  562. BF_ASSERT(calcAppendArgs[0].IsFake());
  563. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  564. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  565. auto subDependSize = mModule->TryConstCalcAppend(bindResult.mMethodInstance, calcAppendArgs);
  566. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  567. {
  568. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  569. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  570. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  571. }
  572. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  573. if ((!subDependSize) && (!mConstAccum))
  574. {
  575. BF_ASSERT(calcAppendMethodModule.mFunc);
  576. subDependSize = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  577. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  578. }
  579. if (subDependSize)
  580. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  581. else
  582. mFailed = true;
  583. }
  584. }
  585. }
  586. if (sizeValue)
  587. {
  588. if (mConstAccum)
  589. {
  590. if (!sizeValue.IsConst())
  591. {
  592. mFailed = true;
  593. if (!mIsFirstConstPass)
  594. return;
  595. }
  596. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  597. }
  598. else
  599. {
  600. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  601. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  602. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  603. }
  604. }
  605. }
  606. }
  607. }
  608. void Visit(BfObjectCreateExpression* objCreateExpr) override
  609. {
  610. DoObjectCreate(objCreateExpr, NULL);
  611. }
  612. void Visit(BfVariableDeclaration* varDecl) override
  613. {
  614. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  615. {
  616. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  617. DoObjectCreate(objectCreateExpr, varDecl);
  618. else
  619. VisitChild(varDecl->mInitializer);
  620. if (varDecl->mNameNode != NULL)
  621. {
  622. BfLocalVariable* localDef = new BfLocalVariable();
  623. localDef->mName = varDecl->mNameNode->ToString();
  624. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  625. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  626. localDef->mIsReadOnly = true;
  627. localDef->mParamFailed = true;
  628. localDef->mReadFromId = 0;
  629. mModule->AddLocalVariableDef(localDef);
  630. }
  631. }
  632. else
  633. {
  634. mModule->Visit(varDecl);
  635. }
  636. }
  637. void Visit(BfExpressionStatement* exprStatement) override
  638. {
  639. VisitChild(exprStatement->mExpression);
  640. }
  641. // void Visit(BfIfStatement* ifStmt) override
  642. // {
  643. // mModule->DoIfStatement(ifStmt,
  644. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  645. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  646. // }
  647. void Visit(BfBlock* block) override
  648. {
  649. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  650. return;
  651. int appendAllocIdx = -1;
  652. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  653. {
  654. auto child = block->mChildArr.mVals[childIdx];
  655. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  656. {
  657. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  658. {
  659. auto emitChild = block->mChildArr.mVals[emitIdx];
  660. mModule->UpdateSrcPos(emitChild);
  661. VisitChild(emitChild);
  662. if ((mFailed) && (!mIsFirstConstPass))
  663. break;
  664. }
  665. break;
  666. }
  667. }
  668. }
  669. };
  670. //////////////////////////////////////////////////////////////////////////
  671. BfModule* gLastCreatedModule = NULL;
  672. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  673. {
  674. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  675. gLastCreatedModule = this;
  676. mContext = context;
  677. mModuleName = moduleName;
  678. if (!moduleName.empty())
  679. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  680. mAddedToCount = false;
  681. mParentModule = NULL;
  682. mNextAltModule = NULL;
  683. mBfIRBuilder = NULL;
  684. mWantsIRIgnoreWrites = false;
  685. mModuleOptions = NULL;
  686. mLastUsedRevision = -1;
  687. mUsedSlotCount = -1;
  688. mIsReified = true;
  689. mReifyQueued = false;
  690. mIsSpecialModule = false;
  691. mIsScratchModule = false;
  692. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  693. mHadBuildError = false;
  694. mHadBuildWarning = false;
  695. mIgnoreErrors = false;
  696. mIgnoreWarnings = false;
  697. mHadIgnoredError = false;
  698. mReportErrors = true;
  699. mIsInsideAutoComplete = false;
  700. mIsDeleting = false;
  701. mSkipInnerLookup = false;
  702. mIsHotModule = false;
  703. mSetIllegalSrcPosition = false;
  704. mNoResolveGenericParams = false;
  705. mWroteToLib = false;
  706. mContext = context;
  707. mCompiler = context->mCompiler;
  708. mSystem = mCompiler->mSystem;
  709. mProject = NULL;
  710. mCurMethodState = NULL;
  711. mAttributeState = NULL;
  712. mCurLocalMethodId = 0;
  713. mParentNodeEntry = NULL;
  714. mRevision = -1;
  715. mRebuildIdx = 0;
  716. mLastModuleWrittenRevision = 0;
  717. mIsModuleMutable = false;
  718. mExtensionCount = 0;
  719. mIncompleteMethodCount = 0;
  720. mOnDemandMethodCount = 0;
  721. mHasGenericMethods = false;
  722. mCurMethodInstance = NULL;
  723. mCurTypeInstance = NULL;
  724. mAwaitingInitFinish = false;
  725. mAwaitingFinish = false;
  726. mHasFullDebugInfo = false;
  727. mHadHotObjectWrites = false;
  728. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  729. mBuiltInFuncs[i] = BfIRFunction();
  730. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  731. }
  732. void BfReportMemory();
  733. BfModule::~BfModule()
  734. {
  735. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  736. if (!mIsDeleting)
  737. RemoveModuleData();
  738. }
  739. void BfModule::RemoveModuleData()
  740. {
  741. BF_ASSERT(!mIsDeleting);
  742. if (!mModuleName.empty())
  743. {
  744. // Note: module names not necessarily unique
  745. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  746. }
  747. CleanupFileInstances();
  748. delete mBfIRBuilder;
  749. mBfIRBuilder = NULL;
  750. //delete mCpu;
  751. for (auto prevModule : mPrevIRBuilders)
  752. delete prevModule;
  753. mPrevIRBuilders.Clear();
  754. for (auto& pairVal : mDeferredMethodCallData)
  755. delete pairVal.mValue;
  756. mDeferredMethodCallData.Clear();
  757. mDeferredMethodIds.Clear();
  758. for (auto& specModulePair : mSpecializedMethodModules)
  759. delete specModulePair.mValue;
  760. mSpecializedMethodModules.Clear();
  761. if (mNextAltModule != NULL)
  762. delete mNextAltModule;
  763. mNextAltModule = NULL;
  764. if (mModuleOptions != NULL)
  765. delete mModuleOptions;
  766. mModuleOptions = NULL;
  767. BfReportMemory();
  768. }
  769. void BfModule::Init(bool isFullRebuild)
  770. {
  771. mContext->mFinishedModuleWorkList.Remove(this);
  772. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  773. BF_ASSERT(mIsReified);
  774. if (!mIsScratchModule)
  775. {
  776. mCompiler->mStats.mModulesStarted++;
  777. if (mIsReified)
  778. mCompiler->mStats.mReifiedModuleCount++;
  779. mAddedToCount = true;
  780. }
  781. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  782. mFuncReferences.Clear();
  783. mClassVDataRefs.Clear();
  784. mClassVDataExtRefs.Clear();
  785. //mTypeDataRefs.Clear();
  786. mDbgRawAllocDataRefs.Clear();
  787. CleanupFileInstances();
  788. mStaticFieldRefs.Clear();
  789. //mInterfaceSlotRefs.Clear();
  790. // If we are just doing an extension then the ownede types aren't rebuilt.
  791. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  792. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  793. if (isFullRebuild)
  794. mRevision = mCompiler->mRevision;
  795. BF_ASSERT(mCurTypeInstance == NULL);
  796. mIsModuleMutable = true;
  797. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  798. #ifdef _DEBUG
  799. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  800. #else
  801. EnsureIRBuilder(false);
  802. #endif
  803. mCurMethodState = NULL;
  804. mAwaitingInitFinish = true;
  805. mOnDemandMethodCount = 0;
  806. mAwaitingFinish = false;
  807. mHasForceLinkMarker = false;
  808. mUsedSlotCount = -1;
  809. }
  810. bool BfModule::WantsFinishModule()
  811. {
  812. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  813. }
  814. void BfModule::FinishInit()
  815. {
  816. BF_ASSERT(mAwaitingInitFinish);
  817. auto moduleOptions = GetModuleOptions();
  818. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  819. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple);
  820. // #ifdef BF_PLATFORM_WINDOWS
  821. // if (mCompiler->mOptions.mToolsetType == BfToolsetType_GNU)
  822. // {
  823. // if (mCompiler->mOptions.mMachineType == BfMachineType_x86)
  824. // mBfIRBuilder->Module_SetTargetTriple("i686-pc-windows-gnu");
  825. // else
  826. // mBfIRBuilder->Module_SetTargetTriple("x86_64-pc-windows-gnu");
  827. // }
  828. // else //if (mCompiler->mOptions.mToolsetType == BfToolsetType_Microsoft)
  829. // {
  830. // if (mCompiler->mOptions.mMachineType == BfMachineType_x86)
  831. // mBfIRBuilder->Module_SetTargetTriple("i686-pc-windows-msvc");
  832. // else
  833. // mBfIRBuilder->Module_SetTargetTriple("x86_64-pc-windows-msvc");
  834. // }
  835. // #elif defined BF_PLATFORM_LINUX
  836. // if (mCompiler->mOptions.mMachineType == BfMachineType_x86)
  837. // mBfIRBuilder->Module_SetTargetTriple("i686-unknown-linux-gnu");
  838. // else
  839. // mBfIRBuilder->Module_SetTargetTriple("x86_64-unknown-linux-gnu");
  840. // #else
  841. // // Leave it default
  842. // mBfIRBuilder->Module_SetTargetTriple("");
  843. // #endif
  844. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  845. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  846. {
  847. // Og+ requires debug info
  848. moduleOptions.mEmitDebugInfo = 1;
  849. }
  850. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  851. // We need to create DIBuilder for mIsSpecialModule so we have it around when we need it
  852. // if ((!mCompiler->mIsResolveOnly) && ((mIsScratchModule) || (moduleOptions.mEmitDebugInfo != 0)))
  853. // {
  854. // BF_ASSERT((!mBfIRBuilder->mIgnoreWrites) || (mIsScratchModule) || (!mIsReified));
  855. // mBfIRBuilder->DbgInit();
  856. // }
  857. // else
  858. // mHasFullDebugInfo = false;
  859. if ((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified))
  860. {
  861. mBfIRBuilder->DbgInit();
  862. }
  863. else
  864. mHasFullDebugInfo = false;
  865. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  866. ((moduleOptions.mEmitDebugInfo != 0)))
  867. {
  868. if (mCompiler->mOptions.IsCodeView())
  869. {
  870. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  871. }
  872. else
  873. {
  874. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  875. }
  876. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  877. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  878. }
  879. mAwaitingInitFinish = false;
  880. }
  881. void BfModule::ReifyModule()
  882. {
  883. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  884. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  885. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  886. mIsReified = true;
  887. mReifyQueued = false;
  888. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  889. mCompiler->mStats.mModulesReified++;
  890. }
  891. void BfModule::UnreifyModule()
  892. {
  893. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  894. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  895. mIsReified = false;
  896. mReifyQueued = false;
  897. StartNewRevision(RebuildKind_None, true);
  898. mCompiler->mStats.mModulesUnreified++;
  899. }
  900. void BfModule::CleanupFileInstances()
  901. {
  902. for (auto& itr : mNamedFileInstanceMap)
  903. {
  904. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  905. delete itr.mValue;
  906. }
  907. mCurFilePosition.mFileInstance = NULL;//
  908. mFileInstanceMap.Clear();
  909. mNamedFileInstanceMap.Clear();
  910. }
  911. void BfModule::Cleanup()
  912. {
  913. CleanupFileInstances();
  914. }
  915. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  916. {
  917. if (HasCompiledOutput())
  918. {
  919. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  920. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  921. {
  922. StartExtension();
  923. }
  924. }
  925. else
  926. {
  927. EnsureIRBuilder();
  928. }
  929. }
  930. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  931. {
  932. BF_ASSERT(!mIsDeleting);
  933. if (mBfIRBuilder == NULL)
  934. {
  935. if ((!mIsScratchModule) && (!mAddedToCount))
  936. {
  937. mCompiler->mStats.mModulesStarted++;
  938. mAddedToCount = true;
  939. }
  940. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  941. /*if (mCompiler->mIsResolveOnly)
  942. BF_ASSERT(mIsResolveOnly);*/
  943. mBfIRBuilder = new BfIRBuilder(this);
  944. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  945. if (mIsScratchModule)
  946. {
  947. mBfIRBuilder->mIgnoreWrites = true;
  948. BF_ASSERT(!dbgVerifyCodeGen);
  949. }
  950. #ifdef _DEBUG
  951. if (mCompiler->mIsResolveOnly)
  952. {
  953. // For "deep" verification testing
  954. /*if (!mIsSpecialModule)
  955. dbgVerifyCodeGen = true;*/
  956. // We only want to turn this off on smaller builds for testing
  957. mBfIRBuilder->mIgnoreWrites = true;
  958. if (dbgVerifyCodeGen)
  959. mBfIRBuilder->mIgnoreWrites = false;
  960. if (!mBfIRBuilder->mIgnoreWrites)
  961. {
  962. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  963. mBfIRBuilder->mDbgVerifyCodeGen = true;
  964. }
  965. }
  966. else if (!mIsReified)
  967. {
  968. mBfIRBuilder->mIgnoreWrites = true;
  969. }
  970. else
  971. {
  972. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  973. // code as we walk the AST
  974. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  975. if (
  976. (mModuleName == "Program")
  977. //|| (mModuleName == "System_Internal")
  978. //|| (mModuleName == "vdata")
  979. //|| (mModuleName == "Hey_Dude_Bro_TestClass")
  980. )
  981. mBfIRBuilder->mDbgVerifyCodeGen = true;
  982. // Just for testing!
  983. //mBfIRBuilder->mIgnoreWrites = true;
  984. }
  985. #else
  986. if (mCompiler->mIsResolveOnly)
  987. {
  988. // Always ignore writes in resolveOnly for release builds
  989. mBfIRBuilder->mIgnoreWrites = true;
  990. }
  991. else
  992. {
  993. // Just for memory testing! This breaks everything.
  994. //mBfIRBuilder->mIgnoreWrites = true;
  995. // For "deep" verification testing
  996. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  997. }
  998. #endif
  999. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  1000. }
  1001. }
  1002. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1003. {
  1004. String name = "FORCELINKMOD_" + module->mModuleName;
  1005. if (outName != NULL)
  1006. *outName = name;
  1007. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1008. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1009. }
  1010. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1011. {
  1012. BP_ZONE("BfModule::StartNewRevision");
  1013. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1014. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1015. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1016. // Already on new revision?
  1017. if ((mRevision == mCompiler->mRevision) && (!force))
  1018. return;
  1019. mHadBuildError = false;
  1020. mHadBuildWarning = false;
  1021. mExtensionCount = 0;
  1022. mRevision = mCompiler->mRevision;
  1023. mRebuildIdx++;
  1024. ClearModuleData();
  1025. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1026. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1027. mStringPoolRefs.Clear();
  1028. mDllImportEntries.Clear();
  1029. mImportFileNames.Clear();
  1030. for (auto& pairVal : mDeferredMethodCallData)
  1031. delete pairVal.mValue;
  1032. mDeferredMethodCallData.Clear();
  1033. mDeferredMethodIds.Clear();
  1034. mModuleRefs.Clear();
  1035. mOutFileNames.Clear();
  1036. mTypeDataRefs.Clear();
  1037. mInterfaceSlotRefs.Clear();
  1038. if (rebuildKind == BfModule::RebuildKind_None)
  1039. {
  1040. for (auto& specPair : mSpecializedMethodModules)
  1041. {
  1042. auto specModule = specPair.mValue;
  1043. if (specModule->mIsReified != mIsReified)
  1044. {
  1045. if (mIsReified)
  1046. specModule->ReifyModule();
  1047. else
  1048. specModule->UnreifyModule();
  1049. }
  1050. }
  1051. }
  1052. else
  1053. {
  1054. for (auto& specPair : mSpecializedMethodModules)
  1055. {
  1056. auto specModule = specPair.mValue;
  1057. delete specModule;
  1058. }
  1059. }
  1060. mSpecializedMethodModules.Clear();
  1061. delete mNextAltModule;
  1062. mNextAltModule = NULL;
  1063. BF_ASSERT(mModuleOptions == NULL);
  1064. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1065. bool needsTypePopulated = false;
  1066. int oldOnDemandCount = 0;
  1067. // We don't have to rebuild types in the unspecialized module because there is no
  1068. // data that's needed -- their method instances are all NULL and the module
  1069. // doesn't get included in the build
  1070. if (this != mContext->mScratchModule)
  1071. {
  1072. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1073. {
  1074. auto typeInst = mOwnedTypeInstances[typeIdx];
  1075. if (!typeInst->IsDeleting())
  1076. {
  1077. typeInst->mIsReified = mIsReified;
  1078. if (rebuildKind != BfModule::RebuildKind_None)
  1079. {
  1080. if (typeInst->IsOnDemand())
  1081. {
  1082. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1083. if (rebuildKind == BfModule::RebuildKind_All)
  1084. mContext->DeleteType(typeInst);
  1085. else
  1086. {
  1087. RebuildMethods(typeInst);
  1088. }
  1089. }
  1090. else
  1091. mContext->RebuildType(typeInst, false, false, false);
  1092. }
  1093. else
  1094. {
  1095. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1096. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1097. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference))
  1098. {
  1099. oldOnDemandCount++;
  1100. }
  1101. }
  1102. if (typeInst->IsDeleting())
  1103. typeIdx--;
  1104. }
  1105. }
  1106. }
  1107. if (!mIsDeleting)
  1108. Init();
  1109. mOnDemandMethodCount += oldOnDemandCount;
  1110. }
  1111. void BfModule::StartExtension()
  1112. {
  1113. BF_ASSERT(!mIsModuleMutable);
  1114. BfLogSysM("Extension started of module %p\n", this);
  1115. mExtensionCount++;
  1116. if (mBfIRBuilder != NULL)
  1117. mPrevIRBuilders.push_back(mBfIRBuilder);
  1118. mBfIRBuilder = NULL;
  1119. mWantsIRIgnoreWrites = false;
  1120. mFuncReferences.Clear();
  1121. mClassVDataRefs.Clear();
  1122. mClassVDataExtRefs.Clear();
  1123. for (auto& kv : mTypeDataRefs)
  1124. kv.mValue = BfIRValue();
  1125. mDbgRawAllocDataRefs.Clear();
  1126. mStringCharPtrPool.Clear();
  1127. mStringObjectPool.Clear();
  1128. mStaticFieldRefs.Clear();
  1129. for (auto& kv : mInterfaceSlotRefs)
  1130. kv.mValue = BfIRValue();
  1131. mDeferredMethodCallData.Clear();
  1132. mDeferredMethodIds.Clear();
  1133. DisownMethods();
  1134. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1135. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1136. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1137. Init(false);
  1138. if (!wasAwaitingInitFinish)
  1139. FinishInit();
  1140. mOnDemandMethodCount = prevOnDemandMethodCount;
  1141. }
  1142. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1143. {
  1144. BfIRValue vDataValue;
  1145. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1146. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1147. else
  1148. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1149. typeValueParams.push_back(vDataValue);
  1150. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1151. {
  1152. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1153. typeValueParams.push_back(GetDefaultValue(primType));
  1154. }
  1155. }
  1156. BfIRValue BfModule::GetConstValue(int64 val)
  1157. {
  1158. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1159. }
  1160. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1161. {
  1162. BfType* checkType = type;
  1163. if (type->IsTypedPrimitive())
  1164. {
  1165. checkType = type->GetUnderlyingType();
  1166. }
  1167. if (checkType->IsPrimitiveType())
  1168. {
  1169. auto primType = (BfPrimitiveType*)checkType;
  1170. if (checkType->IsFloat())
  1171. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1172. else
  1173. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1174. }
  1175. return BfIRValue();
  1176. }
  1177. BfIRValue BfModule::GetConstValue8(int val)
  1178. {
  1179. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1180. }
  1181. BfIRValue BfModule::GetConstValue32(int32 val)
  1182. {
  1183. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1184. }
  1185. BfIRValue BfModule::GetConstValue64(int64 val)
  1186. {
  1187. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1188. }
  1189. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1190. {
  1191. PopulateType(type, BfPopulateType_Data);
  1192. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1193. if (type->IsTypedPrimitive())
  1194. {
  1195. auto underlyingType = type->GetUnderlyingType();
  1196. if (underlyingType == NULL)
  1197. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1198. return GetDefaultValue(type->GetUnderlyingType());
  1199. }
  1200. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1201. type->IsRetTypeType() || type->IsConcreteInterfaceType())
  1202. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1203. if ((type->IsIntegral()) || (type->IsBoolean()))
  1204. {
  1205. auto primType = (BfPrimitiveType*)type;
  1206. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1207. }
  1208. if (type->IsFloat())
  1209. {
  1210. auto primType = (BfPrimitiveType*)type;
  1211. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1212. }
  1213. if (type->IsVoid())
  1214. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1215. return mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(type));
  1216. }
  1217. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1218. {
  1219. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1220. if (type->mSize == 0)
  1221. return BfTypedValue(BfIRValue(), type);
  1222. else
  1223. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1224. }
  1225. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1226. {
  1227. PopulateType(type, BfPopulateType_Data);
  1228. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1229. if (defaultValueKind == BfDefaultValueKind_Undef)
  1230. {
  1231. auto primType = type->ToPrimitiveType();
  1232. if (primType != NULL)
  1233. {
  1234. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode), type);
  1235. }
  1236. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(type)), type);
  1237. }
  1238. BfTypedValue typedValue;
  1239. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1240. {
  1241. if (type->IsRef())
  1242. {
  1243. BfRefType* refType = (BfRefType*)type;
  1244. BfType* underlyingType = refType->GetUnderlyingType();
  1245. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1246. }
  1247. else
  1248. {
  1249. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1250. }
  1251. if (!mBfIRBuilder->mIgnoreWrites)
  1252. {
  1253. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1254. GetConstValue(type->mSize), type->mAlign);
  1255. }
  1256. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1257. typedValue = LoadValue(typedValue);
  1258. return typedValue;
  1259. }
  1260. if ((type->IsRef()) && (!allowRef))
  1261. {
  1262. BfRefType* refType = (BfRefType*)type;
  1263. BfType* underlyingType = refType->GetUnderlyingType();
  1264. if (underlyingType->IsValuelessType())
  1265. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1266. else
  1267. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1268. }
  1269. else
  1270. {
  1271. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1272. }
  1273. return typedValue;
  1274. }
  1275. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1276. {
  1277. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1278. BfIRType strCharType;
  1279. //
  1280. {
  1281. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites);
  1282. strCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Char8), (int)str.length() + 1);
  1283. }
  1284. BfIRValue strConstant;
  1285. if (define)
  1286. {
  1287. strConstant = mBfIRBuilder->CreateConstString(str);
  1288. }
  1289. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(strCharType,
  1290. true, BfIRLinkageType_External,
  1291. strConstant, stringDataName);
  1292. if (define)
  1293. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1294. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1295. }
  1296. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1297. {
  1298. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1299. mBfIRBuilder->PopulateType(stringTypeInst);
  1300. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1301. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1302. BfIRValue stringValData;
  1303. if (define)
  1304. {
  1305. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1306. mStringCharPtrPool[stringId] = stringCharsVal;
  1307. SizedArray<BfIRValue, 8> typeValueParams;
  1308. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1309. auto objData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1310. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1311. typeValueParams.clear();
  1312. typeValueParams.push_back(objData);
  1313. if (lenByteCount == 4)
  1314. {
  1315. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1316. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1317. }
  1318. else
  1319. {
  1320. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1321. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1322. }
  1323. typeValueParams.push_back(stringCharsVal); // mPtr
  1324. stringValData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1325. }
  1326. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1327. mBfIRBuilder->MapTypeInst(stringTypeInst),
  1328. true,
  1329. BfIRLinkageType_External,
  1330. define ? stringValData : BfIRValue(),
  1331. stringObjName);
  1332. auto stringVal = mBfIRBuilder->CreateBitCast(stringValLiteral, mBfIRBuilder->MapType(stringTypeInst, BfIRPopulateType_Full));
  1333. return stringVal;
  1334. }
  1335. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1336. {
  1337. BF_ASSERT(constantStr.IsConst());
  1338. if (constHolder == NULL)
  1339. constHolder = mBfIRBuilder;
  1340. auto constant = constHolder->GetConstant(constantStr);
  1341. if (constant->mTypeCode == BfTypeCode_Int32)
  1342. {
  1343. return constant->mInt32;
  1344. }
  1345. while (constant->mConstType == BfConstType_BitCast)
  1346. {
  1347. auto constBitCast = (BfConstantBitCast*)constant;
  1348. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1349. }
  1350. if (constant->mConstType == BfConstType_GEP32_2)
  1351. {
  1352. auto constGEP = (BfConstantGEP32_2*)constant;
  1353. constant = constHolder->GetConstantById(constGEP->mTarget);
  1354. }
  1355. if (constant->mConstType == BfConstType_GlobalVar)
  1356. {
  1357. auto constGV = (BfGlobalVar*)constant;
  1358. const char* strDataPrefix = "__bfStrData";
  1359. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1360. return atoi(constGV->mName + strlen(strDataPrefix));
  1361. const char* strObjPrefix = "__bfStrObj";
  1362. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1363. return atoi(constGV->mName + strlen(strObjPrefix));
  1364. }
  1365. return -1;
  1366. }
  1367. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1368. {
  1369. int strId = GetStringPoolIdx(constantStr, constHolder);
  1370. if (strId != -1)
  1371. {
  1372. auto& entry = mContext->mStringObjectIdMap[strId];
  1373. return &entry.mString;
  1374. }
  1375. return NULL;
  1376. }
  1377. BfIRValue BfModule::GetStringCharPtr(int stringId)
  1378. {
  1379. BfIRValue* irValue = NULL;
  1380. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1381. return *irValue;
  1382. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1383. if (!mStringObjectPool.ContainsKey(stringId))
  1384. mStringPoolRefs.Add(stringId);
  1385. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1386. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1387. *irValue = strCharPtrConst;
  1388. return strCharPtrConst;
  1389. }
  1390. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue)
  1391. {
  1392. if (strValue.IsConst())
  1393. {
  1394. int stringId = GetStringPoolIdx(strValue);
  1395. BF_ASSERT(stringId != -1);
  1396. return GetStringCharPtr(stringId);
  1397. }
  1398. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1399. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1400. return charPtr;
  1401. }
  1402. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str)
  1403. {
  1404. return GetStringCharPtr(GetStringObjectValue(str));
  1405. }
  1406. BfIRValue BfModule::GetStringObjectValue(int strId)
  1407. {
  1408. BfIRValue* objValue;
  1409. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1410. return *objValue;
  1411. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1412. return GetStringObjectValue(stringPoolEntry.mString, true);
  1413. }
  1414. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define)
  1415. {
  1416. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1417. mBfIRBuilder->PopulateType(stringType);
  1418. int strId = mContext->GetStringLiteralId(str);
  1419. BfIRValue* irValuePtr = NULL;
  1420. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1421. return *irValuePtr;
  1422. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1423. if (!mStringCharPtrPool.ContainsKey(strId))
  1424. mStringPoolRefs.Add(strId);
  1425. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1426. *irValuePtr = strObject;
  1427. mStringPoolRefs.Add(strId);
  1428. return strObject;
  1429. }
  1430. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1431. {
  1432. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1433. type,
  1434. true,
  1435. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1436. constant,
  1437. name.c_str());
  1438. return newConst;
  1439. }
  1440. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1441. {
  1442. auto curScope = mCurMethodState->mCurScope;
  1443. if (curScope->mLabelNode != NULL)
  1444. curScope->mLabelNode->ToString(curScope->mLabel);
  1445. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1446. {
  1447. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1448. while (checkScope != NULL)
  1449. {
  1450. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1451. {
  1452. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1453. if (errorNode != NULL)
  1454. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1455. break;
  1456. }
  1457. checkScope = checkScope->mPrevScope;
  1458. }
  1459. }
  1460. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1461. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1462. {
  1463. if (prevScope->mHadScopeValueRetain)
  1464. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1465. else
  1466. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1467. }
  1468. mCurMethodState->mBlockNestLevel++;
  1469. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1470. {
  1471. // DIScope could be NULL if we're in an unspecialized method (for example)
  1472. if (mCurMethodState->mCurScope->mDIScope)
  1473. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1474. }
  1475. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1476. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1477. }
  1478. void BfModule::RestoreScoreState_LocalVariables()
  1479. {
  1480. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1481. {
  1482. auto localVar = mCurMethodState->mLocals.back();
  1483. LocalVariableDone(localVar, false);
  1484. mCurMethodState->mLocals.pop_back();
  1485. if (localVar->mShadowedLocal != NULL)
  1486. {
  1487. BfLocalVarEntry* localVarEntryPtr;
  1488. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1489. {
  1490. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1491. }
  1492. }
  1493. else
  1494. {
  1495. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1496. }
  1497. delete localVar;
  1498. }
  1499. }
  1500. void BfModule::RestoreScopeState()
  1501. {
  1502. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1503. mCurMethodState->mBlockNestLevel--;
  1504. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1505. {
  1506. BfIRBlock afterEndBlock;
  1507. if (!mCurMethodState->mLeftBlockUncond)
  1508. {
  1509. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1510. mBfIRBuilder->CreateBr(afterEndBlock);
  1511. mBfIRBuilder->ClearDebugLocation_Last();
  1512. }
  1513. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1514. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1515. if (afterEndBlock)
  1516. {
  1517. mBfIRBuilder->AddBlock(afterEndBlock);
  1518. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1519. }
  1520. }
  1521. if (!mCurMethodState->mLeftBlockUncond)
  1522. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1523. RestoreScoreState_LocalVariables();
  1524. if (mCurMethodState->mCurScope->mValueScopeStart)
  1525. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1526. mCurMethodState->mCurScope = prevScopeData;
  1527. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1528. }
  1529. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1530. {
  1531. if (mBfIRBuilder->mIgnoreWrites)
  1532. return mBfIRBuilder->GetFakeVal();
  1533. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1534. mBfIRBuilder->PopulateType(type);
  1535. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1536. if (!mBfIRBuilder->mIgnoreWrites)
  1537. BF_ASSERT(!prevInsertBlock.IsFake());
  1538. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1539. BfIRValue allocaInst;
  1540. if (arraySize)
  1541. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1542. else
  1543. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1544. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1545. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1546. if (name != NULL)
  1547. mBfIRBuilder->SetName(allocaInst, name);
  1548. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1549. if ((addLifetime) && (WantsLifetimes()))
  1550. {
  1551. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1552. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1553. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1554. }
  1555. return allocaInst;
  1556. }
  1557. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1558. {
  1559. if (mBfIRBuilder->mIgnoreWrites)
  1560. return mBfIRBuilder->GetFakeVal();
  1561. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1562. mBfIRBuilder->PopulateType(typeInst);
  1563. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1564. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1565. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1566. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1567. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1568. if (name != NULL)
  1569. mBfIRBuilder->SetName(allocaInst, name);
  1570. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1571. if ((addLifetime) && (WantsLifetimes()))
  1572. {
  1573. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1574. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1575. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1576. }
  1577. return allocaInst;
  1578. }
  1579. void BfModule::AddStackAlloc(BfTypedValue val, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape)
  1580. {
  1581. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1582. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1583. /*if (mCurMethodState->mInHeadScope)
  1584. isScopeAlloc = true;*/
  1585. if (scopeData == NULL)
  1586. return;
  1587. auto checkBaseType = val.mType->ToTypeInstance();
  1588. if ((checkBaseType != NULL) && (checkBaseType->IsObject()))
  1589. {
  1590. bool hadDtorCall = false;
  1591. while (checkBaseType != NULL)
  1592. {
  1593. if ((checkBaseType->mTypeDef->mDtorDef != NULL) /*&& (checkBaseType != mContext->mBfObjectType)*/)
  1594. {
  1595. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1596. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  1597. BfIRValue useVal = val.mValue;
  1598. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1599. if (isDynAlloc)
  1600. {
  1601. //
  1602. }
  1603. else if (condAlloca)
  1604. {
  1605. BF_ASSERT(!IsTargetingBeefBackend());
  1606. BF_ASSERT(!isDynAlloc);
  1607. auto valPtr = CreateAlloca(checkBaseType);
  1608. mBfIRBuilder->CreateStore(useVal, valPtr);
  1609. useVal = valPtr;
  1610. }
  1611. SizedArray<BfIRValue, 1> llvmArgs;
  1612. llvmArgs.push_back(useVal);
  1613. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1614. if (deferredCall != NULL)
  1615. {
  1616. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1617. if (condAlloca)
  1618. deferredCall->mArgsNeedLoad = true;
  1619. }
  1620. hadDtorCall = true;
  1621. break;
  1622. }
  1623. checkBaseType = checkBaseType->mBaseType;
  1624. }
  1625. return;
  1626. }
  1627. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1628. if (mayEscape)
  1629. {
  1630. // Is this worth it?
  1631. // if ((!IsOptimized()) && (val.mType->IsComposite()) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1632. // {
  1633. // auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1634. // bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1635. // if (!isDyn)
  1636. // {
  1637. // int clearSize = val.mType->mSize;
  1638. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod("MemSet");
  1639. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1640. // SizedArray<BfIRValue, 1> llvmArgs;
  1641. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1642. // llvmArgs.push_back(GetConstValue8(0xDD));
  1643. // llvmArgs.push_back(GetConstValue(clearSize));
  1644. // llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1645. // llvmArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0));
  1646. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1647. // }
  1648. // else
  1649. // {
  1650. // const char* funcName = "SetDeleted1";
  1651. // if (val.mType->mSize >= 16)
  1652. // funcName = "SetDeleted16";
  1653. // else if (val.mType->mSize >= 8)
  1654. // funcName = "SetDeleted8";
  1655. // else if (val.mType->mSize >= 4)
  1656. // funcName = "SetDeleted4";
  1657. //
  1658. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1659. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1660. // SizedArray<BfIRValue, 1> llvmArgs;
  1661. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1662. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1663. // }
  1664. // }
  1665. }
  1666. }
  1667. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1668. {
  1669. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1670. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1671. return false;
  1672. auto checkTypeInstance = startTypeInstance;
  1673. while (checkTypeInstance != NULL)
  1674. {
  1675. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1676. {
  1677. if (fieldInstance.mMergedDataIdx != -1)
  1678. {
  1679. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1680. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1681. {
  1682. // For fields added in extensions, we automatically initialize those if necessary
  1683. auto fieldDef = fieldInstance.GetFieldDef();
  1684. if (!fieldDef->mDeclaringType->IsExtension())
  1685. return false;
  1686. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1687. {
  1688. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1689. mBfIRBuilder->SaveDebugLocation();
  1690. if (localVar->IsParam())
  1691. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1692. else
  1693. {
  1694. BF_ASSERT(localVar->mDeclBlock);
  1695. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1696. }
  1697. mBfIRBuilder->ClearDebugLocation();
  1698. BfIRValue curVal;
  1699. if (localVar->mIsThis)
  1700. curVal = mBfIRBuilder->GetArgument(0);
  1701. else
  1702. curVal = localVar->mAddr;
  1703. auto subTypeInstance = startTypeInstance;
  1704. while (subTypeInstance != checkTypeInstance)
  1705. {
  1706. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1707. subTypeInstance = subTypeInstance->mBaseType;
  1708. }
  1709. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1710. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1711. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1712. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1713. mBfIRBuilder->RestoreDebugLocation();
  1714. }
  1715. localVar->mUnassignedFieldFlags &= ~checkMask;
  1716. if (localVar->mUnassignedFieldFlags == 0)
  1717. localVar->mIsAssigned = true;
  1718. }
  1719. }
  1720. }
  1721. checkTypeInstance = checkTypeInstance->mBaseType;
  1722. }
  1723. return localVar->mIsAssigned;
  1724. }
  1725. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1726. {
  1727. //if (localVar->mAddr == NULL)
  1728. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1729. {
  1730. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1731. {
  1732. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1733. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1734. }
  1735. }*/
  1736. BfAstNode* localNameNode = localVar->mNameNode;
  1737. if (localVar->mIsThis)
  1738. {
  1739. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1740. }
  1741. if (localNameNode != NULL)
  1742. {
  1743. bool isOut = false;
  1744. if (localVar->mResolvedType->IsRef())
  1745. {
  1746. auto refType = (BfRefType*)localVar->mResolvedType;
  1747. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1748. }
  1749. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1750. {
  1751. if ((!localVar->mIsAssigned) & (localVar->IsParam()))
  1752. TryLocalVariableInit(localVar);
  1753. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1754. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1755. //bool deferFullAnalysis = true;
  1756. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1757. if (!localVar->mIsAssigned)
  1758. {
  1759. if (deferUsageWarning)
  1760. {
  1761. // Ignore
  1762. }
  1763. else if (localVar->mIsThis)
  1764. {
  1765. bool foundFields = false;
  1766. auto checkTypeInstance = mCurTypeInstance;
  1767. while (checkTypeInstance != NULL)
  1768. {
  1769. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1770. {
  1771. if (fieldInstance.mMergedDataIdx != -1)
  1772. {
  1773. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1774. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1775. {
  1776. auto fieldDef = fieldInstance.GetFieldDef();
  1777. if (fieldDef->mProtection != BfProtection_Hidden)
  1778. {
  1779. if (checkTypeInstance == mCurTypeInstance)
  1780. {
  1781. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  1782. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1783. }
  1784. else
  1785. {
  1786. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  1787. TypeToString(checkTypeInstance).c_str(),
  1788. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1789. }
  1790. }
  1791. foundFields = true;
  1792. }
  1793. }
  1794. }
  1795. checkTypeInstance = checkTypeInstance->mBaseType;
  1796. }
  1797. if (!foundFields)
  1798. {
  1799. if (mCurTypeInstance->mInstSize > 0)
  1800. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  1801. }
  1802. }
  1803. else if (localVar->IsParam())
  1804. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  1805. else if (!deferUsageWarning)
  1806. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1807. }
  1808. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  1809. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1810. }
  1811. }
  1812. }
  1813. void BfModule::MarkDynStack(BfScopeData* scopeData)
  1814. {
  1815. auto checkScope = mCurMethodState->mCurScope;
  1816. while (true)
  1817. {
  1818. if (checkScope == scopeData)
  1819. break;
  1820. checkScope->mHadOuterDynStack = true;
  1821. checkScope = checkScope->mPrevScope;
  1822. }
  1823. }
  1824. void BfModule::SaveStackState(BfScopeData* scopeData)
  1825. {
  1826. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  1827. // scopes within scopeData restore the stack
  1828. auto checkScope = mCurMethodState->mCurScope;
  1829. while (true)
  1830. {
  1831. if (checkScope == scopeData)
  1832. {
  1833. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  1834. {
  1835. if (mBfIRBuilder->mHasDebugInfo)
  1836. mBfIRBuilder->SaveDebugLocation();
  1837. auto prevPos = mBfIRBuilder->GetInsertBlock();
  1838. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  1839. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  1840. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  1841. mBfIRBuilder->SetInsertPoint(prevPos);
  1842. if (mBfIRBuilder->mHasDebugInfo)
  1843. mBfIRBuilder->RestoreDebugLocation();
  1844. }
  1845. break;
  1846. }
  1847. if (checkScope->mSavedStack)
  1848. {
  1849. for (auto usage : checkScope->mSavedStackUses)
  1850. mBfIRBuilder->EraseInstFromParent(usage);
  1851. checkScope->mSavedStackUses.Clear();
  1852. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  1853. checkScope->mSavedStack = BfIRValue();
  1854. }
  1855. checkScope = checkScope->mPrevScope;
  1856. }
  1857. }
  1858. BfIRValue BfModule::ValueScopeStart()
  1859. {
  1860. if (IsTargetingBeefBackend())
  1861. return mBfIRBuilder->CreateValueScopeStart();
  1862. return BfIRValue();
  1863. }
  1864. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  1865. {
  1866. if (valueScopeStart)
  1867. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  1868. }
  1869. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  1870. {
  1871. auto bfParser = astNode->GetSourceData()->ToParserData();
  1872. if (bfParser == NULL)
  1873. return NULL;
  1874. BfFileInstance** fileInstancePtr = NULL;
  1875. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  1876. {
  1877. return *fileInstancePtr;
  1878. }
  1879. else
  1880. {
  1881. // It's possible two parsers have the same file name (ie: mNextRevision)
  1882. BfFileInstance** namedFileInstancePtr = NULL;
  1883. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  1884. {
  1885. auto bfFileInstance = *namedFileInstancePtr;
  1886. *fileInstancePtr = bfFileInstance;
  1887. return bfFileInstance;
  1888. }
  1889. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  1890. auto bfFileInstance = new BfFileInstance();
  1891. *fileInstancePtr = bfFileInstance;
  1892. *namedFileInstancePtr = bfFileInstance;
  1893. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  1894. bfFileInstance->mParser = bfParser;
  1895. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  1896. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasInfo()))
  1897. {
  1898. String fileName = bfParser->mFileName;
  1899. for (int i = 0; i < (int)fileName.length(); i++)
  1900. {
  1901. if (fileName[i] == DIR_SEP_CHAR_ALT)
  1902. fileName[i] = DIR_SEP_CHAR;
  1903. }
  1904. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, slashPos));
  1905. }
  1906. return bfFileInstance;
  1907. }
  1908. }
  1909. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  1910. {
  1911. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  1912. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  1913. return;
  1914. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  1915. if (astNode == NULL)
  1916. return;
  1917. auto bfParser = astNode->GetSourceData()->ToParserData();
  1918. if (bfParser == NULL)
  1919. return;
  1920. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  1921. {
  1922. if (mCurFilePosition.mFileInstance != NULL)
  1923. {
  1924. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  1925. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  1926. }
  1927. auto bfFileInstance = GetFileFromNode(astNode);
  1928. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  1929. {
  1930. mCurFilePosition = bfFileInstance->mPrevPosition;
  1931. }
  1932. else
  1933. {
  1934. mCurFilePosition.mFileInstance = bfFileInstance;
  1935. mCurFilePosition.mCurLine = 0;
  1936. mCurFilePosition.mCurSrcPos = 0;
  1937. }
  1938. }
  1939. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  1940. BF_ASSERT(srcPos < bfParser->mSrcLength);
  1941. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  1942. if (jumpEntry->mCharIdx > srcPos)
  1943. jumpEntry--;
  1944. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  1945. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  1946. mCurFilePosition.mCurColumn = 0;
  1947. while (mCurFilePosition.mCurSrcPos < srcPos)
  1948. {
  1949. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  1950. {
  1951. mCurFilePosition.mCurLine++;
  1952. mCurFilePosition.mCurColumn = 0;
  1953. }
  1954. else
  1955. {
  1956. mCurFilePosition.mCurColumn++;
  1957. }
  1958. mCurFilePosition.mCurSrcPos++;
  1959. }
  1960. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  1961. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1962. {
  1963. int column = mCurFilePosition.mCurColumn + 1;
  1964. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  1965. {
  1966. // Set to illegal position
  1967. column = 0;
  1968. }
  1969. if (mSetIllegalSrcPosition)
  1970. column = 0;
  1971. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  1972. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  1973. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  1974. {
  1975. // This is from a different scope...
  1976. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  1977. {
  1978. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  1979. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  1980. }
  1981. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  1982. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  1983. }
  1984. else
  1985. {
  1986. if (mCurMethodState->mCurScope->mAltDIFile)
  1987. {
  1988. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  1989. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  1990. }
  1991. }
  1992. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  1993. if (mCurMethodState->mCrossingMixin)
  1994. inlineAt = BfIRMDNode();
  1995. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  1996. if ((flags & BfSrcPosFlag_Expression) == 0)
  1997. mBfIRBuilder->CreateStatementStart();
  1998. }
  1999. }
  2000. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2001. {
  2002. // We've turned off expr src pos (for now?)
  2003. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2004. }
  2005. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2006. {
  2007. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2008. }
  2009. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2010. {
  2011. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2012. {
  2013. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2014. {
  2015. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2016. mBfIRBuilder->SetCurrentDebugLocation(0, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2017. }
  2018. else
  2019. {
  2020. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2021. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2022. }
  2023. if ((flags & BfSrcPosFlag_Expression) == 0)
  2024. mBfIRBuilder->CreateStatementStart();
  2025. }
  2026. }
  2027. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2028. {
  2029. // We've turned off expr src pos (for now?)
  2030. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2031. }
  2032. bool BfModule::CheckProtection(BfProtection protection, bool allowProtected, bool allowPrivate)
  2033. {
  2034. if ((protection == BfProtection_Public) ||
  2035. ((protection == BfProtection_Protected) && (allowProtected)) ||
  2036. ((protection == BfProtection_Private) && (allowPrivate)))
  2037. return true;
  2038. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2039. return true;
  2040. return false;
  2041. }
  2042. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2043. {
  2044. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2045. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2046. {
  2047. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2048. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2049. }
  2050. allowProtected = allowPrivate;
  2051. }
  2052. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2053. {
  2054. if (memberProtection == BfProtection_Hidden)
  2055. return false;
  2056. if (memberProtection == BfProtection_Public)
  2057. return true;
  2058. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2059. {
  2060. BfTypeInstance* curCheckType = mCurTypeInstance;
  2061. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2062. {
  2063. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2064. curCheckType = mixinOwner;
  2065. }
  2066. bool allowPrivate = (memberOwner->mTypeDef == curCheckType->mTypeDef) || (IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef));
  2067. if (allowPrivate)
  2068. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2069. else
  2070. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2071. }
  2072. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2073. return true;
  2074. if (memberProtection == BfProtection_Protected)
  2075. {
  2076. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2077. {
  2078. bool allowProtected = false;
  2079. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2080. auto curCheckType = mCurTypeInstance;
  2081. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2082. {
  2083. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2084. curCheckType = mixinOwner;
  2085. }
  2086. auto lookupCheckType = lookupStartType;
  2087. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2088. {
  2089. if (lookupCheckType == curCheckType)
  2090. {
  2091. allowProtected = true;
  2092. break;
  2093. }
  2094. if (lookupCheckType == memberOwner)
  2095. break;
  2096. lookupCheckType = lookupCheckType->mBaseType;
  2097. if (lookupCheckType == NULL)
  2098. break;
  2099. }
  2100. if (!allowProtected)
  2101. {
  2102. // It's possible our outer type is derived from 'memberOwner'
  2103. while (curCheckType->mTypeDef->mNestDepth > 0)
  2104. {
  2105. curCheckType = GetOuterType(curCheckType);
  2106. if (curCheckType == NULL)
  2107. break;
  2108. auto lookupCheckType = lookupStartType;
  2109. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2110. {
  2111. if (lookupCheckType == curCheckType)
  2112. {
  2113. allowProtected = true;
  2114. break;
  2115. }
  2116. if (lookupCheckType == memberOwner)
  2117. break;
  2118. lookupCheckType = lookupCheckType->mBaseType;
  2119. if (lookupCheckType == NULL)
  2120. break;
  2121. }
  2122. }
  2123. }
  2124. if (allowProtected)
  2125. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2126. else
  2127. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2128. }
  2129. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2130. return true;
  2131. }
  2132. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2133. return true;
  2134. return false;
  2135. }
  2136. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2137. {
  2138. if ((mCompiler->mResolvePassData != NULL) &&
  2139. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2140. (astNode->IsFromParser( mCompiler->mResolvePassData->mParser)))
  2141. {
  2142. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2143. }
  2144. }
  2145. void BfModule::SetHadVarUsage()
  2146. {
  2147. mHadVarUsage = true;
  2148. mHadBuildError = true;
  2149. }
  2150. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent)
  2151. {
  2152. BP_ZONE("BfModule::Fail");
  2153. if (mIgnoreErrors)
  2154. {
  2155. mHadIgnoredError = true;
  2156. return NULL;
  2157. }
  2158. if (!mReportErrors)
  2159. {
  2160. mCompiler->mPassInstance->SilentFail();
  2161. return NULL;
  2162. }
  2163. if (refNode != NULL)
  2164. refNode = BfNodeToNonTemporary(refNode);
  2165. //BF_ASSERT(refNode != NULL);
  2166. if (mCurMethodInstance != NULL)
  2167. mCurMethodInstance->mHasFailed = true;
  2168. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2169. return NULL;
  2170. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecializedVariation))
  2171. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2172. if (!mHadBuildError)
  2173. mHadBuildError = true;
  2174. if (mParentModule != NULL)
  2175. mParentModule->mHadBuildError = true;
  2176. if (mCurTypeInstance != NULL)
  2177. AddFailType(mCurTypeInstance);
  2178. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2179. String errorString = error;
  2180. bool isWhileSpecializing = false;
  2181. bool isWhileSpecializingMethod = false;
  2182. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2183. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2184. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2185. errorString += StrFormat("\n while generating append size calculating method");
  2186. else if (refNode == NULL)
  2187. {
  2188. if (mCurTypeInstance != NULL)
  2189. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2190. else if (mProject != NULL)
  2191. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2192. }
  2193. if ((mCurTypeInstance != NULL) && (mCurMethodState != NULL))
  2194. {
  2195. auto checkMethodState = mCurMethodState;
  2196. while (checkMethodState != NULL)
  2197. {
  2198. auto methodInstance = checkMethodState->mMethodInstance;
  2199. if (methodInstance == NULL)
  2200. {
  2201. checkMethodState = checkMethodState->mPrevMethodState;
  2202. continue;
  2203. }
  2204. // Propogatea the fail all the way to the main method (assuming we're in a local method or lambda)
  2205. methodInstance->mHasFailed = true;
  2206. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2207. if (isSpecializedMethod)
  2208. {
  2209. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2210. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2211. if (unspecializedMethod->mHasFailed)
  2212. return NULL; // At least SOME error has already been reported
  2213. }
  2214. if (isSpecializedMethod)
  2215. {
  2216. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2217. isWhileSpecializing = true;
  2218. isWhileSpecializingMethod = true;
  2219. }
  2220. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2221. {
  2222. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2223. isWhileSpecializing = true;
  2224. isWhileSpecializingMethod = true;
  2225. }
  2226. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2227. {
  2228. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2229. isWhileSpecializing = true;
  2230. }
  2231. checkMethodState = checkMethodState->mPrevMethodState;
  2232. }
  2233. // Keep in mind that all method specializations with generic type instances as its method generic params
  2234. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2235. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2236. // those method specializations if that occurs
  2237. if (isWhileSpecializing)
  2238. {
  2239. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2240. if (bfError != NULL)
  2241. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2242. return bfError;
  2243. }
  2244. }
  2245. if (!mHadBuildError)
  2246. mHadBuildError = true;
  2247. // Check mixins
  2248. {
  2249. auto checkMethodInstance = mCurMethodState;
  2250. while (checkMethodInstance != NULL)
  2251. {
  2252. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2253. if (rootMixinState != NULL)
  2254. {
  2255. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2256. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2257. auto mixinState = checkMethodInstance->mMixinState;
  2258. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2259. {
  2260. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2261. mixinState = mixinState->mPrevMixinState;
  2262. }
  2263. return bfError;
  2264. }
  2265. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2266. }
  2267. }
  2268. BfError* bfError = NULL;
  2269. if (refNode == NULL)
  2270. bfError = mCompiler->mPassInstance->Fail(errorString);
  2271. else
  2272. {
  2273. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2274. }
  2275. if (bfError != NULL)
  2276. {
  2277. bfError->mIsPersistent = isPersistent;
  2278. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2279. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2280. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2281. }
  2282. return bfError;
  2283. }
  2284. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2285. {
  2286. if (mIgnoreErrors)
  2287. return NULL;
  2288. if (refNode != NULL)
  2289. refNode = BfNodeToNonTemporary(refNode);
  2290. mHadBuildError = true;
  2291. return mCompiler->mPassInstance->FailAfter(error, refNode);
  2292. }
  2293. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2294. {
  2295. if (mIgnoreErrors || mIgnoreWarnings)
  2296. return NULL;
  2297. if (!mReportErrors)
  2298. {
  2299. mCompiler->mPassInstance->SilentFail();
  2300. return NULL;
  2301. }
  2302. BfAstNode* unwarnNode = refNode;
  2303. //
  2304. {
  2305. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2306. while (parentNodeEntry != NULL)
  2307. {
  2308. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2309. break;
  2310. unwarnNode = parentNodeEntry->mNode;
  2311. parentNodeEntry = parentNodeEntry->mPrev;
  2312. }
  2313. }
  2314. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2315. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2316. {
  2317. return NULL;
  2318. }
  2319. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2320. if (mCurMethodInstance != NULL)
  2321. {
  2322. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2323. return NULL;
  2324. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2325. return NULL; // No ctorCalcAppend warnings
  2326. }
  2327. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2328. return NULL;
  2329. if (refNode != NULL)
  2330. refNode = BfNodeToNonTemporary(refNode);
  2331. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2332. {
  2333. // We used to bubble up warnings into the mixin injection site, BUT
  2334. // we are now assuming any relevant warnings will be given at the declaration site
  2335. return NULL;
  2336. // AddFailType(mCurTypeInstance);
  2337. //
  2338. // BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Warning while injecting mixin", mCurMethodState->mMixinState->GetRoot()->mSource);
  2339. // if (bfError == NULL)
  2340. // return NULL;
  2341. // mHadBuildWarning = true;
  2342. // return mCompiler->mPassInstance->MoreInfo(warning, refNode);
  2343. }
  2344. BfError* bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2345. if (bfError != NULL)
  2346. {
  2347. AddFailType(mCurTypeInstance);
  2348. mHadBuildWarning = true;
  2349. bfError->mIsPersistent = isPersistent;
  2350. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2351. {
  2352. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2353. if (parser != NULL)
  2354. {
  2355. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2356. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2357. }
  2358. }
  2359. }
  2360. return bfError;
  2361. }
  2362. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2363. {
  2364. if (mBfIRBuilder->mOpFailed)
  2365. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2366. }
  2367. void BfModule::NotImpl(BfAstNode* astNode)
  2368. {
  2369. Fail("INTERNAL ERROR: Not implemented", astNode);
  2370. }
  2371. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfType* memberType)
  2372. {
  2373. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2374. if (!allowPrivate)
  2375. allowPrivate |= memberType->IsInterface();
  2376. bool allowProtected = allowPrivate;// allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2377. if (!CheckProtection(protection, allowProtected, allowPrivate))
  2378. {
  2379. return false;
  2380. }
  2381. return true;
  2382. }
  2383. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2384. {
  2385. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2386. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2387. auto memberTypeInstance = memberType->ToTypeInstance();
  2388. if (memberTypeInstance == NULL)
  2389. {
  2390. auto underlyingType = memberType->GetUnderlyingType();
  2391. if (underlyingType != NULL)
  2392. return CheckDefineMemberProtection(protection, underlyingType);
  2393. return true;
  2394. }
  2395. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2396. return false;
  2397. if (memberTypeInstance->IsGenericTypeInstance())
  2398. {
  2399. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2400. auto genericTypeInstance = (BfGenericTypeInstance*) memberTypeInstance;
  2401. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  2402. {
  2403. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2404. return false;
  2405. }
  2406. }
  2407. return true;
  2408. }
  2409. void BfModule::AddDependency(BfType* usedType, BfType* usingType, BfDependencyMap::DependencyDependencyFlag flags)
  2410. {
  2411. if (usedType == usingType)
  2412. return;
  2413. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2414. return;
  2415. if (usedType->IsSpecializedByAutoCompleteMethod())
  2416. return;
  2417. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) &&
  2418. ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0))
  2419. {
  2420. bool addType = true;
  2421. auto checkType = usedType;
  2422. while (true)
  2423. {
  2424. if ((checkType->IsPointer()) || (checkType->IsRef()) || (checkType->IsSizedArray()))
  2425. checkType = checkType->GetUnderlyingType();
  2426. else if (checkType->IsArray())
  2427. {
  2428. checkType = ((BfGenericTypeInstance*)checkType)->mTypeGenericArguments[0];
  2429. }
  2430. else
  2431. break;
  2432. }
  2433. PopulateType(checkType, BfPopulateType_Data);
  2434. if (checkType->IsValuelessType())
  2435. addType = false;
  2436. else if (checkType->IsPrimitiveType())
  2437. addType = false;
  2438. else
  2439. {
  2440. auto checkTypeInst = checkType->ToTypeInstance();
  2441. if (checkTypeInst == NULL)
  2442. {
  2443. addType = false;
  2444. }
  2445. else
  2446. {
  2447. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2448. addType = false;
  2449. }
  2450. }
  2451. if (addType)
  2452. {
  2453. auto checkTypeInst = checkType->ToTypeInstance();
  2454. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2455. BF_ASSERT(hotTypeVersion != NULL);
  2456. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2457. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2458. (checkType->IsComposite()))
  2459. isAllocation = true;
  2460. if (isAllocation)
  2461. {
  2462. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2463. }
  2464. else
  2465. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2466. }
  2467. }
  2468. //BP_ZONE("BfModule::AddDependency");
  2469. /*if (usedType->IsMethodRef())
  2470. {
  2471. auto methodRefType = (BfMethodRefType*)usedType;
  2472. AddDependency(methodRefType->mMethodRef->GetOwner(), usingType, flags);
  2473. return;
  2474. }*/
  2475. // Why in the world were we doing this?
  2476. // This caused functions to get immediately deleted since they appear to have no references ever....
  2477. // if (usedType->IsFunction())
  2478. // {
  2479. // usedType = ResolveTypeDef(mCompiler->mFunctionTypeDef);
  2480. // }
  2481. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2482. {
  2483. auto usingModule = usingType->GetModule();
  2484. BfModule* usedModule;
  2485. if (usedType->IsFunction())
  2486. {
  2487. auto typeInst = usedType->ToTypeInstance();
  2488. if (typeInst->mBaseType == NULL)
  2489. PopulateType(typeInst);
  2490. usedModule = typeInst->mBaseType->GetModule();
  2491. }
  2492. else
  2493. usedModule = usedType->GetModule();
  2494. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2495. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2496. {
  2497. usingModule->mModuleRefs.Add(usedModule);
  2498. }
  2499. }
  2500. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2501. {
  2502. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2503. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2504. if (genericArg == usedType)
  2505. return;
  2506. }
  2507. auto underlyingType = usedType->GetUnderlyingType();
  2508. if (underlyingType != NULL) // Not really a "GenericArg", but... same purpose.
  2509. AddDependency(underlyingType, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2510. BfDependedType* checkDType = usedType->ToDependedType();
  2511. if (checkDType == NULL)
  2512. return;
  2513. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2514. mContext->MarkAsReferenced(checkDType);
  2515. checkDType->mDependencyMap.AddUsedBy(usingType, flags);
  2516. if (checkDType->IsGenericTypeInstance())
  2517. {
  2518. auto genericTypeInstance = (BfGenericTypeInstance*) checkDType;
  2519. for (auto genericArg : genericTypeInstance->mTypeGenericArguments)
  2520. {
  2521. AddDependency(genericArg, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2522. }
  2523. }
  2524. }
  2525. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  2526. {
  2527. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  2528. {
  2529. if (methodInstance->mHotMethod == NULL)
  2530. CheckHotMethod(methodInstance, "");
  2531. BF_ASSERT(methodInstance->mHotMethod != NULL);
  2532. if (devirtualized)
  2533. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  2534. else
  2535. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  2536. }
  2537. }
  2538. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  2539. {
  2540. auto checkTypeInst = typeInst;
  2541. while (checkTypeInst != NULL)
  2542. {
  2543. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  2544. return true;
  2545. checkTypeInst = checkTypeInst->mBaseType;
  2546. }
  2547. return false;
  2548. }
  2549. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  2550. {
  2551. if (mContext->mCurTypeState == NULL)
  2552. return;
  2553. BP_ZONE("PopulateGlobalContainersList");
  2554. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  2555. if (userTypeDef == NULL)
  2556. userTypeDef = mCurTypeInstance->mTypeDef;
  2557. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  2558. {
  2559. mContext->mCurTypeState->mGlobalContainers.Clear();
  2560. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  2561. {
  2562. BfAtomComposite findStr;
  2563. if (namespaceIdx != -1)
  2564. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  2565. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  2566. while (typeDefItr)
  2567. {
  2568. auto typeDef = *typeDefItr;
  2569. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  2570. {
  2571. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  2572. {
  2573. BfGlobalContainerEntry globalEntry;
  2574. globalEntry.mTypeDef = typeDef;
  2575. globalEntry.mTypeInst = NULL;
  2576. typeDef->PopulateMemberSets();
  2577. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  2578. }
  2579. }
  2580. else if (!typeDef->mIsPartial)
  2581. {
  2582. //break;
  2583. }
  2584. typeDefItr.MoveToNextHashMatch();
  2585. }
  2586. }
  2587. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  2588. }
  2589. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  2590. // reifing types
  2591. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  2592. {
  2593. if (globalEntry.mTypeInst == NULL)
  2594. {
  2595. bool include = false;
  2596. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  2597. include = true;
  2598. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  2599. {
  2600. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  2601. include = true;
  2602. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  2603. include = true;
  2604. }
  2605. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  2606. {
  2607. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  2608. include = true;
  2609. }
  2610. if (include)
  2611. {
  2612. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  2613. if (type != NULL)
  2614. globalEntry.mTypeInst = type->ToTypeInstance();
  2615. }
  2616. }
  2617. }
  2618. }
  2619. void PrintUsers(llvm::MDNode* md);
  2620. BfModuleOptions BfModule::GetModuleOptions()
  2621. {
  2622. if (mIsScratchModule)
  2623. return BfModuleOptions();
  2624. if (mModuleOptions != NULL)
  2625. return *mModuleOptions;
  2626. BfModuleOptions moduleOptions;
  2627. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  2628. if (mProject != NULL)
  2629. {
  2630. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  2631. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  2632. }
  2633. auto headModule = this;
  2634. while (headModule->mParentModule != NULL)
  2635. headModule = headModule->mParentModule;
  2636. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata"));
  2637. if (headModule->mOwnedTypeInstances.size() > 0)
  2638. {
  2639. auto typeInst = headModule->mOwnedTypeInstances[0];
  2640. PopulateType(typeInst);
  2641. if (typeInst->mTypeOptionsIdx != -1)
  2642. {
  2643. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  2644. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  2645. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  2646. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  2647. }
  2648. }
  2649. return moduleOptions;
  2650. }
  2651. BfCheckedKind BfModule::GetDefaultCheckedKind()
  2652. {
  2653. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  2654. auto typeOptions = GetTypeOptions();
  2655. if (typeOptions != NULL)
  2656. runtimeChecks = BfTypeOptions::Apply(runtimeChecks, typeOptions->mRuntimeChecks);
  2657. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  2658. }
  2659. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  2660. {
  2661. mContext->mFailTypes.Add(typeInstance);
  2662. }
  2663. void BfModule::CheckAddFailType()
  2664. {
  2665. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  2666. // but we still need to add the owning type to the FailTypes list
  2667. //.. OLD:
  2668. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  2669. /*if (mCurTypeInstance->mModule != this)
  2670. return;*/
  2671. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  2672. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  2673. // being recompiled. This forces types with warnings to be recompiled.
  2674. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  2675. // constantly warning-aware
  2676. if ((mHadBuildError) ||
  2677. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  2678. {
  2679. //mContext->mFailTypes.Add(mCurTypeInstance);
  2680. }
  2681. }
  2682. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  2683. {
  2684. if (!mCompiler->IsHotCompile())
  2685. return;
  2686. typeInst->mDirty = true;
  2687. for (auto& dep : typeInst->mDependencyMap)
  2688. {
  2689. auto depType = dep.mKey;
  2690. auto depFlags = dep.mValue.mFlags;
  2691. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  2692. {
  2693. MarkDerivedDirty(depType->ToTypeInstance());
  2694. }
  2695. }
  2696. }
  2697. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  2698. {
  2699. auto fieldType = fieldInstance->GetResolvedType();
  2700. auto field = fieldInstance->GetFieldDef();
  2701. if (fieldType->IsVar())
  2702. return;
  2703. BfIRValue initValue;
  2704. if (field->mIsConst)
  2705. {
  2706. if (fieldType->IsPointer())
  2707. fieldType = fieldType->GetUnderlyingType();
  2708. }
  2709. if (!field->mIsExtern)
  2710. initValue = GetDefaultValue(fieldType);
  2711. if (fieldInstance->mOwner->IsUnspecializedType())
  2712. {
  2713. // Placeholder
  2714. auto ptrVal = CreatePointerType(fieldType);
  2715. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  2716. }
  2717. else
  2718. {
  2719. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  2720. StringT<128> staticVarName;
  2721. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  2722. if (!fieldType->IsValuelessType())
  2723. {
  2724. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  2725. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  2726. false,
  2727. BfIRLinkageType_External,
  2728. initValue,
  2729. staticVarName,
  2730. isThreadLocal);
  2731. BF_ASSERT(globalVar);
  2732. mStaticFieldRefs[fieldInstance] = globalVar;
  2733. }
  2734. }
  2735. }
  2736. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  2737. {
  2738. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  2739. BfType* fieldType = NULL;
  2740. if (fieldInstance != NULL)
  2741. {
  2742. fieldType = fieldInstance->GetResolvedType();
  2743. if (fieldType == NULL)
  2744. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2745. }
  2746. else
  2747. {
  2748. BF_ASSERT(mCompiler->IsAutocomplete());
  2749. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2750. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  2751. {
  2752. fieldType = typeInstance;
  2753. }
  2754. else
  2755. {
  2756. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  2757. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  2758. if (isLet || isVar)
  2759. fieldType = GetPrimitiveType(BfTypeCode_Var);
  2760. else
  2761. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2762. if (fieldType == NULL)
  2763. fieldType = mContext->mBfObjectType;
  2764. }
  2765. }
  2766. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  2767. return;
  2768. if (mContext->mFieldResolveReentrys.size() > 1)
  2769. {
  2770. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2771. {
  2772. String failStr = "Circular data reference detected between the following fields:";
  2773. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2774. {
  2775. if (i > 1)
  2776. failStr += ",";
  2777. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  2778. }
  2779. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  2780. if (err)
  2781. err->mIsPersistent = true;
  2782. return;
  2783. }
  2784. }
  2785. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2786. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2787. if (fieldInstance == NULL)
  2788. popTypeResolveReentry.Pop();
  2789. auto typeDef = typeInstance->mTypeDef;
  2790. BfIRValue constValue;
  2791. if (fieldDef->mIsExtern)
  2792. {
  2793. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  2794. {
  2795. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  2796. }
  2797. if (fieldDef->mInitializer != NULL)
  2798. {
  2799. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  2800. }
  2801. }
  2802. else if (fieldDef->mInitializer == NULL)
  2803. {
  2804. if (fieldDef->IsEnumCaseEntry())
  2805. {
  2806. if (typeInstance->IsTypedPrimitive())
  2807. {
  2808. BfFieldInstance* prevFieldInstance = NULL;
  2809. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  2810. {
  2811. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  2812. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  2813. {
  2814. prevFieldInstance = checkFieldInst;
  2815. break;
  2816. }
  2817. }
  2818. if (prevFieldInstance == NULL)
  2819. constValue = GetConstValue(0, typeInstance);
  2820. else
  2821. {
  2822. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  2823. if (prevFieldInstance->mConstIdx == -1)
  2824. {
  2825. if (!mCompiler->IsAutocomplete())
  2826. AssertErrorState();
  2827. constValue = GetConstValue(0, typeInstance);
  2828. }
  2829. else
  2830. {
  2831. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  2832. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  2833. }
  2834. }
  2835. }
  2836. }
  2837. else
  2838. {
  2839. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  2840. }
  2841. }
  2842. else
  2843. {
  2844. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2845. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2846. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  2847. BfConstResolver constResolver(this);
  2848. BfMethodState methodState;
  2849. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2850. methodState.mTempKind = BfMethodState::TempKind_Static;
  2851. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2852. if (fieldType->IsVar())
  2853. {
  2854. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2855. if (!initValue)
  2856. {
  2857. AssertErrorState();
  2858. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  2859. }
  2860. if (fieldInstance != NULL)
  2861. {
  2862. fieldInstance->mResolvedType = initValue.mType;
  2863. }
  2864. constValue = initValue.mValue;
  2865. }
  2866. else
  2867. {
  2868. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2869. constValue = uncastedInitValue.mValue;
  2870. }
  2871. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2872. }
  2873. if (fieldInstance != NULL)
  2874. {
  2875. fieldType = fieldInstance->GetResolvedType();
  2876. if ((fieldType == NULL) || (fieldType->IsVar()))
  2877. {
  2878. AssertErrorState();
  2879. // Default const type is 'int'
  2880. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  2881. if (fieldInstance != NULL)
  2882. {
  2883. fieldInstance->mResolvedType = initValue.mType;
  2884. }
  2885. constValue = initValue.mValue;
  2886. }
  2887. if ((constValue) && (fieldInstance->mConstIdx == -1))
  2888. {
  2889. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2890. CurrentAddToConstHolder(constValue);
  2891. fieldInstance->mConstIdx = constValue.mId;
  2892. }
  2893. }
  2894. }
  2895. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  2896. {
  2897. bool isDeclType = BfNodeDynCastExact<BfDeclTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  2898. auto fieldType = fieldInstance->GetResolvedType();
  2899. if ((field->mIsConst) && (!isDeclType))
  2900. {
  2901. ResolveConstField(typeInstance, fieldInstance, field);
  2902. return fieldInstance->GetResolvedType();
  2903. }
  2904. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  2905. if (!fieldInstance->mIsInferredType)
  2906. return fieldType;
  2907. if (!fieldType->IsVar())
  2908. return fieldType;
  2909. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2910. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  2911. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mTypeInstance != typeInstance);
  2912. auto typeDef = typeInstance->mTypeDef;
  2913. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  2914. {
  2915. AssertErrorState();
  2916. SetHadVarUsage();
  2917. return GetPrimitiveType(BfTypeCode_Var);
  2918. }
  2919. bool hadInferenceCycle = false;
  2920. if (mContext->mFieldResolveReentrys.size() > 1)
  2921. {
  2922. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2923. {
  2924. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2925. {
  2926. auto fieldInst = mContext->mFieldResolveReentrys[i];
  2927. auto fieldDef = fieldInst->GetFieldDef();
  2928. auto fieldOwner = fieldInst->mOwner;
  2929. auto fieldModule = fieldOwner->mModule;
  2930. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  2931. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  2932. }
  2933. SetHadVarUsage();
  2934. return GetPrimitiveType(BfTypeCode_Var);
  2935. }
  2936. }
  2937. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2938. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2939. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  2940. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  2941. if ((field->mInitializer == NULL) && (!isDeclType))
  2942. {
  2943. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  2944. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  2945. SetHadVarUsage();
  2946. return GetPrimitiveType(BfTypeCode_Var);
  2947. }
  2948. BfType* resolvedType = NULL;
  2949. if (!hadInferenceCycle)
  2950. {
  2951. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2952. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  2953. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2954. BfMethodState methodState;
  2955. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2956. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  2957. if (!staticOnly)
  2958. {
  2959. //BfLocalVariable localVar;
  2960. //methodState.mLocals.push_back(localVar);
  2961. }
  2962. if (isDeclType)
  2963. {
  2964. auto fieldDef = fieldInstance->GetFieldDef();
  2965. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  2966. }
  2967. else
  2968. {
  2969. BfTypedValue valueFromExpr;
  2970. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  2971. FixIntUnknown(valueFromExpr);
  2972. resolvedType = valueFromExpr.mType;
  2973. }
  2974. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2975. }
  2976. if (resolvedType == NULL)
  2977. return GetPrimitiveType(BfTypeCode_Var);
  2978. fieldInstance->SetResolvedType(resolvedType);
  2979. if (field->mIsStatic)
  2980. {
  2981. }
  2982. else if (fieldInstance->mDataIdx <= 0)
  2983. {
  2984. }
  2985. else
  2986. {
  2987. BF_ASSERT(typeInstance->IsIncomplete());
  2988. }
  2989. return resolvedType;
  2990. }
  2991. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  2992. {
  2993. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  2994. auto fieldType = fieldInstance->GetResolvedType();
  2995. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  2996. {
  2997. int fieldDataCount = 1;
  2998. if (fieldType->IsStruct())
  2999. {
  3000. auto structTypeInst = fieldType->ToTypeInstance();
  3001. fieldDataCount = structTypeInst->mMergedFieldDataCount;
  3002. }
  3003. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3004. auto thisVariable = GetThisVariable();
  3005. if (thisVariable != NULL)
  3006. {
  3007. for (int i = 0; i < fieldDataCount; i++)
  3008. mCurMethodState->LocalDefined(thisVariable, fieldInstance->mMergedDataIdx + i);
  3009. }
  3010. }
  3011. }
  3012. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3013. {
  3014. if (fieldInstance->mCustomAttributes == NULL)
  3015. return false;
  3016. auto fieldDef = fieldInstance->GetFieldDef();
  3017. if (!fieldDef->mIsStatic)
  3018. return false;
  3019. bool isThreadLocal = false;
  3020. if (fieldInstance->mCustomAttributes != NULL)
  3021. {
  3022. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3023. {
  3024. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  3025. return true;
  3026. }
  3027. }
  3028. return false;
  3029. }
  3030. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType)
  3031. {
  3032. if (fieldDef == NULL)
  3033. fieldDef = fieldInstance->GetFieldDef();
  3034. if (fieldType == NULL)
  3035. fieldType = fieldInstance->GetResolvedType();
  3036. if (initializer == NULL)
  3037. {
  3038. if (fieldDef == NULL)
  3039. return BfTypedValue();
  3040. initializer = fieldDef->mInitializer;
  3041. }
  3042. BfTypedValue result;
  3043. if (initializer == NULL)
  3044. {
  3045. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3046. }
  3047. else
  3048. {
  3049. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3050. {
  3051. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3052. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3053. }
  3054. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3055. {
  3056. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3057. BfConstResolver constResolver(this);
  3058. constResolver.Resolve(initializer);
  3059. return GetDefaultTypedValue(fieldType);
  3060. }
  3061. else if (fieldDef->mIsConst)
  3062. {
  3063. BfTypeState typeState;
  3064. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3065. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3066. BfConstResolver constResolver(this);
  3067. if (fieldType->IsVar())
  3068. return constResolver.Resolve(initializer);
  3069. else
  3070. return constResolver.Resolve(initializer, fieldType);
  3071. }
  3072. if (fieldType->IsVar())
  3073. result = CreateValueFromExpression(initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3074. else
  3075. result = CreateValueFromExpression(initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3076. }
  3077. if (fieldInstance != NULL)
  3078. MarkFieldInitialized(fieldInstance);
  3079. return result;
  3080. }
  3081. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3082. {
  3083. }
  3084. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3085. {
  3086. PopulateType(classType);
  3087. if (isInterfacePass)
  3088. {
  3089. for (auto ifaceInst : classType->mInterfaces)
  3090. {
  3091. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3092. continue;
  3093. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3094. continue;
  3095. if (ifaceInst.mDeclaringType->IsExtension())
  3096. {
  3097. bool needsExCheck = false;
  3098. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3099. {
  3100. exChecks->push_back(ifaceInst.mInterfaceType);
  3101. continue;
  3102. }
  3103. }
  3104. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3105. }
  3106. }
  3107. else
  3108. {
  3109. outVals->push_back(classType->mTypeId);
  3110. }
  3111. if (classType->mBaseType != NULL)
  3112. {
  3113. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3114. }
  3115. }
  3116. void BfModule::CreateDynamicCastMethod()
  3117. {
  3118. auto objType = mContext->mBfObjectType;
  3119. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3120. {
  3121. // The main reason to punt on this method for ResolveOnly is because types can be created
  3122. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3123. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3124. // remove this punt when we recycle typeId's
  3125. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3126. mCurMethodState->mHadReturn = true;
  3127. return;
  3128. }
  3129. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3130. auto func = mCurMethodState->mIRFunction;
  3131. auto thisValue = mBfIRBuilder->GetArgument(0);
  3132. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3133. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3134. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3135. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3136. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3137. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3138. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3139. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3140. SizedArray<int, 8> typeMatches;
  3141. SizedArray<BfTypeInstance*, 8> exChecks;
  3142. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3143. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3144. {
  3145. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3146. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3147. BfTypeVector genericArgs;
  3148. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3149. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3150. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3151. typeMatches.push_back(unboundType->mTypeId);
  3152. }
  3153. if (mCurTypeInstance->IsBoxed())
  3154. {
  3155. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3156. BfTypeInstance* innerType = boxedType->mElementType;
  3157. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3158. if (innerType->IsTypedPrimitive())
  3159. {
  3160. auto underlyingType = innerType->GetUnderlyingType();
  3161. typeMatches.push_back(underlyingType->mTypeId);
  3162. }
  3163. auto innerTypeInst = innerType->ToTypeInstance();
  3164. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3165. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3166. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3167. {
  3168. PopulateType(innerTypeInst);
  3169. //TODO: What case was this supposed to handle?
  3170. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3171. }
  3172. }
  3173. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3174. BfIRValue vDataPtr;
  3175. if (!exChecks.empty())
  3176. {
  3177. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3178. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3179. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3180. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3181. }
  3182. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3183. for (auto typeMatch : typeMatches)
  3184. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3185. Array<BfIRValue> incomingFalses;
  3186. for (auto ifaceTypeInst : exChecks)
  3187. {
  3188. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3189. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3190. mBfIRBuilder->SetInsertPoint(nextBB);
  3191. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3192. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3193. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3194. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3195. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3196. incomingFalses.push_back(nextBB);
  3197. }
  3198. mBfIRBuilder->AddBlock(trueBB);
  3199. mBfIRBuilder->SetInsertPoint(trueBB);
  3200. mBfIRBuilder->CreateBr(exitBB);
  3201. mBfIRBuilder->AddBlock(exitBB);
  3202. mBfIRBuilder->SetInsertPoint(exitBB);
  3203. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3204. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3205. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3206. for (auto incomingFalseBlock : incomingFalses)
  3207. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3208. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3209. mBfIRBuilder->CreateRet(phi);
  3210. mCurMethodState->mHadReturn = true;
  3211. }
  3212. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB)
  3213. {
  3214. BfExprEvaluator exprEvaluator(this);
  3215. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3216. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, BfBinaryOp_Equality, NULL, BfBinOpFlag_None, leftValue, rightValue);
  3217. BfTypedValue result = exprEvaluator.GetResult();
  3218. if (result)
  3219. {
  3220. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3221. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3222. mBfIRBuilder->AddBlock(nextBB);
  3223. mBfIRBuilder->SetInsertPoint(nextBB);
  3224. }
  3225. }
  3226. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3227. {
  3228. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3229. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3230. SizedArray<BfIRType, 4> paramTypes;
  3231. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3232. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3233. mBfIRBuilder->SetActiveFunction(func);
  3234. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3235. mBfIRBuilder->SetInsertPoint(entryBlock);
  3236. SizedArray<BfIRValue, 8> args;
  3237. BfExprEvaluator exprEvaluator(this);
  3238. if (mCurMethodInstance->HasThis())
  3239. {
  3240. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true);
  3241. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3242. }
  3243. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3244. {
  3245. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3246. if (paramType->IsValuelessType())
  3247. continue;
  3248. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true), args);
  3249. }
  3250. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3251. mBfIRBuilder->CreateRetVoid();
  3252. }
  3253. void BfModule::CreateValueTypeEqualsMethod()
  3254. {
  3255. if (mCurMethodInstance->mIsUnspecialized)
  3256. return;
  3257. if (mCurTypeInstance->IsTypedPrimitive())
  3258. return;
  3259. if (mBfIRBuilder->mIgnoreWrites)
  3260. return;
  3261. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3262. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3263. bool isValid = true;
  3264. auto compareDType = compareType->ToDependedType();
  3265. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3266. if (compareTypeInst != NULL)
  3267. {
  3268. if (compareType->IsPrimitiveType())
  3269. compareTypeInst = GetWrappedStructType(compareType);
  3270. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3271. {
  3272. isValid = false;
  3273. }
  3274. mBfIRBuilder->PopulateType(compareTypeInst);
  3275. }
  3276. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3277. if (!isValid)
  3278. {
  3279. ClearLifetimeEnds();
  3280. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3281. return;
  3282. }
  3283. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3284. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3285. if (refNode == NULL)
  3286. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3287. UpdateSrcPos(refNode);
  3288. SetIllegalSrcPos();
  3289. auto resultVal = CreateAlloca(boolType);
  3290. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3291. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3292. if (compareType->IsSizedArray())
  3293. {
  3294. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3295. if (sizedArrayType->mElementCount > 6)
  3296. {
  3297. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3298. auto itr = CreateAlloca(intPtrType);
  3299. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3300. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3301. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  3302. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  3303. mBfIRBuilder->CreateBr(loopBB);
  3304. mBfIRBuilder->SetInsertPoint(loopBB);
  3305. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  3306. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  3307. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  3308. mBfIRBuilder->SetInsertPoint(bodyBB);
  3309. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3310. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3311. EmitEquals(leftValue, rightValue, exitBB);
  3312. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  3313. mBfIRBuilder->CreateStore(incValue, itr);
  3314. mBfIRBuilder->CreateBr(loopBB);
  3315. mBfIRBuilder->SetInsertPoint(doneBB);
  3316. }
  3317. else
  3318. {
  3319. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  3320. {
  3321. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3322. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3323. EmitEquals(leftValue, rightValue, exitBB);
  3324. }
  3325. }
  3326. }
  3327. else if (compareType->IsMethodRef())
  3328. {
  3329. auto methodRefType = (BfMethodRefType*)compareType;
  3330. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  3331. BfExprEvaluator exprEvaluator(this);
  3332. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3333. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3334. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  3335. // values for the same method reference -- they will always refer back to the same local variables.
  3336. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  3337. if (dataIdx != -1)
  3338. {
  3339. bool failed = false;
  3340. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  3341. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  3342. BF_ASSERT(!failed);
  3343. EmitEquals(leftValue, rightValue, exitBB);
  3344. }
  3345. }
  3346. else if (compareTypeInst->IsEnum())
  3347. {
  3348. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3349. BfExprEvaluator exprEvaluator(this);
  3350. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3351. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3352. auto dscrType = compareTypeInst->GetDiscriminatorType();
  3353. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  3354. leftValue = LoadValue(leftValue);
  3355. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  3356. rightValue = LoadValue(rightValue);
  3357. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  3358. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  3359. EmitEquals(leftValue, rightValue, exitBB);
  3360. int enumCount = 0;
  3361. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3362. {
  3363. BfFieldInstance* fieldInstance = &fieldRef;
  3364. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3365. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3366. {
  3367. enumCount = -fieldInstance->mDataIdx;
  3368. }
  3369. }
  3370. if (enumCount > 0)
  3371. {
  3372. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  3373. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  3374. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3375. {
  3376. BfFieldInstance* fieldInstance = &fieldRef;
  3377. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3378. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3379. {
  3380. int enumIdx = -fieldInstance->mDataIdx - 1;
  3381. if (fieldInstance->mResolvedType->mSize == 0)
  3382. {
  3383. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  3384. }
  3385. else
  3386. {
  3387. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  3388. mBfIRBuilder->SetInsertPoint(caseBlock);
  3389. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  3390. BfTypedValue leftTuple;
  3391. BfTypedValue rightTuple;
  3392. if (leftPayload.IsAddr())
  3393. {
  3394. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3395. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3396. }
  3397. else
  3398. {
  3399. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3400. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3401. }
  3402. EmitEquals(leftTuple, rightTuple, exitBB);
  3403. mBfIRBuilder->CreateBr(matchedBlock);
  3404. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  3405. }
  3406. }
  3407. }
  3408. mBfIRBuilder->AddBlock(matchedBlock);
  3409. mBfIRBuilder->SetInsertPoint(matchedBlock);
  3410. }
  3411. }
  3412. else if (compareTypeInst->IsUnion())
  3413. {
  3414. auto innerType = compareTypeInst->GetUnionInnerType();
  3415. if (!innerType->IsValuelessType())
  3416. {
  3417. BfExprEvaluator exprEvaluator(this);
  3418. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3419. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  3420. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3421. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  3422. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB);
  3423. }
  3424. }
  3425. else
  3426. {
  3427. BfExprEvaluator exprEvaluator(this);
  3428. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3429. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3430. bool hadComparison = false;
  3431. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3432. {
  3433. BfFieldInstance* fieldInstance = &fieldRef;
  3434. if (fieldInstance->mDataOffset == -1)
  3435. continue;
  3436. if (fieldInstance->mResolvedType->IsValuelessType())
  3437. continue;
  3438. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3439. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3440. if (!fieldInstance->mResolvedType->IsComposite())
  3441. {
  3442. leftValue = LoadValue(leftValue);
  3443. rightValue = LoadValue(rightValue);
  3444. }
  3445. EmitEquals(leftValue, rightValue, exitBB);
  3446. }
  3447. auto baseTypeInst = compareTypeInst->mBaseType;
  3448. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  3449. {
  3450. BfTypedValue leftOrigValue(mCurMethodState->mLocals[0]->mValue, compareTypeInst, true);
  3451. BfTypedValue rightOrigValue(mCurMethodState->mLocals[1]->mValue, compareTypeInst, true);
  3452. BfTypedValue leftValue = Cast(NULL, leftOrigValue, baseTypeInst);
  3453. BfTypedValue rightValue = Cast(NULL, rightOrigValue, baseTypeInst);
  3454. EmitEquals(leftValue, rightValue, exitBB);
  3455. }
  3456. }
  3457. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  3458. mBfIRBuilder->CreateBr(exitBB);
  3459. mBfIRBuilder->AddBlock(exitBB);
  3460. mBfIRBuilder->SetInsertPoint(exitBB);
  3461. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  3462. ClearLifetimeEnds();
  3463. mBfIRBuilder->CreateRet(loadedResult);
  3464. mCurMethodState->mHadReturn = true;
  3465. }
  3466. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  3467. {
  3468. if (mBfIRBuilder->mIgnoreWrites)
  3469. return mBfIRBuilder->GetFakeVal();
  3470. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3471. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3472. BfIRValue* globalVariablePtr = NULL;
  3473. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  3474. int numElements = 1;
  3475. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  3476. {
  3477. numElements += mCompiler->mMaxInterfaceSlots;
  3478. auto maxIFaceVirtIdx = 0;
  3479. if (!typeInstance->IsInterface())
  3480. {
  3481. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3482. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  3483. numElements += typeInstance->GetOrigVTableSize();
  3484. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  3485. if (typeInstance->mHotTypeData != NULL)
  3486. {
  3487. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  3488. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  3489. }
  3490. numElements += ifaceMethodLen;
  3491. }
  3492. if (outNumElements != NULL)
  3493. *outNumElements = numElements;
  3494. }
  3495. StringT<128> classVDataName;
  3496. String memberName = "sBfClassVData";
  3497. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  3498. {
  3499. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3500. memberName += "_";
  3501. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  3502. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  3503. }
  3504. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  3505. if (outMangledName != NULL)
  3506. *outMangledName = classVDataName;
  3507. /*if (itr != mClassVDataRefs.end())
  3508. {
  3509. globalVariable = itr->second;
  3510. }*/
  3511. BfIRValue globalVariable;
  3512. if (globalVariablePtr != NULL)
  3513. {
  3514. globalVariable = *globalVariablePtr;
  3515. }
  3516. else
  3517. {
  3518. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  3519. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3520. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  3521. arrayType,
  3522. true,
  3523. BfIRLinkageType_External,
  3524. BfIRValue(),
  3525. classVDataName);
  3526. mClassVDataRefs[typeInstance] = globalVariable;
  3527. }
  3528. return globalVariable;
  3529. }
  3530. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  3531. {
  3532. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3533. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  3534. }
  3535. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  3536. {
  3537. if (mBfIRBuilder->mIgnoreWrites)
  3538. return mBfIRBuilder->GetFakeVal();
  3539. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  3540. BF_ASSERT(numElements >= 0);
  3541. if (numElements <= 0)
  3542. return BfIRValue();
  3543. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  3544. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  3545. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  3546. BF_ASSERT(declTypeInst == implTypeInst);
  3547. else
  3548. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  3549. if (declTypeInst != implTypeInst)
  3550. {
  3551. BfTypeInstance* highestImpl = declTypeInst;
  3552. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3553. {
  3554. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3555. break; // Start of an ext entry for another type
  3556. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  3557. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  3558. highestImpl = checkImplTypeInst;
  3559. }
  3560. if (highestImpl != implTypeInst)
  3561. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  3562. }
  3563. BfVDataExtEntry mapEntry;
  3564. mapEntry.mDeclTypeInst = declTypeInst;
  3565. mapEntry.mImplTypeInst = implTypeInst;
  3566. BfIRValue* irValuePtr = NULL;
  3567. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  3568. return *irValuePtr;
  3569. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  3570. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  3571. StringT<128> classVDataName;
  3572. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  3573. if (declTypeInst != implTypeInst)
  3574. {
  3575. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  3576. }
  3577. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3578. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3579. SizedArray<BfIRValue, 32> vData;
  3580. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3581. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3582. {
  3583. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3584. break; // Start of an ext entry for another type
  3585. BfIRValue vValue;
  3586. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  3587. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  3588. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  3589. {
  3590. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  3591. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  3592. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  3593. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  3594. {
  3595. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  3596. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  3597. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  3598. vValue = funcPtr;
  3599. }
  3600. }
  3601. if (!vValue)
  3602. vValue = voidPtrNull;
  3603. vData.Add(vValue);
  3604. }
  3605. BF_ASSERT((int)vData.size() == numElements);
  3606. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  3607. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3608. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  3609. BfIRLinkageType_External, BfIRValue(), classVDataName);
  3610. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  3611. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, vData);
  3612. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  3613. mClassVDataExtRefs[mapEntry] = globalVariable;
  3614. return globalVariable;
  3615. }
  3616. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  3617. {
  3618. if (mBfIRBuilder->mIgnoreWrites)
  3619. {
  3620. return mBfIRBuilder->CreateTypeOf(type);
  3621. }
  3622. BfIRValue globalVariable;
  3623. BfIRValue* globalVariablePtr = NULL;
  3624. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  3625. {
  3626. globalVariable = *globalVariablePtr;
  3627. if (globalVariable)
  3628. return globalVariable;
  3629. }
  3630. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  3631. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  3632. auto typeInstance = type->ToTypeInstance();
  3633. StringT<128> typeDataName;
  3634. if (typeInstance != NULL)
  3635. {
  3636. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3637. }
  3638. else
  3639. {
  3640. typeDataName += "sBfTypeData.";
  3641. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type);
  3642. }
  3643. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  3644. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  3645. mTypeDataRefs[type] = globalVariable;
  3646. return globalVariable;
  3647. }
  3648. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  3649. {
  3650. if ((mCompiler->IsHotCompile()) && (!type->mDirty))
  3651. return BfIRValue();
  3652. BfIRValue* irValuePtr = NULL;
  3653. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  3654. {
  3655. return *irValuePtr;
  3656. }
  3657. BfTypeInstance* typeInstance = type->ToTypeInstance();
  3658. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  3659. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  3660. if (typeInstanceType == NULL)
  3661. {
  3662. AssertErrorState();
  3663. return BfIRValue();
  3664. }
  3665. BfIRValue typeTypeData;
  3666. int typeFlags = 0;
  3667. if (needsTypeData)
  3668. {
  3669. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  3670. BfTypeInstance* typeDataSource = NULL;
  3671. if (typeInstance != NULL)
  3672. {
  3673. if (typeInstance->IsUnspecializedType())
  3674. {
  3675. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  3676. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  3677. }
  3678. else if (typeInstance->IsArray())
  3679. {
  3680. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  3681. typeFlags |= BfTypeFlags_Array;
  3682. }
  3683. else if (typeInstance->IsGenericTypeInstance())
  3684. {
  3685. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  3686. typeFlags |= BfTypeFlags_SpecializedGeneric;
  3687. }
  3688. else
  3689. typeDataSource = typeInstanceTypeInstance;
  3690. }
  3691. else if (type->IsPointer())
  3692. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3693. else if (type->IsSizedArray())
  3694. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3695. else
  3696. typeDataSource = mContext->mBfTypeType;
  3697. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  3698. {
  3699. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  3700. }
  3701. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  3702. }
  3703. else
  3704. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  3705. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  3706. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  3707. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  3708. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  3709. BfType* typeIdType = intType;
  3710. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3711. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3712. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  3713. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3714. SizedArray<BfIRValue, 4> typeValueParams;
  3715. GetConstClassValueParam(typeTypeData, typeValueParams);
  3716. BfIRValue objectData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  3717. StringT<128> typeDataName;
  3718. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  3719. {
  3720. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3721. if (typeInstance->mTypeDef->IsGlobalsContainer())
  3722. typeDataName += "@" + typeInstance->mTypeDef->mProject->mName;
  3723. }
  3724. else
  3725. {
  3726. typeDataName += "sBfTypeData.";
  3727. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type);
  3728. }
  3729. int typeCode = BfTypeCode_None;
  3730. if (typeInstance != NULL)
  3731. {
  3732. typeCode = typeInstance->mTypeDef->mTypeCode;
  3733. }
  3734. else if (type->IsPrimitiveType())
  3735. {
  3736. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  3737. typeCode = primType->mTypeDef->mTypeCode;
  3738. }
  3739. else if (type->IsPointer())
  3740. {
  3741. typeCode = BfTypeCode_Pointer;
  3742. typeFlags |= BfTypeFlags_Pointer;
  3743. }
  3744. if (type->IsObject())
  3745. {
  3746. typeFlags |= BfTypeFlags_Object;
  3747. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  3748. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  3749. typeFlags |= BfTypeFlags_HasDestructor;
  3750. }
  3751. if (type->IsStruct())
  3752. typeFlags |= BfTypeFlags_Struct;
  3753. if (type->IsBoxed())
  3754. {
  3755. typeFlags |= BfTypeFlags_Boxed;
  3756. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  3757. typeFlags |= BfTypeFlags_Pointer;
  3758. }
  3759. if (type->IsPrimitiveType())
  3760. typeFlags |= BfTypeFlags_Primitive;
  3761. if (type->IsTypedPrimitive())
  3762. typeFlags |= BfTypeFlags_TypedPrimitive;
  3763. if (type->IsTuple())
  3764. typeFlags |= BfTypeFlags_Tuple;
  3765. if (type->IsNullable())
  3766. typeFlags |= BfTypeFlags_Nullable;
  3767. if (type->IsSizedArray())
  3768. typeFlags |= BfTypeFlags_SizedArray;
  3769. if (type->IsSplattable())
  3770. typeFlags |= BfTypeFlags_Splattable;
  3771. if (type->IsUnion())
  3772. typeFlags |= BfTypeFlags_Union;
  3773. if (type->IsDelegate())
  3774. typeFlags |= BfTypeFlags_Delegate;
  3775. if (type->WantsGCMarking())
  3776. typeFlags |= BfTypeFlags_WantsMarking;
  3777. int memberDataOffset = 0;
  3778. if (typeInstance != NULL)
  3779. {
  3780. for (auto& fieldInstance : typeInstance->mFieldInstances)
  3781. {
  3782. if (fieldInstance.mDataOffset != -1)
  3783. {
  3784. memberDataOffset = fieldInstance.mDataOffset;
  3785. break;
  3786. }
  3787. }
  3788. }
  3789. SizedArray<BfIRValue, 8> typeDataParams =
  3790. {
  3791. objectData,
  3792. GetConstValue(type->mSize, intType), // mSize
  3793. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  3794. GetConstValue(typeFlags, intType), // mTypeFlags
  3795. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  3796. GetConstValue(typeCode, byteType), // mTypeCode
  3797. GetConstValue(type->mAlign, byteType),
  3798. };
  3799. auto typeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  3800. if (typeInstance == NULL)
  3801. {
  3802. BfIRValue typeDataVar;
  3803. if (needsTypeData)
  3804. {
  3805. if (type->IsPointer())
  3806. {
  3807. auto pointerType = (BfPointerType*)type;
  3808. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  3809. {
  3810. typeData,
  3811. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  3812. };
  3813. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3814. auto pointerTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  3815. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  3816. BfIRLinkageType_External, pointerTypeData, typeDataName);
  3817. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3818. }
  3819. else if (type->IsSizedArray())
  3820. {
  3821. auto sizedArrayType = (BfSizedArrayType*)type;
  3822. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  3823. {
  3824. typeData,
  3825. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  3826. GetConstValue(sizedArrayType->mElementCount, intType)
  3827. };
  3828. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3829. auto sizedArrayTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  3830. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  3831. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  3832. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3833. }
  3834. else
  3835. {
  3836. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  3837. BfIRLinkageType_External, typeData, typeDataName);
  3838. }
  3839. }
  3840. else
  3841. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  3842. mTypeDataRefs[typeInstance] = typeDataVar;
  3843. return typeDataVar;
  3844. }
  3845. // Reserve position
  3846. mTypeDataRefs[typeInstance] = BfIRValue();
  3847. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3848. BfTypeDef* typeDef = typeInstance->mTypeDef;
  3849. StringT<128> mangledName;
  3850. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance);
  3851. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  3852. {
  3853. auto methodDef = typeDef->mMethods[methodIdx];
  3854. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  3855. if (methodInstance == NULL)
  3856. continue;
  3857. if (typeInstance->IsUnspecializedType())
  3858. continue;
  3859. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  3860. {
  3861. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  3862. {
  3863. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  3864. // We need to create an empty thunk for this chained method
  3865. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  3866. mBfIRBuilder->SetActiveFunction(func);
  3867. auto block = mBfIRBuilder->CreateBlock("entry", true);
  3868. mBfIRBuilder->SetInsertPoint(block);
  3869. mBfIRBuilder->CreateRetVoid();
  3870. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  3871. }
  3872. }
  3873. }
  3874. SizedArray<BfIRValue, 32> vData;
  3875. BfIRValue classVDataVar;
  3876. String classVDataName;
  3877. if (typeInstance->mSlotNum >= 0)
  3878. {
  3879. // For interfaces we ONLY emit the slot num
  3880. int virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  3881. StringT<128> slotVarName;
  3882. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  3883. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3884. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  3885. GetConstValue32(virtSlotIdx), slotVarName);
  3886. }
  3887. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  3888. {
  3889. int dynCastDataElems = 0;
  3890. int numElements = 1;
  3891. int vDataOfs = 1; // The number of intptrs before the iface slot map
  3892. numElements += mCompiler->mMaxInterfaceSlots;
  3893. if (!typeInstance->IsInterface())
  3894. {
  3895. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3896. numElements += mCompiler->GetDynCastVDataCount();
  3897. numElements += typeInstance->mVirtualMethodTableSize;
  3898. }
  3899. int expectNumElements = 0;
  3900. if (!typeDef->mIsStatic)
  3901. {
  3902. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  3903. }
  3904. vData.push_back(BfIRValue()); // Type*
  3905. SizedArray<BfIRValue, 1> extVTableData;
  3906. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  3907. if (!typeInstance->IsInterface())
  3908. {
  3909. Array<int32> dynCastData;
  3910. if (typeInstance->IsBoxed())
  3911. {
  3912. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  3913. dynCastData.Add(underlyingType->mInheritanceId);
  3914. }
  3915. else
  3916. dynCastData.Add(typeInstance->mInheritanceId);
  3917. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  3918. dynCastData.Add(0);
  3919. dynCastData.Add(0);
  3920. auto checkTypeInst = typeInstance;
  3921. while (checkTypeInst != NULL)
  3922. {
  3923. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3924. {
  3925. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  3926. {
  3927. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  3928. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  3929. }
  3930. }
  3931. checkTypeInst = checkTypeInst->GetImplBaseType();
  3932. }
  3933. if (mSystem->mPtrSize == 8)
  3934. {
  3935. int intPtrCount = (dynCastDataElems + 1) / 2;
  3936. vDataOfs += intPtrCount;
  3937. uint64* intPtrData = (uint64*)&dynCastData[0];
  3938. for (int i = 0; i < intPtrCount; i++)
  3939. {
  3940. uint64 val = intPtrData[i];
  3941. if (val == 0)
  3942. {
  3943. vData.push_back(voidPtrNull);
  3944. }
  3945. else
  3946. {
  3947. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  3948. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3949. }
  3950. }
  3951. }
  3952. else
  3953. {
  3954. int intPtrCount = dynCastDataElems;
  3955. vDataOfs += intPtrCount;
  3956. uint32* intPtrData = (uint32*)&dynCastData[0];
  3957. for (int i = 0; i < intPtrCount; i++)
  3958. {
  3959. uint32 val = intPtrData[i];
  3960. if (val == 0)
  3961. {
  3962. vData.push_back(voidPtrNull);
  3963. }
  3964. else
  3965. {
  3966. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  3967. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3968. }
  3969. }
  3970. }
  3971. }
  3972. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  3973. vData.push_back(voidPtrNull);
  3974. struct _InterfaceMatchEntry
  3975. {
  3976. BfTypeInterfaceEntry* mEntry;
  3977. BfTypeInstance* mEntrySource;
  3978. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  3979. };
  3980. int highestIFaceVirtIdx = 0;
  3981. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  3982. auto checkTypeInst = typeInstance;
  3983. bool forceInterfaceSet = false;
  3984. while (checkTypeInst != NULL)
  3985. {
  3986. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3987. {
  3988. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  3989. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject))
  3990. continue;
  3991. _InterfaceMatchEntry* matchEntry = NULL;
  3992. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  3993. {
  3994. auto prevEntry = matchEntry->mEntry;
  3995. bool isBetter = TypeIsSubTypeOf(checkTypeInst, matchEntry->mEntrySource);
  3996. bool isWorse = TypeIsSubTypeOf(matchEntry->mEntrySource, checkTypeInst);
  3997. if (forceInterfaceSet)
  3998. {
  3999. isBetter = true;
  4000. isWorse = false;
  4001. }
  4002. if (isBetter == isWorse)
  4003. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  4004. if (isBetter == isWorse)
  4005. {
  4006. if (matchEntry->mAmbiguousEntries.empty())
  4007. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  4008. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  4009. continue;
  4010. }
  4011. else if (isBetter)
  4012. {
  4013. matchEntry->mEntry = &interfaceEntry;
  4014. matchEntry->mEntrySource = checkTypeInst;
  4015. matchEntry->mAmbiguousEntries.Clear();
  4016. }
  4017. else
  4018. continue;
  4019. }
  4020. else
  4021. {
  4022. _InterfaceMatchEntry matchEntry;
  4023. matchEntry.mEntry = &interfaceEntry;
  4024. matchEntry.mEntrySource = checkTypeInst;
  4025. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  4026. }
  4027. }
  4028. checkTypeInst = checkTypeInst->GetImplBaseType();
  4029. }
  4030. for (auto interfacePair : interfaceMap)
  4031. {
  4032. auto& interfaceMatchEntry = interfacePair.mValue;
  4033. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  4034. {
  4035. 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());
  4036. if (error != NULL)
  4037. {
  4038. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  4039. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  4040. }
  4041. }
  4042. }
  4043. if ((!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4044. {
  4045. int startTabIdx = (int)vData.size();
  4046. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4047. BfTypeInstance* checkTypeInst = typeInstance;
  4048. while (checkTypeInst != NULL)
  4049. {
  4050. origVirtTypeStack.push_back(checkTypeInst);
  4051. checkTypeInst = checkTypeInst->GetImplBaseType();
  4052. }
  4053. Array<BfVirtualMethodEntry> origVTable;
  4054. int origVirtIdx = 0;
  4055. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4056. {
  4057. HashSet<String> reslotNames;
  4058. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4059. {
  4060. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4061. if (entry.mDeclaringMethod.mMethodNum == -1)
  4062. continue;
  4063. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4064. if ((methodInstance == NULL) || (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4065. {
  4066. if (origVTable.empty())
  4067. origVTable = typeInstance->mVirtualMethodTable;
  4068. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4069. if (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject))
  4070. {
  4071. // Prepare to reslot...
  4072. entry.mImplementingMethod = entry.mDeclaringMethod;
  4073. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4074. }
  4075. else
  4076. {
  4077. // Decl isn't accessible, null out entry
  4078. entry.mImplementingMethod = BfMethodRef();
  4079. }
  4080. }
  4081. }
  4082. if (!reslotNames.IsEmpty())
  4083. {
  4084. BfAmbiguityContext ambiguityContext;
  4085. ambiguityContext.mTypeInstance = typeInstance;
  4086. ambiguityContext.mModule = this;
  4087. ambiguityContext.mIsProjectSpecific = true;
  4088. ambiguityContext.mIsReslotting = true;
  4089. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4090. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4091. {
  4092. auto methodInstance = methodGroup.mDefault;
  4093. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4094. continue;
  4095. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4096. continue;
  4097. if (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))
  4098. continue;
  4099. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4100. continue;
  4101. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4102. }
  4103. ambiguityContext.Finish();
  4104. }
  4105. }
  4106. bool isInExts = false;
  4107. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4108. {
  4109. BfIRValue vValue = voidPtrNull;
  4110. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4111. BfModuleMethodInstance moduleMethodInst;
  4112. if (entry.mDeclaringMethod.mMethodNum == -1)
  4113. {
  4114. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4115. isInExts = true;
  4116. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4117. if (vExt)
  4118. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4119. }
  4120. else
  4121. {
  4122. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4123. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4124. {
  4125. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4126. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4127. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4128. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4129. {
  4130. BF_ASSERT(typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4131. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  4132. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4133. vValue = funcPtr;
  4134. }
  4135. }
  4136. }
  4137. while (origVirtTypeStack.size() != 0)
  4138. {
  4139. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4140. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4141. {
  4142. // Moved past current base vtable size
  4143. origVirtTypeStack.pop_back();
  4144. continue;
  4145. }
  4146. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4147. {
  4148. // We are within the original vtable size
  4149. int idx = startTabIdx + origVirtIdx;
  4150. origVirtIdx++;
  4151. vData.push_back(vValue);
  4152. }
  4153. else
  4154. {
  4155. // This is a new entry, it only gets added to the ext
  4156. BF_ASSERT(isInExts);
  4157. }
  4158. break;
  4159. }
  4160. }
  4161. if (!origVTable.empty())
  4162. typeInstance->mVirtualMethodTable = origVTable;
  4163. }
  4164. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4165. if (typeInstance->mHotTypeData != NULL)
  4166. {
  4167. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4168. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4169. }
  4170. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4171. int iFaceMethodStartIdx = (int)vData.size();
  4172. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4173. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4174. vData[i] = voidPtrNull;
  4175. if (expectNumElements != 0)
  4176. BF_ASSERT(expectNumElements == vData.size());
  4177. //BF_ASSERT(vData.size() == expectNumElements);
  4178. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4179. // ifaceMethodExtData.Add(voidPtrNull);
  4180. int ifaceEntryIdx = iFaceMethodStartIdx;
  4181. for (auto& interfacePair : interfaceMap)
  4182. {
  4183. auto interfaceEntry = interfacePair.mValue.mEntry;
  4184. bool makeEmpty = false;
  4185. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject))
  4186. makeEmpty = true;
  4187. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4188. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4189. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4190. {
  4191. BfIRValue pushValue;
  4192. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4193. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4194. continue;
  4195. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4196. continue;
  4197. if (makeEmpty)
  4198. {
  4199. pushValue = voidPtrNull;
  4200. }
  4201. else
  4202. {
  4203. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4204. auto methodInstance = (BfMethodInstance*)methodRef;
  4205. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4206. {
  4207. BF_ASSERT(methodInstance->mIsReified);
  4208. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4209. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4210. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4211. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4212. pushValue = funcPtr;
  4213. }
  4214. else
  4215. {
  4216. pushValue = voidPtrNull;
  4217. }
  4218. }
  4219. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4220. if (idx < ifaceMethodExtStart)
  4221. {
  4222. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  4223. vData[iFaceMethodStartIdx + idx] = pushValue;
  4224. }
  4225. else
  4226. {
  4227. BF_ASSERT(useExt);
  4228. int extIdx = idx - ifaceMethodExtStart;
  4229. while (extIdx >= ifaceMethodExtData.size())
  4230. ifaceMethodExtData.Add(voidPtrNull);
  4231. ifaceMethodExtData[extIdx] = pushValue;
  4232. }
  4233. }
  4234. }
  4235. if (typeInstance->IsBoxed())
  4236. {
  4237. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  4238. if (boxedType->IsBoxedStructPtr())
  4239. {
  4240. // Force override of GetHashCode so we use the pointer address as the hash code
  4241. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  4242. // Force override of GetHashCode so we use the pointer address as the hash code
  4243. for (auto& checkIFace : checkTypeInst->mInterfaces)
  4244. {
  4245. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4246. {
  4247. BfIRValue pushValue;
  4248. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4249. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4250. continue;
  4251. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4252. continue;
  4253. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4254. auto methodInstance = (BfMethodInstance*)methodRef;
  4255. BF_ASSERT(methodInstance->mIsReified);
  4256. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4257. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4258. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4259. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4260. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4261. vData[iFaceMethodStartIdx + idx] = funcPtr;
  4262. }
  4263. }
  4264. }
  4265. }
  4266. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic))
  4267. {
  4268. BfIRValue ifaceMethodExtVar;
  4269. if (!ifaceMethodExtData.IsEmpty())
  4270. {
  4271. StringT<128> classVDataName;
  4272. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  4273. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  4274. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4275. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4276. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  4277. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, ifaceMethodExtData);
  4278. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  4279. }
  4280. for (auto& ifaceInstPair : interfaceMap)
  4281. {
  4282. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  4283. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  4284. if (slotNum >= 0)
  4285. {
  4286. BfIRValue vtablePtr;
  4287. int idx = interfaceEntry->mStartVirtualIdx;
  4288. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4289. if (endVirtualIdx > ifaceMethodExtStart)
  4290. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  4291. else
  4292. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  4293. int slotVirtIdx = slotNum + vDataOfs;
  4294. if (vData[slotVirtIdx] == voidPtrNull)
  4295. {
  4296. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  4297. }
  4298. else
  4299. {
  4300. if (mCompiler->IsHotCompile())
  4301. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  4302. else
  4303. Fail("Interface slot collision error", typeDef->GetRefNode());
  4304. }
  4305. }
  4306. }
  4307. }
  4308. }
  4309. BfIRValue typeNameConst;
  4310. BfIRValue namespaceConst;
  4311. if (needsTypeNames)
  4312. {
  4313. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  4314. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  4315. }
  4316. else
  4317. {
  4318. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  4319. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4320. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4321. }
  4322. int baseTypeId = 0;
  4323. if (typeInstance->mBaseType != NULL)
  4324. {
  4325. baseTypeId = typeInstance->mBaseType->mTypeId;
  4326. }
  4327. SizedArray<BfIRValue, 16> customAttrs;
  4328. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  4329. BfIRValue castedClassVData;
  4330. if (classVDataVar)
  4331. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  4332. else
  4333. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  4334. bool freflectIncludeTypeData = false;
  4335. bool reflectIncludeAllFields = false;
  4336. bool reflectIncludeAllMethods = false;
  4337. if (TypeIsSubTypeOf(typeInstance, attributeType))
  4338. {
  4339. reflectIncludeAllFields = true;
  4340. reflectIncludeAllMethods = true;
  4341. }
  4342. enum ReflectKind
  4343. {
  4344. ReflectKind_None = 0,
  4345. ReflectKind_Type = 1,
  4346. ReflectKind_NonStaticFields = 2,
  4347. ReflectKind_StaticFields = 4,
  4348. ReflectKind_DefaultConstructor = 8,
  4349. ReflectKind_Constructors = 0x10,
  4350. ReflectKind_StaticMethods = 0x20,
  4351. ReflectKind_Methods = 0x40,
  4352. ReflectKind_User = 0x80,
  4353. ReflectKind_All = 0x7F,
  4354. ReflectKind_ApplyToInnerTypes = 0x80
  4355. };
  4356. ReflectKind reflectKind = ReflectKind_Type;
  4357. auto _GetReflectUser = [&](BfTypeInstance* attrType)
  4358. {
  4359. ReflectKind reflectKind = ReflectKind_None;
  4360. if (attrType->mCustomAttributes != NULL)
  4361. {
  4362. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  4363. {
  4364. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  4365. {
  4366. for (auto& prop : customAttr.mSetProperties)
  4367. {
  4368. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  4369. if (propDef->mName == "ReflectUser")
  4370. {
  4371. if (prop.mParam.mValue.IsConst())
  4372. {
  4373. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  4374. reflectKind = (ReflectKind)(reflectKind | (ReflectKind)constant->mInt32);
  4375. }
  4376. }
  4377. }
  4378. // Check for Flags arg
  4379. if (customAttr.mCtorArgs.size() < 2)
  4380. continue;
  4381. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  4382. if (constant == NULL)
  4383. continue;
  4384. if (constant->mTypeCode == BfTypeCode_Boolean)
  4385. continue;
  4386. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4387. reflectKind = (ReflectKind)(reflectKind | ReflectKind_User);
  4388. }
  4389. }
  4390. }
  4391. return reflectKind;
  4392. };
  4393. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  4394. {
  4395. ReflectKind reflectKind = ReflectKind_None;
  4396. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  4397. if (customAttrs != NULL)
  4398. {
  4399. for (auto& attr : customAttrs->mAttributes)
  4400. {
  4401. reflectKind = (ReflectKind)(reflectKind | _GetReflectUser(attr.mType));
  4402. }
  4403. }
  4404. return reflectKind;
  4405. };
  4406. //
  4407. {
  4408. auto checkTypeInstance = typeInstance;
  4409. while (checkTypeInstance != NULL)
  4410. {
  4411. if (checkTypeInstance->mCustomAttributes != NULL)
  4412. {
  4413. auto checkReflectKind = ReflectKind_None;
  4414. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  4415. {
  4416. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4417. {
  4418. if (customAttr.mCtorArgs.size() > 0)
  4419. {
  4420. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  4421. checkReflectKind = (ReflectKind)((int)checkReflectKind | constant->mInt32);
  4422. }
  4423. else
  4424. {
  4425. checkReflectKind = ReflectKind_All;
  4426. }
  4427. }
  4428. else
  4429. {
  4430. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4431. checkReflectKind = (ReflectKind)(checkReflectKind | userReflectKind);
  4432. }
  4433. }
  4434. if ((checkTypeInstance == typeInstance) ||
  4435. ((checkReflectKind & ReflectKind_ApplyToInnerTypes) != 0))
  4436. {
  4437. reflectKind = (ReflectKind)(reflectKind | checkReflectKind);
  4438. }
  4439. }
  4440. checkTypeInstance = GetOuterType(checkTypeInstance);
  4441. }
  4442. }
  4443. // Fields
  4444. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  4445. BfIRValue emptyValueType = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  4446. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  4447. {
  4448. if (customAttributes == NULL)
  4449. return -1;
  4450. Array<BfCustomAttribute*> reflectAttributes;
  4451. for (auto& attr : customAttributes->mAttributes)
  4452. {
  4453. bool wantAttribute = false;
  4454. if (attr.mType->mCustomAttributes != NULL)
  4455. {
  4456. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  4457. if (usageAttribute != NULL)
  4458. {
  4459. // Check for Flags arg
  4460. if (usageAttribute->mCtorArgs.size() < 2)
  4461. continue;
  4462. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  4463. if (constant == NULL)
  4464. continue;
  4465. if (constant->mTypeCode == BfTypeCode_Boolean)
  4466. continue;
  4467. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4468. wantAttribute = true;
  4469. }
  4470. }
  4471. if ((wantAttribute) && (attr.mType->mIsReified))
  4472. {
  4473. reflectAttributes.Add(&attr);
  4474. }
  4475. }
  4476. if (reflectAttributes.size() == 0)
  4477. return -1;
  4478. #define PUSH_INT8(val) data.push_back((uint8)val)
  4479. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4480. #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); }
  4481. #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); \
  4482. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4483. SizedArray<uint8, 16> data;
  4484. int customAttrIdx = (int)customAttrs.size();
  4485. data.push_back((uint8)reflectAttributes.size());
  4486. for (auto attr : reflectAttributes)
  4487. {
  4488. // Size prefix
  4489. int sizeIdx = (int)data.size();
  4490. PUSH_INT16(0); // mSize
  4491. PUSH_INT32(attr->mType->mTypeId); // mType
  4492. PUSH_INT16(attr->mCtor->mIdx);
  4493. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  4494. int argIdx = 0;
  4495. for (auto arg : attr->mCtorArgs)
  4496. {
  4497. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4498. bool handled = false;
  4499. if (constant != NULL)
  4500. {
  4501. auto argType = ctorMethodInstance->GetParamType(argIdx);
  4502. if (argType->IsObject())
  4503. {
  4504. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  4505. int stringId = constant->mInt32;
  4506. int* orderedIdPtr;
  4507. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4508. {
  4509. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4510. }
  4511. GetStringObjectValue(stringId);
  4512. PUSH_INT8(0xFF); // String
  4513. PUSH_INT32(*orderedIdPtr);
  4514. continue;
  4515. }
  4516. PUSH_INT8(constant->mTypeCode);
  4517. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4518. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4519. (constant->mTypeCode == BfTypeCode_Double))
  4520. {
  4521. PUSH_INT64(constant->mInt64);
  4522. }
  4523. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4524. (constant->mTypeCode == BfTypeCode_UInt32))
  4525. {
  4526. PUSH_INT32(constant->mInt32);
  4527. }
  4528. else if (constant->mTypeCode == BfTypeCode_Single)
  4529. {
  4530. float val = (float)constant->mDouble;
  4531. PUSH_INT32(*(int*)&val);
  4532. }
  4533. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4534. (constant->mTypeCode == BfTypeCode_UInt16))
  4535. {
  4536. PUSH_INT16(constant->mInt16);
  4537. }
  4538. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4539. (constant->mTypeCode == BfTypeCode_UInt8))
  4540. {
  4541. PUSH_INT8(constant->mInt8);
  4542. }
  4543. else if (constant->mTypeCode == BfTypeCode_Object)
  4544. {
  4545. BF_FATAL("Unhandled");
  4546. }
  4547. else
  4548. {
  4549. BF_FATAL("Unhandled");
  4550. }
  4551. }
  4552. else if (!handled)
  4553. {
  4554. BF_FATAL("Unhandled");
  4555. }
  4556. argIdx++;
  4557. }
  4558. int size = (int)data.size() - sizeIdx;
  4559. *((uint16*)&data[sizeIdx]) = size;
  4560. }
  4561. #undef PUSH_INT8
  4562. #undef PUSH_INT16
  4563. #undef PUSH_INT32
  4564. SizedArray<BfIRValue, 16> dataValues;
  4565. for (uint8 val : data)
  4566. dataValues.push_back(GetConstValue8(val));
  4567. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  4568. auto customAttrConst = mBfIRBuilder->CreateConstArray(dataArrayType, dataValues);
  4569. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  4570. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  4571. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  4572. customAttrs.push_back(customAttrArrayPtr);
  4573. return customAttrIdx;
  4574. };
  4575. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  4576. SizedArray<int, 16> reflectFieldIndices;
  4577. for (int pass = 0; pass < 2; pass++)
  4578. {
  4579. bool skippedField = false;
  4580. reflectFieldIndices.clear();
  4581. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  4582. {
  4583. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4584. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4585. if (fieldDef == NULL)
  4586. continue;
  4587. auto fieldReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4588. bool includeField = reflectIncludeAllFields;
  4589. if (fieldInstance->mCustomAttributes != NULL)
  4590. {
  4591. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4592. {
  4593. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4594. {
  4595. includeField = true;
  4596. }
  4597. else
  4598. {
  4599. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4600. fieldReflectKind = (ReflectKind)(fieldReflectKind | userReflectKind);
  4601. }
  4602. }
  4603. }
  4604. if ((fieldReflectKind & ReflectKind_User) != 0)
  4605. includeField = true;
  4606. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_NonStaticFields) != 0))
  4607. includeField = true;
  4608. if ((fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_StaticFields) != 0))
  4609. includeField = true;
  4610. includeField |= forceReflectFields;
  4611. if (!includeField)
  4612. {
  4613. skippedField = true;
  4614. continue;
  4615. }
  4616. reflectFieldIndices.Add(fieldIdx);
  4617. }
  4618. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  4619. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  4620. // possible because we write out a SplatData structure containing just TypeIds in that case
  4621. if (pass == 0)
  4622. {
  4623. if (!typeInstance->IsSplattable())
  4624. break;
  4625. if (!skippedField)
  4626. break;
  4627. if (reflectFieldIndices.size() == 0)
  4628. break;
  4629. }
  4630. }
  4631. SizedArray<BfIRValue, 16> fieldTypes;
  4632. enum FieldFlags
  4633. {
  4634. FieldFlags_Protected = 3,
  4635. FieldFlags_Public = 6,
  4636. FieldFlags_Static = 0x10,
  4637. FieldFlags_Const = 0x40,
  4638. FieldFlags_SpecialName = 0x80,
  4639. FieldFlags_EnumPayload = 0x100,
  4640. FieldFlags_EnumDiscriminator = 0x200
  4641. };
  4642. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  4643. {
  4644. BfType* payloadType = typeInstance->GetUnionInnerType();
  4645. if (!payloadType->IsValuelessType())
  4646. {
  4647. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  4648. SizedArray<BfIRValue, 8> payloadFieldVals =
  4649. {
  4650. emptyValueType,
  4651. payloadNameConst, // mName
  4652. GetConstValue(0, longType), // mConstValue
  4653. GetConstValue(0, intType), // mDataOffset
  4654. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  4655. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  4656. GetConstValue(-1, intType), // mCustomAttributesIdx
  4657. };
  4658. auto payloadFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  4659. fieldTypes.push_back(payloadFieldData);
  4660. }
  4661. BfType* dscrType = typeInstance->GetDiscriminatorType();
  4662. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  4663. SizedArray<BfIRValue, 8> dscrFieldVals =
  4664. {
  4665. emptyValueType,
  4666. dscrNameConst, // mName
  4667. GetConstValue(0, longType), // mConstValue
  4668. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intType), // mDataOffset
  4669. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  4670. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  4671. GetConstValue(-1, intType), // mCustomAttributesIdx
  4672. };
  4673. auto dscrFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  4674. fieldTypes.push_back(dscrFieldData);
  4675. }
  4676. for (auto fieldIdx : reflectFieldIndices)
  4677. {
  4678. if (!needsTypeData)
  4679. break;
  4680. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4681. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4682. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  4683. int typeId = 0;
  4684. auto fieldType = fieldInstance->GetResolvedType();
  4685. if (fieldType->IsGenericParam())
  4686. {
  4687. //TODO:
  4688. }
  4689. else
  4690. typeId = fieldType->mTypeId;
  4691. FieldFlags fieldFlags = (FieldFlags)0;
  4692. if (fieldDef->mProtection == BfProtection_Protected)
  4693. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  4694. if (fieldDef->mProtection == BfProtection_Public)
  4695. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  4696. if (fieldDef->mIsStatic)
  4697. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  4698. if (fieldDef->mIsConst)
  4699. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  4700. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  4701. BfIRValue constValue = GetConstValue(0, longType);
  4702. if (fieldInstance->GetFieldDef()->mIsConst)
  4703. {
  4704. if (fieldInstance->mConstIdx != -1)
  4705. {
  4706. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4707. constValue = mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constant->mUInt64);
  4708. }
  4709. }
  4710. SizedArray<BfIRValue, 8> fieldVals =
  4711. {
  4712. emptyValueType,
  4713. fieldNameConst, // mName
  4714. constValue, // mConstValue
  4715. GetConstValue(fieldInstance->mDataOffset, intType), // mDataOffset
  4716. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4717. GetConstValue(fieldFlags, shortType), // mFlags
  4718. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  4719. };
  4720. auto fieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  4721. fieldTypes.push_back(fieldData);
  4722. }
  4723. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  4724. BfIRValue fieldDataPtr;
  4725. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  4726. if (fieldTypes.size() == 0)
  4727. {
  4728. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()))
  4729. {
  4730. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  4731. SizedArray<BfIRValue, 3> splatTypes;
  4732. SizedArray<BfIRValue, 3> splatOffsets;
  4733. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  4734. {
  4735. auto checkTypeInstance = checkType->ToTypeInstance();
  4736. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  4737. PopulateType(checkTypeInstance);
  4738. if (checkType->IsStruct())
  4739. {
  4740. int dataEnd = offset;
  4741. if (checkTypeInstance->mBaseType != NULL)
  4742. _CheckSplat(checkTypeInstance->mBaseType, offset);
  4743. if (checkTypeInstance->mIsUnion)
  4744. {
  4745. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  4746. _CheckSplat(unionInnerType, offset);
  4747. }
  4748. else
  4749. {
  4750. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  4751. {
  4752. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  4753. if (fieldInstance->mDataIdx >= 0)
  4754. {
  4755. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  4756. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  4757. }
  4758. }
  4759. }
  4760. if (checkTypeInstance->IsEnum())
  4761. {
  4762. // Add discriminator
  4763. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  4764. if (!checkTypeInstance->mIsPacked)
  4765. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  4766. _CheckSplat(dscrType, dataEnd);
  4767. }
  4768. }
  4769. else if (checkType->IsMethodRef())
  4770. {
  4771. // auto methodRefType = (BfMethodRefType*)checkType;
  4772. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  4773. // {
  4774. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  4775. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  4776. // else
  4777. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  4778. // }
  4779. }
  4780. else if (!checkType->IsValuelessType())
  4781. {
  4782. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  4783. splatOffsets.Add(GetConstValue(offset, intType));
  4784. }
  4785. };
  4786. _CheckSplat(type, 0);
  4787. while (splatTypes.size() < 3)
  4788. {
  4789. splatTypes.Add(GetConstValue(0, typeIdType));
  4790. splatOffsets.Add(GetConstValue(0, intType));
  4791. }
  4792. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  4793. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  4794. SizedArray<BfIRValue, 8> splatVals =
  4795. {
  4796. emptyValueType,
  4797. splatTypesConst,
  4798. splatOffsetsConst
  4799. };
  4800. auto fieldSplatData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  4801. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  4802. fieldSplatData, typeDataName + ".splats");
  4803. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4804. }
  4805. else
  4806. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  4807. }
  4808. else
  4809. {
  4810. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  4811. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstArray(fieldDataConstType, fieldTypes);
  4812. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  4813. fieldDataConst, "fields." + typeDataName);
  4814. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4815. }
  4816. /// Methods
  4817. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  4818. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  4819. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  4820. SizedArray<BfIRValue, 16> methodTypes;
  4821. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4822. {
  4823. if (!needsTypeData)
  4824. break;
  4825. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  4826. if (!methodInstanceGroup->IsImplemented())
  4827. continue;
  4828. auto methodDef = typeDef->mMethods[methodIdx];
  4829. if (methodDef->mNoReflect)
  4830. continue;
  4831. auto defaultMethod = methodInstanceGroup->mDefault;
  4832. if (defaultMethod == NULL)
  4833. continue;
  4834. if (defaultMethod->mIsUnspecialized)
  4835. continue;
  4836. if (!defaultMethod->mIsReified)
  4837. continue;
  4838. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  4839. continue;
  4840. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  4841. continue;
  4842. auto methodReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4843. bool includeMethod = reflectIncludeAllMethods;
  4844. BfCustomAttributes* methodCustomAttributes = NULL;
  4845. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  4846. {
  4847. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  4848. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  4849. {
  4850. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4851. {
  4852. includeMethod = true;
  4853. }
  4854. else
  4855. {
  4856. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4857. methodReflectKind = (ReflectKind)(methodReflectKind | userReflectKind);
  4858. }
  4859. }
  4860. }
  4861. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4862. continue;
  4863. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  4864. {
  4865. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  4866. {
  4867. if (paramDecl->mAttributes != NULL)
  4868. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  4869. }
  4870. if (methodDeclaration->mReturnAttributes != NULL)
  4871. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(methodDeclaration->mReturnAttributes, BfAttributeTargets_ReturnValue));
  4872. }
  4873. if ((methodReflectKind & (ReflectKind_Methods | ReflectKind_User)) != 0)
  4874. includeMethod = true;
  4875. if ((methodDef->mIsStatic) && ((methodReflectKind & ReflectKind_StaticMethods) != 0))
  4876. includeMethod = true;
  4877. if (!includeMethod)
  4878. continue;
  4879. BfModuleMethodInstance moduleMethodInstance;
  4880. BfIRValue funcVal = voidPtrNull;
  4881. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  4882. (!typeInstance->IsUnspecializedType()) &&
  4883. (methodDef->mMethodType != BfMethodType_Ignore) &&
  4884. (methodDef->mMethodType != BfMethodType_Mixin) &&
  4885. (!methodDef->mIsAbstract) &&
  4886. (methodDef->mGenericParams.size() == 0))
  4887. {
  4888. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx);
  4889. if (moduleMethodInstance.mFunc)
  4890. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  4891. }
  4892. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  4893. enum MethodFlags
  4894. {
  4895. MethodFlags_Protected = 3,
  4896. MethodFlags_Public = 6,
  4897. MethodFlags_Static = 0x10,
  4898. MethodFlags_Virtual = 0x40,
  4899. MethodFlags_StdCall = 0x1000,
  4900. MethodFlags_FastCall = 0x2000,
  4901. MethodFlags_Mutating = 0x4000,
  4902. };
  4903. MethodFlags methodFlags = (MethodFlags)0;
  4904. if (methodDef->mProtection == BfProtection_Protected)
  4905. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Protected);
  4906. if (methodDef->mProtection == BfProtection_Public)
  4907. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Public);
  4908. if (methodDef->mIsStatic)
  4909. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Static);
  4910. if (methodDef->mIsVirtual)
  4911. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Virtual);
  4912. if (methodDef->mCallingConvention == BfCallingConvention_Fastcall)
  4913. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  4914. if (methodDef->mIsMutating)
  4915. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Mutating);
  4916. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  4917. enum ParamFlags
  4918. {
  4919. ParamFlag_None = 0,
  4920. ParamFlag_Splat = 1,
  4921. ParamFlag_Implicit = 2,
  4922. };
  4923. SizedArray<BfIRValue, 8> paramVals;
  4924. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  4925. {
  4926. String paramName = defaultMethod->GetParamName(paramIdx);
  4927. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  4928. ParamFlags paramFlags = ParamFlag_None;
  4929. if (defaultMethod->GetParamIsSplat(paramIdx))
  4930. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  4931. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  4932. SizedArray<BfIRValue, 8> paramDataVals =
  4933. {
  4934. emptyValueType,
  4935. paramNameConst,
  4936. GetConstValue(paramType->mTypeId, typeIdType),
  4937. GetConstValue((int32)paramFlags, shortType),
  4938. GetConstValue(customAttrIdx, intType) // defaultIdx
  4939. };
  4940. auto paramData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  4941. paramVals.Add(paramData);
  4942. }
  4943. BfIRValue paramsVal;
  4944. if (paramVals.size() > 0)
  4945. {
  4946. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  4947. BfIRValue paramDataConst = mBfIRBuilder->CreateConstArray(paramDataArrayType, paramVals);
  4948. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  4949. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  4950. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  4951. }
  4952. else
  4953. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  4954. int vDataVal = -1;
  4955. if (defaultMethod->mVirtualTableIdx != -1)
  4956. {
  4957. int vDataIdx = -1;
  4958. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  4959. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  4960. {
  4961. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  4962. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  4963. if (extMethodIdx >= 0)
  4964. {
  4965. // Extension?
  4966. int vExtOfs = typeInst->GetOrigBaseVTableSize();
  4967. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  4968. }
  4969. else
  4970. {
  4971. // Map this new virtual index back to the original index
  4972. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  4973. }
  4974. }
  4975. else
  4976. {
  4977. vDataIdx += defaultMethod->mVirtualTableIdx;
  4978. }
  4979. if (vDataVal == -1)
  4980. vDataVal = vDataIdx * mSystem->mPtrSize;
  4981. }
  4982. SizedArray<BfIRValue, 8> methodDataVals =
  4983. {
  4984. emptyValueType,
  4985. methodNameConst, // mName
  4986. funcVal, // mFuncPtr
  4987. paramsVal,
  4988. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  4989. GetConstValue((int)paramVals.size(), shortType),
  4990. GetConstValue(methodFlags, shortType),
  4991. GetConstValue(vDataVal, intType),
  4992. GetConstValue(-1, intType),
  4993. };
  4994. auto methodData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  4995. methodTypes.push_back(methodData);
  4996. }
  4997. BfIRValue methodDataPtr;
  4998. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  4999. if (methodTypes.size() == 0)
  5000. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  5001. else
  5002. {
  5003. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  5004. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methodTypes);
  5005. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  5006. methodDataConst, "methods." + typeDataName);
  5007. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  5008. }
  5009. /////
  5010. int underlyingType = 0;
  5011. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  5012. {
  5013. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  5014. }
  5015. int outerTypeId = 0;
  5016. auto outerType = GetOuterType(typeInstance);
  5017. if (outerType != NULL)
  5018. outerTypeId = outerType->mTypeId;
  5019. BfIRValue customAttrDataPtr;
  5020. if (customAttrs.size() > 0)
  5021. {
  5022. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  5023. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstArray(customAttrsArrayType, customAttrs);
  5024. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  5025. customAttrsConst, "customAttrs." + typeDataName);
  5026. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  5027. }
  5028. else
  5029. {
  5030. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  5031. }
  5032. SizedArray<BfIRValue, 32> typeDataVals =
  5033. {
  5034. typeData,
  5035. castedClassVData, // mTypeClassVData
  5036. typeNameConst, // mName
  5037. namespaceConst, // mNamespace
  5038. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  5039. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  5040. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  5041. GetConstValue(baseTypeId, typeIdType), // mBaseType
  5042. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  5043. GetConstValue(outerTypeId, typeIdType), // mOuterType
  5044. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  5045. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  5046. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  5047. GetConstValue(0, byteType), // mInterfaceCount
  5048. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  5049. GetConstValue(0, shortType), // mPropertyDataCount
  5050. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  5051. GetConstValue(0, shortType), // mConstructorDataCount
  5052. voidPtrNull, // mInterfaceDataPtr
  5053. methodDataPtr, // mMethodDataPtr
  5054. voidPtrNull, // mPropertyDataPtr
  5055. fieldDataPtr, // mFieldDataPtr
  5056. voidPtrNull, // mConstructorDataPtr
  5057. customAttrDataPtr, // mCustomAttrDataPtr
  5058. };
  5059. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5060. auto typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, typeDataVals);
  5061. if (!needsTypeData)
  5062. {
  5063. // No need for anything beyond typeInstanceData
  5064. }
  5065. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5066. {
  5067. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5068. SizedArray<BfIRValue, 4> unspecializedData =
  5069. {
  5070. typeInstanceData,
  5071. GetConstValue((int)genericTypeInstance->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5072. };
  5073. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5074. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5075. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, unspecializedData);
  5076. }
  5077. else if (typeInstance->IsGenericTypeInstance())
  5078. {
  5079. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5080. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5081. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5082. SizedArray<BfIRValue, 4> resolvedTypes;
  5083. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  5084. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5085. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5086. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5087. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5088. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstArray(genericArrayType, resolvedTypes);
  5089. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5090. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5091. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5092. SizedArray<BfIRValue, 3> specGenericData =
  5093. {
  5094. typeInstanceData,
  5095. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5096. resovledTypesPtr, // mFieldDataPtr
  5097. };
  5098. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5099. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, specGenericData);
  5100. if (typeInstance->IsArray())
  5101. {
  5102. auto arrayType = (BfArrayType*)typeInstance;
  5103. BfType* elementType = genericTypeInstance->mTypeGenericArguments[0];
  5104. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5105. SizedArray<BfIRValue, 4> arrayData =
  5106. {
  5107. typeInstanceData,
  5108. GetConstValue(elementType->mSize, intType), // mElementSize
  5109. GetConstValue(1, byteType), // mRank
  5110. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5111. };
  5112. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5113. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5114. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, arrayData);
  5115. }
  5116. }
  5117. BfIRValue typeDataVar;
  5118. if (needsTypeData)
  5119. {
  5120. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5121. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5122. if (mBfIRBuilder->DbgHasInfo())
  5123. {
  5124. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, NULL, 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5125. }
  5126. }
  5127. else
  5128. {
  5129. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5130. }
  5131. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5132. mTypeDataRefs[typeInstance] = typeDataVar;
  5133. if (classVDataVar)
  5134. {
  5135. BF_ASSERT(!classVDataName.IsEmpty());
  5136. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5137. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5138. auto classVDataConstData = mBfIRBuilder->CreateConstArray(classVDataConstDataType, vData);
  5139. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5140. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5141. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5142. else
  5143. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5144. if (mBfIRBuilder->DbgHasInfo())
  5145. {
  5146. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5147. BfType* voidPtrType = CreatePointerType(voidType);
  5148. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5149. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5150. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, NULL, 0, arrayType, false, classVDataVar);
  5151. }
  5152. }
  5153. return typeDataVar;
  5154. }
  5155. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5156. {
  5157. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  5158. return value;
  5159. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5160. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5161. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5162. }
  5163. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5164. {
  5165. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5166. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  5167. // When we access classes with static constructors FROM a static constructor,
  5168. // we call that other class's static constructor first. Recursion cannot occur, since
  5169. // we simply ignore subsequent attempts to re-enter the constructor
  5170. if (!typeInstance->mHasStaticInitMethod)
  5171. return;
  5172. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  5173. return;
  5174. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  5175. return;
  5176. auto checkTypeDef = typeInstance->mTypeDef;
  5177. checkTypeDef->PopulateMemberSets();
  5178. BfMethodDef* nextMethodDef = NULL;
  5179. BfMemberSetEntry* entry;
  5180. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  5181. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5182. while (nextMethodDef != NULL)
  5183. {
  5184. auto checkMethod = nextMethodDef;
  5185. nextMethodDef = nextMethodDef->mNextWithSameName;
  5186. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  5187. if (methodModule)
  5188. {
  5189. auto methodInstance = methodModule.mMethodInstance;
  5190. if ((methodInstance != NULL) &&
  5191. (methodInstance->mMethodDef->mIsStatic) &&
  5192. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  5193. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  5194. {
  5195. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  5196. break;
  5197. }
  5198. }
  5199. }
  5200. }
  5201. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  5202. {
  5203. auto methodOwner = methodInstance->GetOwner();
  5204. auto methodDef = methodInstance->mMethodDef;
  5205. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5206. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  5207. if (!hasExternSpecifier)
  5208. return BfIRFunction();
  5209. if (methodInstance->GetCustomAttributes() == NULL)
  5210. return BfIRFunction();
  5211. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  5212. {
  5213. String typeName = TypeToString(customAttribute.mType);
  5214. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  5215. {
  5216. methodInstance->mIsIntrinsic = true;
  5217. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  5218. String error;
  5219. if ((constant != NULL) && (BfIRConstHolder::IsInt(constant->mTypeCode)))
  5220. {
  5221. int stringId = constant->mInt32;
  5222. auto entry = mContext->mStringObjectIdMap[stringId];
  5223. int intrinId = BfIRCodeGen::GetIntrinsicId(entry.mString);
  5224. if (intrinId != -1)
  5225. {
  5226. if (intrinId == BfIRIntrinsic_Malloc)
  5227. {
  5228. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  5229. }
  5230. else if (intrinId == BfIRIntrinsic_Free)
  5231. {
  5232. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  5233. }
  5234. SizedArray<BfIRType, 2> paramTypes;
  5235. for (auto& param : methodInstance->mParams)
  5236. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5237. return mBfIRBuilder->GetIntrinsic(intrinId, paramTypes);
  5238. }
  5239. else if (reportFailure)
  5240. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  5241. }
  5242. else if (reportFailure)
  5243. error = "Intrinsic name must be a constant string";
  5244. if (reportFailure)
  5245. {
  5246. BfAstNode* ref = methodDeclaration->mAttributes;
  5247. Fail(error, ref);
  5248. }
  5249. }
  5250. }
  5251. return BfIRFunction();
  5252. }
  5253. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  5254. {
  5255. if (mBfIRBuilder->mIgnoreWrites)
  5256. return mBfIRBuilder->GetFakeFunction();
  5257. if (!mBuiltInFuncs[(int)funcTypeId])
  5258. {
  5259. SizedArray<BfIRType, 4> paramTypes;
  5260. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  5261. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5262. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  5263. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5264. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  5265. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  5266. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  5267. BfIRFunctionType funcType;
  5268. BfIRFunction func;
  5269. switch (funcTypeId)
  5270. {
  5271. case BfBuiltInFuncType_PrintF:
  5272. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  5273. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  5274. break;
  5275. case BfBuiltInFuncType_Malloc:
  5276. {
  5277. if (mCompiler->mOptions.mDebugAlloc)
  5278. {
  5279. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  5280. }
  5281. else
  5282. {
  5283. String funcName = mCompiler->mOptions.mMallocLinkName;
  5284. if (funcName.IsEmpty())
  5285. funcName = "malloc";
  5286. func = mBfIRBuilder->GetFunction(funcName);
  5287. if (!func)
  5288. {
  5289. paramTypes.clear();
  5290. paramTypes.push_back(intType);
  5291. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  5292. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5293. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  5294. }
  5295. }
  5296. }
  5297. break;
  5298. case BfBuiltInFuncType_Free:
  5299. {
  5300. if (mCompiler->mOptions.mDebugAlloc)
  5301. {
  5302. func = GetInternalMethod("Dbg_RawFree").mFunc;
  5303. }
  5304. else
  5305. {
  5306. String funcName = mCompiler->mOptions.mFreeLinkName;
  5307. if (funcName.IsEmpty())
  5308. funcName = "free";
  5309. func = mBfIRBuilder->GetFunction(funcName);
  5310. if (!func)
  5311. {
  5312. paramTypes.clear();
  5313. paramTypes.push_back(nullPtrType);
  5314. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5315. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5316. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  5317. }
  5318. }
  5319. }
  5320. break;
  5321. case BfBuiltInFuncType_LoadSharedLibraries:
  5322. paramTypes.clear();
  5323. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5324. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  5325. break;
  5326. default: break;
  5327. }
  5328. mBuiltInFuncs[(int)funcTypeId] = func;
  5329. return func;
  5330. }
  5331. return mBuiltInFuncs[(int)funcTypeId];
  5332. }
  5333. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, const Array<BfGenericParamDef*>& genericParamDefs, int genericParamIdx)
  5334. {
  5335. BfGenericParamDef* genericParamDef = genericParamDefs[genericParamIdx];
  5336. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  5337. BfAutoComplete* bfAutocomplete = NULL;
  5338. if (mCompiler->mResolvePassData != NULL)
  5339. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  5340. if (bfAutocomplete != NULL)
  5341. {
  5342. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  5343. {
  5344. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  5345. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  5346. {
  5347. String filter = nameNode->ToString();
  5348. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  5349. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  5350. if (nameIdx != 0)
  5351. {
  5352. for (auto checkGenericParam : genericParamDefs)
  5353. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", checkGenericParam->mName.c_str()), filter);
  5354. }
  5355. }
  5356. }
  5357. }
  5358. for (auto constraintTypeRef : genericParamDef->mInterfaceConstraints)
  5359. {
  5360. if (bfAutocomplete != NULL)
  5361. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  5362. //TODO: Constraints may refer to other generic params (of either type or method)
  5363. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  5364. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  5365. if (constraintType != NULL)
  5366. {
  5367. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5368. {
  5369. bool isValidTypeCode = false;
  5370. BfTypeCode typeCode = BfTypeCode_None;
  5371. if (constraintType->IsTypedPrimitive())
  5372. {
  5373. auto underlyingType = constraintType->GetUnderlyingType();
  5374. if (underlyingType->IsPrimitiveType())
  5375. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  5376. }
  5377. if (constraintType->IsPrimitiveType())
  5378. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  5379. switch (typeCode)
  5380. {
  5381. case BfTypeCode_Int8:
  5382. case BfTypeCode_UInt8:
  5383. case BfTypeCode_Int16:
  5384. case BfTypeCode_UInt16:
  5385. case BfTypeCode_Int32:
  5386. case BfTypeCode_UInt32:
  5387. case BfTypeCode_Int64:
  5388. case BfTypeCode_UInt64:
  5389. case BfTypeCode_IntPtr:
  5390. case BfTypeCode_UIntPtr:
  5391. case BfTypeCode_IntUnknown:
  5392. case BfTypeCode_UIntUnknown:
  5393. case BfTypeCode_Single:
  5394. case BfTypeCode_Double:
  5395. case BfTypeCode_Char8:
  5396. case BfTypeCode_Char16:
  5397. case BfTypeCode_Char32:
  5398. isValidTypeCode = true;
  5399. break;
  5400. default: break;
  5401. }
  5402. if (isValidTypeCode)
  5403. {
  5404. genericParamInstance->mTypeConstraint = constraintType;
  5405. }
  5406. else
  5407. {
  5408. Fail("Const constraint must be a primitive type", constraintTypeRef);
  5409. }
  5410. }
  5411. else
  5412. {
  5413. if (constraintType->IsPrimitiveType())
  5414. {
  5415. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  5416. continue;
  5417. }
  5418. if (constraintType->IsArray())
  5419. {
  5420. 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);
  5421. continue;
  5422. }
  5423. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  5424. {
  5425. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  5426. continue;
  5427. }
  5428. if (constraintType->IsInterface())
  5429. {
  5430. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  5431. }
  5432. else
  5433. {
  5434. auto constraintTypeInst = constraintType->ToTypeInstance();
  5435. if (genericParamInstance->mTypeConstraint != NULL)
  5436. {
  5437. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  5438. {
  5439. // Allow more specific type
  5440. genericParamInstance->mTypeConstraint = constraintTypeInst;
  5441. }
  5442. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  5443. {
  5444. // Silently ignore less-specific type
  5445. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  5446. {
  5447. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  5448. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  5449. }
  5450. }
  5451. else
  5452. {
  5453. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  5454. return;
  5455. }
  5456. }
  5457. else
  5458. genericParamInstance->mTypeConstraint = constraintType;
  5459. }
  5460. }
  5461. }
  5462. }
  5463. if (((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  5464. (genericParamInstance->mTypeConstraint == NULL))
  5465. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  5466. }
  5467. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  5468. {
  5469. if (genericParamSource.mMethodInstance != NULL)
  5470. {
  5471. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance);
  5472. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  5473. return MethodToString(methodInst);
  5474. }
  5475. else
  5476. {
  5477. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  5478. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  5479. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  5480. return TypeToString(typeInst);
  5481. }
  5482. }
  5483. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  5484. {
  5485. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  5486. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  5487. BfType* origCheckArgType = checkArgType;
  5488. if (origCheckArgType->IsRef())
  5489. origCheckArgType = origCheckArgType->GetUnderlyingType();
  5490. bool argMayBeReferenceType = false;
  5491. int checkGenericParamFlags = 0;
  5492. if (checkArgType->IsGenericParam())
  5493. {
  5494. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  5495. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  5496. if (checkGenericParamInst->mTypeConstraint != NULL)
  5497. checkArgType = checkGenericParamInst->mTypeConstraint;
  5498. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  5499. {
  5500. argMayBeReferenceType = false;
  5501. }
  5502. else
  5503. {
  5504. argMayBeReferenceType = true;
  5505. }
  5506. }
  5507. if (checkArgType->IsObjectOrInterface())
  5508. argMayBeReferenceType = true;
  5509. BfTypeInstance* typeConstraintInst = NULL;
  5510. if (genericParamInst->mTypeConstraint != NULL)
  5511. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  5512. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  5513. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  5514. {
  5515. if (!ignoreErrors)
  5516. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  5517. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5518. return false;
  5519. }
  5520. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  5521. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  5522. {
  5523. if (!ignoreErrors)
  5524. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  5525. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5526. return false;
  5527. }
  5528. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  5529. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  5530. {
  5531. if (!ignoreErrors)
  5532. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  5533. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5534. return false;
  5535. }
  5536. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5537. {
  5538. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  5539. {
  5540. if (!ignoreErrors)
  5541. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  5542. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5543. return false;
  5544. }
  5545. }
  5546. else
  5547. {
  5548. if (checkArgType->IsConstExprValue())
  5549. {
  5550. if (!ignoreErrors)
  5551. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  5552. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5553. return false;
  5554. }
  5555. }
  5556. if ((genericParamInst->mInterfaceConstraints.size() == 0) && (genericParamInst->mTypeConstraint == NULL))
  5557. return true;
  5558. if (checkArgType->IsPointer())
  5559. {
  5560. auto ptrType = (BfPointerType*)checkArgType;
  5561. checkArgType = ptrType->mElementType;
  5562. }
  5563. if (genericParamInst->mTypeConstraint != NULL)
  5564. {
  5565. bool constraintMatched = false;
  5566. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5567. {
  5568. if (checkArgType->IsConstExprValue())
  5569. {
  5570. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  5571. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  5572. {
  5573. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  5574. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  5575. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  5576. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  5577. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  5578. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  5579. {
  5580. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  5581. {
  5582. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5583. {
  5584. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  5585. {
  5586. if (!ignoreErrors)
  5587. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5588. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5589. return false;
  5590. }
  5591. }
  5592. else
  5593. {
  5594. if (!ignoreErrors)
  5595. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with integer const '%lld', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5596. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5597. return false;
  5598. }
  5599. }
  5600. else
  5601. {
  5602. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5603. {
  5604. char valStr[64];
  5605. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  5606. if (!ignoreErrors)
  5607. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with floating point const '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5608. valStr, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5609. return false;
  5610. }
  5611. }
  5612. }
  5613. }
  5614. }
  5615. }
  5616. else
  5617. {
  5618. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  5619. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  5620. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5621. if ((checkArgType->IsMethodRef()) && (convCheckConstraint->IsDelegate()))
  5622. {
  5623. auto methodRefType = (BfMethodRefType*)checkArgType;
  5624. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  5625. BfExprEvaluator exprEvaluator(this);
  5626. if (exprEvaluator.IsExactMethodMatch(methodRefType->mMethodRef, invokeMethod))
  5627. constraintMatched = true;
  5628. }
  5629. else if (CanImplicitlyCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  5630. {
  5631. constraintMatched = true;
  5632. }
  5633. else if (origCheckArgType->IsWrappableType())
  5634. {
  5635. if (origCheckArgType->IsSizedArray())
  5636. {
  5637. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  5638. if (convCheckConstraint->IsGenericTypeInstance())
  5639. {
  5640. auto convCheckConstraintInst = (BfGenericTypeInstance*)convCheckConstraint;
  5641. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  5642. {
  5643. if (convCheckConstraintInst->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  5644. {
  5645. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mTypeGenericArguments[1];
  5646. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  5647. constraintMatched = true;
  5648. }
  5649. }
  5650. }
  5651. }
  5652. if (!constraintMatched)
  5653. {
  5654. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5655. if (CanImplicitlyCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  5656. constraintMatched = true;
  5657. }
  5658. }
  5659. if (!constraintMatched)
  5660. {
  5661. if (!ignoreErrors)
  5662. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5663. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  5664. TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  5665. return false;
  5666. }
  5667. }
  5668. }
  5669. if ((genericParamInst->mInterfaceConstraints.size() > 0) && (origCheckArgType->IsInterface()))
  5670. {
  5671. PopulateType(origCheckArgType);
  5672. auto checkTypeInst = origCheckArgType->ToTypeInstance();
  5673. if (checkTypeInst->mTypeDef->mIsConcrete)
  5674. {
  5675. if (!ignoreErrors)
  5676. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be concrete interface '%s' for '%s', must be a concrete type", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5677. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5678. return false;
  5679. }
  5680. }
  5681. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  5682. {
  5683. BfType* convCheckConstraint = checkConstraint;
  5684. if (convCheckConstraint->IsUnspecializedType())
  5685. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5686. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  5687. bool implementsInterface = false;
  5688. if (origCheckArgType != checkArgType)
  5689. {
  5690. implementsInterface = CanImplicitlyCast(origCheckArgType, convCheckConstraint);
  5691. }
  5692. if (!implementsInterface)
  5693. implementsInterface = CanImplicitlyCast(checkArgType, convCheckConstraint);
  5694. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  5695. {
  5696. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5697. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5698. implementsInterface = true;
  5699. }
  5700. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  5701. {
  5702. auto underlyingType = origCheckArgType->GetUnderlyingType();
  5703. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  5704. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5705. implementsInterface = true;
  5706. }
  5707. if (!implementsInterface)
  5708. {
  5709. if (!ignoreErrors)
  5710. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5711. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  5712. return false;
  5713. }
  5714. }
  5715. return true;
  5716. }
  5717. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  5718. {
  5719. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  5720. {
  5721. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  5722. return genericParamType;
  5723. }
  5724. auto genericParamType = new BfGenericParamType();
  5725. genericParamType->mContext = mContext;
  5726. genericParamType->mGenericParamKind = paramKind;
  5727. genericParamType->mGenericParamIdx = paramIdx;
  5728. PopulateType(genericParamType);
  5729. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  5730. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  5731. BfResolvedTypeSet::LookupContext lookupCtx;
  5732. lookupCtx.mModule = this;
  5733. BfResolvedTypeSet::Entry* typeEntry = NULL;
  5734. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  5735. BF_ASSERT(inserted);
  5736. typeEntry->mValue = genericParamType;
  5737. return genericParamType;
  5738. }
  5739. static int sValueFromExprIdx = 0;
  5740. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  5741. {
  5742. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  5743. if ((result) && (!ignoreNullable))
  5744. {
  5745. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  5746. //TODO: Make this work, needed for 'void' and such
  5747. BfType* nullableType = NULL;
  5748. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  5749. {
  5750. BfTypeVector typeVec;
  5751. typeVec.push_back(result.mType);
  5752. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  5753. BF_ASSERT(nullableType != NULL);
  5754. }
  5755. // Go back to start and do any setup we need
  5756. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5757. BfTypedValue nullableTypedValue;
  5758. if (nullableType != NULL)
  5759. {
  5760. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  5761. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  5762. GetConstValue(nullableType->mSize), nullableType->mAlign);
  5763. }
  5764. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5765. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  5766. mBfIRBuilder->SetInsertPoint(notNullBB);
  5767. result = LoadValue(result);
  5768. if (nullableTypedValue)
  5769. {
  5770. auto elementType = nullableType->GetUnderlyingType();
  5771. if (elementType->IsValuelessType())
  5772. {
  5773. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  5774. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5775. result = nullableTypedValue;
  5776. }
  5777. else
  5778. {
  5779. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  5780. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  5781. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  5782. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5783. result = nullableTypedValue;
  5784. }
  5785. }
  5786. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5787. AddBasicBlock(pendingNullCond->mDoneBB);
  5788. if (nullableType == NULL)
  5789. {
  5790. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 2);
  5791. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  5792. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  5793. result.mValue = phi;
  5794. }
  5795. }
  5796. else
  5797. {
  5798. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5799. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5800. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5801. AddBasicBlock(pendingNullCond->mDoneBB);
  5802. }
  5803. delete mCurMethodState->mPendingNullConditional;
  5804. mCurMethodState->mPendingNullConditional = NULL;
  5805. return result;
  5806. }
  5807. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  5808. {
  5809. BfScopeData newScope;
  5810. newScope.mOuterIsConditional = true;
  5811. newScope.mAllowTargeting = false;
  5812. mCurMethodState->AddScope(&newScope);
  5813. NewScopeState();
  5814. exprEvaluator.mBfEvalExprFlags = flags;
  5815. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5816. RestoreScopeState();
  5817. }
  5818. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5819. {
  5820. //
  5821. {
  5822. BP_ZONE("CreateValueFromExpression:CheckStack");
  5823. StackHelper stackHelper;
  5824. if (!stackHelper.CanStackExpand(64 * 1024))
  5825. {
  5826. BfTypedValue result;
  5827. if (!stackHelper.Execute([&]()
  5828. {
  5829. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5830. }))
  5831. {
  5832. Fail("Expression too complex to compile", expr);
  5833. }
  5834. return result;
  5835. }
  5836. }
  5837. BP_ZONE("BfModule::CreateValueFromExpression");
  5838. if (outOrigType != NULL)
  5839. *outOrigType = NULL;
  5840. exprEvaluator.mExpectingType = wantTypeRef;
  5841. exprEvaluator.mBfEvalExprFlags = flags;
  5842. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  5843. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  5844. {
  5845. EvaluateWithNewScope(exprEvaluator, expr, flags);
  5846. }
  5847. else
  5848. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5849. if (!exprEvaluator.mResult)
  5850. {
  5851. if (!mCompiler->mPassInstance->HasFailed())
  5852. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  5853. return BfTypedValue();
  5854. }
  5855. auto typedVal = exprEvaluator.mResult;
  5856. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  5857. {
  5858. BF_ASSERT(typedVal.mType->IsGenericParam());
  5859. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  5860. bool handled = false;
  5861. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5862. {
  5863. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  5864. if (genericTypeConstraint != NULL)
  5865. {
  5866. auto primType = genericTypeConstraint->ToPrimitiveType();
  5867. if (primType != NULL)
  5868. {
  5869. BfTypedValue result;
  5870. result.mKind = BfTypedValueKind_Value;
  5871. result.mType = genericTypeConstraint;
  5872. result.mValue = mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode);
  5873. typedVal = result;
  5874. handled = true;
  5875. }
  5876. }
  5877. }
  5878. if (!handled)
  5879. {
  5880. //Fail("Only const generic parameters can be used as values", expr);
  5881. AssertErrorState();
  5882. return BfTypedValue();
  5883. }
  5884. }
  5885. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  5886. FixIntUnknown(typedVal);
  5887. exprEvaluator.CheckResultForReading(typedVal);
  5888. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  5889. {
  5890. if ((flags & BfEvalExprFlags_NoCast) == 0)
  5891. {
  5892. // Only allow a 'ref' type if we have an explicit 'ref' operator
  5893. bool allowRef = false;
  5894. BfExpression* checkExpr = expr;
  5895. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  5896. checkExpr = parenExpr->mExpression;
  5897. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  5898. {
  5899. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  5900. allowRef = true;
  5901. }
  5902. if (!allowRef)
  5903. typedVal = RemoveRef(typedVal);
  5904. }
  5905. }
  5906. if (!typedVal.mType->IsComposite()) // Load non-structs by default
  5907. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5908. if (wantTypeRef != NULL)
  5909. {
  5910. if (outOrigType != NULL)
  5911. *outOrigType = typedVal.mType;
  5912. if ((flags & BfEvalExprFlags_NoCast) == 0)
  5913. {
  5914. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  5915. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  5916. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  5917. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  5918. if (!typedVal)
  5919. return typedVal;
  5920. }
  5921. //WTF- why did we have this?
  5922. /*if ((flags & BfEvalExprFlags_ExplicitCast) == 0)
  5923. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);*/
  5924. if (exprEvaluator.mIsVolatileReference)
  5925. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5926. }
  5927. // if ((typedVal.IsSplat()) && ((flags & BfEvalExprFlags_AllowSplat) == 0))
  5928. // typedVal = MakeAddressable(typedVal);
  5929. //typedVal = AggregateSplat(typedVal);
  5930. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  5931. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5932. return typedVal;
  5933. }
  5934. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5935. {
  5936. BfExprEvaluator exprEvaluator(this);
  5937. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5938. }
  5939. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  5940. {
  5941. BfExprEvaluator exprEvaluator(this);
  5942. exprEvaluator.Evaluate(expr);
  5943. if (!exprEvaluator.mResult)
  5944. {
  5945. Fail("Invalid expression type", expr);
  5946. return BfTypedValue();
  5947. }
  5948. if (!exprEvaluator.mResult.IsAddr())
  5949. {
  5950. Fail("Cannot assign to value", expr);
  5951. return BfTypedValue();
  5952. }
  5953. return exprEvaluator.mResult;
  5954. }
  5955. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  5956. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  5957. {
  5958. auto typeInstance = typedValue.mType->ToTypeInstance();
  5959. if (zeroMemory)
  5960. {
  5961. int zeroAlign = typedValue.mType->mAlign;
  5962. if (typeInstance != NULL)
  5963. zeroAlign = typeInstance->mInstAlign;
  5964. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  5965. }
  5966. if (!typedValue.mType->IsObject())
  5967. {
  5968. return;
  5969. }
  5970. if ((scopeData == NULL) && (mCurMethodState != NULL))
  5971. return; // Handled in heap alloc funcs
  5972. auto typeDef = typeInstance->mTypeDef;
  5973. mBfIRBuilder->PopulateType(typedValue.mType);
  5974. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  5975. bool isAutocomplete = mCompiler->IsAutocomplete();
  5976. BfIRValue vDataRef;
  5977. if (!isAutocomplete)
  5978. {
  5979. vDataRef = GetClassVDataPtr(typeInstance);
  5980. }
  5981. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  5982. auto ptrType = CreatePointerType(i8Type);
  5983. auto ptrPtrType = CreatePointerType(ptrType);
  5984. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  5985. PopulateType(ptrType, BfPopulateType_Declaration);
  5986. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  5987. if (!isAutocomplete)
  5988. {
  5989. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5990. {
  5991. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  5992. SizedArray<BfIRValue, 4> llvmArgs;
  5993. llvmArgs.push_back(objectPtr);
  5994. llvmArgs.push_back(vDataRef);
  5995. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  5996. if (objectStackInitMethod)
  5997. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  5998. }
  5999. else
  6000. {
  6001. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  6002. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  6003. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6004. }
  6005. }
  6006. }
  6007. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  6008. {
  6009. BfIRValue result;
  6010. BfType* ptrType;
  6011. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  6012. ptrType = type;
  6013. else
  6014. ptrType = CreatePointerType(type);
  6015. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  6016. {
  6017. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6018. SizedArray<BfExpression*, 2> argExprs;
  6019. BfTypedValueExpression typedValueExpr;
  6020. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  6021. typedValueExpr.mRefNode = refNode;
  6022. argExprs.push_back(&typedValueExpr);
  6023. BfTypedValueExpression appendSizeValueExpr;
  6024. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  6025. appendSizeValueExpr.mRefNode = refNode;
  6026. argExprs.push_back(&appendSizeValueExpr);
  6027. BfExprEvaluator exprEvaluator(this);
  6028. BfTypedValue allocResult;
  6029. if (allocTarget.mScopedInvocationTarget != NULL)
  6030. {
  6031. SizedArray<BfTypeReference*, 2> genericArgs;
  6032. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  6033. allocResult = LoadValue(exprEvaluator.mResult);
  6034. }
  6035. else if (allocTarget.mCustomAllocator)
  6036. {
  6037. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6038. if (customTypeInst != NULL)
  6039. {
  6040. BfTypedValueExpression typeValueExpr;
  6041. String allocMethodName = "Alloc";
  6042. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  6043. {
  6044. allocMethodName = "AllocTyped";
  6045. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  6046. auto typeRefVal = CreateTypeDataRef(type);
  6047. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  6048. typeValueExpr.mRefNode = refNode;
  6049. argExprs.Insert(0, &typeValueExpr);
  6050. }
  6051. if (HasMixin(customTypeInst, allocMethodName, 2))
  6052. {
  6053. BfSizedArray<BfExpression*> argExprArr;
  6054. argExprArr.mSize = (int)argExprs.size();
  6055. argExprArr.mVals = &argExprs[0];
  6056. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  6057. allocResult = exprEvaluator.GetResult();
  6058. }
  6059. else
  6060. {
  6061. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6062. BfResolvedArgs argValues(&sizedArgExprs);
  6063. exprEvaluator.ResolveArgValues(argValues);
  6064. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  6065. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  6066. }
  6067. }
  6068. }
  6069. if (allocResult)
  6070. {
  6071. if (allocResult.mType->IsVoidPtr())
  6072. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  6073. else
  6074. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  6075. return result;
  6076. }
  6077. }
  6078. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  6079. return result;
  6080. if (mCompiler->mOptions.mDebugAlloc)
  6081. {
  6082. BfIRValue allocData = GetDbgRawAllocData(type);
  6083. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  6084. SizedArray<BfIRValue, 2> llvmArgs;
  6085. llvmArgs.push_back(sizeValue);
  6086. llvmArgs.push_back(allocData);
  6087. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  6088. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6089. }
  6090. BfModuleMethodInstance moduleMethodInstance;
  6091. moduleMethodInstance = GetInternalMethod("Malloc");
  6092. SizedArray<BfIRValue, 1> llvmArgs;
  6093. llvmArgs.push_back(sizeValue);
  6094. auto func = moduleMethodInstance.mFunc;
  6095. if ((!func) || (func.IsFake()))
  6096. {
  6097. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  6098. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  6099. }
  6100. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  6101. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  6102. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  6103. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6104. return result;
  6105. }
  6106. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  6107. {
  6108. if (type->IsStruct())
  6109. {
  6110. auto typeInstance = type->ToTypeInstance();
  6111. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  6112. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6113. }
  6114. else if (type->IsObjectOrInterface())
  6115. {
  6116. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6117. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  6118. BF_ASSERT(moduleMethodInst.mFunc);
  6119. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6120. }
  6121. else
  6122. {
  6123. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6124. BfExprEvaluator exprEvaluator(this);
  6125. SizedArray<BfResolvedArg, 1> resolvedArgs;
  6126. BfResolvedArg resolvedArg;
  6127. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  6128. resolvedArgs.Add(resolvedArg);
  6129. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  6130. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  6131. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  6132. BF_ASSERT(moduleMethodInst.mFunc);
  6133. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6134. }
  6135. return BfIRValue();
  6136. }
  6137. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  6138. {
  6139. BfIRValue allocDataValue;
  6140. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  6141. return allocDataValue;
  6142. BfIRValue markFuncPtr;
  6143. if (type->WantsGCMarking())
  6144. markFuncPtr = GetMarkFuncPtr(type);
  6145. else
  6146. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6147. BfIRValue typeDataRef = CreateTypeDataRef(type);
  6148. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  6149. BfTypeInstance* typeInstance = type->ToTypeInstance();
  6150. if (typeInstance == NULL)
  6151. {
  6152. typeInstance = GetWrappedStructType(type);
  6153. if (typeInstance != NULL)
  6154. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6155. }
  6156. if (typeInstance != NULL)
  6157. PopulateType(typeInstance);
  6158. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6159. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  6160. {
  6161. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6162. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6163. }
  6164. SizedArray<BfIRValue, 2> dataValues;
  6165. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  6166. dataValues.Add(typeDataRef);
  6167. dataValues.Add(markFuncPtr);
  6168. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  6169. BfIRValue dataStruct = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  6170. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  6171. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  6172. return allocDataValue;
  6173. }
  6174. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  6175. {
  6176. BP_ZONE("AllocFromType");
  6177. BfScopeData* scopeData = allocTarget.mScopeData;
  6178. auto typeInstance = type->ToTypeInstance();
  6179. if ((typeInstance == NULL) && (type->IsGenericParam()))
  6180. typeInstance = mContext->mBfObjectType;
  6181. bool isHeapAlloc = scopeData == NULL;
  6182. bool isScopeAlloc = scopeData != NULL;
  6183. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  6184. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  6185. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  6186. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  6187. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  6188. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  6189. {
  6190. BfPointerType* ptrType = CreatePointerType(type);
  6191. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  6192. return val;
  6193. }
  6194. if (typeInstance != NULL)
  6195. mBfIRBuilder->PopulateType(typeInstance);
  6196. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  6197. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  6198. {
  6199. if (arraySize)
  6200. {
  6201. if (isRawArrayAlloc)
  6202. {
  6203. BfPointerType* ptrType = CreatePointerType(type);
  6204. return GetDefaultValue(ptrType);
  6205. }
  6206. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6207. return GetDefaultValue(arrayType);
  6208. }
  6209. if (type->IsValueType())
  6210. {
  6211. BfPointerType* ptrType = CreatePointerType(type);
  6212. return GetDefaultValue(ptrType);
  6213. }
  6214. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  6215. }
  6216. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6217. BfIRValue sizeValue;
  6218. BfIRType allocType = mBfIRBuilder->MapType(type);
  6219. int allocSize = type->mSize;
  6220. int allocAlign = type->mAlign;
  6221. if (typeInstance != NULL)
  6222. {
  6223. if (!mBfIRBuilder->mIgnoreWrites)
  6224. typeInstance->mHasBeenInstantiated = true;
  6225. allocSize = typeInstance->mInstSize;
  6226. allocAlign = typeInstance->mInstAlign;
  6227. //if (typeInstance->IsEnum())
  6228. //allocType = typeInstance->mIRType;
  6229. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  6230. }
  6231. if (alignOverride != -1)
  6232. allocAlign = alignOverride;
  6233. // The "dynSize" cases:
  6234. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  6235. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  6236. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  6237. // though we'd expect their stack space to be released
  6238. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  6239. {
  6240. MarkDynStack(scopeData);
  6241. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6242. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  6243. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6244. BfType* voidPtrType = CreatePointerType(voidType);
  6245. if (!mCurMethodState->mDynStackRevIdx)
  6246. {
  6247. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  6248. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6249. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6250. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  6251. mBfIRBuilder->ClearDebugLocation(storeInst);
  6252. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6253. }
  6254. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  6255. auto bytePtrType = CreatePointerType(byteType);
  6256. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  6257. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  6258. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6259. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6260. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  6261. mBfIRBuilder->ClearDebugLocation(storeInst);
  6262. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  6263. mBfIRBuilder->ClearDebugLocation(storeInst);
  6264. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6265. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  6266. if (IsTargetingBeefBackend())
  6267. {
  6268. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  6269. // to ensure there isn't any register collision during looping is just to not allow it to
  6270. // bind to a register at all
  6271. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  6272. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  6273. }
  6274. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  6275. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  6276. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  6277. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  6278. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  6279. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  6280. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  6281. mBfIRBuilder->AddBlock(verCheckBB);
  6282. mBfIRBuilder->SetInsertPoint(verCheckBB);
  6283. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  6284. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  6285. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  6286. mBfIRBuilder->AddBlock(resizeBB);
  6287. mBfIRBuilder->SetInsertPoint(resizeBB);
  6288. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6289. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  6290. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  6291. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  6292. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  6293. mBfIRBuilder->CreateBr(endBB);
  6294. mBfIRBuilder->AddBlock(endBB);
  6295. mBfIRBuilder->SetInsertPoint(endBB);
  6296. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  6297. };
  6298. if (isScopeAlloc)
  6299. {
  6300. if (arraySize)
  6301. {
  6302. bool isConstantArraySize = arraySize.IsConst();
  6303. if (isRawArrayAlloc)
  6304. {
  6305. BfPointerType* ptrType = CreatePointerType(type);
  6306. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6307. {
  6308. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6309. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  6310. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  6311. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  6312. }
  6313. else
  6314. {
  6315. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6316. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  6317. if (!isDynAlloc)
  6318. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6319. else
  6320. {
  6321. MarkDynStack(scopeData);
  6322. SaveStackState(scopeData);
  6323. }
  6324. int typeSize = type->GetStride();
  6325. BfIRValue allocaInst;
  6326. BfIRValue result;
  6327. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  6328. {
  6329. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6330. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  6331. result = allocaInst;
  6332. }
  6333. else
  6334. {
  6335. if (typeInstance->IsStruct())
  6336. typeSize = typeInstance->GetInstStride();
  6337. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  6338. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6339. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6340. auto ptrType = CreatePointerType(typeInstance);
  6341. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  6342. if (!isDynAlloc)
  6343. mBfIRBuilder->ClearDebugLocation(result);
  6344. }
  6345. if (!isDynAlloc)
  6346. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6347. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  6348. if (!isDynAlloc)
  6349. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6350. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  6351. if (arraySize.IsConst())
  6352. {
  6353. auto constant = mBfIRBuilder->GetConstant(arraySize);
  6354. if (constant->mInt64 == 0)
  6355. noDtorCall = true;
  6356. }
  6357. if (!noDtorCall)
  6358. {
  6359. bool isConstSize = arraySize.IsConst();
  6360. BfIRBlock clearBlock;
  6361. BfIRBlock contBlock;
  6362. if (!isConstSize)
  6363. {
  6364. clearBlock = mBfIRBuilder->CreateBlock("clear");
  6365. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  6366. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  6367. mBfIRBuilder->AddBlock(clearBlock);
  6368. mBfIRBuilder->SetInsertPoint(clearBlock);
  6369. }
  6370. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6371. if (!isConstSize)
  6372. {
  6373. mBfIRBuilder->CreateBr(contBlock);
  6374. mBfIRBuilder->AddBlock(contBlock);
  6375. mBfIRBuilder->SetInsertPoint(contBlock);
  6376. }
  6377. }
  6378. //InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6379. return result;
  6380. }
  6381. }
  6382. else
  6383. {
  6384. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6385. {
  6386. // Generate and check new size
  6387. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6388. auto firstElementField = &arrayType->mFieldInstances.back();
  6389. int arrayClassSize = firstElementField->mDataOffset;
  6390. sizeValue = GetConstValue(arrayClassSize);
  6391. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6392. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6393. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  6394. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  6395. if (!noDtorCall)
  6396. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6397. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6398. return typedVal.mValue;
  6399. }
  6400. else
  6401. {
  6402. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6403. auto firstElementField = &arrayType->mFieldInstances.back();
  6404. int arrayClassSize = firstElementField->mDataOffset;
  6405. sizeValue = GetConstValue(arrayClassSize);
  6406. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6407. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6408. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6409. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6410. if (!isDynAlloc)
  6411. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6412. else
  6413. {
  6414. MarkDynStack(scopeData);
  6415. SaveStackState(scopeData);
  6416. }
  6417. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  6418. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6419. if (!isDynAlloc)
  6420. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6421. mBfIRBuilder->SetAllocaAlignment(allocaInst, arrayType->mAlign);
  6422. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  6423. mBfIRBuilder->ClearDebugLocation_Last();
  6424. if (!isDynAlloc)
  6425. mBfIRBuilder->SetInsertPoint(prevBlock);
  6426. if (!noDtorCall)
  6427. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6428. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6429. return typedVal.mValue;
  6430. }
  6431. }
  6432. }
  6433. else if (appendSizeValue)
  6434. {
  6435. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  6436. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  6437. // use the "dynSize" version conservatively
  6438. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6439. {
  6440. // Generate and check new size
  6441. sizeValue = GetConstValue(typeInstance->mInstSize);
  6442. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6443. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  6444. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  6445. if (!noDtorCall)
  6446. AddStackAlloc(typedVal, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  6447. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6448. return typedVal.mValue;
  6449. }
  6450. else // stack alloc, unlooped, with append
  6451. {
  6452. sizeValue = GetConstValue(typeInstance->mInstSize);
  6453. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6454. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6455. bool wasDynAlloc = isDynAlloc;
  6456. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6457. if (!isDynAlloc)
  6458. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6459. else
  6460. {
  6461. MarkDynStack(scopeData);
  6462. SaveStackState(scopeData);
  6463. }
  6464. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  6465. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  6466. if (!isDynAlloc)
  6467. {
  6468. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6469. }
  6470. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6471. bool mayBeLarge = false;
  6472. if (sizeValue.IsConst())
  6473. {
  6474. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  6475. if (constantInt->mInt64 >= 4096)
  6476. mayBeLarge = true;
  6477. }
  6478. else
  6479. mayBeLarge = true;
  6480. if (((type->IsObject() && (!mayBeLarge))) ||
  6481. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6482. ((zeroMemory) && (!mayBeLarge)))
  6483. {
  6484. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6485. }
  6486. BfIRValue castedVal;
  6487. if (!isDynAlloc)
  6488. {
  6489. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6490. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6491. mBfIRBuilder->ClearDebugLocation(castedVal);
  6492. mBfIRBuilder->SetInsertPoint(prevBlock);
  6493. if (WantsLifetimes())
  6494. {
  6495. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6496. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6497. }
  6498. }
  6499. else
  6500. {
  6501. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6502. }
  6503. auto typedVal = BfTypedValue(castedVal, typeInstance);
  6504. if (!noDtorCall)
  6505. {
  6506. bool doCondAlloca = false;
  6507. if (!IsTargetingBeefBackend())
  6508. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  6509. AddStackAlloc(typedVal, NULL, scopeData, doCondAlloca, true);
  6510. }
  6511. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6512. return typedVal.mValue;
  6513. }
  6514. }
  6515. else // "Normal" stack alloc
  6516. {
  6517. BF_ASSERT(!sizeValue);
  6518. //TODO: If sizeValue is a constant then do this in the head IR builder
  6519. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6520. if (!isLoopedAlloc)
  6521. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6522. else
  6523. {
  6524. MarkDynStack(scopeData);
  6525. SaveStackState(scopeData);
  6526. }
  6527. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  6528. if (!isLoopedAlloc)
  6529. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6530. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6531. bool mayBeLarge = allocSize >= 4096;
  6532. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  6533. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6534. ((zeroMemory) && (!mayBeLarge)))
  6535. {
  6536. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  6537. // and memset is always safe
  6538. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6539. }
  6540. auto typedVal = BfTypedValue(allocaInst, type);
  6541. if (!isLoopedAlloc)
  6542. {
  6543. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6544. mBfIRBuilder->SetInsertPoint(prevBlock);
  6545. if (WantsLifetimes())
  6546. {
  6547. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6548. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6549. }
  6550. }
  6551. if (!noDtorCall)
  6552. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6553. if (typeInstance != NULL)
  6554. {
  6555. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  6556. }
  6557. else
  6558. {
  6559. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  6560. }
  6561. return allocaInst;
  6562. }
  6563. }
  6564. else if (arraySize)
  6565. {
  6566. if (isRawArrayAlloc)
  6567. {
  6568. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6569. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  6570. }
  6571. else
  6572. {
  6573. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6574. typeInstance = arrayType;
  6575. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6576. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6577. appendSizeValue = elementDataSize;
  6578. if (!type->IsSizeAligned())
  6579. {
  6580. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  6581. }
  6582. }
  6583. }
  6584. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  6585. {
  6586. auto vDataRef = GetClassVDataPtr(typeInstance);
  6587. BfIRValue result;
  6588. bool isResultInitialized = false;
  6589. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6590. if (typeInstance->mTypeOptionsIdx != -1)
  6591. {
  6592. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6593. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6594. }
  6595. if (!sizeValue)
  6596. sizeValue = GetConstValue(typeInstance->mInstSize);
  6597. if (appendSizeValue)
  6598. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6599. BfIRValue origSizeValue = sizeValue;
  6600. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  6601. if (isAllocEx)
  6602. {
  6603. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  6604. if (prepareStackTraceMethod)
  6605. {
  6606. SizedArray<BfIRValue, 2> irArgs;
  6607. irArgs.Add(sizeValue);
  6608. irArgs.Add(GetConstValue(stackCount));
  6609. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  6610. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  6611. }
  6612. }
  6613. if (allocTarget.mCustomAllocator)
  6614. {
  6615. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6616. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  6617. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  6618. {
  6619. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6620. mBfIRBuilder->PopulateType(classVDataType);
  6621. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6622. mBfIRBuilder->PopulateType(typeInstType);
  6623. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  6624. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  6625. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  6626. BfTypedValueExpression typedValueExpr;
  6627. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  6628. typedValueExpr.mRefNode = allocTarget.mRefNode;
  6629. BfExprEvaluator exprEvaluator(this);
  6630. SizedArray<BfExpression*, 2> argExprs;
  6631. argExprs.push_back(&typedValueExpr);
  6632. BfTypedValueExpression sizeValueExpr;
  6633. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  6634. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  6635. argExprs.push_back(&sizeValueExpr);
  6636. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6637. BfResolvedArgs argValues(&sizedArgExprs);
  6638. exprEvaluator.ResolveArgValues(argValues);
  6639. exprEvaluator.mNoBind = true;
  6640. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  6641. if (allocResult)
  6642. {
  6643. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  6644. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  6645. else
  6646. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  6647. isResultInitialized = true;
  6648. }
  6649. }
  6650. }
  6651. if (!result)
  6652. {
  6653. if (hasCustomAllocator)
  6654. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  6655. }
  6656. if (result)
  6657. {
  6658. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6659. {
  6660. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  6661. SizedArray<BfIRValue, 4> llvmArgs;
  6662. llvmArgs.push_back(objectPtr);
  6663. llvmArgs.push_back(origSizeValue);
  6664. llvmArgs.push_back(vDataRef);
  6665. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  6666. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  6667. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  6668. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  6669. }
  6670. else
  6671. {
  6672. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  6673. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6674. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  6675. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  6676. }
  6677. }
  6678. else
  6679. {
  6680. if ((mBfIRBuilder->mIgnoreWrites) || (mCompiler->mIsResolveOnly))
  6681. return GetDefaultValue(typeInstance);
  6682. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6683. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  6684. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6685. {
  6686. SizedArray<BfIRValue, 4> llvmArgs;
  6687. llvmArgs.push_back(vData);
  6688. llvmArgs.push_back(sizeValue);
  6689. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  6690. llvmArgs.push_back(GetConstValue(stackCount));
  6691. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  6692. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  6693. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6694. }
  6695. else
  6696. {
  6697. SizedArray<BfIRValue, 4> llvmArgs;
  6698. llvmArgs.push_back(sizeValue);
  6699. BfIRFunction irFunc;
  6700. if (mCompiler->mOptions.mDebugAlloc)
  6701. {
  6702. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  6703. irFunc = moduleMethodInstance.mFunc;
  6704. }
  6705. if (!irFunc)
  6706. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6707. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  6708. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  6709. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  6710. mBfIRBuilder->CreateStore(vData, vdataPtr);
  6711. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6712. }
  6713. }
  6714. if ((zeroMemory) && (arraySize))
  6715. {
  6716. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6717. typeInstance = arrayType;
  6718. auto firstElementField = &arrayType->mFieldInstances.back();
  6719. int arrayClassSize = firstElementField->mDataOffset;
  6720. BfIRValue elementDataSize;
  6721. bool skipZero = false;
  6722. if (arraySize.IsConst())
  6723. {
  6724. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6725. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6726. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  6727. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  6728. if (constVal->mInt64 <= 0)
  6729. skipZero = true;
  6730. }
  6731. else
  6732. {
  6733. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  6734. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6735. }
  6736. if (!skipZero)
  6737. {
  6738. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6739. auto ptrType = CreatePointerType(i8Type);
  6740. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  6741. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  6742. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  6743. appendSizeValue = elementDataSize;
  6744. }
  6745. }
  6746. return result;
  6747. }
  6748. else
  6749. {
  6750. if (!sizeValue)
  6751. sizeValue = GetConstValue(allocSize);
  6752. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  6753. }
  6754. }
  6755. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  6756. {
  6757. if ((type == NULL) || (refNode == NULL))
  6758. return;
  6759. auto typeInstance = type->ToTypeInstance();
  6760. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  6761. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  6762. }
  6763. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  6764. {
  6765. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6766. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6767. }
  6768. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  6769. {
  6770. if (sizeMultiple == 0)
  6771. sizeMultiple = align;
  6772. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  6773. {
  6774. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  6775. {
  6776. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6777. BF_ASSERT(localVar->mName == "appendIdx");
  6778. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  6779. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6780. if (align > 1)
  6781. {
  6782. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6783. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6784. }
  6785. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  6786. }
  6787. else
  6788. {
  6789. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  6790. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  6791. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  6792. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6793. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6794. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  6795. }
  6796. }
  6797. if (mCurMethodState->mCurAppendAlign == 0)
  6798. mCurMethodState->mCurAppendAlign = sizeMultiple;
  6799. else
  6800. {
  6801. if (sizeMultiple % align == 0)
  6802. mCurMethodState->mCurAppendAlign = align;
  6803. else
  6804. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  6805. }
  6806. }
  6807. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  6808. {
  6809. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6810. BF_ASSERT(localVar->mName == "appendIdx");
  6811. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  6812. BfIRValue retValue;
  6813. BfTypeInstance* retTypeInstance = NULL;
  6814. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  6815. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  6816. if (arraySize)
  6817. {
  6818. if (isRawArrayAlloc)
  6819. {
  6820. EmitAppendAlign(type->mAlign);
  6821. BfPointerType* ptrType = CreatePointerType(type);
  6822. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6823. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6824. if (mSystem->mPtrSize != 4)
  6825. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6826. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6827. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6828. if (zeroMemory)
  6829. {
  6830. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  6831. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  6832. }
  6833. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  6834. }
  6835. else
  6836. {
  6837. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6838. EmitAppendAlign(arrayType->mAlign, type->mSize);
  6839. auto firstElementField = &arrayType->mFieldInstances.back();
  6840. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  6841. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  6842. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6843. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6844. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6845. if (mSystem->mPtrSize != 4)
  6846. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6847. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6848. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6849. if (zeroMemory)
  6850. {
  6851. // Only zero out the actual elements
  6852. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  6853. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  6854. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  6855. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  6856. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  6857. }
  6858. retTypeInstance = arrayType;
  6859. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  6860. }
  6861. }
  6862. else
  6863. {
  6864. auto typeInst = type->ToTypeInstance();
  6865. BfIRValue sizeValue;
  6866. BfIRType toType;
  6867. if (typeInst != NULL)
  6868. {
  6869. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  6870. sizeValue = GetConstValue(typeInst->mInstSize);
  6871. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  6872. }
  6873. else
  6874. {
  6875. EmitAppendAlign(type->mAlign, type->mSize);
  6876. sizeValue = GetConstValue(type->mSize);
  6877. auto toPtrType = CreatePointerType(type);
  6878. toType = mBfIRBuilder->MapType(toPtrType);
  6879. }
  6880. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6881. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6882. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6883. retTypeInstance = typeInst;
  6884. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  6885. }
  6886. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  6887. {
  6888. mBfIRBuilder->PopulateType(retTypeInstance);
  6889. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  6890. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  6891. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  6892. auto curThis = GetThis();
  6893. BfIRValue newFlags;
  6894. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6895. {
  6896. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  6897. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  6898. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  6899. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  6900. }
  6901. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  6902. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  6903. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  6904. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6905. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6906. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6907. {
  6908. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  6909. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  6910. }
  6911. }
  6912. if (appendSizeValue)
  6913. {
  6914. EmitAppendAlign(appendAllocAlign);
  6915. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6916. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  6917. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6918. }
  6919. return retValue;
  6920. }
  6921. bool BfModule::IsOptimized()
  6922. {
  6923. if (mProject == NULL)
  6924. return false;
  6925. int optLevel = GetModuleOptions().mOptLevel;
  6926. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  6927. }
  6928. bool BfModule::IsTargetingBeefBackend()
  6929. {
  6930. if (mProject == NULL)
  6931. return false;
  6932. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  6933. }
  6934. bool BfModule::WantsLifetimes()
  6935. {
  6936. if (mProject == NULL)
  6937. return false;
  6938. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  6939. }
  6940. bool BfModule::HasCompiledOutput()
  6941. {
  6942. return (!mSystem->mIsResolveOnly) && (mIsReified);
  6943. }
  6944. // We will skip the object access check for any occurances of this value
  6945. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  6946. {
  6947. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  6948. return;
  6949. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  6950. return;
  6951. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  6952. return;
  6953. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  6954. }
  6955. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  6956. {
  6957. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  6958. return;
  6959. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  6960. return;
  6961. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  6962. auto typeOptions = GetTypeOptions();
  6963. if (typeOptions != NULL)
  6964. emitObjectAccessCheck = BfTypeOptions::Apply(emitObjectAccessCheck, typeOptions->mEmitObjectAccessCheck);
  6965. if (!emitObjectAccessCheck)
  6966. return;
  6967. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  6968. {
  6969. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  6970. return;
  6971. }
  6972. if (typedVal.IsAddr())
  6973. typedVal = LoadValue(typedVal);
  6974. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  6975. }
  6976. void BfModule::EmitEnsureInstructionAt()
  6977. {
  6978. if (mProject == NULL)
  6979. return;
  6980. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  6981. return;
  6982. mBfIRBuilder->CreateEnsureInstructionAt();
  6983. }
  6984. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  6985. {
  6986. if (mBfIRBuilder->mIgnoreWrites)
  6987. return; // Nothing needed here
  6988. auto irb = mBfIRBuilder;
  6989. auto checkBB = irb->CreateBlock("as.check");
  6990. auto isNull = irb->CreateIsNull(targetValue.mValue);
  6991. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  6992. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6993. auto intPtrType = CreatePointerType(intType);
  6994. auto intPtrPtrType = CreatePointerType(intPtrType);
  6995. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  6996. auto int32PtrType = CreatePointerType(int32Type);
  6997. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6998. if (mCompiler->mOptions.mAllowHotSwapping)
  6999. {
  7000. BfExprEvaluator exprEvaluator(this);
  7001. AddBasicBlock(checkBB);
  7002. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7003. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  7004. SizedArray<BfIRValue, 4> irArgs;
  7005. irArgs.push_back(objectParam);
  7006. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  7007. auto callResult = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  7008. auto resultType = ResolveTypeDef(mSystem->mTypeBool);
  7009. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  7010. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7011. }
  7012. else
  7013. {
  7014. AddBasicBlock(checkBB);
  7015. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  7016. vDataPtr = irb->CreateLoad(vDataPtr);
  7017. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7018. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  7019. if (targetType->IsInterface())
  7020. {
  7021. auto targetTypeInst = targetType->ToTypeInstance();
  7022. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7023. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  7024. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  7025. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7026. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  7027. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  7028. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  7029. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  7030. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  7031. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7032. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  7033. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  7034. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7035. }
  7036. else
  7037. {
  7038. if (!targetType->IsTypeInstance())
  7039. targetType = GetWrappedStructType(targetType);
  7040. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7041. int inheritanceIdOfs = mSystem->mPtrSize;
  7042. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7043. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7044. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  7045. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  7046. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  7047. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  7048. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  7049. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7050. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  7051. fieldInst = &typeTypeInstance->mFieldInstances[10];
  7052. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  7053. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7054. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  7055. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  7056. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  7057. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7058. }
  7059. }
  7060. }
  7061. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  7062. {
  7063. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  7064. auto typeOptions = GetTypeOptions();
  7065. if (typeOptions != NULL)
  7066. emitDynamicCastCheck = BfTypeOptions::Apply(emitDynamicCastCheck, typeOptions->mEmitDynamicCastCheck);
  7067. if (emitDynamicCastCheck)
  7068. {
  7069. int wantTypeId = 0;
  7070. if (!type->IsGenericParam())
  7071. wantTypeId = type->mTypeId;
  7072. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  7073. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  7074. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  7075. AddBasicBlock(failBlock);
  7076. SizedArray<BfIRValue, 8> llvmArgs;
  7077. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7078. llvmArgs.push_back(bitAddr);
  7079. llvmArgs.push_back(GetConstValue32(wantTypeId));
  7080. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  7081. BF_ASSERT(objDynCheck);
  7082. if (objDynCheck)
  7083. {
  7084. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  7085. }
  7086. mBfIRBuilder->CreateBr(endBlock);
  7087. AddBasicBlock(endBlock);
  7088. }
  7089. }
  7090. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  7091. {
  7092. BP_ZONE("BoxValue");
  7093. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  7094. if (typedVal.mType->IsNullable())
  7095. {
  7096. typedVal = MakeAddressable(typedVal);
  7097. auto innerType = typedVal.mType->GetUnderlyingType();
  7098. if (!innerType->IsValueType())
  7099. {
  7100. Fail("Only value types can be boxed", srcNode);
  7101. return BfTypedValue();
  7102. }
  7103. auto prevBB = mBfIRBuilder->GetInsertBlock();
  7104. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  7105. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  7106. mBfIRBuilder->PopulateType(typedVal.mType);
  7107. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  7108. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  7109. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  7110. auto boxedType = CreateBoxedType(innerType);
  7111. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7112. auto resultType = toType;
  7113. if (resultType == NULL)
  7114. resultType = boxedType;
  7115. mBfIRBuilder->AddBlock(boxBB);
  7116. mBfIRBuilder->SetInsertPoint(boxBB);
  7117. BfScopeData newScope;
  7118. newScope.mOuterIsConditional = true;
  7119. mCurMethodState->AddScope(&newScope);
  7120. NewScopeState();
  7121. BfIRValue nullableValueAddr;
  7122. BfIRValue loadedVal;
  7123. if (innerType->IsValuelessType())
  7124. {
  7125. loadedVal = mBfIRBuilder->GetFakeVal();
  7126. }
  7127. else
  7128. {
  7129. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  7130. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  7131. }
  7132. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  7133. RestoreScopeState();
  7134. if (!boxedVal)
  7135. return BfTypedValue();
  7136. mBfIRBuilder->CreateBr(endBB);
  7137. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  7138. mBfIRBuilder->AddBlock(endBB);
  7139. mBfIRBuilder->SetInsertPoint(endBB);
  7140. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  7141. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  7142. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  7143. return BfTypedValue(phi, resultType);
  7144. }
  7145. bool alreadyCheckedCast = false;
  7146. BfTypeInstance* toTypeInstance = NULL;
  7147. if (toType != NULL)
  7148. toTypeInstance = toType->ToTypeInstance();
  7149. bool isStructPtr = typedVal.mType->IsStructPtr();
  7150. if (fromStructTypeInstance == NULL)
  7151. {
  7152. auto primType = (BfPrimitiveType*)typedVal.mType;
  7153. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  7154. if (isStructPtr)
  7155. {
  7156. if ((toTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7157. alreadyCheckedCast = true;
  7158. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  7159. }
  7160. }
  7161. if (fromStructTypeInstance == NULL)
  7162. return BfTypedValue();
  7163. // Need to box it
  7164. auto boxedType = CreateBoxedType(typedVal.mType);
  7165. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed()) && (boxedType == toType);
  7166. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7167. {
  7168. if (typedVal.mType->IsPointer())
  7169. {
  7170. NOP;
  7171. }
  7172. mBfIRBuilder->PopulateType(boxedType);
  7173. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7174. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  7175. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  7176. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  7177. if (boxedType->IsUnspecializedType())
  7178. {
  7179. BF_ASSERT(mCurMethodInstance->mIsUnspecialized);
  7180. }
  7181. else
  7182. {
  7183. PopulateType(fromStructTypeInstance);
  7184. if (!fromStructTypeInstance->IsValuelessType())
  7185. {
  7186. typedVal = LoadValue(typedVal);
  7187. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  7188. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  7189. {
  7190. auto ptrType = CreatePointerType(typedVal.mType);
  7191. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  7192. }
  7193. if (typedVal.IsSplat())
  7194. {
  7195. AggregateSplatIntoAddr(typedVal, valPtr);
  7196. }
  7197. else
  7198. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  7199. }
  7200. }
  7201. if (toType == NULL)
  7202. {
  7203. return BfTypedValue(allocaInst, boxedType);
  7204. }
  7205. else
  7206. {
  7207. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  7208. return BfTypedValue(castedValue, toType);
  7209. }
  7210. }
  7211. return BfTypedValue();
  7212. }
  7213. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  7214. {
  7215. BfTypeInstance* checkTypeInst = typeInst;
  7216. while (checkTypeInst != NULL)
  7217. {
  7218. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  7219. {
  7220. if (checkProp->mName == propDef->mName)
  7221. {
  7222. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  7223. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  7224. {
  7225. propDef = checkProp;
  7226. typeInst = checkTypeInst;
  7227. return true;
  7228. }
  7229. }
  7230. }
  7231. checkTypeInst = checkTypeInst->mBaseType;
  7232. }
  7233. return false;
  7234. }
  7235. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7236. {
  7237. if (!typeInstance->mResolvingVarField)
  7238. {
  7239. if (typeInstance->IsIncomplete())
  7240. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7241. }
  7242. else
  7243. {
  7244. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  7245. {
  7246. AssertErrorState();
  7247. return NULL;
  7248. }
  7249. }
  7250. if (assertName != NULL)
  7251. {
  7252. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7253. }
  7254. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  7255. if (methodGroup.mDefault == NULL)
  7256. {
  7257. if (!mCompiler->mIsResolveOnly)
  7258. {
  7259. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl));
  7260. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  7261. // Get it from the owning module so we don't create a reference prematurely...
  7262. auto declModule = typeInstance->mModule;
  7263. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified)).mMethodInstance;
  7264. }
  7265. else
  7266. {
  7267. auto declModule = typeInstance->mModule;
  7268. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass)).mMethodInstance;
  7269. }
  7270. }
  7271. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7272. //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
  7273. // be from a call to the NON-raw version
  7274. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  7275. // {
  7276. // methodInstance->mIsReified = mIsReified;
  7277. // if (methodInstance->mMethodProcessRequest == NULL)
  7278. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  7279. // }
  7280. return methodInstance;
  7281. }
  7282. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  7283. {
  7284. if (methodDef->mIsLocalMethod)
  7285. {
  7286. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  7287. }
  7288. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7289. }
  7290. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  7291. {
  7292. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7293. while (typeInstance != NULL)
  7294. {
  7295. typeInstance->mTypeDef->PopulateMemberSets();
  7296. BfMemberSetEntry* entry = NULL;
  7297. BfMethodDef* methodDef = NULL;
  7298. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7299. methodDef = (BfMethodDef*)entry->mMemberDef;
  7300. while (methodDef != NULL)
  7301. {
  7302. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  7303. (methodDef->mGenericParams.size() == 0) &&
  7304. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7305. return GetRawMethodInstance(typeInstance, methodDef);
  7306. methodDef = methodDef->mNextWithSameName;
  7307. }
  7308. if (!checkBase)
  7309. break;
  7310. typeInstance = typeInstance->mBaseType;
  7311. }
  7312. return NULL;
  7313. }
  7314. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance)
  7315. {
  7316. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7317. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  7318. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  7319. if (!owner->IsGenericTypeInstance())
  7320. return methodInstance;
  7321. auto genericType = (BfGenericTypeInstance*)owner;
  7322. if (genericType->IsUnspecializedType())
  7323. return methodInstance;
  7324. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  7325. if (unspecializedType == NULL)
  7326. {
  7327. AssertErrorState();
  7328. return methodInstance;
  7329. }
  7330. if (unspecializedType == NULL)
  7331. return methodInstance;
  7332. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  7333. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  7334. }
  7335. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  7336. {
  7337. int genericCount = 0;
  7338. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  7339. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  7340. {
  7341. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  7342. if (param->IsGenericParam())
  7343. genericCount++;
  7344. }
  7345. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  7346. genericCount++;
  7347. return genericCount;
  7348. }
  7349. BfModule* BfModule::GetSpecializedMethodModule(const Array<BfProject*>& projectList)
  7350. {
  7351. BF_ASSERT(!mIsScratchModule);
  7352. BF_ASSERT(mIsReified);
  7353. BfModule* mainModule = this;
  7354. if (mParentModule != NULL)
  7355. mainModule = mParentModule;
  7356. BfModule* specModule = NULL;
  7357. BfModule** specModulePtr = NULL;
  7358. if (mainModule->mSpecializedMethodModules.TryGetValue(projectList, &specModulePtr))
  7359. {
  7360. return *specModulePtr;
  7361. }
  7362. else
  7363. {
  7364. String specModuleName = mModuleName;
  7365. for (auto bfProject : projectList)
  7366. specModuleName += StrFormat("@%s", bfProject->mName.c_str());
  7367. specModule = new BfModule(mContext, specModuleName);
  7368. specModule->mProject = mainModule->mProject;
  7369. specModule->mParentModule = mainModule;
  7370. specModule->mIsSpecializedMethodModuleRoot = true;
  7371. specModule->Init();
  7372. mainModule->mSpecializedMethodModules[projectList] = specModule;
  7373. }
  7374. return specModule;
  7375. }
  7376. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  7377. {
  7378. if (mCompiler->IsSkippingExtraResolveChecks())
  7379. return BfIRValue();
  7380. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  7381. {
  7382. //BF_ASSERT(!methodInstance->mIRFunction);
  7383. return BfIRValue();
  7384. }
  7385. auto methodDef = methodInstance->mMethodDef;
  7386. StringT<128> methodName;
  7387. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  7388. if (isInlined != methodInstance->mAlwaysInline)
  7389. {
  7390. if (isInlined)
  7391. methodName += "__INLINE";
  7392. else
  7393. methodName += "__NOINLINE";
  7394. }
  7395. if (tryExisting)
  7396. {
  7397. auto func = mBfIRBuilder->GetFunction(methodName);
  7398. if (func)
  7399. return func;
  7400. }
  7401. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  7402. {
  7403. if (methodDeclaration->mExternSpecifier != NULL)
  7404. {
  7405. auto intrinsic = GetIntrinsic(methodInstance);
  7406. if (intrinsic)
  7407. return intrinsic;
  7408. // If we have multiple entries with the same name, they could have different arguments and will generate other errors...
  7409. /*auto func = mBfIRBuilder->GetFunction(methodName);
  7410. if (func)
  7411. return func;*/
  7412. }
  7413. }
  7414. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  7415. {
  7416. return CreateDllImportGlobalVar(methodInstance, false);
  7417. }
  7418. BfIRType returnType;
  7419. SizedArray<BfIRType, 8> paramTypes;
  7420. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  7421. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes);
  7422. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  7423. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  7424. if (callingConv != BfIRCallingConv_CDecl)
  7425. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  7426. SetupIRMethod(methodInstance, func, isInlined);
  7427. // auto srcModule = methodInstance->GetOwner()->GetModule();
  7428. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  7429. // {
  7430. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  7431. // {
  7432. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  7433. // }
  7434. // }
  7435. return func;
  7436. }
  7437. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7438. {
  7439. if (assertName != NULL)
  7440. {
  7441. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7442. }
  7443. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7444. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7445. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  7446. {
  7447. // Can't use it, not reified
  7448. methodInstance = NULL;
  7449. }
  7450. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  7451. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  7452. {
  7453. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  7454. return BfModuleMethodInstance(methodInstance, func);
  7455. }
  7456. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector());
  7457. }
  7458. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7459. {
  7460. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7461. while (typeInstance != NULL)
  7462. {
  7463. typeInstance->mTypeDef->PopulateMemberSets();
  7464. BfMemberSetEntry* entry = NULL;
  7465. BfMethodDef* methodDef = NULL;
  7466. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7467. methodDef = (BfMethodDef*)entry->mMemberDef;
  7468. while (methodDef != NULL)
  7469. {
  7470. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7471. (methodDef->mGenericParams.size() == 0) &&
  7472. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7473. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7474. methodDef = methodDef->mNextWithSameName;
  7475. }
  7476. if (!checkBase)
  7477. break;
  7478. typeInstance = typeInstance->mBaseType;
  7479. }
  7480. return BfModuleMethodInstance();
  7481. }
  7482. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  7483. {
  7484. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7485. while (typeInstance != NULL)
  7486. {
  7487. typeInstance->mTypeDef->PopulateMemberSets();
  7488. BfMemberSetEntry* entry = NULL;
  7489. BfMethodDef* methodDef = NULL;
  7490. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7491. methodDef = (BfMethodDef*)entry->mMemberDef;
  7492. while (methodDef != NULL)
  7493. {
  7494. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7495. (methodDef->mGenericParams.size() == 0) &&
  7496. (paramTypes.size() == methodDef->mParams.size()))
  7497. {
  7498. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7499. if (moduleMethodInstance.mMethodInstance != NULL)
  7500. {
  7501. bool matches = true;
  7502. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  7503. {
  7504. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  7505. matches = false;
  7506. }
  7507. if (matches)
  7508. return moduleMethodInstance;
  7509. }
  7510. }
  7511. methodDef = methodDef->mNextWithSameName;
  7512. }
  7513. if (!checkBase)
  7514. break;
  7515. typeInstance = typeInstance->mBaseType;
  7516. }
  7517. return BfModuleMethodInstance();
  7518. }
  7519. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  7520. {
  7521. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  7522. PopulateType(internalType);
  7523. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  7524. if (!moduleMethodInstance)
  7525. {
  7526. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  7527. }
  7528. return moduleMethodInstance;
  7529. }
  7530. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7531. {
  7532. while (typeInstance != NULL)
  7533. {
  7534. typeInstance->mTypeDef->PopulateMemberSets();
  7535. BfMemberSetEntry* entry = NULL;
  7536. BfMethodDef* methodDef = NULL;
  7537. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7538. methodDef = (BfMethodDef*)entry->mMemberDef;
  7539. while (methodDef != NULL)
  7540. {
  7541. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7542. (methodDef->mGenericParams.size() == 0) &&
  7543. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7544. {
  7545. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  7546. if (!methodInstanceGroup.IsImplemented())
  7547. return false;
  7548. if (methodInstanceGroup.mDefault == NULL)
  7549. return false;
  7550. return methodInstanceGroup.mDefault->mIsReified;
  7551. }
  7552. methodDef = methodDef->mNextWithSameName;
  7553. }
  7554. if (!checkBase)
  7555. break;
  7556. typeInstance = typeInstance->mBaseType;
  7557. }
  7558. return false;
  7559. }
  7560. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7561. {
  7562. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7563. while (typeInstance != NULL)
  7564. {
  7565. typeInstance->mTypeDef->PopulateMemberSets();
  7566. BfMemberSetEntry* entry = NULL;
  7567. BfMethodDef* methodDef = NULL;
  7568. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7569. methodDef = (BfMethodDef*)entry->mMemberDef;
  7570. while (methodDef != NULL)
  7571. {
  7572. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  7573. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7574. return true;
  7575. methodDef = methodDef->mNextWithSameName;
  7576. }
  7577. if (!checkBase)
  7578. break;
  7579. typeInstance = typeInstance->mBaseType;
  7580. }
  7581. return BfModuleMethodInstance();
  7582. }
  7583. BfFieldInstance* BfModule::GetFieldByName(BfTypeInstance* typeInstance, const StringImpl& fieldName)
  7584. {
  7585. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7586. typeInstance->mTypeDef->PopulateMemberSets();
  7587. BfMemberSetEntry* entry = NULL;
  7588. BfFieldDef* fieldDef = NULL;
  7589. if (typeInstance->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  7590. {
  7591. fieldDef = (BfFieldDef*)entry->mMemberDef;
  7592. return &typeInstance->mFieldInstances[fieldDef->mIdx];
  7593. }
  7594. // for (auto& fieldInst : typeInstance->mFieldInstances)
  7595. // {
  7596. // auto fieldDef = fieldInst.GetFieldDef();
  7597. // if ((fieldDef != NULL) && (fieldDef->mName == fieldName))
  7598. // return &fieldInst;
  7599. // }
  7600. return NULL;
  7601. }
  7602. String BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* methodGenericArgs)
  7603. {
  7604. auto methodDef = methodInst->mMethodDef;
  7605. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  7606. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7607. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  7608. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7609. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  7610. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7611. type = ResolveGenericType(type, *methodGenericArgs);
  7612. String methodName;
  7613. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  7614. {
  7615. methodName = TypeToString(type, typeNameFlags);
  7616. if (methodName == "$")
  7617. methodName = "";
  7618. else
  7619. methodName += ".";
  7620. }
  7621. String accessorString;
  7622. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  7623. if (methodInst->mMethodDef->mIsLocalMethod)
  7624. {
  7625. int atPos = (int)methodDefName.IndexOf('$');
  7626. methodDefName.RemoveToEnd(atPos);
  7627. methodDefName.Replace("@", ".");
  7628. }
  7629. else
  7630. {
  7631. int atPos = (int)methodDefName.IndexOf('$');
  7632. if (atPos != -1)
  7633. {
  7634. accessorString = methodDefName.Substring(0, atPos);
  7635. if ((accessorString == "get") || (accessorString == "set"))
  7636. {
  7637. methodDefName = methodDefName.Substring(atPos + 1);
  7638. }
  7639. else
  7640. accessorString = "";
  7641. }
  7642. }
  7643. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  7644. {
  7645. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7646. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7647. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7648. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  7649. methodName += ".";
  7650. }
  7651. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  7652. {
  7653. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7654. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7655. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7656. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  7657. methodName += ".";
  7658. }
  7659. if (methodDef->mMethodType == BfMethodType_Operator)
  7660. {
  7661. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  7662. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  7663. {
  7664. // Don't add explicit/implicit part, since that's not available in GCC mangling
  7665. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  7666. {
  7667. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7668. methodName += "explicit ";
  7669. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7670. methodName += "explicit ";
  7671. }*/
  7672. methodName += "operator ";
  7673. if (methodInst->mReturnType != NULL)
  7674. methodName += TypeToString(methodInst->mReturnType);
  7675. }
  7676. else
  7677. {
  7678. methodName += "operator";
  7679. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  7680. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  7681. }
  7682. }
  7683. else if (methodDef->mMethodType == BfMethodType_Ctor)
  7684. {
  7685. if (methodDef->mIsStatic)
  7686. methodName += "__BfStaticCtor";
  7687. else
  7688. methodName += "this";
  7689. accessorString = "";
  7690. }
  7691. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  7692. {
  7693. methodDef->GetRefNode()->ToString(methodName);
  7694. methodName += " get accessor";
  7695. return methodName;
  7696. }
  7697. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  7698. {
  7699. methodDef->GetRefNode()->ToString(methodName);
  7700. methodName += " set accessor";
  7701. return methodName;
  7702. }
  7703. else
  7704. methodName += methodDefName;
  7705. BfTypeVector newMethodGenericArgs;
  7706. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7707. {
  7708. methodName += "<";
  7709. for (int i = 0; i < (int) methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  7710. {
  7711. if (i > 0)
  7712. methodName += ", ";
  7713. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7714. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  7715. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7716. if (allowResolveGenericParamNames)
  7717. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7718. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  7719. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7720. {
  7721. bool hasEmpty = false;
  7722. for (auto arg : *methodGenericArgs)
  7723. {
  7724. if (arg == NULL)
  7725. hasEmpty = true;
  7726. }
  7727. if (hasEmpty)
  7728. {
  7729. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  7730. {
  7731. auto arg = (*methodGenericArgs)[genericIdx];
  7732. if (arg != NULL)
  7733. newMethodGenericArgs.push_back(arg);
  7734. else
  7735. {
  7736. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  7737. if (genericParamInst->mTypeConstraint != NULL)
  7738. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  7739. else
  7740. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  7741. }
  7742. }
  7743. methodGenericArgs = &newMethodGenericArgs;
  7744. }
  7745. if (type->IsUnspecializedType())
  7746. type = ResolveGenericType(type, *methodGenericArgs);
  7747. }
  7748. methodName += TypeToString(type, typeNameFlags);
  7749. }
  7750. methodName += ">";
  7751. }
  7752. if (accessorString.length() == 0)
  7753. {
  7754. int dispParamIdx = 0;
  7755. methodName += "(";
  7756. for (int paramIdx = 0; paramIdx < (int) methodInst->GetParamCount(); paramIdx++)
  7757. {
  7758. int paramKind = methodInst->GetParamKind(paramIdx);
  7759. if (paramKind == BfParamKind_ImplicitCapture)
  7760. continue;
  7761. if (dispParamIdx > 0)
  7762. methodName += ", ";
  7763. if (paramKind == BfParamKind_Params)
  7764. methodName += "params ";
  7765. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7766. BfType* type = methodInst->GetParamType(paramIdx);
  7767. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7768. type = ResolveGenericType(type, *methodGenericArgs);
  7769. methodName += TypeToString(type, typeNameFlags);
  7770. methodName += " ";
  7771. methodName += methodInst->GetParamName(paramIdx);
  7772. dispParamIdx++;
  7773. }
  7774. methodName += ")";
  7775. }
  7776. if (accessorString.length() != 0)
  7777. {
  7778. methodName += " " + accessorString;
  7779. }
  7780. return methodName;
  7781. }
  7782. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  7783. {
  7784. if ((flagsLeft & checkFlag) == 0)
  7785. return;
  7786. if (!str.empty())
  7787. {
  7788. if (flagsLeft == checkFlag)
  7789. {
  7790. if ((int)str.IndexOf(',') != -1)
  7791. str += ", and ";
  7792. else
  7793. str += " and ";
  7794. }
  7795. else
  7796. str += ", ";
  7797. }
  7798. str += addString;
  7799. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  7800. }
  7801. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  7802. {
  7803. String resultStr;
  7804. auto flagsLeft = attrTarget;
  7805. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  7806. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  7807. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  7808. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  7809. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  7810. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  7811. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  7812. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  7813. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  7814. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  7815. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  7816. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  7817. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  7818. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  7819. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  7820. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  7821. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  7822. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  7823. if (resultStr.IsEmpty())
  7824. return "<nothing>";
  7825. return resultStr;
  7826. }
  7827. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  7828. {
  7829. auto constant = mBfIRBuilder->GetConstant(irVal);
  7830. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  7831. if (stringPoolIdx != -1)
  7832. {
  7833. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_Int32, stringPoolIdx);
  7834. return;
  7835. }
  7836. if (constant->mConstType == BfConstType_Array)
  7837. {
  7838. auto constArray = (BfConstantArray*)constant;
  7839. SizedArray<BfIRValue, 8> newVals;
  7840. for (auto val : constArray->mValues)
  7841. {
  7842. auto newVal = val;
  7843. CurrentAddToConstHolder(newVal);
  7844. newVals.push_back(newVal);
  7845. }
  7846. irVal = mCurTypeInstance->mConstHolder->CreateConstArray(constArray->mType, newVals);
  7847. return;
  7848. }
  7849. auto origConst = irVal;
  7850. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  7851. {
  7852. auto bitcast = (BfConstantBitCast*)constant;
  7853. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  7854. }
  7855. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  7856. }
  7857. void BfModule::ClearConstData()
  7858. {
  7859. mBfIRBuilder->ClearConstData();
  7860. mStringObjectPool.Clear();
  7861. mStringCharPtrPool.Clear();
  7862. mStringPoolRefs.Clear();
  7863. }
  7864. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  7865. {
  7866. bool isString = false;
  7867. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  7868. if (wantType->IsPointer())
  7869. isString = true;
  7870. if (!isString)
  7871. {
  7872. switch (constant->mTypeCode)
  7873. {
  7874. case BfTypeCode_Boolean:
  7875. case BfTypeCode_Int8:
  7876. case BfTypeCode_UInt8:
  7877. case BfTypeCode_Int16:
  7878. case BfTypeCode_UInt16:
  7879. case BfTypeCode_Int32:
  7880. case BfTypeCode_UInt32:
  7881. case BfTypeCode_Int64:
  7882. case BfTypeCode_UInt64:
  7883. case BfTypeCode_IntPtr:
  7884. case BfTypeCode_UIntPtr:
  7885. case BfTypeCode_IntUnknown:
  7886. case BfTypeCode_UIntUnknown:
  7887. case BfTypeCode_Char8:
  7888. case BfTypeCode_Char16:
  7889. case BfTypeCode_Char32:
  7890. case BfTypeCode_Single:
  7891. case BfTypeCode_Double:
  7892. {
  7893. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  7894. auto typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  7895. if (typedValue.mType == wantType)
  7896. return typedValue;
  7897. if (wantType->IsTypedPrimitive())
  7898. {
  7899. if (typedValue.mType == wantType->GetUnderlyingType())
  7900. {
  7901. typedValue.mType = wantType;
  7902. return typedValue;
  7903. }
  7904. }
  7905. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  7906. BF_ASSERT(castedTypedValue);
  7907. return castedTypedValue;
  7908. }
  7909. break;
  7910. default: break;
  7911. }
  7912. }
  7913. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  7914. BF_ASSERT(irValue);
  7915. if (!irValue)
  7916. return BfTypedValue();
  7917. return BfTypedValue(irValue, wantType, false);
  7918. }
  7919. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  7920. {
  7921. if (constant->mTypeCode == BfTypeCode_NullPtr)
  7922. {
  7923. return GetDefaultValue(wantType);
  7924. }
  7925. bool isString = false;
  7926. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  7927. if (((wantType->IsPointer()) || (isString)) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  7928. {
  7929. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  7930. BfIRValue stringObjConst = GetStringObjectValue(str);
  7931. if (wantType->IsObject())
  7932. return stringObjConst;
  7933. return GetStringCharPtr(stringObjConst);
  7934. }
  7935. if (constant->mConstType == BfConstType_Array)
  7936. {
  7937. auto elementType = wantType->GetUnderlyingType();
  7938. auto constArray = (BfConstantArray*)constant;
  7939. SizedArray<BfIRValue, 8> newVals;
  7940. for (auto val : constArray->mValues)
  7941. {
  7942. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  7943. }
  7944. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  7945. }
  7946. return mBfIRBuilder->CreateConst(constant, constHolder);
  7947. }
  7948. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  7949. {
  7950. if (attrTarget == BfAttributeTargets_SkipValidate)
  7951. return;
  7952. for (auto& customAttribute : customAttributes->mAttributes)
  7953. {
  7954. if (!customAttribute.mAwaitingValidation)
  7955. continue;
  7956. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  7957. {
  7958. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  7959. customAttribute.mRef->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  7960. }
  7961. customAttribute.mAwaitingValidation = false;
  7962. }
  7963. }
  7964. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  7965. {
  7966. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  7967. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  7968. {
  7969. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  7970. }
  7971. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  7972. if (mCompiler->IsAutocomplete())
  7973. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  7974. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  7975. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  7976. BfAutoComplete* autoComplete = NULL;
  7977. if (mCompiler->mResolvePassData != NULL)
  7978. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  7979. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  7980. {
  7981. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  7982. BfCustomAttribute customAttribute;
  7983. customAttribute.mAwaitingValidation = true;
  7984. customAttribute.mRef = attributesDirective;
  7985. if (attributesDirective->mAttrOpenToken != NULL)
  7986. targetOverride = (BfAttributeTargets)0;
  7987. if (attributesDirective->mAttributeTypeRef == NULL)
  7988. {
  7989. AssertErrorState();
  7990. continue;
  7991. }
  7992. String attrName = attributesDirective->mAttributeTypeRef->ToString();
  7993. BfType* attrType = NULL;
  7994. BfAtomComposite nameComposite;
  7995. BfTypeDef* attrTypeDef = NULL;
  7996. if (mSystem->ParseAtomComposite(attrName + "Attribute", nameComposite))
  7997. {
  7998. BfTypeLookupError error;
  7999. error.mRefNode = attributesDirective->mAttributeTypeRef;
  8000. attrTypeDef = FindTypeDefRaw(nameComposite, 0, mCurTypeInstance, GetActiveTypeDef(NULL, true), &error);
  8001. }
  8002. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  8003. {
  8004. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  8005. if (attrTypeDef != NULL)
  8006. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  8007. }
  8008. if (attrTypeDef == NULL)
  8009. {
  8010. TypeRefNotFound(attributesDirective->mAttributeTypeRef, "Attribute");
  8011. continue;
  8012. }
  8013. bool isBypassedAttr = false;
  8014. if (attrTypeDef != NULL)
  8015. {
  8016. attrType = mContext->mUnreifiedModule->ResolveTypeDef(attrTypeDef, BfPopulateType_Identity);
  8017. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  8018. // We solve it by having a 'bypass' for known attributes that Object depends on
  8019. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  8020. {
  8021. if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  8022. {
  8023. BfTypeInstance* attrTypeInst = attrType->ToTypeInstance();
  8024. for (auto methodDef : attrTypeDef->mMethods)
  8025. {
  8026. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  8027. {
  8028. customAttribute.mType = attrType->ToTypeInstance();
  8029. customAttribute.mCtor = methodDef;
  8030. isBypassedAttr = true;
  8031. break;
  8032. }
  8033. }
  8034. }
  8035. }
  8036. if (isBypassedAttr)
  8037. {
  8038. customAttribute.mAwaitingValidation = false;
  8039. customAttributes->mAttributes.push_back(customAttribute);
  8040. continue;
  8041. }
  8042. if (mContext->mCurTypeState != NULL)
  8043. {
  8044. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8045. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8046. }
  8047. else
  8048. {
  8049. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8050. }
  8051. }
  8052. // Don't allow this
  8053. /*else if (mContext->mCurTypeState != NULL)
  8054. {
  8055. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8056. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_DataAndMethods);
  8057. }
  8058. else
  8059. {
  8060. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef);
  8061. }*/
  8062. BfTypeInstance* attrTypeInst = NULL;
  8063. if (attrType == NULL)
  8064. continue;
  8065. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  8066. attrTypeInst = attrType->ToTypeInstance();
  8067. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  8068. {
  8069. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  8070. continue;
  8071. }
  8072. if (mCurTypeInstance != NULL)
  8073. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8074. customAttribute.mType = attrTypeInst;
  8075. BfConstResolver constResolver(this);
  8076. bool inPropSet = false;
  8077. SizedArray<BfResolvedArg, 2> argValues;
  8078. for (BfExpression* arg : attributesDirective->mArguments)
  8079. {
  8080. if (arg == NULL)
  8081. {
  8082. continue;
  8083. }
  8084. if (autoComplete != NULL)
  8085. autoComplete->mShowAttributeProperties = attrTypeInst;
  8086. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  8087. {
  8088. inPropSet = true;
  8089. if (autoComplete != NULL)
  8090. autoComplete->CheckNode(assignExpr->mLeft);
  8091. String findName = assignExpr->mLeft->ToString();
  8092. BfPropertyDef* bestProp = NULL;
  8093. BfTypeInstance* bestPropTypeInst = NULL;
  8094. BfFieldDef* bestField = NULL;
  8095. BfTypeInstance* bestFieldTypeInst = NULL;
  8096. auto checkTypeInst = attrTypeInst;
  8097. while (checkTypeInst != NULL)
  8098. {
  8099. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  8100. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  8101. {
  8102. if (prop->mName == findName)
  8103. {
  8104. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  8105. {
  8106. bestProp = prop;
  8107. bestPropTypeInst = checkTypeInst;
  8108. }
  8109. }
  8110. }
  8111. for (auto field : checkTypeInst->mTypeDef->mFields)
  8112. {
  8113. if (field->mName == findName)
  8114. {
  8115. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  8116. {
  8117. bestField = field;
  8118. bestFieldTypeInst = checkTypeInst;
  8119. }
  8120. }
  8121. }
  8122. if ((bestProp != NULL) || (bestField != NULL))
  8123. break;
  8124. checkTypeInst = checkTypeInst->mBaseType;
  8125. }
  8126. bool handledExpr = false;
  8127. if (bestField != NULL)
  8128. {
  8129. handledExpr = true;
  8130. if (mCompiler->mResolvePassData != NULL)
  8131. {
  8132. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  8133. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8134. {
  8135. autoComplete->mDefField = bestField;
  8136. autoComplete->mDefType = attrTypeDef;
  8137. }
  8138. }
  8139. if (bestField->mProtection != BfProtection_Public)
  8140. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8141. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8142. BfCustomAttributeSetField setField;
  8143. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  8144. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  8145. if (assignExpr->mRight != NULL)
  8146. {
  8147. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  8148. if (result)
  8149. {
  8150. CurrentAddToConstHolder(result.mValue);
  8151. setField.mParam = result;
  8152. customAttribute.mSetField.push_back(setField);
  8153. }
  8154. }
  8155. }
  8156. else if (bestProp == NULL)
  8157. {
  8158. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  8159. }
  8160. else
  8161. {
  8162. BfMethodDef* setMethod = NULL;
  8163. for (auto methodDef : bestProp->mMethods)
  8164. {
  8165. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8166. {
  8167. setMethod = methodDef;
  8168. break;
  8169. }
  8170. }
  8171. if (setMethod == NULL)
  8172. {
  8173. Fail("Property has no setter", assignExpr->mLeft);
  8174. }
  8175. else
  8176. {
  8177. if (mCompiler->mResolvePassData != NULL)
  8178. {
  8179. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  8180. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8181. {
  8182. autoComplete->mDefProp = bestProp;
  8183. autoComplete->mDefType = attrTypeDef;
  8184. }
  8185. }
  8186. handledExpr = true;
  8187. if (bestProp->mProtection != BfProtection_Public)
  8188. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8189. BfResolvedArg resolvedArg;
  8190. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8191. BfCustomAttributeSetProperty setProperty;
  8192. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  8193. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  8194. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  8195. if (methodInstance.mMethodInstance != NULL)
  8196. {
  8197. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  8198. if (assignExpr->mRight != NULL)
  8199. {
  8200. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  8201. if (result)
  8202. {
  8203. BF_ASSERT(result.mType == propType);
  8204. CurrentAddToConstHolder(result.mValue);
  8205. setProperty.mParam = result;
  8206. customAttribute.mSetProperties.push_back(setProperty);
  8207. }
  8208. }
  8209. }
  8210. }
  8211. }
  8212. if ((!handledExpr) && (assignExpr->mRight != NULL))
  8213. constResolver.Resolve(assignExpr->mRight);
  8214. }
  8215. else
  8216. {
  8217. if (inPropSet)
  8218. {
  8219. Fail("Named attribute argument expected", arg); // CS1016
  8220. }
  8221. BfDeferEvalChecker deferEvalChecker;
  8222. arg->Accept(&deferEvalChecker);
  8223. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  8224. BfResolvedArg resolvedArg;
  8225. resolvedArg.mExpression = arg;
  8226. if (deferParamEval)
  8227. {
  8228. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  8229. }
  8230. else
  8231. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  8232. if (!inPropSet)
  8233. argValues.push_back(resolvedArg);
  8234. }
  8235. if (autoComplete != NULL)
  8236. autoComplete->mShowAttributeProperties = NULL;
  8237. }
  8238. auto wasCapturingMethodInfo = false;
  8239. if (autoComplete != NULL)
  8240. {
  8241. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8242. if (attributesDirective->mCtorOpenParen != NULL)
  8243. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  8244. }
  8245. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  8246. attrTypeDef = attrTypeInst->mTypeDef;
  8247. bool success = true;
  8248. bool isFailurePass = false;
  8249. for (int pass = 0; pass < 2; pass++)
  8250. {
  8251. bool isFailurePass = pass == 1;
  8252. for (auto checkMethod : attrTypeDef->mMethods)
  8253. {
  8254. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  8255. continue; // Don't match private default ctor if there's a user-defined one
  8256. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  8257. continue;
  8258. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, false, false)))
  8259. continue;
  8260. methodMatcher.CheckMethod(attrTypeInst, checkMethod, isFailurePass);
  8261. }
  8262. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8263. break;
  8264. }
  8265. if (autoComplete != NULL)
  8266. {
  8267. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  8268. {
  8269. autoComplete->mIsCapturingMethodMatchInfo = true;
  8270. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  8271. }
  8272. else
  8273. autoComplete->mIsCapturingMethodMatchInfo = false;
  8274. }
  8275. if (methodMatcher.mBestMethodDef == NULL)
  8276. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8277. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8278. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  8279. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  8280. {
  8281. Fail("Custom attribute circular reference", attributesDirective);
  8282. }
  8283. if (mCurTypeInstance != NULL)
  8284. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8285. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  8286. success = false;
  8287. for (auto& arg : argValues)
  8288. {
  8289. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  8290. {
  8291. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  8292. constResolver.Resolve(expr);
  8293. }
  8294. }
  8295. // Move all those to the constHolder
  8296. for (auto& ctorArg : customAttribute.mCtorArgs)
  8297. {
  8298. CurrentAddToConstHolder(ctorArg);
  8299. }
  8300. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  8301. {
  8302. targetOverride = BfAttributeTargets_ReturnValue;
  8303. if (attrTarget != BfAttributeTargets_Method)
  8304. {
  8305. 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.",
  8306. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  8307. }
  8308. success = false;
  8309. }
  8310. if ((success) && (targetOverride != (BfAttributeTargets)0))
  8311. {
  8312. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  8313. {
  8314. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  8315. if (methodInfoEx->mMethodCustomAttributes == NULL)
  8316. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  8317. if (success)
  8318. {
  8319. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  8320. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  8321. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  8322. }
  8323. }
  8324. else
  8325. {
  8326. // Failed - ignore
  8327. success = false;
  8328. }
  8329. }
  8330. if (success)
  8331. {
  8332. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  8333. {
  8334. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  8335. {
  8336. if (prevCustomAttribute.mType == attrTypeInst)
  8337. {
  8338. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  8339. }
  8340. }
  8341. }
  8342. }
  8343. if (success)
  8344. {
  8345. customAttributes->mAttributes.push_back(customAttribute);
  8346. }
  8347. }
  8348. ValidateCustomAttributes(customAttributes, attrTarget);
  8349. }
  8350. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType)
  8351. {
  8352. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  8353. GetCustomAttributes(customAttributes, attributesDirective, attrType);
  8354. return customAttributes;
  8355. }
  8356. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered)
  8357. {
  8358. if (mCurTypeInstance->mCustomAttributes != NULL)
  8359. {
  8360. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8361. {
  8362. String typeName = TypeToString(customAttribute.mType);
  8363. if (typeName == "System.PackedAttribute")
  8364. {
  8365. isPacked = true;
  8366. }
  8367. else if (typeName == "System.UnionAttribute")
  8368. {
  8369. isUnion = true;
  8370. }
  8371. else if (typeName == "System.CReprAttribute")
  8372. {
  8373. isCRepr = true;
  8374. isOrdered = true;
  8375. }
  8376. else if (typeName == "System.OrderedAttribute")
  8377. {
  8378. isOrdered = true;
  8379. }
  8380. else if (typeName == "System.AlwaysIncludeAttribute")
  8381. {
  8382. for (auto setProp : customAttribute.mSetProperties)
  8383. {
  8384. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  8385. if (propertyDef->mName == "AssumeInstantiated")
  8386. {
  8387. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8388. if ((constant != NULL) && (constant->mBool))
  8389. mCurTypeInstance->mHasBeenInstantiated = true;
  8390. }
  8391. }
  8392. }
  8393. }
  8394. }
  8395. }
  8396. // Checking to see if we're an attribute or not
  8397. void BfModule::ProcessCustomAttributeData()
  8398. {
  8399. bool isAttribute = false;
  8400. auto checkTypeInst = mCurTypeInstance->mBaseType;
  8401. while (checkTypeInst != NULL)
  8402. {
  8403. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  8404. isAttribute = true;
  8405. checkTypeInst = checkTypeInst->mBaseType;
  8406. }
  8407. if (!isAttribute)
  8408. return;
  8409. auto attributeData = new BfAttributeData();
  8410. bool hasCustomAttribute = false;
  8411. if (mCurTypeInstance->mCustomAttributes != NULL)
  8412. {
  8413. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8414. {
  8415. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  8416. {
  8417. if (customAttribute.mCtorArgs.size() > 0)
  8418. {
  8419. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  8420. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8421. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8422. }
  8423. for (auto& setProp : customAttribute.mSetProperties)
  8424. {
  8425. BfPropertyDef* propDef = setProp.mPropertyRef;
  8426. if (propDef->mName == "AllowMultiple")
  8427. {
  8428. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8429. if (constant != NULL)
  8430. attributeData->mAllowMultiple = constant->mBool;
  8431. }
  8432. else if (propDef->mName == "Inherited")
  8433. {
  8434. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8435. if (constant != NULL)
  8436. attributeData->mInherited = constant->mBool;
  8437. }
  8438. else if (propDef->mName == "ValidOn")
  8439. {
  8440. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8441. if (constant != NULL)
  8442. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8443. }
  8444. }
  8445. hasCustomAttribute = true;
  8446. }
  8447. }
  8448. }
  8449. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  8450. {
  8451. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  8452. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  8453. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  8454. }
  8455. mCurTypeInstance->mAttributeData = attributeData;
  8456. }
  8457. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  8458. {
  8459. auto constant = constHolder->GetConstant(irValue);
  8460. if (constant == NULL)
  8461. return false;
  8462. if (!BfIRConstHolder::IsInt(constant->mTypeCode))
  8463. return false;
  8464. int stringId = constant->mInt32;
  8465. BfStringPoolEntry* entry = NULL;
  8466. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  8467. {
  8468. str = entry->mString;
  8469. }
  8470. else
  8471. {
  8472. BF_DBG_FATAL("Failed to find string by id");
  8473. }
  8474. return true;
  8475. }
  8476. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  8477. {
  8478. BfVariant variant;
  8479. variant.mTypeCode = BfTypeCode_None;
  8480. BfType* primType = NULL;
  8481. if (value.mType->IsPrimitiveType())
  8482. primType = (BfPrimitiveType*)value.mType;
  8483. else if (value.mType->IsTypedPrimitive())
  8484. primType = value.mType->GetUnderlyingType();
  8485. if (primType)
  8486. {
  8487. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  8488. if (constant != NULL)
  8489. {
  8490. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  8491. {
  8492. variant.mTypeCode = BfTypeCode_Let;
  8493. return variant;
  8494. }
  8495. switch (constant->mTypeCode)
  8496. {
  8497. case BfTypeCode_Int8:
  8498. case BfTypeCode_UInt8:
  8499. case BfTypeCode_Int16:
  8500. case BfTypeCode_UInt16:
  8501. case BfTypeCode_Int32:
  8502. case BfTypeCode_UInt32:
  8503. case BfTypeCode_Int64:
  8504. case BfTypeCode_UInt64:
  8505. case BfTypeCode_IntPtr:
  8506. case BfTypeCode_UIntPtr:
  8507. case BfTypeCode_IntUnknown:
  8508. case BfTypeCode_UIntUnknown:
  8509. case BfTypeCode_Single:
  8510. case BfTypeCode_Double:
  8511. case BfTypeCode_Char8:
  8512. case BfTypeCode_Char16:
  8513. case BfTypeCode_Char32:
  8514. variant.mTypeCode = constant->mTypeCode;
  8515. variant.mInt64 = constant->mInt64;
  8516. break;
  8517. default:
  8518. if (refNode != NULL)
  8519. Fail("Invalid const expression type", refNode);
  8520. break;
  8521. }
  8522. }
  8523. }
  8524. return variant;
  8525. }
  8526. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  8527. {
  8528. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  8529. {
  8530. auto elementType = typedValue.mType->GetUnderlyingType();
  8531. if (typedValue.IsAddr())
  8532. {
  8533. if (elementType->IsValuelessType())
  8534. {
  8535. BF_ASSERT(!typedValue.mValue);
  8536. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8537. }
  8538. else
  8539. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  8540. }
  8541. else
  8542. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8543. if (typedValue.mType->IsValuelessType())
  8544. {
  8545. BF_ASSERT(typedValue.mValue.IsFake());
  8546. }
  8547. }
  8548. return typedValue;
  8549. }
  8550. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  8551. {
  8552. if (!typedValue.IsAddr())
  8553. return typedValue;
  8554. if (typedValue.mType->IsValuelessType())
  8555. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  8556. BfIRValue loadedVal = typedValue.mValue;
  8557. if (loadedVal)
  8558. {
  8559. /*if (isVolatile)
  8560. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  8561. PopulateType(typedValue.mType, BfPopulateType_Data);
  8562. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  8563. }
  8564. return BfTypedValue(loadedVal, typedValue.mType, false);
  8565. }
  8566. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  8567. {
  8568. if (typedValue.IsSplat())
  8569. return AggregateSplat(typedValue);
  8570. if (typedValue.IsAddr())
  8571. return LoadValue(typedValue);
  8572. return typedValue;
  8573. }
  8574. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  8575. {
  8576. if (!typedValue.IsSplat())
  8577. return typedValue;
  8578. if (typedValue.mType->IsValuelessType())
  8579. return typedValue;
  8580. int elementIdx = 0;
  8581. auto _ExtractValue = [&](BfType* checkType)
  8582. {
  8583. if (valueArrPtr != NULL)
  8584. return valueArrPtr[elementIdx++];
  8585. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  8586. };
  8587. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8588. {
  8589. if (checkType->IsStruct())
  8590. {
  8591. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8592. auto checkTypeInstance = checkType->ToTypeInstance();
  8593. if (checkTypeInstance->mBaseType != NULL)
  8594. {
  8595. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  8596. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  8597. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  8598. }
  8599. if (checkTypeInstance->mIsUnion)
  8600. {
  8601. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8602. if (!unionInnerType->IsValuelessType())
  8603. {
  8604. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  8605. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  8606. }
  8607. if (checkTypeInstance->IsEnum())
  8608. {
  8609. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8610. BfIRValue fieldValue = checkTypeLambda(dscrType);
  8611. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  8612. }
  8613. }
  8614. else
  8615. {
  8616. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8617. {
  8618. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8619. if (fieldInstance->mDataIdx >= 0)
  8620. {
  8621. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  8622. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  8623. }
  8624. }
  8625. }
  8626. return curValue;
  8627. }
  8628. else if (checkType->IsMethodRef())
  8629. {
  8630. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8631. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8632. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8633. {
  8634. BfIRValue fieldValue;
  8635. auto checkType = methodRefType->GetCaptureType(dataIdx);
  8636. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8637. {
  8638. fieldValue = checkTypeLambda(checkType);
  8639. }
  8640. else
  8641. {
  8642. fieldValue = _ExtractValue(checkType);
  8643. }
  8644. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  8645. }
  8646. return curValue;
  8647. }
  8648. else if (!checkType->IsValuelessType())
  8649. {
  8650. return _ExtractValue(checkType);
  8651. }
  8652. return BfIRValue();
  8653. };
  8654. BfIRValue value = checkTypeLambda(typedValue.mType);
  8655. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  8656. }
  8657. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  8658. {
  8659. if (!typedValue.IsSplat())
  8660. return;
  8661. if (typedValue.mType->IsValuelessType())
  8662. return;
  8663. /*static int sCallIdx = 0;
  8664. if (!mCompiler->mIsResolveOnly)
  8665. sCallIdx++;
  8666. int callIdx = sCallIdx;*/
  8667. int elementIdx = 0;
  8668. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  8669. {
  8670. if (checkType->IsStruct())
  8671. {
  8672. auto checkTypeInstance = checkType->ToTypeInstance();
  8673. if (checkTypeInstance->mBaseType != NULL)
  8674. {
  8675. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  8676. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  8677. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  8678. }
  8679. if (checkTypeInstance->mIsUnion)
  8680. {
  8681. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8682. if (!unionInnerType->IsValuelessType())
  8683. {
  8684. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  8685. checkTypeLambda(unionInnerType, fieldAddrVal);
  8686. }
  8687. if (checkTypeInstance->IsEnum())
  8688. {
  8689. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8690. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  8691. checkTypeLambda(dscrType, fieldAddrVal);
  8692. }
  8693. }
  8694. else
  8695. {
  8696. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8697. {
  8698. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8699. if (fieldInstance->mDataIdx >= 0)
  8700. {
  8701. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  8702. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  8703. }
  8704. }
  8705. }
  8706. }
  8707. else if (checkType->IsMethodRef())
  8708. {
  8709. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8710. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8711. {
  8712. auto dataType = methodRefType->GetCaptureType(dataIdx);
  8713. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  8714. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8715. {
  8716. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  8717. }
  8718. else
  8719. {
  8720. // static int sItrCount = 0;
  8721. // sItrCount++;
  8722. // int curItr = sItrCount;
  8723. // if (curItr == 1)
  8724. // {
  8725. // NOP;
  8726. // }
  8727. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  8728. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  8729. }
  8730. }
  8731. }
  8732. else if (!checkType->IsValuelessType())
  8733. {
  8734. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  8735. mBfIRBuilder->CreateStore(val, curAddrVal);
  8736. }
  8737. };
  8738. checkTypeLambda(typedValue.mType, addrVal);
  8739. }
  8740. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  8741. {
  8742. bool wasReadOnly = typedVal.IsReadOnly();
  8743. if ((typedVal.mType->IsValueType()) &&
  8744. (!typedVal.mType->IsValuelessType()))
  8745. {
  8746. wasReadOnly = true; // Any non-addr is implicitly read-only
  8747. //static int gCallIdx = 0;
  8748. if (typedVal.IsAddr())
  8749. return typedVal;
  8750. BfType* type = typedVal.mType;
  8751. PopulateType(type);
  8752. auto tempVar = CreateAlloca(type);
  8753. if (typedVal.IsSplat())
  8754. AggregateSplatIntoAddr(typedVal, tempVar);
  8755. else
  8756. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  8757. return BfTypedValue(tempVar, type,
  8758. typedVal.IsThis() ?
  8759. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  8760. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  8761. }
  8762. return LoadValue(typedVal);
  8763. }
  8764. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  8765. {
  8766. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  8767. typedValue.mKind = BfTypedValueKind_Addr;
  8768. return typedValue;
  8769. }
  8770. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  8771. {
  8772. BfIRValue val;
  8773. if (typedValue.mValue.IsArg())
  8774. {
  8775. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  8776. if (isAddr != NULL)
  8777. {
  8778. if (wantType != NULL)
  8779. *isAddr = wantType->IsComposite();
  8780. else
  8781. *isAddr = false;
  8782. }
  8783. else if (wantType->IsComposite())
  8784. val = mBfIRBuilder->CreateLoad(val);
  8785. }
  8786. if (!val)
  8787. {
  8788. auto checkMethodState = mCurMethodState;
  8789. while (checkMethodState != NULL)
  8790. {
  8791. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  8792. {
  8793. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  8794. if (decompAddr == typedValue.mValue)
  8795. {
  8796. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  8797. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  8798. {
  8799. // This is really backing for a POINTER to a composite inside a methodRef
  8800. val = mBfIRBuilder->CreateLoad(val);
  8801. }
  8802. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  8803. {
  8804. *isAddr = true;
  8805. return val;
  8806. }
  8807. else
  8808. {
  8809. val = mBfIRBuilder->CreateLoad(val);
  8810. break;
  8811. }
  8812. }
  8813. }
  8814. if (val)
  8815. break;
  8816. checkMethodState = checkMethodState->mPrevMethodState;
  8817. }
  8818. }
  8819. if (val)
  8820. {
  8821. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  8822. {
  8823. BF_ASSERT(wantType != NULL);
  8824. if (wantType != NULL)
  8825. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  8826. }
  8827. return val;
  8828. }
  8829. BF_FATAL("Splat not found");
  8830. return BfIRValue();
  8831. }
  8832. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  8833. {
  8834. int useFieldIdx = fieldIdx;
  8835. BfType* fieldType = NULL;
  8836. if (fieldInstance != NULL)
  8837. {
  8838. fieldType = fieldInstance->mResolvedType;
  8839. if (typedValue.mType->IsUnion())
  8840. {
  8841. if (fieldIdx == 1)
  8842. {
  8843. if (typedValue.IsSplat())
  8844. {
  8845. BfTypedValue innerVal = typedValue;
  8846. innerVal.mType = fieldType;
  8847. return innerVal;
  8848. }
  8849. }
  8850. }
  8851. }
  8852. else
  8853. {
  8854. if (typedValue.mType->IsPayloadEnum())
  8855. {
  8856. auto typeInst = typedValue.mType->ToTypeInstance();
  8857. if (fieldIdx == 1)
  8858. fieldType = typeInst->GetUnionInnerType();
  8859. else if (fieldIdx == 2)
  8860. {
  8861. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  8862. }
  8863. }
  8864. else if (typedValue.mType->IsUnion())
  8865. {
  8866. if (fieldIdx == 1)
  8867. {
  8868. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  8869. if (typedValue.IsSplat())
  8870. {
  8871. BfTypedValue innerVal = typedValue;
  8872. innerVal.mType = fieldType;
  8873. return innerVal;
  8874. }
  8875. }
  8876. }
  8877. }
  8878. BF_ASSERT(typedValue.mType->IsStruct());
  8879. if (typedValue.IsSplat())
  8880. {
  8881. if (typedValue.mType->IsPayloadEnum())
  8882. {
  8883. if (fieldIdx == 1)
  8884. {
  8885. // Payload
  8886. auto typeInst = typedValue.mType->ToTypeInstance();
  8887. auto unionInnerType = typeInst->GetUnionInnerType();
  8888. bool isAddr = false;
  8889. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  8890. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  8891. }
  8892. if (fieldIdx == 2)
  8893. {
  8894. // Discriminator
  8895. auto typeInst = typedValue.mType->ToTypeInstance();
  8896. auto unionInnerType = typeInst->GetUnionInnerType();
  8897. auto dscrType = typeInst->GetDiscriminatorType();
  8898. int argIdx = typedValue.mValue.mId;
  8899. int componentIdx = 0;
  8900. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  8901. bool isAddr;
  8902. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  8903. return BfTypedValue(irVal, dscrType, isAddr);
  8904. }
  8905. }
  8906. int componentIdx = 0;
  8907. BfTypedValue retVal;
  8908. BfFieldInstance* wantFieldInstance = fieldInstance;
  8909. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8910. {
  8911. if (checkType->IsStruct())
  8912. {
  8913. auto checkTypeInstance = checkType->ToTypeInstance();
  8914. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  8915. {
  8916. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  8917. fieldType = checkTypeInstance->GetUnionInnerType();
  8918. checkTypeLambda(fieldType);
  8919. if (checkType->IsEnum())
  8920. {
  8921. // Past discriminator...
  8922. componentIdx++;
  8923. }
  8924. return;
  8925. }
  8926. if (checkTypeInstance->mBaseType != NULL)
  8927. checkTypeLambda(checkTypeInstance->mBaseType);
  8928. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8929. {
  8930. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8931. if (fieldInstance == wantFieldInstance)
  8932. {
  8933. bool isAddr = false;
  8934. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  8935. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  8936. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  8937. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  8938. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  8939. {
  8940. retVal = LoadValue(retVal);
  8941. }
  8942. break;
  8943. }
  8944. if (fieldInstance->mDataIdx >= 0)
  8945. checkTypeLambda(fieldInstance->GetResolvedType());
  8946. }
  8947. }
  8948. else if (!checkType->IsValuelessType())
  8949. {
  8950. componentIdx++;
  8951. //argIdx++;
  8952. }
  8953. };
  8954. checkTypeLambda(typedValue.mType);
  8955. BF_ASSERT(retVal);
  8956. return retVal;
  8957. }
  8958. if (typedValue.IsAddr())
  8959. {
  8960. BF_ASSERT(fieldType != NULL);
  8961. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  8962. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  8963. }
  8964. else
  8965. {
  8966. BF_ASSERT(fieldType != NULL);
  8967. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  8968. }
  8969. }
  8970. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  8971. {
  8972. if (typedValue.IsAddr())
  8973. {
  8974. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  8975. return mBfIRBuilder->CreateLoad(addrVal);
  8976. }
  8977. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  8978. }
  8979. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  8980. {
  8981. if (elementType->IsSizeAligned())
  8982. {
  8983. if (isElementIndex)
  8984. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  8985. else
  8986. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  8987. }
  8988. auto ptrType = CreatePointerType(elementType);
  8989. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  8990. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  8991. auto intVal = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  8992. auto newIntVal = mBfIRBuilder->CreateAdd(intVal, ofsScaledVal);
  8993. return mBfIRBuilder->CreateIntToPtr(newIntVal, mBfIRBuilder->MapType(ptrType));
  8994. }
  8995. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  8996. {
  8997. if (elementType->IsSizeAligned())
  8998. {
  8999. if (isElementIndex)
  9000. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  9001. else
  9002. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  9003. }
  9004. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  9005. }
  9006. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  9007. {
  9008. if (modifyType == NULL)
  9009. modifyType = "modify";
  9010. if (typedValue.mType->IsVar())
  9011. return true;
  9012. if (typedValue.IsReadOnly())
  9013. {
  9014. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  9015. return false;
  9016. }
  9017. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  9018. {
  9019. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  9020. return false;
  9021. }
  9022. if (typedValue.mKind == BfTypedValueKind_TempAddr)
  9023. {
  9024. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  9025. return false;
  9026. }
  9027. return true;
  9028. }
  9029. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  9030. {
  9031. if (methodA->mMethodDef->mIsLocalMethod)
  9032. {
  9033. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  9034. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  9035. if (sepPosA != sepPosB)
  9036. return false;
  9037. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  9038. return false;
  9039. }
  9040. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  9041. return false;
  9042. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  9043. return false;
  9044. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  9045. {
  9046. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  9047. return false;
  9048. }
  9049. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  9050. {
  9051. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  9052. return false;
  9053. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  9054. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  9055. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  9056. return false;
  9057. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  9058. return false;
  9059. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  9060. {
  9061. if (methodA->mReturnType != methodB->mReturnType)
  9062. return false;
  9063. }
  9064. }
  9065. int implicitParamCountA = methodA->GetImplicitParamCount();
  9066. int implicitParamCountB = methodB->GetImplicitParamCount();
  9067. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  9068. return false;
  9069. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  9070. return false;
  9071. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  9072. {
  9073. if ((methodA->GetParamType(paramIdx + implicitParamCountA) != methodB->GetParamType(paramIdx + implicitParamCountB)) ||
  9074. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  9075. return false;
  9076. }
  9077. // Compare generic params. Generic params are part of the method signature here
  9078. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  9079. return false;
  9080. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  9081. {
  9082. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  9083. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  9084. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  9085. return false;
  9086. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  9087. return false;
  9088. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  9089. return false;
  9090. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  9091. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  9092. return false;
  9093. }
  9094. return true;
  9095. }
  9096. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  9097. {
  9098. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  9099. return false;
  9100. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  9101. return false;
  9102. if (iMethodInst->mMethodDef->mIsOperator)
  9103. {
  9104. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  9105. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  9106. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  9107. return false;
  9108. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  9109. return false;
  9110. }
  9111. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  9112. return false;
  9113. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  9114. {
  9115. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  9116. return false;
  9117. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  9118. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  9119. if (iParamType->IsSelf())
  9120. {
  9121. if (methodParamType != methodInstance->GetOwner())
  9122. return false;
  9123. }
  9124. else if (!iParamType->IsGenericParam())
  9125. {
  9126. if (methodParamType != iParamType)
  9127. return false;
  9128. }
  9129. else
  9130. {
  9131. if (!methodParamType->IsGenericParam())
  9132. return false;
  9133. auto genericParamType = (BfGenericParamType*)methodParamType;
  9134. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  9135. return false;
  9136. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  9137. bool hadInterface = false;
  9138. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  9139. if (interfaceConstraint == iParamType)
  9140. hadInterface = true;
  9141. if (!hadInterface)
  9142. return false;
  9143. }
  9144. }
  9145. return true;
  9146. }
  9147. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  9148. {
  9149. BfMethodInstance* methodInstance = methodRef;
  9150. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  9151. {
  9152. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  9153. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  9154. {
  9155. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  9156. BfMethodRef methodRef = methodInstance;
  9157. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  9158. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  9159. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  9160. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  9161. (mIsReified))
  9162. {
  9163. specializedMethodRefInfo->mHasReifiedRef = true;
  9164. }
  9165. }
  9166. }
  9167. }
  9168. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9169. {
  9170. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  9171. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9172. if (mBfIRBuilder == NULL)
  9173. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9174. if (methodInstance->GetOwner()->IsFunction())
  9175. {
  9176. // No actual ref needed- not an actual generated function
  9177. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9178. }
  9179. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  9180. if (!isGenFunction)
  9181. AddMethodReference(methodInstance, flags);
  9182. if (mBfIRBuilder->mIgnoreWrites)
  9183. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  9184. if (mCompiler->IsSkippingExtraResolveChecks())
  9185. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9186. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  9187. {
  9188. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9189. }
  9190. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9191. BfMethodRef methodRef = methodInstance;
  9192. if (isInlined)
  9193. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  9194. else
  9195. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  9196. if (!isGenFunction)
  9197. {
  9198. BfIRValue* irFuncPtr = NULL;
  9199. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  9200. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  9201. }
  9202. if (mAwaitingInitFinish)
  9203. FinishInit();
  9204. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  9205. if (!isGenFunction)
  9206. mFuncReferences[methodRef] = func;
  9207. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  9208. if ((isInlined) && (!mIsScratchModule))
  9209. {
  9210. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  9211. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  9212. // type instance
  9213. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  9214. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  9215. for (auto ownedTypeInst : mOwnedTypeInstances)
  9216. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  9217. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  9218. {
  9219. mIncompleteMethodCount++;
  9220. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9221. inlineMethodRequest->mType = methodInstance->GetOwner();
  9222. inlineMethodRequest->mFromModule = this;
  9223. inlineMethodRequest->mFunc = func;
  9224. inlineMethodRequest->mFromModuleRevision = mRevision;
  9225. inlineMethodRequest->mMethodInstance = methodInstance;
  9226. BF_ASSERT(mIsModuleMutable);
  9227. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9228. }
  9229. }
  9230. return BfModuleMethodInstance(methodInstance, func);
  9231. }
  9232. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  9233. {
  9234. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  9235. if (mBfIRBuilder == NULL)
  9236. {
  9237. // To allow for custom attribute data
  9238. PrepareForIRWriting(typeInst);
  9239. }
  9240. BfModule* declareModule = this;
  9241. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  9242. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  9243. declareModule = declareModule->mParentModule;
  9244. // Check for attributes
  9245. if (typeInst == mContext->mBfObjectType)
  9246. {
  9247. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  9248. if (methodDecl != NULL)
  9249. {
  9250. auto attributesDirective = methodDecl->mAttributes;
  9251. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9252. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9253. {
  9254. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9255. }
  9256. }
  9257. }
  9258. else
  9259. {
  9260. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  9261. GetMethodCustomAttributes(methodInstance);
  9262. }
  9263. BF_ASSERT(mModuleOptions == NULL);
  9264. if (methodInstance->GetCustomAttributes() != NULL)
  9265. {
  9266. auto project = typeInst->mTypeDef->mProject;
  9267. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  9268. BfModuleOptions wantOptions = moduleOptions;
  9269. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  9270. if (typeOptions != NULL)
  9271. {
  9272. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  9273. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  9274. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  9275. }
  9276. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  9277. {
  9278. StringT<128> attrName;
  9279. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  9280. {
  9281. attrName.Clear();
  9282. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  9283. Array<int>* arrPtr;
  9284. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  9285. {
  9286. for (auto optionsIdx : *arrPtr)
  9287. {
  9288. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  9289. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  9290. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  9291. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  9292. }
  9293. }
  9294. }
  9295. }
  9296. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  9297. {
  9298. auto lastCheckModule = this;
  9299. auto checkModule = this->mNextAltModule;
  9300. while (checkModule != NULL)
  9301. {
  9302. if (*checkModule->mModuleOptions == wantOptions)
  9303. {
  9304. declareModule = checkModule;
  9305. break;
  9306. }
  9307. lastCheckModule = checkModule;
  9308. checkModule = checkModule->mNextAltModule;
  9309. }
  9310. // Not found?
  9311. if (declareModule == this)
  9312. {
  9313. String specModuleName = mModuleName + "@@";
  9314. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  9315. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  9316. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  9317. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  9318. declareModule = new BfModule(mContext, specModuleName);
  9319. declareModule->mProject = project;
  9320. declareModule->mModuleOptions = new BfModuleOptions();
  9321. *declareModule->mModuleOptions = wantOptions;
  9322. declareModule->mParentModule = lastCheckModule;
  9323. declareModule->Init();
  9324. lastCheckModule->mNextAltModule = declareModule;
  9325. }
  9326. }
  9327. }
  9328. declareModule->PrepareForIRWriting(typeInst);
  9329. return declareModule;
  9330. }
  9331. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  9332. {
  9333. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  9334. {
  9335. // Don't bother inlining for resolve-only
  9336. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9337. }
  9338. bool processNow = false;
  9339. bool keepInCurrentModule = false;
  9340. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  9341. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  9342. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  9343. {
  9344. return BfModuleMethodInstance();
  9345. }
  9346. if (methodDef->mIsLocalMethod)
  9347. {
  9348. auto rootMethodState = mCurMethodState->GetRootMethodState();
  9349. BfLocalMethod* localMethod;
  9350. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  9351. {
  9352. // Handle the def in the correct method state
  9353. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  9354. }
  9355. BF_FATAL("Cannot find local method");
  9356. return BfModuleMethodInstance();
  9357. }
  9358. #ifdef _DEBUG
  9359. for (auto arg : methodGenericArguments)
  9360. BF_ASSERT(!arg->IsVar());
  9361. #endif
  9362. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  9363. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  9364. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  9365. // a FinishInit
  9366. if ((typeInst->IsIncomplete()) &&
  9367. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  9368. {
  9369. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  9370. // for resolve-only because we don't differentiate between reified/unreified there
  9371. PopulateType(typeInst, BfPopulateType_Full);
  9372. }
  9373. bool tryModuleMethodLookup = false;
  9374. BfModuleMethodInstance moduleMethodInst;
  9375. BfModule* instModule = typeInst->mModule;
  9376. if (keepInCurrentModule)
  9377. {
  9378. // Stay here
  9379. instModule = this;
  9380. }
  9381. if (this == mContext->mUnreifiedModule)
  9382. {
  9383. // Stay in this 'resolve only' module here
  9384. }
  9385. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  9386. {
  9387. BF_ASSERT(this == mContext->mUnreifiedModule);
  9388. }
  9389. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  9390. {
  9391. BF_ASSERT(instModule == mParentModule);
  9392. }
  9393. else if (instModule != this)
  9394. {
  9395. if ((!mIsReified) && (instModule->mIsReified))
  9396. {
  9397. BF_ASSERT(!mCompiler->mIsResolveOnly);
  9398. // A resolve-only module is specializing a method from a type in a reified module,
  9399. // we need to take care that this doesn't cause anything new to become reified
  9400. return mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  9401. }
  9402. else
  9403. {
  9404. if ((mIsReified) && (!instModule->mIsReified))
  9405. {
  9406. if (!instModule->mReifyQueued)
  9407. {
  9408. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  9409. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  9410. mContext->mReifyModuleWorkList.Add(instModule);
  9411. instModule->mReifyQueued = true;
  9412. }
  9413. // This ensures that the method will actually be created when it gets reified
  9414. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  9415. specializationRequest->mFromModule = typeInst->mModule;
  9416. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  9417. specializationRequest->mMethodDef = methodDef;
  9418. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  9419. specializationRequest->mType = typeInst;
  9420. }
  9421. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9422. // Not extern
  9423. // Create the instance in the proper module and then create a reference in this one
  9424. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  9425. tryModuleMethodLookup = true;
  9426. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  9427. {
  9428. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  9429. }
  9430. }
  9431. }
  9432. if (tryModuleMethodLookup)
  9433. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  9434. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  9435. {
  9436. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  9437. if (moduleMethodInstance)
  9438. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  9439. return moduleMethodInst;
  9440. }
  9441. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  9442. bool hadConcreteInterfaceGenericArgument = false;
  9443. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  9444. isReified = false;
  9445. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  9446. {
  9447. isReified = false;
  9448. }
  9449. BfTypeVector sanitizedMethodGenericArguments;
  9450. Array<BfProject*> projectList;
  9451. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  9452. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  9453. isUnspecializedPass = false;
  9454. // 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
  9455. bool isExternalExtensionMethod = false;
  9456. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  9457. {
  9458. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  9459. {
  9460. auto specProject = methodDef->mDeclaringType->mProject;
  9461. isExternalExtensionMethod = true;
  9462. if (typeInst->IsGenericTypeInstance())
  9463. {
  9464. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9465. if (genericTypeInst->mProjectsReferenced.empty())
  9466. genericTypeInst->GenerateProjectsReferenced();
  9467. if (genericTypeInst->mProjectsReferenced.Contains(specProject))
  9468. {
  9469. // This is a generic type where a generic param is already confined to the project in question
  9470. isExternalExtensionMethod = false;
  9471. }
  9472. }
  9473. if (isExternalExtensionMethod)
  9474. {
  9475. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  9476. projectList.push_back(methodDef->mDeclaringType->mProject);
  9477. }
  9478. }
  9479. }
  9480. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  9481. {
  9482. int typeProjectsCounts = 0;
  9483. if (typeInst->IsGenericTypeInstance())
  9484. {
  9485. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9486. if (genericTypeInst->mProjectsReferenced.empty())
  9487. genericTypeInst->GenerateProjectsReferenced();
  9488. typeProjectsCounts = (int)genericTypeInst->mProjectsReferenced.size();
  9489. projectList.Insert(0, &genericTypeInst->mProjectsReferenced[0], genericTypeInst->mProjectsReferenced.size());
  9490. }
  9491. else
  9492. {
  9493. typeProjectsCounts = 1;
  9494. projectList.Insert(0, typeInst->mTypeDef->mProject);
  9495. }
  9496. isUnspecializedPass = true;
  9497. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  9498. {
  9499. auto genericArgType = methodGenericArguments[genericArgIdx];
  9500. //BF_ASSERT(!genericArgType->IsRef());
  9501. if (genericArgType->IsConcreteInterfaceType())
  9502. {
  9503. hadConcreteInterfaceGenericArgument = true;
  9504. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  9505. genericArgType = concreteInterfaceType->mInterface;
  9506. }
  9507. if (genericArgType->IsGenericParam())
  9508. {
  9509. auto genericParam = (BfGenericParamType*) genericArgType;
  9510. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  9511. isUnspecializedPass = false;
  9512. }
  9513. else
  9514. {
  9515. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  9516. isUnspecializedPass = false;
  9517. }
  9518. sanitizedMethodGenericArguments.push_back(genericArgType);
  9519. }
  9520. if ((int)projectList.size() > typeProjectsCounts)
  9521. {
  9522. // Just leave the new items
  9523. projectList.RemoveRange(0, typeProjectsCounts);
  9524. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  9525. {
  9526. return lhs->mName < rhs->mName;
  9527. });
  9528. }
  9529. else
  9530. {
  9531. projectList.Clear();
  9532. }
  9533. }
  9534. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  9535. BfMethodInstanceGroup* methodInstGroup = NULL;
  9536. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9537. {
  9538. BF_ASSERT(!typeInst->IsInterface());
  9539. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  9540. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  9541. {
  9542. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  9543. // if (checkGroup.mDefault == NULL)
  9544. // {
  9545. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  9546. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  9547. // methodInstGroup = &checkGroup;
  9548. // break;
  9549. // }
  9550. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  9551. {
  9552. methodInstGroup = &checkGroup;
  9553. break;
  9554. }
  9555. }
  9556. if (methodInstGroup == NULL)
  9557. {
  9558. // Allocate a new entry
  9559. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  9560. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  9561. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  9562. methodInstGroup->mOwner = typeInst;
  9563. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9564. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9565. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  9566. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9567. else
  9568. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9569. }
  9570. }
  9571. else
  9572. {
  9573. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  9574. }
  9575. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9576. {
  9577. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  9578. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9579. }
  9580. BfIRFunction prevIRFunc;
  9581. bool doingRedeclare = false;
  9582. BfMethodInstance* methodInstance = NULL;
  9583. auto _SetReified = [&]()
  9584. {
  9585. methodInstance->mIsReified = true;
  9586. };
  9587. if (lookupMethodGenericArguments.size() == 0)
  9588. {
  9589. methodInstance = methodInstGroup->mDefault;
  9590. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  9591. {
  9592. MarkDerivedDirty(typeInst);
  9593. if (mIsScratchModule)
  9594. {
  9595. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  9596. _SetReified();
  9597. CheckHotMethod(methodInstance, "");
  9598. }
  9599. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  9600. {
  9601. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  9602. // the specializations to handle that for us
  9603. return BfModuleMethodInstance(methodInstance);
  9604. }
  9605. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  9606. {
  9607. if (methodDef->mIsAbstract)
  9608. {
  9609. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9610. _SetReified();
  9611. }
  9612. else
  9613. {
  9614. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9615. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9616. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  9617. doingRedeclare = true;
  9618. mOnDemandMethodCount++;
  9619. }
  9620. }
  9621. else
  9622. {
  9623. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  9624. // We haven't processed it yet
  9625. _SetReified();
  9626. CheckHotMethod(methodInstance, "");
  9627. if (methodInstance->mDeclModule == this)
  9628. {
  9629. if (methodInstance->mMethodProcessRequest != NULL)
  9630. {
  9631. // Disconnect method process request
  9632. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  9633. }
  9634. }
  9635. else
  9636. {
  9637. if (methodInstance->mMethodProcessRequest != NULL)
  9638. {
  9639. // Disconnect method process request
  9640. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == mContext->mUnreifiedModule);
  9641. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  9642. methodInstance->mMethodProcessRequest = NULL;
  9643. }
  9644. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  9645. {
  9646. // Add new request in proper module
  9647. methodInstance->mDeclModule = this;
  9648. }
  9649. else
  9650. {
  9651. if (methodInstance->mDeclModule == NULL)
  9652. {
  9653. //
  9654. }
  9655. else if (methodInstance->mDeclModule != this)
  9656. {
  9657. // Is from specialized module?
  9658. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  9659. }
  9660. }
  9661. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9662. {
  9663. methodInstance->mIRFunction = BfIRFunction();
  9664. if (!mIsModuleMutable)
  9665. StartExtension();
  9666. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  9667. {
  9668. StringT<128> mangledName;
  9669. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  9670. bool isIntrinsic = false;
  9671. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  9672. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  9673. }
  9674. }
  9675. AddMethodToWorkList(methodInstance);
  9676. }
  9677. }
  9678. }
  9679. }
  9680. else
  9681. {
  9682. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  9683. if (methodInstGroup->mMethodSpecializationMap == NULL)
  9684. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  9685. BfMethodInstance** methodInstancePtr = NULL;
  9686. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  9687. {
  9688. methodInstance = *methodInstancePtr;
  9689. if ((isReified) && (!methodInstance->mIsReified))
  9690. {
  9691. MarkDerivedDirty(typeInst);
  9692. if (methodInstance->mHasBeenProcessed)
  9693. {
  9694. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  9695. delete methodInstance;
  9696. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9697. methodInstance = NULL;
  9698. }
  9699. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9700. {
  9701. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  9702. delete methodInstance;
  9703. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9704. methodInstance = NULL;
  9705. }
  9706. else
  9707. {
  9708. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  9709. // We haven't processed it yet
  9710. _SetReified();
  9711. CheckHotMethod(methodInstance, "");
  9712. }
  9713. }
  9714. }
  9715. }
  9716. if ((methodInstance != NULL) && (!doingRedeclare))
  9717. {
  9718. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  9719. {
  9720. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  9721. BF_ASSERT(!methodInstance->mIsReified);*/
  9722. if (methodInstance->mIsReified != isReified)
  9723. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  9724. if ((!isReified) &&
  9725. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  9726. {
  9727. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  9728. methodInstance->mIRFunction = BfIRFunction();
  9729. }
  9730. methodInstance->mIsReified = isReified;
  9731. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  9732. {
  9733. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  9734. }
  9735. if (!methodInstance->mMethodDef->mIsAbstract)
  9736. {
  9737. AddMethodToWorkList(methodInstance);
  9738. }
  9739. else
  9740. {
  9741. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  9742. }
  9743. }
  9744. if (mExtensionCount > 0)
  9745. {
  9746. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  9747. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  9748. {
  9749. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  9750. if (mAwaitingInitFinish)
  9751. FinishInit();
  9752. // We need to refer to a function that was defined in a prior module
  9753. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9754. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  9755. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  9756. methodInstance->mDeclModule = this;
  9757. // Add this inlined def to ourselves
  9758. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized))
  9759. {
  9760. mIncompleteMethodCount++;
  9761. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9762. inlineMethodRequest->mType = typeInst;
  9763. inlineMethodRequest->mFromModule = this;
  9764. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  9765. inlineMethodRequest->mFromModuleRevision = mRevision;
  9766. inlineMethodRequest->mMethodInstance = methodInstance;
  9767. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9768. BF_ASSERT(mIsModuleMutable);
  9769. }
  9770. }
  9771. }
  9772. if (mCompiler->IsSkippingExtraResolveChecks())
  9773. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9774. else
  9775. {
  9776. if (methodInstance->mDeclModule != this)
  9777. return ReferenceExternalMethodInstance(methodInstance, flags);
  9778. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  9779. {
  9780. auto importKind = methodInstance->GetImportCallKind();
  9781. if (importKind != BfImportCallKind_None)
  9782. {
  9783. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  9784. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  9785. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  9786. }
  9787. }
  9788. return BfModuleMethodInstance(methodInstance);
  9789. }
  9790. }
  9791. if (!doingRedeclare)
  9792. {
  9793. BfModule* specModule = NULL;
  9794. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  9795. {
  9796. specModule = GetSpecializedMethodModule(projectList);
  9797. }
  9798. if ((specModule != NULL) && (specModule != this))
  9799. {
  9800. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  9801. if (mAwaitingInitFinish)
  9802. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  9803. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  9804. }
  9805. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  9806. {
  9807. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  9808. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  9809. }
  9810. }
  9811. if (methodInstance == NULL)
  9812. {
  9813. if (lookupMethodGenericArguments.size() == 0)
  9814. {
  9815. BF_ASSERT(methodInstGroup->mDefault == NULL);
  9816. methodInstance = new BfMethodInstance();
  9817. methodInstGroup->mDefault = methodInstance;
  9818. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  9819. }
  9820. else
  9821. {
  9822. BfMethodInstance** methodInstancePtr = NULL;
  9823. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  9824. BF_ASSERT(added);
  9825. methodInstance = new BfMethodInstance();
  9826. *methodInstancePtr = methodInstance;
  9827. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  9828. }
  9829. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  9830. methodInstance->mIRFunction = prevIRFunc; // Take it over
  9831. }
  9832. /*// 24 bits for typeid, 20 for method id, 20 for specialization index
  9833. methodInstance->mMethodId = ((int64)typeInst->mTypeId) + ((int64)methodInstGroup->mMethodIdx << 24);
  9834. if (methodInstGroup->mMethodSpecializationMap != NULL)
  9835. methodInstance->mMethodId += ((int64)methodInstGroup->mMethodSpecializationMap->size() << 44);*/
  9836. methodInstance->mMethodDef = methodDef;
  9837. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  9838. methodInstance->mMethodInstanceGroup = methodInstGroup;
  9839. methodInstance->mIsReified = isReified;
  9840. SetupMethodIdHash(methodInstance);
  9841. if (hadConcreteInterfaceGenericArgument)
  9842. methodInstance->mIgnoreBody = true;
  9843. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9844. {
  9845. methodInstance->mIsForeignMethodDef = true;
  9846. BF_ASSERT(foreignType != NULL);
  9847. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  9848. }
  9849. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  9850. {
  9851. if (!lookupMethodGenericArguments.empty())
  9852. {
  9853. auto compareType = lookupMethodGenericArguments[0];
  9854. PopulateType(compareType, BfPopulateType_Data);
  9855. if (compareType->IsSplattable())
  9856. methodInstance->mAlwaysInline = true;
  9857. }
  9858. }
  9859. if (methodDef->mDeclaringType->mTypeDeclaration != typeInst->mTypeDef->mTypeDeclaration)
  9860. {
  9861. // With extensions we can have multiple definitions of the same method
  9862. //methodInstance->mMangleWithIdx = true;
  9863. }
  9864. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  9865. BF_ASSERT(typeInst == methodInstance->GetOwner());
  9866. auto methodDeclaration = methodDef->GetMethodDeclaration();
  9867. if (isUnspecializedPass)
  9868. {
  9869. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  9870. {
  9871. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  9872. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  9873. }
  9874. }
  9875. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  9876. {
  9877. if (!sanitizedMethodGenericArguments.IsEmpty())
  9878. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  9879. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  9880. {
  9881. Fail("Internal error");
  9882. BF_FATAL("Generic method argument counts mismatch");
  9883. return NULL;
  9884. }
  9885. for (auto genericArg : sanitizedMethodGenericArguments)
  9886. {
  9887. if (genericArg->IsPrimitiveType())
  9888. genericArg = GetWrappedStructType(genericArg);
  9889. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  9890. if (genericArg->IsMethodRef())
  9891. {
  9892. auto methodRefType = (BfMethodRefType*)genericArg;
  9893. //AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_);
  9894. }
  9895. }
  9896. }
  9897. // Generic constraints
  9898. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  9899. {
  9900. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  9901. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  9902. }
  9903. bool addToWorkList = !processNow;
  9904. if (mCompiler->GetAutoComplete() != NULL)
  9905. {
  9906. if (typeInst->IsSpecializedByAutoCompleteMethod())
  9907. addToWorkList = false;
  9908. }
  9909. BF_ASSERT(declareModule != NULL);
  9910. methodInstance->mDeclModule = declareModule;
  9911. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  9912. {
  9913. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  9914. // of a reified module -
  9915. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  9916. // BUT if we don't reify it then we have to remove the body after processing.
  9917. // 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
  9918. // the proper reified module.
  9919. declareModule = mContext->mUnreifiedModule;
  9920. }
  9921. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  9922. {
  9923. BF_ASSERT(!methodInstance->mIsReified);
  9924. declareModule = mContext->mUnreifiedModule;
  9925. }
  9926. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  9927. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  9928. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  9929. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  9930. if (processNow)
  9931. {
  9932. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  9933. ProcessMethod(methodInstance);
  9934. }
  9935. if (mCompiler->IsSkippingExtraResolveChecks())
  9936. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9937. return BfModuleMethodInstance(methodInstance);
  9938. }
  9939. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9940. {
  9941. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  9942. if (methodInstance->mIsForeignMethodDef)
  9943. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  9944. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  9945. }
  9946. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  9947. {
  9948. if (!methodInstance->mMethodDef->mIsLocalMethod)
  9949. return NULL;
  9950. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  9951. if (outerLocal == NULL)
  9952. return NULL;
  9953. BfTypeVector genericArgs;
  9954. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  9955. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  9956. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  9957. }
  9958. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  9959. {
  9960. HashContext hashCtx;
  9961. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  9962. {
  9963. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  9964. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  9965. if (methodInstance->GetNumGenericArguments() != 0)
  9966. {
  9967. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  9968. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  9969. hashCtx.Mixin(methodGenericArg->mTypeId);
  9970. }
  9971. };
  9972. _MixinMethodInstance(methodInstance);
  9973. if (methodInstance->mMethodDef->mIsLocalMethod)
  9974. {
  9975. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  9976. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  9977. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  9978. }
  9979. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  9980. }
  9981. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  9982. {
  9983. BfIRValue globalValue;
  9984. BfIRValue* globalValuePtr = NULL;
  9985. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  9986. {
  9987. globalValue = *globalValuePtr;
  9988. }
  9989. if (!globalValue)
  9990. {
  9991. // This is necessary to reify the interface type
  9992. PopulateType(ifaceType);
  9993. StringT<128> slotVarName;
  9994. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  9995. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  9996. BfIRValue value;
  9997. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  9998. {
  9999. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  10000. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  10001. int virtSlotIdx = ifaceType->mSlotNum + 1;
  10002. value = GetConstValue32(virtSlotIdx);*/
  10003. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  10004. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  10005. }
  10006. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  10007. mInterfaceSlotRefs[ifaceType] = globalValue;
  10008. }
  10009. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  10010. }
  10011. void BfModule::HadSlotCountDependency()
  10012. {
  10013. if (mCompiler->mIsResolveOnly)
  10014. return;
  10015. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  10016. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  10017. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  10018. }
  10019. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  10020. {
  10021. if (mIsScratchModule)
  10022. {
  10023. // Just fake it for the extern and unspecialized modules
  10024. auto ptrType = CreatePointerType(fieldInstance->GetResolvedType());
  10025. return BfTypedValue(GetDefaultValue(ptrType), fieldInstance->GetResolvedType(), true);
  10026. }
  10027. BfIRValue globalValue;
  10028. auto fieldDef = fieldInstance->GetFieldDef();
  10029. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  10030. {
  10031. if (fieldInstance->mConstIdx != -1)
  10032. {
  10033. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  10034. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  10035. }
  10036. else
  10037. {
  10038. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  10039. }
  10040. }
  10041. BfIRValue* globalValuePtr = NULL;
  10042. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  10043. {
  10044. globalValue = *globalValuePtr;
  10045. BF_ASSERT(globalValue);
  10046. }
  10047. else
  10048. {
  10049. StringT<128> staticVarName;
  10050. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  10051. auto typeType = fieldInstance->GetResolvedType();
  10052. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  10053. {
  10054. typeType = typeType->GetUnderlyingType();
  10055. }
  10056. PopulateType(typeType);
  10057. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  10058. {
  10059. globalValue = mBfIRBuilder->CreateGlobalVariable(
  10060. mBfIRBuilder->MapType(typeType),
  10061. false,
  10062. BfIRLinkageType_External,
  10063. BfIRValue(),
  10064. staticVarName,
  10065. IsThreadLocal(fieldInstance));
  10066. if (!mBfIRBuilder->mIgnoreWrites)
  10067. {
  10068. // Only store this if we actually did the creation
  10069. BF_ASSERT(globalValue);
  10070. mStaticFieldRefs[fieldInstance] = globalValue;
  10071. }
  10072. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  10073. }
  10074. }
  10075. auto type = fieldInstance->GetResolvedType();
  10076. if (type->IsValuelessType())
  10077. return BfTypedValue(globalValue, type);
  10078. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  10079. }
  10080. BfTypedValue BfModule::GetThis()
  10081. {
  10082. auto useMethodState = mCurMethodState;
  10083. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  10084. {
  10085. useMethodState = useMethodState->mPrevMethodState;
  10086. }
  10087. if (useMethodState != NULL)
  10088. {
  10089. // Fake a 'this' for var field resolution
  10090. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  10091. {
  10092. auto thisType = mCurTypeInstance;
  10093. if (thisType->IsValueType())
  10094. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  10095. else
  10096. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  10097. }
  10098. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  10099. {
  10100. return BfTypedValue();
  10101. }
  10102. }
  10103. else
  10104. {
  10105. //TODO: Do we allow useMethodState to be NULL anymore?
  10106. return BfTypedValue();
  10107. }
  10108. // if (useMethodState->HasNonStaticMixin())
  10109. // {
  10110. // auto checkMethodState = useMethodState;
  10111. // while (checkMethodState != NULL)
  10112. // {
  10113. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10114. // {
  10115. // auto varDecl = checkMethodState->mLocals[localIdx];
  10116. // if (varDecl->mName == "this")
  10117. // {
  10118. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10119. // if (varDecl->mIsSplat)
  10120. // {
  10121. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10122. // }
  10123. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  10124. // {
  10125. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  10126. // }
  10127. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  10128. // }
  10129. // }
  10130. //
  10131. // checkMethodState = checkMethodState->mPrevMethodState;
  10132. // }
  10133. // }
  10134. // Check mixin state for 'this'
  10135. {
  10136. auto checkMethodState = useMethodState;
  10137. while (checkMethodState != NULL)
  10138. {
  10139. if (checkMethodState->mMixinState != NULL)
  10140. {
  10141. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  10142. if (thisValue)
  10143. {
  10144. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10145. if (!thisValue.mType->IsValueType())
  10146. thisValue = LoadValue(thisValue);
  10147. return thisValue;
  10148. }
  10149. }
  10150. checkMethodState = checkMethodState->mPrevMethodState;
  10151. }
  10152. }
  10153. auto curMethodInstance = mCurMethodInstance;
  10154. if (useMethodState->mMethodInstance != NULL)
  10155. curMethodInstance = useMethodState->mMethodInstance;
  10156. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  10157. {
  10158. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  10159. {
  10160. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  10161. if (constLocal.mIsThis)
  10162. {
  10163. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  10164. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  10165. }
  10166. }
  10167. return BfTypedValue();
  10168. }
  10169. bool preferValue = !IsTargetingBeefBackend();
  10170. if (useMethodState->mLocals.IsEmpty())
  10171. {
  10172. // 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
  10173. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  10174. return BfTypedValue();
  10175. }
  10176. auto thisLocal = useMethodState->mLocals[0];
  10177. BF_ASSERT(thisLocal->mIsThis);
  10178. BfIRValue thisValue;
  10179. if ((preferValue) || (!thisLocal->mAddr) /*|| (thisLocal->mIsSplat)*/)
  10180. thisValue = thisLocal->mValue;
  10181. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  10182. thisValue = thisLocal->mAddr;
  10183. else
  10184. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  10185. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10186. if (useMethodState->mClosureState != NULL)
  10187. {
  10188. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  10189. if (closureTypeInst != NULL)
  10190. {
  10191. if (closureTypeInst->mFieldInstances.size() > 0)
  10192. {
  10193. auto& field = closureTypeInst->mFieldInstances[0];
  10194. auto fieldDef = field.GetFieldDef();
  10195. if (fieldDef->mName == "__this")
  10196. {
  10197. if (mCurMethodState->mClosureState->mCapturing)
  10198. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  10199. // This is a captured 'this'
  10200. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  10201. if (field.mResolvedType->IsRef())
  10202. {
  10203. auto refType = (BfRefType*)field.mResolvedType;
  10204. auto underlyingType = refType->GetUnderlyingType();
  10205. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  10206. }
  10207. if (field.mResolvedType->IsObject())
  10208. {
  10209. result = LoadValue(result);
  10210. result.mKind = BfTypedValueKind_ThisValue;
  10211. }
  10212. else
  10213. {
  10214. if (fieldDef->mIsReadOnly)
  10215. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  10216. else
  10217. result.mKind = BfTypedValueKind_ThisAddr;
  10218. }
  10219. return result;
  10220. }
  10221. }
  10222. return BfTypedValue();
  10223. }
  10224. if (useMethodState->mClosureState->mCapturing)
  10225. {
  10226. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  10227. if (thisType->IsValueType())
  10228. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  10229. else
  10230. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  10231. }
  10232. }
  10233. auto localDef = useMethodState->mLocals[0];
  10234. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  10235. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  10236. {
  10237. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  10238. {
  10239. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  10240. }
  10241. if (localDef->mIsSplat)
  10242. {
  10243. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10244. }
  10245. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  10246. }
  10247. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  10248. }
  10249. BfLocalVariable* BfModule::GetThisVariable()
  10250. {
  10251. if (mCurMethodState == NULL)
  10252. return NULL;
  10253. auto methodState = mCurMethodState->GetNonCaptureState();
  10254. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  10255. return methodState->mLocals[0];
  10256. return NULL;
  10257. }
  10258. bool BfModule::IsInGeneric()
  10259. {
  10260. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10261. }
  10262. bool BfModule::IsInSpecializedGeneric()
  10263. {
  10264. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  10265. return false;
  10266. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10267. }
  10268. bool BfModule::IsInSpecializedSection()
  10269. {
  10270. return IsInSpecializedGeneric() ||
  10271. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  10272. }
  10273. bool BfModule::IsInUnspecializedGeneric()
  10274. {
  10275. if (mCurMethodInstance != NULL)
  10276. return mCurMethodInstance->mIsUnspecialized;
  10277. return false;
  10278. }
  10279. //////////////////////////////////////////////////////////////////////////
  10280. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  10281. {
  10282. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  10283. if (type->IsValuelessType())
  10284. return mBfIRBuilder->GetFakeVal();
  10285. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  10286. if ((!doLifetimeEnd) && (WantsLifetimes()))
  10287. {
  10288. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  10289. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  10290. }
  10291. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  10292. auto typeOptions = GetTypeOptions();
  10293. if (typeOptions != NULL)
  10294. initLocalVariables = BfTypeOptions::Apply(initLocalVariables, typeOptions->mInitLocalVariables);
  10295. // Local variable inits are implicitly handled in the Beef Backend
  10296. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  10297. {
  10298. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10299. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10300. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  10301. mBfIRBuilder->ClearDebugLocation(storeInst);
  10302. mBfIRBuilder->SetInsertPoint(prevBlock);
  10303. }
  10304. return allocaInst;
  10305. }
  10306. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  10307. {
  10308. if (localVar->mResolvedType->IsVar())
  10309. {
  10310. BF_ASSERT((mCurMethodInstance->mIsUnspecialized) || (mCurMethodState->mClosureState != NULL) || (mHadVarUsage));
  10311. }
  10312. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  10313. mCurMethodState->mLocals.push_back(localVar);
  10314. BfLocalVarEntry* localVarEntryPtr;
  10315. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  10316. {
  10317. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  10318. localVarEntryPtr->mLocalVar = localVar;
  10319. }
  10320. }
  10321. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  10322. {
  10323. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()))
  10324. {
  10325. if ((!localVarDef->mValue.IsConst()) && (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  10326. {
  10327. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  10328. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  10329. }
  10330. }
  10331. if ((addDebugInfo) && (mBfIRBuilder->DbgHasInfo()) &&
  10332. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  10333. (mHasFullDebugInfo) &&
  10334. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  10335. {
  10336. auto varType = localVarDef->mResolvedType;
  10337. if (localVarDef->mResolvedType->IsValuelessType())
  10338. {
  10339. }
  10340. else
  10341. {
  10342. bool isByAddr = false;
  10343. auto diValue = localVarDef->mValue;
  10344. if (localVarDef->mConstValue)
  10345. diValue = localVarDef->mConstValue;
  10346. else if (localVarDef->mAddr)
  10347. {
  10348. diValue = localVarDef->mAddr;
  10349. isByAddr = true;
  10350. }
  10351. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  10352. bool didConstToMem = false;
  10353. bool isConstant = false;
  10354. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  10355. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10356. else if (localVarDef->mConstValue)
  10357. {
  10358. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  10359. isConstant =
  10360. (constant->mConstType < BfConstType_GlobalVar) ||
  10361. (constant->mConstType == BfConstType_AggZero) ||
  10362. (constant->mConstType == BfConstType_Array);
  10363. if (isConstant)
  10364. {
  10365. if (localVarDef->mResolvedType->IsComposite())
  10366. {
  10367. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  10368. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  10369. if (IsTargetingBeefBackend())
  10370. {
  10371. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  10372. didConstToMem = true;
  10373. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10374. }
  10375. else
  10376. {
  10377. isByAddr = true;
  10378. mBfIRBuilder->SaveDebugLocation();
  10379. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10380. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10381. mBfIRBuilder->ClearDebugLocation();
  10382. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  10383. auto addrVal = CreateAlloca(ptrType);
  10384. mBfIRBuilder->CreateStore(constMem, addrVal);
  10385. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10386. diValue = addrVal;
  10387. didConstToMem = true;
  10388. mBfIRBuilder->SetInsertPoint(prevBlock);
  10389. mBfIRBuilder->RestoreDebugLocation();
  10390. }
  10391. }
  10392. if (mCompiler->mOptions.IsCodeView())
  10393. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10394. }
  10395. }
  10396. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10397. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  10398. localVarDef->mDbgVarInst = diVariable;
  10399. if (mBfIRBuilder->HasDebugLocation())
  10400. {
  10401. if ((isConstant) && (!didConstToMem))
  10402. {
  10403. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  10404. }
  10405. else
  10406. {
  10407. if ((IsTargetingBeefBackend()) && (doAliasValue))
  10408. {
  10409. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  10410. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  10411. }
  10412. if (isByAddr)
  10413. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  10414. else if (diValue)
  10415. {
  10416. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  10417. }
  10418. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  10419. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  10420. }
  10421. }
  10422. }
  10423. }
  10424. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  10425. DoAddLocalVariable(localVarDef);
  10426. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10427. if (localVarDef->mLocalVarId == -1)
  10428. {
  10429. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  10430. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  10431. }
  10432. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10433. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  10434. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  10435. {
  10436. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  10437. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  10438. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  10439. }
  10440. return localVarDef;
  10441. }
  10442. void BfModule::CreateDIRetVal()
  10443. {
  10444. if (!WantsDebugInfo())
  10445. return;
  10446. /*if (!mCurMethodState->mRetVal)
  10447. {
  10448. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  10449. return;
  10450. }*/
  10451. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  10452. {
  10453. BF_ASSERT((!mBfIRBuilder->mIgnoreWrites) || (mHadVarUsage));
  10454. BfType* dbgType = mCurMethodInstance->mReturnType;
  10455. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  10456. if (mCurMethodInstance->HasStructRet())
  10457. {
  10458. BF_ASSERT(mCurMethodState->mRetValAddr);
  10459. dbgType = CreatePointerType(dbgType);
  10460. dbgValue = mCurMethodState->mRetValAddr;
  10461. }
  10462. else
  10463. {
  10464. BF_ASSERT(!mCurMethodState->mRetValAddr);
  10465. }
  10466. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10467. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  10468. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  10469. }
  10470. }
  10471. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  10472. {
  10473. BfLocalVarEntry* localVarEntryPtr = NULL;
  10474. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  10475. {
  10476. auto checkLocal = localVarEntryPtr->mLocalVar;
  10477. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  10478. {
  10479. BfError* error;
  10480. if (checkLocal->mIsImplicitParam)
  10481. return; // Ignore 'redefinition'
  10482. if (checkLocal->IsParam())
  10483. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  10484. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  10485. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10486. else
  10487. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10488. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  10489. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  10490. return;
  10491. }
  10492. }
  10493. }
  10494. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  10495. {
  10496. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  10497. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  10498. {
  10499. if (tokenNode->GetToken() == BfToken_Colon)
  10500. {
  10501. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  10502. {
  10503. Fail("Cannot access method scope across deferred block boundary", scopeName);
  10504. return NULL;
  10505. }
  10506. return &mCurMethodState->mHeadScope;
  10507. }
  10508. else if (tokenNode->GetToken() == BfToken_Mixin)
  10509. {
  10510. if (fromMixinState == NULL)
  10511. {
  10512. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  10513. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  10514. return mCurMethodState->mCurScope;
  10515. }
  10516. fromMixinState->mUsedInvocationScope = true;
  10517. return fromMixinState->mTargetScope;
  10518. }
  10519. else if (tokenNode->GetToken() == BfToken_New)
  10520. return NULL;
  10521. }
  10522. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  10523. {
  10524. auto findLabel = scopeName->ToString();
  10525. bool crossedDeferredBlock = false;
  10526. auto checkScope = mCurMethodState->mCurScope;
  10527. while (checkScope != NULL)
  10528. {
  10529. if (checkScope->mIsDeferredBlock)
  10530. crossedDeferredBlock = true;
  10531. if (checkScope->mLabel == findLabel)
  10532. {
  10533. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  10534. {
  10535. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  10536. return NULL;
  10537. }
  10538. return checkScope;
  10539. }
  10540. checkScope = checkScope->mPrevScope;
  10541. }
  10542. if (!inMixinDecl)
  10543. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  10544. }
  10545. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  10546. {
  10547. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  10548. }
  10549. return mCurMethodState->mCurScope;
  10550. }
  10551. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  10552. {
  10553. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  10554. }
  10555. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  10556. {
  10557. auto scopeData = FindScope(scopeName, false);
  10558. if (scopeData == NULL)
  10559. return NULL;
  10560. int scopeDepth = scopeData->GetDepth();
  10561. // Find the first break data that is at or below the depth of our requested scope
  10562. auto breakData = mCurMethodState->mBreakData;
  10563. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  10564. {
  10565. if (breakData->mScope->mIsConditional)
  10566. return NULL;
  10567. breakData = breakData->mPrevBreakData;
  10568. }
  10569. return breakData;
  10570. }
  10571. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  10572. {
  10573. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  10574. if (!IsTargetingBeefBackend())
  10575. return;
  10576. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  10577. {
  10578. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10579. }
  10580. }
  10581. void BfModule::ClearLifetimeEnds()
  10582. {
  10583. auto scopeData = mCurMethodState->mCurScope;
  10584. while (scopeData != NULL)
  10585. {
  10586. scopeData->mDeferredLifetimeEnds.Clear();
  10587. scopeData = scopeData->mPrevScope;
  10588. }
  10589. }
  10590. bool BfModule::WantsDebugInfo()
  10591. {
  10592. if ((mCurMethodInstance != NULL) &&
  10593. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  10594. return false;
  10595. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  10596. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  10597. }
  10598. BfTypeOptions* BfModule::GetTypeOptions()
  10599. {
  10600. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  10601. return mCurMethodState->mMethodTypeOptions;
  10602. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  10603. }
  10604. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  10605. {
  10606. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10607. while (checkScope != NULL)
  10608. {
  10609. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  10610. return true;
  10611. if (checkScope == scope)
  10612. break;
  10613. checkScope = checkScope->mPrevScope;
  10614. }
  10615. return false;
  10616. }
  10617. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  10618. {
  10619. // Is there anything we need to do here?
  10620. if (mBfIRBuilder->mIgnoreWrites)
  10621. {
  10622. // Just visit deferred blocks
  10623. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10624. while (checkScope != NULL)
  10625. {
  10626. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10627. while (deferredCallEntry != NULL)
  10628. {
  10629. if (deferredCallEntry->mDeferredBlock != NULL)
  10630. {
  10631. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  10632. }
  10633. deferredCallEntry = deferredCallEntry->mNext;
  10634. }
  10635. if (checkScope == scopeData)
  10636. break;
  10637. checkScope = checkScope->mPrevScope;
  10638. }
  10639. return;
  10640. }
  10641. // Why did we want to do SetIllegalSrcPos here?
  10642. // Don't we always want to step onto these instances?
  10643. // Find a case where we don't and perhaps only do it there.
  10644. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  10645. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  10646. //SetIllegalSrcPos();
  10647. bool setSrcPos = false;
  10648. bool wantsNop = true;
  10649. BfAstNode* deferCloseNode = NULL;
  10650. if (mCurMethodState->mInPostReturn)
  10651. {
  10652. // These won't get used, they are post-return
  10653. return;
  10654. }
  10655. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  10656. BfScopeData* scopeJumpBlock = NULL;
  10657. bool hadExtraDeferredLifetimeEnds = false;
  10658. auto _FlushLifetimeEnds = [&]()
  10659. {
  10660. for (auto lifetimeEnd : deferredLifetimeEnds)
  10661. {
  10662. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10663. mBfIRBuilder->ClearDebugLocation_Last();
  10664. }
  10665. deferredLifetimeEnds.clear();
  10666. };
  10667. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10668. while (checkScope != NULL)
  10669. {
  10670. if (checkScope->mCloseNode != NULL)
  10671. deferCloseNode = checkScope->mCloseNode;
  10672. if (doneBlock)
  10673. {
  10674. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  10675. for (auto& checkHandler : checkScope->mDeferredHandlers)
  10676. {
  10677. if (checkHandler.mDoneBlock == doneBlock)
  10678. {
  10679. scopeJumpBlock = checkScope;
  10680. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  10681. mBfIRBuilder->ClearDebugLocation_Last();
  10682. _FlushLifetimeEnds();
  10683. break;
  10684. }
  10685. }
  10686. if (scopeJumpBlock != NULL)
  10687. break;
  10688. }
  10689. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  10690. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  10691. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  10692. if (hasWork)
  10693. {
  10694. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  10695. if (deferCloseNode != NULL)
  10696. {
  10697. UpdateSrcPos(deferCloseNode);
  10698. }
  10699. if (doneBlock)
  10700. {
  10701. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  10702. String blockName = "deferredCalls";
  10703. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  10704. BfDeferredHandler deferredHandler;
  10705. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  10706. {
  10707. mBfIRBuilder->SaveDebugLocation();
  10708. mBfIRBuilder->ClearDebugLocation();
  10709. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  10710. mBfIRBuilder->RestoreDebugLocation();
  10711. }
  10712. else
  10713. {
  10714. // Definitely chain
  10715. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  10716. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  10717. mBfIRBuilder->ClearDebugLocation_Last();
  10718. _FlushLifetimeEnds();
  10719. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  10720. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  10721. }
  10722. deferredHandler.mDoneBlock = doneBlock;
  10723. if (!mBfIRBuilder->mIgnoreWrites)
  10724. checkScope->mDeferredHandlers.push_back(deferredHandler);
  10725. if (checkScope == &mCurMethodState->mHeadScope)
  10726. {
  10727. if (!mCurMethodState->mDIRetVal)
  10728. {
  10729. // 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
  10730. // be scoped to the physical method
  10731. /*if (deferCloseNode != NULL)
  10732. {
  10733. UpdateSrcPos(deferCloseNode);
  10734. }*/
  10735. CreateDIRetVal();
  10736. }
  10737. }
  10738. if (checkScope != mCurMethodState->mTailScope)
  10739. {
  10740. if (deferredHandler.mHandlerBlock.IsFake())
  10741. {
  10742. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  10743. }
  10744. if (!mBfIRBuilder->mIgnoreWrites)
  10745. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  10746. }
  10747. }
  10748. std::unordered_set<BfDeferredCallEntry*> handledSet;
  10749. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10750. while (deferredCallEntry != NULL)
  10751. {
  10752. BfDeferredCallEmitState deferredCallEmitState;
  10753. deferredCallEmitState.mCloseNode = deferCloseNode;
  10754. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  10755. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  10756. if (deferCloseNode != NULL)
  10757. {
  10758. UpdateSrcPos(deferCloseNode);
  10759. }
  10760. if (wantsNop)
  10761. EmitEnsureInstructionAt();
  10762. wantsNop = false;
  10763. if (deferredCallEntry->mDeferredBlock != NULL)
  10764. {
  10765. auto itr = handledSet.insert(deferredCallEntry);
  10766. if (!itr.second)
  10767. {
  10768. // Already handled, can happen if we defer again within the block
  10769. deferredCallEntry = deferredCallEntry->mNext;
  10770. continue;
  10771. }
  10772. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  10773. EmitDeferredCall(*deferredCallEntry);
  10774. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  10775. {
  10776. // The list changed, start over and ignore anything we've already handled
  10777. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10778. }
  10779. else
  10780. deferredCallEntry = deferredCallEntry->mNext;
  10781. }
  10782. else
  10783. {
  10784. EmitDeferredCall(*deferredCallEntry);
  10785. deferredCallEntry = deferredCallEntry->mNext;
  10786. }
  10787. }
  10788. if (checkScope->mSavedStack)
  10789. {
  10790. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  10791. if (mCurMethodState->mDynStackRevIdx)
  10792. {
  10793. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  10794. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  10795. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  10796. }
  10797. }
  10798. }
  10799. if (!checkScope->mIsScopeHead)
  10800. {
  10801. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  10802. if (!IsTargetingBeefBackend())
  10803. {
  10804. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10805. {
  10806. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10807. }
  10808. }
  10809. else
  10810. {
  10811. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10812. {
  10813. deferredLifetimeEnds.Add(lifetimeEnd);
  10814. }
  10815. }
  10816. }
  10817. if (checkScope == scopeData)
  10818. break;
  10819. checkScope = checkScope->mPrevScope;
  10820. }
  10821. if ((doneBlock) && (scopeJumpBlock == NULL))
  10822. {
  10823. mBfIRBuilder->CreateBr(doneBlock);
  10824. mBfIRBuilder->ClearDebugLocation_Last();
  10825. }
  10826. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  10827. // may have been created when other scope lifetimes were available
  10828. _FlushLifetimeEnds();
  10829. // Emit lifetimeEnds after the branch for Beef
  10830. /*if (IsTargetingBeefBackend())
  10831. {
  10832. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  10833. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10834. while (checkScope != NULL)
  10835. {
  10836. if (checkScope == scopeJumpBlock)
  10837. break;
  10838. if (!checkScope->mIsScopeHead)
  10839. {
  10840. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10841. {
  10842. if (needsEnsureInst)
  10843. {
  10844. needsEnsureInst = false;
  10845. }
  10846. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10847. }
  10848. }
  10849. if (checkScope == scopeData)
  10850. break;
  10851. checkScope = checkScope->mPrevScope;
  10852. }
  10853. }*/
  10854. }
  10855. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  10856. {
  10857. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  10858. {
  10859. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  10860. while (deferredLocalAssignData != NULL)
  10861. {
  10862. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  10863. break;
  10864. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  10865. deferredLocalAssignData->mIsUnconditional = false;
  10866. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  10867. }
  10868. }
  10869. //for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  10870. // We mark all unassigned variables as assigned now, for avoiding "may be unassigned" usage cases like:
  10871. // int b;
  10872. // if (cond) return;
  10873. // else b = 1;
  10874. // Use(b);
  10875. for (int localIdx = 0; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  10876. {
  10877. auto localDef = mCurMethodState->mLocals[localIdx];
  10878. if ((!localDef->mIsAssigned) && (!localDef->IsParam()))
  10879. mCurMethodState->LocalDefined(localDef);
  10880. }
  10881. }
  10882. void BfModule::CreateReturn(BfIRValue val)
  10883. {
  10884. if (mCurMethodInstance->mReturnType->IsComposite())
  10885. {
  10886. // Store to sret
  10887. BF_ASSERT(val);
  10888. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(0));
  10889. mBfIRBuilder->CreateRetVoid();
  10890. }
  10891. else
  10892. {
  10893. if (mCurMethodInstance->mReturnType->IsValuelessType())
  10894. {
  10895. mBfIRBuilder->CreateRetVoid();
  10896. }
  10897. else
  10898. {
  10899. BF_ASSERT(val);
  10900. mBfIRBuilder->CreateRet(val);
  10901. }
  10902. }
  10903. }
  10904. void BfModule::EmitReturn(BfIRValue val)
  10905. {
  10906. if (mCurMethodState->mIRExitBlock)
  10907. {
  10908. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  10909. {
  10910. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  10911. {
  10912. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  10913. if (!mCurMethodState->mRetVal)
  10914. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  10915. mBfIRBuilder->CreateStore(val, retVal);
  10916. }
  10917. }
  10918. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  10919. }
  10920. else
  10921. {
  10922. EmitDeferredScopeCalls(false, NULL);
  10923. if (mCurMethodInstance->mReturnType->IsValuelessType())
  10924. mBfIRBuilder->CreateRetVoid();
  10925. else
  10926. mBfIRBuilder->CreateRet(val);
  10927. }
  10928. mCurMethodState->SetHadReturn(true);
  10929. mCurMethodState->mLeftBlockUncond = true;
  10930. }
  10931. void BfModule::EmitDefaultReturn()
  10932. {
  10933. if (mCurMethodState->mInDeferredBlock)
  10934. return;
  10935. if (mCurMethodState->mIRExitBlock)
  10936. {
  10937. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  10938. }
  10939. else
  10940. {
  10941. if (mCurMethodInstance->mReturnType->IsVoid())
  10942. mBfIRBuilder->CreateRetVoid();
  10943. else
  10944. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  10945. }
  10946. mCurMethodState->SetHadReturn(true);
  10947. mCurMethodState->mLeftBlockUncond = true;
  10948. }
  10949. void BfModule::AssertErrorState()
  10950. {
  10951. if (mIgnoreErrors)
  10952. return;
  10953. if (mHadBuildError)
  10954. return;
  10955. if (mCurTypeInstance != NULL)
  10956. {
  10957. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  10958. return;
  10959. }
  10960. if (mCurMethodInstance != NULL)
  10961. {
  10962. if (mCurMethodInstance->mIsUnspecializedVariation)
  10963. return;
  10964. }
  10965. // We want the module to be marked as failed even if it's just an error in the parser
  10966. if (mCurMethodInstance != NULL)
  10967. mCurMethodInstance->mHasFailed = true;
  10968. mHadBuildError = true;
  10969. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  10970. if (mCurTypeInstance != NULL)
  10971. {
  10972. if (mCurTypeInstance->mTypeFailed)
  10973. return;
  10974. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  10975. return;
  10976. }
  10977. if (mCurMethodInstance != NULL)
  10978. {
  10979. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  10980. return;
  10981. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  10982. return;
  10983. }
  10984. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  10985. }
  10986. void BfModule::AssertParseErrorState()
  10987. {
  10988. if (mCompiler->mRevision == 1)
  10989. AssertErrorState();
  10990. }
  10991. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  10992. {
  10993. BF_ASSERT(delegateType->IsDelegate());
  10994. auto typeInst = delegateType->ToTypeInstance();
  10995. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  10996. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  10997. return invokeMethodInstance->mReturnType;
  10998. }
  10999. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  11000. {
  11001. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  11002. }
  11003. void BfModule::CreateDelegateInvokeMethod()
  11004. {
  11005. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  11006. //mBfIRBuilder->ClearDebugLocation();
  11007. SetIllegalSrcPos();
  11008. auto typeInstance = mCurTypeInstance;
  11009. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  11010. SizedArray<BfIRType, 4> staticParamTypes;
  11011. SizedArray<BfIRValue, 4> staticFuncArgs;
  11012. SizedArray<BfIRValue, 4> memberFuncArgs;
  11013. auto multicastDelegateType = typeInstance->mBaseType;
  11014. if (multicastDelegateType->mFieldInstances.size() != 2)
  11015. {
  11016. AssertErrorState();
  11017. return;
  11018. }
  11019. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  11020. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  11021. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  11022. BfExprEvaluator exprEvaluator(this);
  11023. SizedArray<BfIRType, 8> origParamTypes;
  11024. BfIRType origReturnType;
  11025. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  11026. if (mCurMethodInstance->mReturnType->IsValueType())
  11027. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  11028. int thisIdx = 0;
  11029. if (mCurMethodInstance->HasStructRet())
  11030. {
  11031. thisIdx = 1;
  11032. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11033. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11034. }
  11035. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  11036. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  11037. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  11038. {
  11039. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  11040. exprEvaluator.PushArg(localVal, staticFuncArgs);
  11041. exprEvaluator.PushArg(localVal, memberFuncArgs);
  11042. }
  11043. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  11044. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  11045. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  11046. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  11047. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  11048. auto doneBB = mBfIRBuilder->CreateBlock("done");
  11049. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  11050. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  11051. BfIRValue nonStaticResult;
  11052. BfIRValue staticResult;
  11053. auto callingConv = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11054. /// Non-static invocation
  11055. {
  11056. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11057. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  11058. mBfIRBuilder->SetInsertPoint(trueBB);
  11059. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  11060. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11061. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  11062. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11063. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  11064. if (callingConv != BfIRCallingConv_CDecl)
  11065. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  11066. mCurMethodState->SetHadReturn(false);
  11067. mCurMethodState->mLeftBlockUncond = false;
  11068. mCurMethodState->mLeftBlockCond = false;
  11069. mBfIRBuilder->CreateBr(doneBB);
  11070. }
  11071. // Static invocation
  11072. {
  11073. mBfIRBuilder->AddBlock(falseBB);
  11074. mBfIRBuilder->SetInsertPoint(falseBB);
  11075. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11076. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  11077. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11078. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  11079. if (callingConv == BfIRCallingConv_ThisCall)
  11080. callingConv = BfIRCallingConv_CDecl;
  11081. if (callingConv != BfIRCallingConv_CDecl)
  11082. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  11083. // if (!mSystem->IsCompatibleCallingConvention(BfCallingConvention_Unspecified, mCurMethodInstance->mMethodDef->mCallingConvention))
  11084. // {
  11085. // if (mCurMethodInstance->mMethodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11086. //
  11087. // }
  11088. mCurMethodState->SetHadReturn(false);
  11089. mCurMethodState->mLeftBlockUncond = false;
  11090. mCurMethodState->mLeftBlockCond = false;
  11091. mBfIRBuilder->CreateBr(doneBB);
  11092. }
  11093. mBfIRBuilder->AddBlock(doneBB);
  11094. mBfIRBuilder->SetInsertPoint(doneBB);
  11095. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->HasStructRet()))
  11096. {
  11097. mBfIRBuilder->CreateRetVoid();
  11098. }
  11099. else
  11100. {
  11101. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(mCurMethodInstance->mReturnType), 2);
  11102. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  11103. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  11104. mBfIRBuilder->CreateRet(phi);
  11105. }
  11106. }
  11107. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  11108. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  11109. {
  11110. auto typeDef = typeInstance->mTypeDef;
  11111. auto methodDeclaration = methodDef->mMethodDeclaration;
  11112. if (!mCompiler->mIsResolveOnly)
  11113. return true;
  11114. if (typeInstance->IsGenericTypeInstance())
  11115. {
  11116. // We only really want to process the unspecialized type for autocompletion
  11117. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  11118. return false;
  11119. }
  11120. BfAstNode* checkNode = methodDeclaration;
  11121. if (methodDeclaration == NULL)
  11122. checkNode = methodDef->mBody;
  11123. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  11124. {
  11125. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  11126. return true;
  11127. }
  11128. return false;
  11129. }
  11130. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  11131. {
  11132. methodInst->mAppendAllocAlign = 1;
  11133. }
  11134. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  11135. {
  11136. BP_ZONE("BfModule::TryConstCalcAppend");
  11137. if (mCompiler->mIsResolveOnly)
  11138. return BfTypedValue();
  11139. // We want to regenerate all ctor calls when the method internals change
  11140. {
  11141. auto checkTypeInst = methodInst->GetOwner();
  11142. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  11143. {
  11144. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  11145. checkTypeInst = GetBaseType(checkTypeInst);
  11146. }
  11147. }
  11148. if (!methodInst->mMayBeConst)
  11149. return BfTypedValue();
  11150. // Do we need to iterate in order to resolve mAppendAllocAlign?
  11151. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  11152. bool wasAllConst = true;
  11153. int argIdx = 0;
  11154. int paramIdx = 0;
  11155. while (true)
  11156. {
  11157. if (argIdx >= (int)args.size())
  11158. break;
  11159. auto paramType = methodInst->GetParamType(paramIdx);
  11160. PopulateType(paramType);
  11161. int argCount = 0;
  11162. if (!paramType->IsValuelessType())
  11163. {
  11164. if (methodInst->GetParamIsSplat(paramIdx))
  11165. argCount = paramType->GetSplatCount();
  11166. else
  11167. argCount = 1;
  11168. for (int argOfs = 0; argOfs < argCount; argOfs++)
  11169. {
  11170. auto arg = args[argIdx + argOfs];
  11171. if (!arg.IsConst())
  11172. {
  11173. wasAllConst = false;
  11174. if (!isFirstRun)
  11175. {
  11176. auto& param = methodInst->mParams[argIdx];
  11177. if (param.mReferencedInConstPass)
  11178. {
  11179. // If this param is required as part of the const calculation then
  11180. // we require that it be const...
  11181. return BfTypedValue();
  11182. }
  11183. }
  11184. }
  11185. }
  11186. }
  11187. paramIdx++;
  11188. argIdx += argCount;
  11189. }
  11190. auto methodDef = methodInst->mMethodDef;
  11191. auto methodDecl = methodDef->GetMethodDeclaration();
  11192. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11193. if (methodDeclBlock == NULL)
  11194. return BfTypedValue();
  11195. BfTypedValue constValue;
  11196. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11197. auto checkState = mCurMethodState->mConstResolveState;
  11198. while (checkState != NULL)
  11199. {
  11200. if (checkState->mMethodInstance == methodInst)
  11201. {
  11202. return BfTypedValue();
  11203. }
  11204. checkState = checkState->mPrevConstResolveState;
  11205. }
  11206. //auto accumValue = GetConstValue(0);
  11207. bool failed = false;
  11208. //
  11209. {
  11210. BfConstResolveState constResolveState;
  11211. constResolveState.mMethodInstance = methodInst;
  11212. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  11213. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11214. BfMethodState methodState;
  11215. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  11216. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  11217. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  11218. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  11219. methodState.mConstResolveState = &constResolveState;
  11220. int argIdx = 0;
  11221. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11222. {
  11223. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  11224. continue;
  11225. auto paramType = methodInst->GetParamType(paramIdx);
  11226. // Fix this after we allow structs to be consts
  11227. //BF_ASSERT(!paramType->IsSplattable());
  11228. BfLocalVariable* localVar = new BfLocalVariable();
  11229. localVar->mName = methodInst->GetParamName(paramIdx);
  11230. localVar->mResolvedType = paramType;
  11231. localVar->mConstValue = args[argIdx];
  11232. localVar->mParamIdx = paramIdx;
  11233. AddLocalVariableDef(localVar);
  11234. argIdx++;
  11235. }
  11236. AppendAllocVisitor appendAllocVisitor;
  11237. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  11238. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  11239. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  11240. if (baseCtorAppendValue)
  11241. {
  11242. if (baseCtorAppendValue.mValue.IsFake())
  11243. appendAllocVisitor.mFailed = true;
  11244. else
  11245. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  11246. }
  11247. appendAllocVisitor.mModule = this;
  11248. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11249. if (!appendAllocVisitor.mFailed)
  11250. constValue = appendAllocVisitor.mConstAccum;
  11251. if (isFirstRun)
  11252. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  11253. if (isFirstRun)
  11254. {
  11255. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11256. {
  11257. auto localVar = mCurMethodState->mLocals[paramIdx];
  11258. if (localVar->mReadFromId != -1)
  11259. {
  11260. auto& param = methodInst->mParams[paramIdx];
  11261. param.mReferencedInConstPass = true;
  11262. }
  11263. }
  11264. }
  11265. }
  11266. mBfIRBuilder->SetInsertPoint(prevBlock);
  11267. if (!constValue)
  11268. {
  11269. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  11270. // all-const args
  11271. if (wasAllConst)
  11272. {
  11273. methodInst->mMayBeConst = false;
  11274. }
  11275. }
  11276. return constValue;
  11277. }
  11278. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  11279. {
  11280. // Any errors should only be shown in the actual CTOR call
  11281. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  11282. auto methodDef = mCurMethodInstance->mMethodDef;
  11283. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  11284. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11285. BfTypeInstance* targetType = NULL;
  11286. if (ctorDeclaration->mInitializer != NULL)
  11287. {
  11288. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11289. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11290. }
  11291. else
  11292. targetType = mCurTypeInstance->mBaseType;
  11293. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  11294. return NULL;
  11295. auto targetRefNode = methodDef->GetRefNode();
  11296. BfType* targetThisType = targetType;
  11297. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  11298. BfExprEvaluator exprEvaluator(this);
  11299. BfResolvedArgs argValues;
  11300. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11301. {
  11302. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11303. }
  11304. //
  11305. {
  11306. }
  11307. BfFunctionBindResult bindResult;
  11308. bindResult.mSkipThis = true;
  11309. bindResult.mWantsArgs = true;
  11310. {
  11311. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11312. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11313. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11314. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11315. }
  11316. if (bindResult.mMethodInstance == NULL)
  11317. {
  11318. AssertErrorState();
  11319. return BfTypedValue();
  11320. }
  11321. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  11322. {
  11323. return BfTypedValue();
  11324. }
  11325. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11326. bindResult.mIRArgs.RemoveAt(0);
  11327. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  11328. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  11329. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  11330. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  11331. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  11332. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  11333. if (appendSizeTypedValue)
  11334. return appendSizeTypedValue;
  11335. if (constOnly)
  11336. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  11337. bool needsRecalc = false;
  11338. for (auto irArg : bindResult.mIRArgs)
  11339. {
  11340. if (irArg.IsFake())
  11341. needsRecalc = true;
  11342. }
  11343. auto calcAppendArgs = bindResult.mIRArgs;
  11344. if (needsRecalc)
  11345. {
  11346. // Do it again, but without mIgnoreWrites set
  11347. BfResolvedArgs argValues;
  11348. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11349. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11350. BfFunctionBindResult bindResult;
  11351. bindResult.mSkipThis = true;
  11352. bindResult.mWantsArgs = true;
  11353. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11354. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11355. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11356. bindResult.mIRArgs.RemoveAt(0);
  11357. calcAppendArgs = bindResult.mIRArgs;
  11358. }
  11359. BF_ASSERT(calcAppendMethodModule.mFunc);
  11360. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  11361. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  11362. return appendSizeTypedValue;
  11363. }
  11364. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  11365. void BfModule::EmitCtorCalcAppend()
  11366. {
  11367. if (mCompiler->mIsResolveOnly)
  11368. return;
  11369. auto methodDef = mCurMethodInstance->mMethodDef;
  11370. auto methodDecl = methodDef->GetMethodDeclaration();
  11371. Array<BfAstNode*> deferredNodeList;
  11372. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11373. if (methodDeclBlock == NULL)
  11374. return;
  11375. AppendAllocVisitor appendAllocVisitor;
  11376. auto baseCalcAppend = CallBaseCtorCalc(false);
  11377. if (baseCalcAppend)
  11378. {
  11379. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  11380. }
  11381. appendAllocVisitor.mModule = this;
  11382. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11383. }
  11384. void BfModule::CreateStaticCtor()
  11385. {
  11386. auto typeDef = mCurTypeInstance->mTypeDef;
  11387. auto methodDef = mCurMethodInstance->mMethodDef;
  11388. BfIRBlock exitBB;
  11389. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  11390. {
  11391. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  11392. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  11393. mBfIRBuilder->MapType(boolType),
  11394. false,
  11395. BfIRLinkageType_Internal,
  11396. GetDefaultValue(boolType),
  11397. "didStaticInit");
  11398. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  11399. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  11400. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  11401. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  11402. mBfIRBuilder->SetInsertPoint(initBB);
  11403. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  11404. }
  11405. // Do DLL imports
  11406. if (!mDllImportEntries.empty())
  11407. {
  11408. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  11409. PopulateType(internalType);
  11410. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  11411. if (!getSharedProcAddressInstance)
  11412. {
  11413. if (!mCompiler->mPassInstance->HasFailed())
  11414. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  11415. }
  11416. }
  11417. // Fill in initializer values
  11418. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11419. {
  11420. for (auto fieldDef : typeDef->mFields)
  11421. {
  11422. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  11423. {
  11424. // For extensions, only handle these fields in the appropriate extension
  11425. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  11426. continue;
  11427. UpdateSrcPos(fieldDef->mInitializer);
  11428. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  11429. if (!fieldInst->mFieldIncluded)
  11430. continue;
  11431. if (fieldInst->mResolvedType->IsVar())
  11432. {
  11433. BF_ASSERT(mHadVarUsage);
  11434. continue;
  11435. }
  11436. auto assignValue = GetFieldInitializerValue(fieldInst);
  11437. if (assignValue)
  11438. {
  11439. assignValue = LoadValue(assignValue);
  11440. if (!assignValue.mType->IsValuelessType())
  11441. {
  11442. auto staticVarRef = ReferenceStaticField(fieldInst).mValue;
  11443. mBfIRBuilder->CreateStore(assignValue.mValue, staticVarRef);
  11444. }
  11445. }
  11446. }
  11447. }
  11448. }
  11449. else
  11450. {
  11451. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11452. {
  11453. if (tempTypeDef->mFullName == typeDef->mFullName)
  11454. {
  11455. for (auto fieldDef : tempTypeDef->mFields)
  11456. {
  11457. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  11458. {
  11459. if (fieldDef->mInitializer != NULL)
  11460. {
  11461. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  11462. {
  11463. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  11464. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  11465. }
  11466. BfType* wantType = NULL;
  11467. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  11468. {
  11469. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  11470. }
  11471. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  11472. }
  11473. }
  11474. }
  11475. }
  11476. }
  11477. }
  11478. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11479. CallChainedMethods(mCurMethodInstance, false);
  11480. }
  11481. void BfModule::EmitDtorBody()
  11482. {
  11483. if (mCurTypeInstance->IsClosure())
  11484. {
  11485. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  11486. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  11487. auto thisVal = GetThis();
  11488. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  11489. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  11490. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11491. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  11492. SizedArray<BfIRValue, 1> args;
  11493. args.push_back(thisVal.mValue);
  11494. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  11495. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11496. // Fall through to Object::~this call
  11497. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  11498. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  11499. SizedArray<BfIRValue, 1> vals = { basePtr };
  11500. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  11501. mBfIRBuilder->SetCallCallingConv(result, GetCallingConvention(dtorFunc.mMethodInstance));
  11502. mBfIRBuilder->SetTailCall(result);
  11503. return;
  11504. }
  11505. auto typeDef = mCurTypeInstance->mTypeDef;
  11506. auto methodDef = mCurMethodInstance->mMethodDef;
  11507. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11508. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11509. CallChainedMethods(mCurMethodInstance, true);
  11510. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11511. {
  11512. VisitCodeBlock(bodyBlock);
  11513. if (bodyBlock->mCloseBrace != NULL)
  11514. {
  11515. UpdateSrcPos(bodyBlock->mCloseBrace);
  11516. }
  11517. }
  11518. else
  11519. {
  11520. if (methodDeclaration != NULL)
  11521. UpdateSrcPos(methodDeclaration);
  11522. else if (typeDef->mTypeDeclaration != NULL)
  11523. UpdateSrcPos(typeDef->mTypeDeclaration);
  11524. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  11525. {
  11526. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken);
  11527. }
  11528. }
  11529. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11530. {
  11531. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  11532. {
  11533. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  11534. auto fieldDef = fieldInst->GetFieldDef();
  11535. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  11536. {
  11537. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  11538. {
  11539. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken);
  11540. }
  11541. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  11542. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11543. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  11544. continue;
  11545. UpdateSrcPos(fieldDtor);
  11546. BfScopeData scopeData;
  11547. mCurMethodState->AddScope(&scopeData);
  11548. NewScopeState();
  11549. UpdateSrcPos(fieldDtor);
  11550. bool hasDbgInfo = (!fieldDef->mIsConst);
  11551. if (hasDbgInfo)
  11552. {
  11553. mBfIRBuilder->SaveDebugLocation();
  11554. mBfIRBuilder->ClearDebugLocation();
  11555. }
  11556. BfIRValue value;
  11557. if (fieldDef->mIsStatic)
  11558. {
  11559. value = ReferenceStaticField(fieldInst).mValue;
  11560. }
  11561. else
  11562. {
  11563. if (!mCurTypeInstance->IsValueType())
  11564. {
  11565. auto thisValue = GetThis();
  11566. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  11567. }
  11568. else
  11569. {
  11570. AssertErrorState();
  11571. value = mBfIRBuilder->CreateConstNull(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInst->mResolvedType)));
  11572. }
  11573. }
  11574. BfIRValue staticVal;
  11575. if (hasDbgInfo)
  11576. {
  11577. BfIRValue dbgShowValue = value;
  11578. BfLocalVariable* localDef = new BfLocalVariable();
  11579. localDef->mName = "_";
  11580. localDef->mResolvedType = fieldInst->mResolvedType;
  11581. localDef->mAddr = value;
  11582. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  11583. {
  11584. // Create another pointer indirection, a ref to the gep
  11585. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  11586. auto allocaInst = CreateAlloca(refFieldType);
  11587. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  11588. localDef->mResolvedType = refFieldType;
  11589. localDef->mAddr = allocaInst;
  11590. }
  11591. mBfIRBuilder->RestoreDebugLocation();
  11592. auto defLocalVar = AddLocalVariableDef(localDef, true);
  11593. // Put back so we actually modify the correct value*/
  11594. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  11595. defLocalVar->mAddr = value;
  11596. }
  11597. while (fieldDtor != NULL)
  11598. {
  11599. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11600. {
  11601. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11602. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11603. }
  11604. UpdateSrcPos(fieldDtor);
  11605. VisitEmbeddedStatement(fieldDtor->mBody);
  11606. fieldDtor = fieldDtor->mNextFieldDtor;
  11607. }
  11608. RestoreScopeState();
  11609. }
  11610. }
  11611. if (!methodDef->mIsStatic)
  11612. {
  11613. auto checkBaseType = mCurTypeInstance->mBaseType;
  11614. while (checkBaseType != NULL)
  11615. {
  11616. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11617. {
  11618. if (bodyBlock->mCloseBrace != NULL)
  11619. UpdateSrcPos(bodyBlock->mCloseBrace);
  11620. }
  11621. else
  11622. {
  11623. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  11624. }
  11625. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  11626. {
  11627. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  11628. if (mCompiler->IsSkippingExtraResolveChecks())
  11629. {
  11630. // Nothing
  11631. }
  11632. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  11633. {
  11634. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  11635. {
  11636. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  11637. SizedArray<BfIRValue, 1> vals = { basePtr };
  11638. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  11639. mBfIRBuilder->SetCallCallingConv(callInst, GetCallingConvention(dtorMethodInstance.mMethodInstance));
  11640. }
  11641. }
  11642. else
  11643. {
  11644. // Invalid base dtor declaration
  11645. AssertErrorState();
  11646. }
  11647. break;
  11648. }
  11649. checkBaseType = checkBaseType->mBaseType;
  11650. }
  11651. }
  11652. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  11653. }
  11654. else
  11655. {
  11656. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  11657. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  11658. // resolve pass, NOT the autocomplete expression
  11659. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11660. {
  11661. if (tempTypeDef->mFullName == typeDef->mFullName)
  11662. {
  11663. for (auto fieldDef : tempTypeDef->mFields)
  11664. {
  11665. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  11666. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11667. {
  11668. BfType* fieldType = NULL;
  11669. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  11670. {
  11671. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  11672. auto curFieldDef = curFieldInstance->GetFieldDef();
  11673. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  11674. fieldType = curFieldInstance->GetResolvedType();
  11675. }
  11676. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11677. BfScopeData scopeData;
  11678. mCurMethodState->AddScope(&scopeData);
  11679. NewScopeState();
  11680. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  11681. if (fieldType != NULL)
  11682. {
  11683. BfLocalVariable* localDef = new BfLocalVariable();
  11684. localDef->mName = "_";
  11685. localDef->mResolvedType = fieldType;
  11686. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  11687. localDef->mIsAssigned = true;
  11688. AddLocalVariableDef(localDef);
  11689. }
  11690. while (fieldDtor != NULL)
  11691. {
  11692. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11693. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11694. UpdateSrcPos(fieldDtor);
  11695. VisitEmbeddedStatement(fieldDtor->mBody);
  11696. fieldDtor = fieldDtor->mNextFieldDtor;
  11697. }
  11698. RestoreScopeState();
  11699. }
  11700. }
  11701. }
  11702. }
  11703. }
  11704. }
  11705. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  11706. {
  11707. auto typeInstance = methodInstance->GetOwner();
  11708. bool foundDllImportAttr = false;
  11709. BfCallingConvention callingConvention = methodInstance->mMethodDef->mCallingConvention;
  11710. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  11711. {
  11712. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  11713. {
  11714. foundDllImportAttr = true;
  11715. }
  11716. }
  11717. if (!foundDllImportAttr)
  11718. {
  11719. AssertErrorState();
  11720. return BfIRValue();
  11721. }
  11722. String name = "bf_hs_preserve@";
  11723. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  11724. name += "__imp";
  11725. BfIRType returnType;
  11726. SizedArray<BfIRType, 8> paramTypes;
  11727. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11728. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11729. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  11730. BfIRValue initVal;
  11731. if (define)
  11732. {
  11733. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  11734. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  11735. }
  11736. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  11737. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  11738. {
  11739. auto voidType = GetPrimitiveType(BfTypeCode_None);
  11740. auto ptrType = CreatePointerType(voidType);
  11741. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  11742. }
  11743. return globalVar;
  11744. }
  11745. void BfModule::CreateDllImportMethod()
  11746. {
  11747. if (mBfIRBuilder->mIgnoreWrites)
  11748. return;
  11749. auto globalVar = mFuncReferences[mCurMethodInstance];
  11750. if (!globalVar)
  11751. return;
  11752. bool allowTailCall = true;
  11753. mBfIRBuilder->ClearDebugLocation();
  11754. bool isHotCompile = mCompiler->IsHotCompile();
  11755. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  11756. if (isHotCompile)
  11757. {
  11758. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  11759. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  11760. }
  11761. auto callingConvention = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11762. BfIRType returnType;
  11763. SizedArray<BfIRType, 8> paramTypes;
  11764. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11765. SizedArray<BfIRValue, 8> args;
  11766. for (int i = 0; i < (int)paramTypes.size(); i++)
  11767. args.push_back(mBfIRBuilder->GetArgument(i));
  11768. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11769. if (isHotCompile)
  11770. {
  11771. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  11772. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  11773. if (callingConvention == BfIRCallingConv_StdCall)
  11774. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  11775. else
  11776. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11777. if (allowTailCall)
  11778. mBfIRBuilder->SetTailCall(result);
  11779. CreateReturn(result);
  11780. mCurMethodState->mHadReturn = true;
  11781. }
  11782. if (HasCompiledOutput())
  11783. {
  11784. BfDllImportEntry dllImportEntry;
  11785. dllImportEntry.mFuncVar = globalVar;
  11786. dllImportEntry.mMethodInstance = mCurMethodInstance;
  11787. mDllImportEntries.push_back(dllImportEntry);
  11788. }
  11789. }
  11790. BfIRCallingConv BfModule::GetCallingConvention(BfTypeInstance* typeInst, BfMethodDef* methodDef)
  11791. {
  11792. if (mSystem->mPtrSize == 8)
  11793. return BfIRCallingConv_CDecl;
  11794. if (methodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11795. return BfIRCallingConv_StdCall;
  11796. if ((!methodDef->mIsStatic) && (!typeInst->IsValuelessType()) &&
  11797. ((!typeInst->IsSplattable()) || (methodDef->HasNoThisSplat())))
  11798. return BfIRCallingConv_ThisCall;
  11799. return BfIRCallingConv_CDecl;
  11800. }
  11801. BfIRCallingConv BfModule::GetCallingConvention(BfMethodInstance* methodInstance)
  11802. {
  11803. return GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  11804. }
  11805. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  11806. {
  11807. BfMethodDef* methodDef = NULL;
  11808. if (methodInstance != NULL)
  11809. methodDef = methodInstance->mMethodDef;
  11810. if (!func)
  11811. return;
  11812. if (mCompiler->mOptions.mNoFramePointerElim)
  11813. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  11814. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  11815. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  11816. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  11817. if (methodInstance == NULL)
  11818. return;
  11819. if (methodDef->mImportKind == BfImportKind_Export)
  11820. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  11821. if (methodDef->mNoReturn)
  11822. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  11823. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  11824. if (callingConv != BfIRCallingConv_CDecl)
  11825. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  11826. if (isInlined)
  11827. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  11828. int argIdx = 0;
  11829. int paramIdx = 0;
  11830. if (methodInstance->HasThis())
  11831. {
  11832. paramIdx = -1;
  11833. }
  11834. int argCount = methodInstance->GetIRFunctionParamCount(this);
  11835. if (methodInstance->HasStructRet())
  11836. {
  11837. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  11838. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  11839. argIdx++;
  11840. }
  11841. while (argIdx < argCount)
  11842. {
  11843. while ((paramIdx != -1) && (methodInstance->IsParamSkipped(paramIdx)))
  11844. paramIdx++;
  11845. BfType* resolvedTypeRef = NULL;
  11846. String paramName;
  11847. bool isSplattable = false;
  11848. bool isThis = paramIdx == -1;
  11849. if (isThis)
  11850. {
  11851. paramName = "this";
  11852. if (methodInstance->mIsClosure)
  11853. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  11854. else
  11855. resolvedTypeRef = methodInstance->GetOwner();
  11856. isSplattable = (resolvedTypeRef->IsSplattable()) && (!methodDef->HasNoThisSplat());
  11857. }
  11858. else if (!methodDef->mNoSplat)
  11859. {
  11860. paramName = methodInstance->GetParamName(paramIdx);
  11861. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  11862. if (resolvedTypeRef->IsMethodRef())
  11863. isSplattable = true;
  11864. else if (resolvedTypeRef->IsSplattable())
  11865. {
  11866. if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  11867. isSplattable = true;
  11868. }
  11869. }
  11870. //
  11871. {
  11872. auto loweredTypeCode = resolvedTypeRef->GetLoweredType();
  11873. if (loweredTypeCode != BfTypeCode_None)
  11874. resolvedTypeRef = GetPrimitiveType(loweredTypeCode);
  11875. }
  11876. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  11877. {
  11878. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  11879. int addDeref = -1;
  11880. if (resolvedTypeRef->IsRef())
  11881. {
  11882. auto refType = (BfRefType*)resolvedTypeRef;
  11883. auto elementType = refType->mElementType;
  11884. PopulateType(elementType, BfPopulateType_Data);
  11885. addDeref = elementType->mSize;
  11886. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  11887. AssertErrorState();
  11888. }
  11889. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  11890. {
  11891. if (mCompiler->mOptions.mAllowStructByVal)
  11892. {
  11893. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal);
  11894. }
  11895. else
  11896. {
  11897. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  11898. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  11899. addDeref = resolvedTypeRef->mSize;
  11900. }
  11901. }
  11902. else if (resolvedTypeRef->IsPrimitiveType())
  11903. {
  11904. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  11905. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  11906. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  11907. }
  11908. if (addDeref >= 0)
  11909. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  11910. argIdx++;
  11911. };
  11912. if (isSplattable)
  11913. {
  11914. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  11915. {
  11916. if (checkType->IsStruct())
  11917. {
  11918. auto checkTypeInstance = checkType->ToTypeInstance();
  11919. if (checkTypeInstance->mBaseType != NULL)
  11920. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  11921. if (checkTypeInstance->mIsUnion)
  11922. {
  11923. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  11924. checkTypeLambda(unionInnerType, curName + "_data");
  11925. }
  11926. else
  11927. {
  11928. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11929. {
  11930. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11931. auto fieldDef = fieldInstance->GetFieldDef();
  11932. if (fieldInstance->mDataIdx >= 0)
  11933. {
  11934. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  11935. }
  11936. }
  11937. }
  11938. if (checkTypeInstance->IsEnum())
  11939. {
  11940. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  11941. argIdx++;
  11942. }
  11943. }
  11944. else if (checkType->IsMethodRef())
  11945. {
  11946. auto methodRefType = (BfMethodRefType*)checkType;
  11947. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  11948. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  11949. {
  11950. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  11951. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11952. {
  11953. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  11954. }
  11955. else
  11956. {
  11957. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  11958. }
  11959. }
  11960. }
  11961. else if (!checkType->IsValuelessType())
  11962. {
  11963. _SetupParam(curName, checkType);
  11964. }
  11965. };
  11966. checkTypeLambda(resolvedTypeRef, paramName);
  11967. paramIdx++;
  11968. continue;
  11969. }
  11970. _SetupParam(paramName, resolvedTypeRef);
  11971. //argIdx++;
  11972. paramIdx++;
  11973. }
  11974. }
  11975. void BfModule::EmitCtorBody(bool& skipBody)
  11976. {
  11977. auto methodInstance = mCurMethodInstance;
  11978. auto methodDef = methodInstance->mMethodDef;
  11979. auto methodDeclaration = methodDef->mMethodDeclaration;
  11980. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11981. auto typeDef = mCurTypeInstance->mTypeDef;
  11982. // Prologue
  11983. mBfIRBuilder->ClearDebugLocation();
  11984. bool hadThisInitializer = false;
  11985. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11986. {
  11987. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11988. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11989. if (targetToken->GetToken() == BfToken_This)
  11990. {
  11991. hadThisInitializer = true;
  11992. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  11993. mCurMethodState->LocalDefined(GetThisVariable());
  11994. }
  11995. }
  11996. // Zero out memory for default ctor
  11997. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  11998. {
  11999. if (mCurTypeInstance->IsTypedPrimitive())
  12000. {
  12001. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12002. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  12003. }
  12004. else if (mCurTypeInstance->mInstSize > 0)
  12005. {
  12006. BfIRValue fillValue = GetConstValue8(0);
  12007. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  12008. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12009. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12010. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  12011. }
  12012. }
  12013. BfAstNode* baseCtorNode = NULL;
  12014. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL) && (ctorDeclaration->mInitializer->mTarget != NULL))
  12015. baseCtorNode = ctorDeclaration->mInitializer->mTarget;
  12016. else if (methodDef->mBody != NULL)
  12017. baseCtorNode = methodDef->mBody;
  12018. else if (ctorDeclaration != NULL)
  12019. baseCtorNode = ctorDeclaration;
  12020. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  12021. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  12022. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  12023. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  12024. else
  12025. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  12026. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor))
  12027. {
  12028. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  12029. if (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension)
  12030. {
  12031. BfMethodDef* defaultCtor = NULL;
  12032. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  12033. {
  12034. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  12035. {
  12036. defaultCtor = methodDef;
  12037. }
  12038. }
  12039. if (defaultCtor != NULL)
  12040. {
  12041. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  12042. SetIllegalSrcPos();
  12043. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  12044. BfExprEvaluator exprEvaluator(this);
  12045. SizedArray<BfIRValue, 1> irArgs;
  12046. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  12047. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  12048. }
  12049. }
  12050. }
  12051. // Initialize fields (if applicable)
  12052. if (mCurTypeInstance->IsBoxed())
  12053. {
  12054. skipBody = true;
  12055. }
  12056. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  12057. {
  12058. // Field initializers occur in CtorNoBody methods for extensions
  12059. }
  12060. else if (!hadThisInitializer)
  12061. {
  12062. // If we had a 'this' initializer, that other ctor will have initialized our fields
  12063. if ((!mCompiler->mIsResolveOnly) ||
  12064. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  12065. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  12066. {
  12067. bool hadInlineInitBlock = false;
  12068. BfScopeData scopeData;
  12069. for (auto fieldDef : typeDef->mFields)
  12070. {
  12071. // For extensions, only handle these fields in the appropriate extension
  12072. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12073. continue;
  12074. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  12075. {
  12076. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12077. if (!fieldInst->mFieldIncluded)
  12078. continue;
  12079. if (fieldInst->mDataIdx < 0)
  12080. continue;
  12081. if (fieldDef->mInitializer == NULL)
  12082. {
  12083. if (fieldDef->mProtection != BfProtection_Hidden)
  12084. continue;
  12085. if (mCurTypeInstance->IsObject()) // Already zeroed out
  12086. continue;
  12087. }
  12088. if (fieldInst->mResolvedType == NULL)
  12089. {
  12090. BF_ASSERT(mHadBuildError);
  12091. continue;
  12092. }
  12093. if (fieldDef->mInitializer != NULL)
  12094. {
  12095. if (!hadInlineInitBlock)
  12096. {
  12097. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  12098. {
  12099. UpdateSrcPos(baseCtorNode);
  12100. // 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
  12101. EmitEnsureInstructionAt();
  12102. BfType* thisType = mCurTypeInstance;
  12103. if (thisType->IsValueType())
  12104. thisType = CreateRefType(thisType);
  12105. SizedArray<BfIRMDNode, 1> diParamTypes;
  12106. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  12107. mCurMethodState->AddScope(&scopeData);
  12108. NewScopeState();
  12109. int flags = 0;
  12110. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  12111. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  12112. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  12113. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  12114. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  12115. UpdateSrcPos(fieldDef->mInitializer);
  12116. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12117. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  12118. //
  12119. {
  12120. auto loadedThis = GetThis();
  12121. // LLVM can't handle two variables pointing to the same value
  12122. BfIRValue copiedThisPtr;
  12123. copiedThisPtr = CreateAlloca(thisType);
  12124. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  12125. mBfIRBuilder->ClearDebugLocation(storeInst);
  12126. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  12127. }
  12128. hadInlineInitBlock = true;
  12129. }
  12130. }
  12131. UpdateSrcPos(fieldDef->mInitializer);
  12132. }
  12133. BfIRValue fieldAddr;
  12134. if (!mCurTypeInstance->IsTypedPrimitive())
  12135. {
  12136. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  12137. }
  12138. else
  12139. {
  12140. AssertErrorState();
  12141. }
  12142. auto assignValue = GetFieldInitializerValue(fieldInst);
  12143. if ((fieldAddr) && (assignValue))
  12144. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  12145. }
  12146. }
  12147. if (hadInlineInitBlock)
  12148. {
  12149. RestoreScopeState();
  12150. // This gets set to false because of AddScope but we actually are still in the head block
  12151. mCurMethodState->mInHeadScope = true;
  12152. }
  12153. }
  12154. else // Autocomplete case
  12155. {
  12156. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  12157. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  12158. // resolve pass, NOT the autocomplete expression
  12159. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12160. {
  12161. if (tempTypeDef->mFullName == typeDef->mFullName)
  12162. {
  12163. for (auto fieldDef : tempTypeDef->mFields)
  12164. {
  12165. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12166. {
  12167. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12168. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12169. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12170. if ((wantType != NULL) &&
  12171. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  12172. wantType = NULL;
  12173. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12174. }
  12175. }
  12176. }
  12177. }
  12178. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  12179. for (auto fieldDef : typeDef->mFields)
  12180. {
  12181. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12182. {
  12183. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12184. if (fieldDef->mInitializer != NULL)
  12185. MarkFieldInitialized(fieldInst);
  12186. }
  12187. }
  12188. }
  12189. }
  12190. // Call base ctor (if applicable)
  12191. BfTypeInstance* targetType = NULL;
  12192. BfAstNode* targetRefNode = NULL;
  12193. if (ctorDeclaration != NULL)
  12194. targetRefNode = ctorDeclaration->mInitializer;
  12195. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  12196. targetRefNode = invocationExpr->mTarget;
  12197. if (baseCtorNode != NULL)
  12198. {
  12199. UpdateSrcPos(baseCtorNode);
  12200. }
  12201. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12202. {
  12203. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12204. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12205. }
  12206. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  12207. {
  12208. auto baseType = mCurTypeInstance->mBaseType;
  12209. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  12210. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  12211. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  12212. {
  12213. // Try to find a ctor without any params first
  12214. bool foundBaseCtor = false;
  12215. bool hadCtorWithAllDefaults = false;
  12216. for (int pass = 0; pass < 2; pass++)
  12217. {
  12218. for (auto checkMethodDef : baseType->mTypeDef->mMethods)
  12219. {
  12220. bool allowPriv = checkMethodDef->mProtection != BfProtection_Private;
  12221. // Allow calling of the default base ctor if it is implicitly defined
  12222. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  12223. allowPriv = true;
  12224. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowPriv))
  12225. {
  12226. if (checkMethodDef->mParams.size() == 0)
  12227. {
  12228. foundBaseCtor = true;
  12229. if (HasCompiledOutput())
  12230. {
  12231. SizedArray<BfIRValue, 1> args;
  12232. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, checkMethodDef, BfTypeVector());
  12233. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12234. {
  12235. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  12236. args.push_back(basePtr);
  12237. }
  12238. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  12239. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  12240. auto callingConv = GetCallingConvention(ctorBodyMethodInstance.mMethodInstance->GetOwner(), ctorBodyMethodInstance.mMethodInstance->mMethodDef);
  12241. if (callingConv != BfIRCallingConv_CDecl)
  12242. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  12243. // if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12244. // mBfIRBuilder->SetCallCallingConv(callInst, BfIRCallingConv_ThisCall);
  12245. break;
  12246. }
  12247. }
  12248. else if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  12249. hadCtorWithAllDefaults = true;
  12250. }
  12251. }
  12252. if (foundBaseCtor)
  12253. break;
  12254. }
  12255. if (!foundBaseCtor)
  12256. {
  12257. targetType = mCurTypeInstance->mBaseType;
  12258. if (ctorDeclaration != NULL)
  12259. targetRefNode = ctorDeclaration->mThisToken;
  12260. else if (typeDef->mTypeDeclaration != NULL)
  12261. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  12262. }
  12263. }
  12264. }
  12265. if (methodDef->mHasAppend)
  12266. {
  12267. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  12268. }
  12269. if (targetType != NULL)
  12270. {
  12271. auto autoComplete = mCompiler->GetAutoComplete();
  12272. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  12273. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12274. {
  12275. auto invocationExpr = ctorDeclaration->mInitializer;
  12276. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  12277. }
  12278. BfType* targetThisType = targetType;
  12279. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  12280. BfExprEvaluator exprEvaluator(this);
  12281. BfResolvedArgs argValues;
  12282. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12283. {
  12284. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  12285. if (gDebugStuff)
  12286. {
  12287. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  12288. }
  12289. }
  12290. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12291. BfTypedValue appendIdxVal;
  12292. if (methodDef->mHasAppend)
  12293. {
  12294. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  12295. BF_ASSERT(localVar->mName == "appendIdx");
  12296. auto intRefType = CreateRefType(localVar->mResolvedType);
  12297. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  12298. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  12299. }
  12300. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  12301. if (autoComplete != NULL)
  12302. {
  12303. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  12304. {
  12305. if (autoComplete->mMethodMatchInfo != NULL)
  12306. autoComplete->mIsCapturingMethodMatchInfo = true;
  12307. else
  12308. autoComplete->mIsCapturingMethodMatchInfo = false;
  12309. }
  12310. else
  12311. autoComplete->mIsCapturingMethodMatchInfo = false;
  12312. }
  12313. }
  12314. }
  12315. void BfModule::EmitEnumToStringBody()
  12316. {
  12317. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12318. auto strVal = CreateAlloca(stringType);
  12319. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  12320. BfExprEvaluator exprEvaluator(this);
  12321. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12322. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  12323. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  12324. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  12325. BfType* discriminatorType = NULL;
  12326. BfTypedValue rawPayload;
  12327. BfIRValue enumVal;
  12328. if (mCurTypeInstance->IsPayloadEnum())
  12329. {
  12330. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  12331. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  12332. enumTypedValue = LoadValue(enumTypedValue);
  12333. enumVal = enumTypedValue.mValue;
  12334. rawPayload = ExtractValue(GetThis(), NULL, 1);
  12335. }
  12336. else
  12337. enumVal = mBfIRBuilder->GetArgument(0);
  12338. Array<BfType*> paramTypes;
  12339. paramTypes.Add(stringType);
  12340. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12341. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  12342. HashSet<int64> handledCases;
  12343. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12344. {
  12345. if (fieldInstance.mIsEnumPayloadCase)
  12346. {
  12347. int tagId = -fieldInstance.mDataIdx - 1;
  12348. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12349. mBfIRBuilder->AddBlock(caseBlock);
  12350. mBfIRBuilder->SetInsertPoint(caseBlock);
  12351. BF_ASSERT(discriminatorType->IsPrimitiveType());
  12352. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  12353. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12354. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12355. auto stringDestVal = LoadValue(stringDestAddr);
  12356. SizedArray<BfIRValue, 2> args;
  12357. args.Add(stringDestVal.mValue);
  12358. args.Add(caseStr);
  12359. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12360. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  12361. BF_ASSERT(payloadType->IsTuple());
  12362. if (payloadType->mFieldInstances.size() != 0)
  12363. {
  12364. auto payload = rawPayload;
  12365. if (payload.mType != payloadType)
  12366. {
  12367. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  12368. }
  12369. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  12370. SizedArray<BfIRValue, 2> irArgs;
  12371. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  12372. stringDestVal = LoadValue(stringDestAddr);
  12373. irArgs.Add(stringDestVal.mValue);
  12374. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  12375. }
  12376. mBfIRBuilder->CreateBr(endBlock);
  12377. continue;
  12378. }
  12379. if (fieldInstance.mConstIdx == -1)
  12380. continue;
  12381. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  12382. if (!handledCases.TryAdd(constant->mInt64, NULL))
  12383. {
  12384. // Duplicate
  12385. continue;
  12386. }
  12387. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12388. mBfIRBuilder->AddBlock(caseBlock);
  12389. mBfIRBuilder->SetInsertPoint(caseBlock);
  12390. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  12391. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12392. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12393. mBfIRBuilder->CreateStore(caseStr, strVal);
  12394. mBfIRBuilder->CreateBr(appendBlock);
  12395. }
  12396. mBfIRBuilder->AddBlock(appendBlock);
  12397. mBfIRBuilder->SetInsertPoint(appendBlock);
  12398. SizedArray<BfIRValue, 2> args;
  12399. auto stringDestVal = LoadValue(stringDestAddr);
  12400. args.Add(stringDestVal.mValue);
  12401. args.Add(mBfIRBuilder->CreateLoad(strVal));
  12402. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12403. mBfIRBuilder->CreateBr(endBlock);
  12404. mBfIRBuilder->AddBlock(noMatchBlock);
  12405. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  12406. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  12407. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  12408. args.clear();
  12409. args.Add(int64Val);
  12410. stringDestVal = LoadValue(stringDestAddr);
  12411. args.Add(stringDestVal.mValue);
  12412. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  12413. mBfIRBuilder->CreateBr(endBlock);
  12414. mBfIRBuilder->AddBlock(endBlock);
  12415. mBfIRBuilder->SetInsertPoint(endBlock);
  12416. }
  12417. void BfModule::EmitTupleToStringBody()
  12418. {
  12419. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12420. BfExprEvaluator exprEvaluator(this);
  12421. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12422. Array<BfType*> paramTypes;
  12423. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  12424. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12425. paramTypes.Clear();
  12426. paramTypes.Add(stringType);
  12427. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12428. auto _AppendChar = [&](char c)
  12429. {
  12430. SizedArray<BfIRValue, 2> args;
  12431. auto stringDestVal = LoadValue(stringDestRef);
  12432. args.Add(stringDestVal.mValue);
  12433. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  12434. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  12435. };
  12436. int fieldIdx = 0;
  12437. auto thisValue = GetThis();
  12438. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  12439. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  12440. BfIRValue commaStr;
  12441. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  12442. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  12443. _AppendChar('(');
  12444. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12445. {
  12446. if (fieldInstance.mDataIdx == -1)
  12447. continue;
  12448. if (fieldIdx > 0)
  12449. {
  12450. if (!commaStr)
  12451. commaStr = GetStringObjectValue(", ");
  12452. SizedArray<BfIRValue, 2> args;
  12453. auto stringDestVal = LoadValue(stringDestRef);
  12454. args.Add(stringDestVal.mValue);
  12455. args.Add(commaStr);
  12456. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12457. }
  12458. fieldIdx++;
  12459. if (fieldInstance.mResolvedType->IsValuelessType())
  12460. continue;
  12461. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  12462. if (fieldValue.mType->IsPrimitiveType())
  12463. {
  12464. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  12465. }
  12466. auto typeInstance = fieldValue.mType->ToTypeInstance();
  12467. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  12468. {
  12469. BfExprEvaluator exprEvaluator(this);
  12470. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12471. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  12472. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  12473. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  12474. methodMatcher.TryDevirtualizeCall(fieldValue);
  12475. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12476. BfResolvedArg resolvedArg;
  12477. auto stringDestVal = LoadValue(stringDestRef);
  12478. resolvedArg.mTypedValue = stringDestVal;
  12479. resolvedArg.mResolvedType = stringDestVal.mType;
  12480. resolvedArgs.Add(resolvedArg);
  12481. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12482. continue;
  12483. }
  12484. if (fieldValue.mType->IsObjectOrInterface())
  12485. {
  12486. BF_ASSERT(!fieldValue.IsAddr());
  12487. SizedArray<BfIRValue, 2> args;
  12488. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  12489. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12490. stringDestVal = LoadValue(stringDestVal);
  12491. args.Add(stringDestVal.mValue);
  12492. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  12493. continue;
  12494. }
  12495. BfExprEvaluator exprEvaluator(this);
  12496. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12497. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  12498. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  12499. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  12500. methodMatcher.TryDevirtualizeCall(fieldValue);
  12501. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  12502. {
  12503. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  12504. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12505. // Just append the type name
  12506. String typeName = TypeToString(fieldInstance.mResolvedType);
  12507. auto strVal = GetStringObjectValue(typeName);
  12508. SizedArray<BfIRValue, 2> args;
  12509. auto stringDestVal = LoadValue(stringDestRef);
  12510. args.Add(stringDestVal.mValue);
  12511. args.Add(strVal);
  12512. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12513. continue;
  12514. }
  12515. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12516. BfResolvedArg resolvedArg;
  12517. auto stringDestVal = LoadValue(stringDestRef);
  12518. resolvedArg.mTypedValue = stringDestVal;
  12519. resolvedArg.mResolvedType = stringDestVal.mType;
  12520. resolvedArgs.Add(resolvedArg);
  12521. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12522. }
  12523. _AppendChar(')');
  12524. }
  12525. void BfModule::EmitIteratorBlock(bool& skipBody)
  12526. {
  12527. auto methodInstance = mCurMethodInstance;
  12528. auto methodDef = methodInstance->mMethodDef;
  12529. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12530. auto typeDef = mCurTypeInstance->mTypeDef;
  12531. BfType* innerRetType = NULL;
  12532. BfTypeInstance* usingInterface = NULL;
  12533. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  12534. if (retTypeInst != NULL)
  12535. {
  12536. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  12537. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  12538. {
  12539. innerRetType = retTypeInst->mTypeGenericArguments[0];
  12540. }
  12541. }
  12542. if (innerRetType == NULL)
  12543. {
  12544. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  12545. return;
  12546. }
  12547. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  12548. if (blockBody == NULL)
  12549. return;
  12550. }
  12551. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  12552. {
  12553. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  12554. if (fieldTypeInst == NULL)
  12555. return;
  12556. if (!markVal.mType->IsComposite())
  12557. markVal = LoadValue(markVal);
  12558. BfExprEvaluator exprEvaluator(this);
  12559. PopulateType(markVal.mType, BfPopulateType_Data);
  12560. if (markVal.mType->IsObjectOrInterface())
  12561. {
  12562. BfIRValue val = markVal.mValue;
  12563. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  12564. SizedArray<BfIRValue, 1> args;
  12565. args.push_back(val);
  12566. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  12567. }
  12568. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  12569. {
  12570. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  12571. if (markMemberMethodInstance)
  12572. {
  12573. SizedArray<BfIRValue, 1> args;
  12574. //(1, markVal.mValue);
  12575. //exprEvaluator.PushArg(markVal, args);
  12576. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  12577. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  12578. }
  12579. }
  12580. }
  12581. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  12582. {
  12583. Array<BfMethodInstance*> methodInstances;
  12584. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  12585. {
  12586. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  12587. auto chainedMethodInst = methodInstGroup.mDefault;
  12588. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  12589. {
  12590. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  12591. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  12592. {
  12593. methodInstances.push_back(chainedMethodInst);
  12594. }
  12595. }
  12596. }
  12597. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  12598. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  12599. {
  12600. bool isBetter;
  12601. bool isWorse;
  12602. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  12603. if (isBetter == isWorse)
  12604. {
  12605. return false;
  12606. }
  12607. return isWorse;
  12608. });
  12609. if (reverse)
  12610. std::reverse(methodInstances.begin(), methodInstances.end());
  12611. for (auto chainedMethodInst : methodInstances)
  12612. {
  12613. auto declModule = this;
  12614. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  12615. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  12616. BfExprEvaluator exprEvaluator(this);
  12617. SizedArray<BfIRValue, 1> args;
  12618. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  12619. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  12620. }
  12621. }
  12622. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  12623. {
  12624. BF_ASSERT(mCurMethodInstance->mIsReified);
  12625. if (mCurTypeInstance->mHotTypeData == NULL)
  12626. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  12627. auto hotMethod = mCurMethodInstance->mHotMethod;
  12628. for (auto depData : hotMethod->mReferences)
  12629. {
  12630. // Only virtual decls are allowed to already be there
  12631. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  12632. }
  12633. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  12634. int prevSize = (int)hotMethod->mReferences.size();
  12635. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  12636. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12637. refCount++;
  12638. hotMethod->mReferences.Reserve(refCount);
  12639. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12640. {
  12641. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  12642. hotThis->mRefCount++;
  12643. hotMethod->mReferences.Insert(0, hotThis);
  12644. prevSize++;
  12645. }
  12646. for (auto val : builder->mAllocatedData)
  12647. {
  12648. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  12649. hotMethod->mReferences.Add(hotAllocation);
  12650. }
  12651. for (auto val : builder->mUsedData)
  12652. hotMethod->mReferences.Add(val);
  12653. for (auto val : builder->mCalledMethods)
  12654. hotMethod->mReferences.Add(val);
  12655. for (auto val : builder->mDevirtualizedCalledMethods)
  12656. {
  12657. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  12658. hotMethod->mReferences.Add(devirtualizedMethod);
  12659. }
  12660. for (auto val : builder->mFunctionPtrs)
  12661. {
  12662. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  12663. hotMethod->mReferences.Add(funcRef);
  12664. }
  12665. for (auto val : builder->mInnerMethods)
  12666. {
  12667. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  12668. hotMethod->mReferences.Add(innerMethod);
  12669. }
  12670. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  12671. {
  12672. auto depData = hotMethod->mReferences[refIdx];
  12673. BF_ASSERT(depData != NULL);
  12674. depData->mRefCount++;
  12675. }
  12676. //hotMethod->mReferences.Sort([](BfHotDepData* lhs, BfHotDepData* rhs) { return lhs < rhs; });
  12677. }
  12678. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  12679. {
  12680. auto methodDef = methodInstance->mMethodDef;
  12681. auto methodDeclaration = methodDef->mMethodDeclaration;
  12682. bool isThisStruct = false;
  12683. if (thisType != NULL)
  12684. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  12685. int argIdx = 0;
  12686. if (methodInstance->HasStructRet())
  12687. argIdx++;
  12688. if (!methodDef->mIsStatic)
  12689. {
  12690. BfLocalVariable* paramVar = new BfLocalVariable();
  12691. paramVar->mResolvedType = thisType;
  12692. paramVar->mName = "this";
  12693. if (!thisType->IsValuelessType())
  12694. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12695. else
  12696. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12697. if ((thisType->IsComposite()) && (!methodDef->HasNoThisSplat()))
  12698. {
  12699. if (thisType->IsSplattable())
  12700. paramVar->mIsSplat = true;
  12701. else
  12702. paramVar->mIsLowered = thisType->GetLoweredType() != BfTypeCode_None;
  12703. }
  12704. auto thisTypeInst = thisType->ToTypeInstance();
  12705. paramVar->mIsStruct = isThisStruct;
  12706. paramVar->mAddr = BfIRValue();
  12707. paramVar->mIsThis = true;
  12708. paramVar->mParamIdx = -1;
  12709. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  12710. {
  12711. paramVar->mIsAssigned = false;
  12712. }
  12713. else
  12714. {
  12715. paramVar->mIsAssigned = true;
  12716. }
  12717. paramVar->mReadFromId = -1;
  12718. paramVar->Init();
  12719. if (methodDeclaration == NULL)
  12720. UseDefaultSrcPos();
  12721. AddLocalVariableDef(paramVar);
  12722. if (!thisType->IsValuelessType())
  12723. {
  12724. if (wantsDIData)
  12725. {
  12726. BfType* thisPtrType = thisType;
  12727. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  12728. if (!thisType->IsValueType())
  12729. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  12730. diParams->push_back(diType);
  12731. }
  12732. if (paramVar->mIsSplat)
  12733. {
  12734. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12735. }
  12736. else
  12737. {
  12738. argIdx++;
  12739. }
  12740. }
  12741. }
  12742. bool hadParams = false;
  12743. bool hasDefault = false;
  12744. int compositeVariableIdx = -1;
  12745. int paramIdx = 0;
  12746. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12747. {
  12748. // We already issues a type error for this param if we had one in declaration processing
  12749. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  12750. BfLocalVariable* paramVar = new BfLocalVariable();
  12751. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  12752. BfType* unresolvedType = methodInstance->GetParamType(paramIdx, false);
  12753. if (unresolvedType == NULL)
  12754. {
  12755. AssertErrorState();
  12756. unresolvedType = mContext->mBfObjectType;
  12757. paramVar->mParamFailed = true;
  12758. }
  12759. auto resolvedType = methodInstance->GetParamType(paramIdx, true);
  12760. prevIgnoreErrors.Restore();
  12761. PopulateType(resolvedType, BfPopulateType_Declaration);
  12762. paramVar->mResolvedType = resolvedType;
  12763. paramVar->mName = methodInstance->GetParamName(paramIdx);
  12764. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  12765. if (!isParamSkipped)
  12766. {
  12767. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12768. if (resolvedType->IsMethodRef())
  12769. {
  12770. paramVar->mIsSplat = true;
  12771. }
  12772. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  12773. {
  12774. int splatCount = resolvedType->GetSplatCount();
  12775. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  12776. paramVar->mIsSplat = true;
  12777. }
  12778. }
  12779. else
  12780. {
  12781. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  12782. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12783. }
  12784. paramVar->mIsLowered = resolvedType->GetLoweredType() != BfTypeCode_None;
  12785. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  12786. paramVar->mParamIdx = paramIdx;
  12787. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  12788. paramVar->mReadFromId = 0;
  12789. if (resolvedType->IsRef())
  12790. {
  12791. auto refType = (BfRefType*)resolvedType;
  12792. paramVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  12793. }
  12794. else
  12795. {
  12796. paramVar->mIsAssigned = true;
  12797. if (methodDef->mMethodType != BfMethodType_Mixin)
  12798. paramVar->mIsReadOnly = true;
  12799. }
  12800. if (paramVar->mResolvedType->IsGenericParam())
  12801. {
  12802. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  12803. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  12804. {
  12805. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  12806. paramVar->mResolvedType = typedVal.mType;
  12807. paramVar->mConstValue = typedVal.mValue;
  12808. }
  12809. }
  12810. if (paramVar->mResolvedType->IsConstExprValue())
  12811. {
  12812. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  12813. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  12814. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  12815. BF_ASSERT(unspecParamType->IsGenericParam());
  12816. if (unspecParamType->IsGenericParam())
  12817. {
  12818. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  12819. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  12820. {
  12821. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12822. if (genericParamInst->mTypeConstraint != NULL)
  12823. {
  12824. BfExprEvaluator exprEvaluator(this);
  12825. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  12826. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  12827. auto checkType = genericParamInst->mTypeConstraint;
  12828. if (checkType->IsTypedPrimitive())
  12829. checkType = checkType->GetUnderlyingType();
  12830. if (exprEvaluator.mResult.mType == checkType)
  12831. {
  12832. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12833. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  12834. BF_ASSERT(paramVar->mConstValue.IsConst());
  12835. }
  12836. else
  12837. {
  12838. AssertErrorState();
  12839. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12840. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  12841. }
  12842. }
  12843. }
  12844. }
  12845. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  12846. if (paramVar->mResolvedType->IsConstExprValue())
  12847. {
  12848. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  12849. //AssertErrorState();
  12850. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  12851. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  12852. }
  12853. }
  12854. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  12855. {
  12856. if (compositeVariableIdx == -1)
  12857. {
  12858. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  12859. BfLocalVariable* localVar = new BfLocalVariable();
  12860. auto paramInst = &methodInstance->mParams[paramIdx];
  12861. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  12862. localVar->mName = paramDef->mName;
  12863. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12864. localVar->mCompositeCount = 0;
  12865. DoAddLocalVariable(localVar);
  12866. }
  12867. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  12868. }
  12869. CheckVariableDef(paramVar);
  12870. paramVar->Init();
  12871. AddLocalVariableDef(paramVar);
  12872. if (!isParamSkipped)
  12873. {
  12874. if (wantsDIData)
  12875. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  12876. if (paramVar->mIsSplat)
  12877. {
  12878. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12879. }
  12880. else
  12881. {
  12882. argIdx++;
  12883. }
  12884. }
  12885. }
  12886. // Try to find an ending delegate params composite
  12887. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  12888. {
  12889. auto paramDef = methodDef->mParams.back();
  12890. if (paramDef->mParamKind == BfParamKind_Params)
  12891. {
  12892. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12893. if (paramsType == NULL)
  12894. {
  12895. AssertErrorState();
  12896. }
  12897. else if (paramsType->IsGenericParam())
  12898. {
  12899. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  12900. if (genericParamInstance->mTypeConstraint != NULL)
  12901. {
  12902. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  12903. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  12904. ((typeInstConstraint != NULL) &&
  12905. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  12906. {
  12907. BfLocalVariable* localVar = new BfLocalVariable();
  12908. localVar->mName = paramDef->mName;
  12909. localVar->mResolvedType = paramsType;
  12910. localVar->mCompositeCount = 0;
  12911. DoAddLocalVariable(localVar);
  12912. }
  12913. }
  12914. }
  12915. else if (paramsType->IsDelegate())
  12916. {
  12917. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  12918. if (invokeMethodInstance != NULL)
  12919. {
  12920. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  12921. // and wasn't cleared by the preceding loop
  12922. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  12923. BfLocalVariable* localVar = new BfLocalVariable();
  12924. localVar->mName = paramDef->mName;
  12925. localVar->mResolvedType = paramsType;
  12926. localVar->mCompositeCount = 0;
  12927. DoAddLocalVariable(localVar);
  12928. }
  12929. }
  12930. }
  12931. }
  12932. }
  12933. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  12934. {
  12935. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  12936. // return;
  12937. auto _ClearState = [&]()
  12938. {
  12939. mCurMethodState->mLocalMethods.Clear();
  12940. for (auto& local : mCurMethodState->mLocals)
  12941. delete local;
  12942. mCurMethodState->mLocals.Clear();
  12943. mCurMethodState->mLocalVarSet.Clear();
  12944. };
  12945. // 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
  12946. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  12947. // however (compiler bug), so this is the safest way
  12948. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  12949. {
  12950. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  12951. {
  12952. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  12953. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  12954. if (!mHadBuildError)
  12955. {
  12956. // Process as a closure - that allows us to look back and see the const locals and stuff
  12957. BfClosureState closureState;
  12958. mCurMethodState->mClosureState = &closureState;
  12959. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  12960. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  12961. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  12962. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  12963. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  12964. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  12965. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  12966. _ClearState();
  12967. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  12968. {
  12969. auto localVar = new BfLocalVariable();
  12970. *localVar = constLocal;
  12971. DoAddLocalVariable(localVar);
  12972. }
  12973. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  12974. bool doProcess = !mCompiler->mCanceling;
  12975. if (doProcess)
  12976. {
  12977. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  12978. ProcessMethod(deferredLocalMethod->mMethodInstance);
  12979. }
  12980. }
  12981. delete deferredLocalMethod;
  12982. mSystem->CheckLockYield();
  12983. }
  12984. }
  12985. for (auto& kv : mCurMethodState->mLocalMethodCache)
  12986. {
  12987. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  12988. }
  12989. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  12990. {
  12991. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  12992. {
  12993. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  12994. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  12995. BfClosureState closureState;
  12996. mCurMethodState->mClosureState = &closureState;
  12997. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  12998. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  12999. if (lambdaInstance->mClosureTypeInstance != NULL)
  13000. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  13001. else
  13002. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  13003. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13004. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  13005. _ClearState();
  13006. for (auto& constLocal : lambdaInstance->mConstLocals)
  13007. {
  13008. //if (constLocal.mIsThis)
  13009. {
  13010. // Valueless 'this'
  13011. closureState.mConstLocals.Add(constLocal);
  13012. }
  13013. /*else
  13014. {
  13015. auto localVar = new BfLocalVariable();
  13016. *localVar = constLocal;
  13017. DoAddLocalVariable(localVar);
  13018. }*/
  13019. }
  13020. BfMethodInstanceGroup methodInstanceGroup;
  13021. methodInstanceGroup.mOwner = mCurTypeInstance;
  13022. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  13023. bool doProcess = !mCompiler->mCanceling;
  13024. if (doProcess)
  13025. {
  13026. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  13027. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13028. ProcessMethod(lambdaInstance->mMethodInstance);
  13029. if (lambdaInstance->mDtorMethodInstance != NULL)
  13030. {
  13031. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13032. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  13033. }
  13034. }
  13035. }
  13036. mSystem->CheckLockYield();
  13037. }
  13038. }
  13039. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  13040. {
  13041. if (checkType->IsComposite())
  13042. PopulateType(checkType, BfPopulateType_Data);
  13043. if (!checkType->WantsGCMarking())
  13044. return;
  13045. auto typeInstance = checkType->ToTypeInstance();
  13046. bool callMarkMethod = false;
  13047. // Call the actual marking method
  13048. if (memberDepth == 0)
  13049. {
  13050. // Don't call marking method on self
  13051. }
  13052. else if (checkType->IsObjectOrInterface())
  13053. {
  13054. if (!objectOffsets.Add(curOffset))
  13055. {
  13056. return;
  13057. }
  13058. callMarkMethod = true;
  13059. }
  13060. else if (checkType->IsSizedArray())
  13061. {
  13062. callMarkMethod = true;
  13063. }
  13064. else if (typeInstance != NULL)
  13065. {
  13066. typeInstance->mTypeDef->PopulateMemberSets();
  13067. BfMemberSetEntry* entry = NULL;
  13068. BfMethodDef* methodDef = NULL;
  13069. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  13070. {
  13071. methodDef = (BfMethodDef*)entry->mMemberDef;
  13072. if (methodDef->HasBody())
  13073. {
  13074. callMarkMethod = true;
  13075. }
  13076. }
  13077. }
  13078. if (callMarkMethod)
  13079. {
  13080. BfTypedValue markValue;
  13081. auto memberType = checkType;
  13082. if (memberType->IsObjectOrInterface())
  13083. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  13084. auto memberPtrType = CreatePointerType(memberType);
  13085. if (curOffset == 0)
  13086. {
  13087. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13088. }
  13089. else
  13090. {
  13091. if (!thisValue.mType->IsPointer())
  13092. {
  13093. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  13094. auto int8PtrType = CreatePointerType(int8Type);
  13095. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  13096. }
  13097. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  13098. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13099. }
  13100. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13101. return;
  13102. }
  13103. auto methodDef = mCurMethodInstance->mMethodDef;
  13104. if (checkType->IsPayloadEnum())
  13105. {
  13106. for (auto& fieldInst : typeInstance->mFieldInstances)
  13107. {
  13108. if (!fieldInst.mIsEnumPayloadCase)
  13109. continue;
  13110. auto fieldDef = fieldInst.GetFieldDef();
  13111. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13112. }
  13113. return;
  13114. }
  13115. if (typeInstance == NULL)
  13116. return;
  13117. for (auto& fieldInst : typeInstance->mFieldInstances)
  13118. {
  13119. auto fieldDef = fieldInst.GetFieldDef();
  13120. if (fieldDef == NULL)
  13121. continue;
  13122. if (fieldDef->mIsStatic)
  13123. continue;
  13124. if (typeInstance == mCurTypeInstance)
  13125. {
  13126. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  13127. // we may be marking member values that can never contain a value anyway, but this is benign
  13128. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13129. continue;
  13130. }
  13131. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  13132. }
  13133. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  13134. {
  13135. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13136. }
  13137. }
  13138. void BfModule::EmitGCMarkMembers()
  13139. {
  13140. auto methodDef = mCurMethodInstance->mMethodDef;
  13141. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  13142. BfModuleMethodInstance markFromGCThreadMethodInstance;
  13143. if (gcType != NULL)
  13144. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  13145. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  13146. {
  13147. if (mCurTypeInstance->IsBoxed())
  13148. {
  13149. // This already gets filled in by the normal boxed forwarding
  13150. }
  13151. else
  13152. {
  13153. auto thisValue = GetThis();
  13154. if (thisValue.IsSplat())
  13155. {
  13156. BfIRFunction func = mCurMethodInstance->mIRFunction;
  13157. int argIdx = 0;
  13158. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  13159. {
  13160. if (checkType->IsStruct())
  13161. {
  13162. auto checkTypeInstance = checkType->ToTypeInstance();
  13163. if (checkTypeInstance->mBaseType != NULL)
  13164. checkTypeLambda(checkTypeInstance->mBaseType);
  13165. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13166. {
  13167. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13168. if (fieldInstance->mDataIdx >= 0)
  13169. checkTypeLambda(fieldInstance->GetResolvedType());
  13170. }
  13171. }
  13172. else if (checkType->IsMethodRef())
  13173. {
  13174. BF_FATAL("Not handled");
  13175. }
  13176. else if (checkType->WantsGCMarking())
  13177. {
  13178. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  13179. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13180. argIdx++;
  13181. }
  13182. };
  13183. checkTypeLambda(thisValue.mType);
  13184. }
  13185. else if (!methodDef->mIsStatic)
  13186. {
  13187. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  13188. {
  13189. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  13190. if (moduleMethodInst)
  13191. {
  13192. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  13193. if (methodBaseType != mContext->mBfObjectType)
  13194. {
  13195. auto thisValue = GetThis();
  13196. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  13197. SizedArray<BfIRValue, 1> args;
  13198. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  13199. {
  13200. BfExprEvaluator exprEvaluator(this);
  13201. exprEvaluator.SplatArgs(baseValue, args);
  13202. }
  13203. else
  13204. {
  13205. args.push_back(baseValue.mValue);
  13206. }
  13207. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  13208. }
  13209. }
  13210. }
  13211. }
  13212. if (!methodDef->mIsStatic)
  13213. {
  13214. HashSet<int> objectOffsets;
  13215. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  13216. }
  13217. else
  13218. {
  13219. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13220. {
  13221. if (thisValue.IsSplat())
  13222. break;
  13223. auto fieldDef = fieldInst.GetFieldDef();
  13224. if (fieldDef == NULL)
  13225. continue;
  13226. if (fieldInst.mIsThreadLocal)
  13227. continue;
  13228. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  13229. {
  13230. // For extensions, only handle these fields in the appropriate extension
  13231. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13232. continue;
  13233. if (!fieldInst.mFieldIncluded)
  13234. continue;
  13235. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  13236. if (fieldTypeInst != NULL)
  13237. {
  13238. auto fieldDef = fieldInst.GetFieldDef();
  13239. BfTypedValue markVal;
  13240. if (fieldDef->mIsConst)
  13241. continue;
  13242. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  13243. continue;
  13244. mBfIRBuilder->PopulateType(fieldTypeInst);
  13245. if (fieldTypeInst->IsValuelessType())
  13246. continue;
  13247. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  13248. {
  13249. markVal = ReferenceStaticField(&fieldInst);
  13250. }
  13251. else if (!fieldDef->mIsStatic)
  13252. {
  13253. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  13254. }
  13255. if (markVal)
  13256. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  13257. }
  13258. }
  13259. }
  13260. }
  13261. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13262. CallChainedMethods(mCurMethodInstance, false);
  13263. }
  13264. }
  13265. }
  13266. void BfModule::EmitGCFindTLSMembers()
  13267. {
  13268. auto methodDef = mCurMethodInstance->mMethodDef;
  13269. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  13270. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  13271. BF_ASSERT(reportTLSMark);
  13272. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13273. {
  13274. auto fieldDef = fieldInst.GetFieldDef();
  13275. if (fieldDef == NULL)
  13276. continue;
  13277. if (!fieldInst.mIsThreadLocal)
  13278. continue;
  13279. // For extensions, only handle these fields in the appropriate extension
  13280. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13281. continue;
  13282. if (!fieldInst.mFieldIncluded)
  13283. continue;
  13284. if (fieldDef->mIsConst)
  13285. continue;
  13286. auto fieldType = fieldInst.mResolvedType;
  13287. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  13288. continue;
  13289. if (fieldType->IsValuelessType())
  13290. continue;
  13291. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  13292. if (markVal)
  13293. {
  13294. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  13295. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  13296. SizedArray<BfIRValue, 2> llvmArgs;
  13297. llvmArgs.push_back(fieldRefPtr);
  13298. llvmArgs.push_back(markFuncPtr);
  13299. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  13300. }
  13301. }
  13302. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13303. CallChainedMethods(mCurMethodInstance, false);
  13304. }
  13305. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  13306. {
  13307. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  13308. if (mAwaitingInitFinish)
  13309. FinishInit();
  13310. if (!methodInstance->mIsReified)
  13311. BF_ASSERT(!mIsReified);
  13312. if (methodInstance->mMethodInfoEx != NULL)
  13313. {
  13314. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13315. {
  13316. if (methodGenericArg->IsMethodRef())
  13317. {
  13318. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  13319. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  13320. }
  13321. }
  13322. }
  13323. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  13324. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  13325. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  13326. {
  13327. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  13328. }
  13329. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  13330. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  13331. (mCompiler->mResolvePassData != NULL))
  13332. {
  13333. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  13334. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  13335. }
  13336. if (methodInstance->mHasBeenProcessed)
  13337. {
  13338. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  13339. return;
  13340. }
  13341. if (methodInstance->mFailedConstraints)
  13342. {
  13343. // The only way this should be able to happen is if we fail our generic param check
  13344. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  13345. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  13346. methodInstance->mHasBeenProcessed = true;
  13347. return;
  13348. }
  13349. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  13350. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  13351. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  13352. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  13353. {
  13354. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13355. auto owningModule = methodInstance->GetOwner()->mModule;
  13356. if (owningModule->mIsScratchModule)
  13357. {
  13358. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  13359. }
  13360. else
  13361. {
  13362. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  13363. if (owningModule->mOnDemandMethodCount > 0)
  13364. owningModule->mOnDemandMethodCount--;
  13365. }
  13366. }
  13367. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  13368. // self-referencing append allocations in ctor@calcAppend
  13369. methodInstance->mHasBeenProcessed = true;
  13370. mIncompleteMethodCount--;
  13371. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  13372. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  13373. auto methodDef = methodInstance->mMethodDef;
  13374. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13375. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  13376. {
  13377. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  13378. // so we get the new vdata for it
  13379. methodInstance->GetOwner()->mDirty = true;
  13380. }
  13381. int dependentGenericStartIdx = 0;
  13382. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  13383. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  13384. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13385. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  13386. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  13387. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  13388. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  13389. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  13390. if ((methodInstance->mIsReified) &&
  13391. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  13392. {
  13393. mCurTypeInstance->mHasBeenInstantiated = true;
  13394. }
  13395. // Warnings are shown in the capture phase
  13396. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  13397. mIgnoreWarnings = true;
  13398. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  13399. UseDefaultSrcPos();
  13400. // We may not actually be populated in relatively rare autocompelte cases
  13401. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  13402. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  13403. BfAstNode* nameNode = NULL;
  13404. if (methodDeclaration != NULL)
  13405. {
  13406. nameNode = methodDeclaration->mNameNode;
  13407. if (nameNode == NULL)
  13408. {
  13409. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  13410. nameNode = ctorDeclaration->mThisToken;
  13411. }
  13412. }
  13413. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  13414. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  13415. {
  13416. if (methodInstance->GetExplicitInterface() == NULL)
  13417. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  13418. else
  13419. {
  13420. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  13421. {
  13422. auto ifaceInst = ifaceEntry.mInterfaceType;
  13423. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  13424. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  13425. if (methodInstance->GetExplicitInterface() != ifaceInst)
  13426. continue;
  13427. ifaceInst->mTypeDef->PopulateMemberSets();
  13428. BfMethodDef* nextMethod = NULL;
  13429. BfMemberSetEntry* entry = NULL;
  13430. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  13431. nextMethod = (BfMethodDef*)entry->mMemberDef;
  13432. while (nextMethod != NULL)
  13433. {
  13434. auto checkMethod = nextMethod;
  13435. nextMethod = nextMethod->mNextWithSameName;
  13436. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  13437. if (implMethodInst == methodInstance)
  13438. {
  13439. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  13440. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  13441. }
  13442. }
  13443. }
  13444. }
  13445. if (methodDef->mIsOverride)
  13446. {
  13447. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  13448. {
  13449. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  13450. if (ventry.mDeclaringMethod.mMethodNum == -1)
  13451. continue;
  13452. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  13453. if (virtMethod != NULL)
  13454. {
  13455. if (virtMethod == methodInstance)
  13456. {
  13457. // Is matching method
  13458. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  13459. {
  13460. auto baseType = mCurTypeInstance->mBaseType;
  13461. if (baseType != NULL)
  13462. {
  13463. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  13464. baseType = baseType->mBaseType;
  13465. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  13466. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  13467. }
  13468. }
  13469. break;
  13470. }
  13471. }
  13472. }
  13473. }
  13474. }
  13475. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  13476. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13477. {
  13478. if (mBfIRBuilder->mIgnoreWrites)
  13479. return;
  13480. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  13481. if (!methodInstance->mIRFunction)
  13482. {
  13483. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  13484. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13485. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  13486. }
  13487. if (HasCompiledOutput())
  13488. {
  13489. BfDllImportEntry dllImportEntry;
  13490. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  13491. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13492. mDllImportEntries.push_back(dllImportEntry);
  13493. }
  13494. return;
  13495. }
  13496. StringT<128> mangledName;
  13497. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  13498. if (!methodInstance->mIRFunction)
  13499. {
  13500. bool isIntrinsic = false;
  13501. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  13502. }
  13503. if (methodInstance->mIsIntrinsic)
  13504. return;
  13505. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  13506. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  13507. if (methodDef->mBody != NULL)
  13508. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13509. else if (methodDeclaration != NULL)
  13510. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13511. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13512. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13513. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  13514. {
  13515. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  13516. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13517. {
  13518. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  13519. }
  13520. }
  13521. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  13522. BfMethodState methodState;
  13523. if (mCurMethodState != NULL)
  13524. methodState.mClosureState = mCurMethodState->mClosureState;
  13525. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  13526. {
  13527. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  13528. if (methodInstance->mHotMethod == NULL)
  13529. CheckHotMethod(methodInstance, mangledName);
  13530. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  13531. }
  13532. methodState.mPrevMethodState = mCurMethodState;
  13533. methodState.mMethodInstance = methodInstance;
  13534. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  13535. if (methodInstance->GetCustomAttributes() != NULL)
  13536. {
  13537. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  13538. if (typeOptionsIdx != -1)
  13539. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  13540. }
  13541. BfTypeState typeState(mCurTypeInstance);
  13542. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  13543. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  13544. BfMethodInstance* unspecializedMethodInstance = NULL;
  13545. if ((prevMethodState.mPrevVal != NULL) &&
  13546. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  13547. {
  13548. // This is 'inner' (probably a closure) - use binding from outer function
  13549. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  13550. }
  13551. else if ((methodInstance->mIsUnspecialized) ||
  13552. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  13553. {
  13554. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13555. }
  13556. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  13557. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation))))
  13558. {
  13559. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  13560. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  13561. if (!unspecializedMethodInstance->mHasBeenProcessed)
  13562. {
  13563. // Make sure the unspecialized method is processed so we can take its bindings
  13564. // Clear mCurMethodState so we don't think we're in a local method
  13565. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  13566. mContext->ProcessMethod(unspecializedMethodInstance);
  13567. }
  13568. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13569. }
  13570. if (methodDef->mMethodType == BfMethodType_Operator)
  13571. {
  13572. auto operatorDef = (BfOperatorDef*) methodDef;
  13573. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  13574. auto paramErrorRefNode = refNode;
  13575. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  13576. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  13577. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  13578. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  13579. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  13580. {
  13581. if (methodDef->mParams.size() != 2)
  13582. {
  13583. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  13584. }
  13585. else
  13586. {
  13587. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13588. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  13589. {
  13590. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  13591. }
  13592. }
  13593. BfType* wantType = NULL;
  13594. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  13595. {
  13596. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  13597. }
  13598. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  13599. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  13600. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  13601. }
  13602. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  13603. {
  13604. if (methodDef->mParams.size() != 1)
  13605. {
  13606. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  13607. }
  13608. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  13609. {
  13610. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  13611. }
  13612. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  13613. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  13614. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  13615. {
  13616. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  13617. }
  13618. }
  13619. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  13620. {
  13621. if (methodDef->mParams.size() != 1)
  13622. {
  13623. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  13624. }
  13625. if (mCurMethodInstance->mReturnType->IsVoid())
  13626. {
  13627. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  13628. }
  13629. }
  13630. else // Conversion
  13631. {
  13632. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  13633. {
  13634. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  13635. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  13636. }
  13637. if (methodDef->mParams.size() != 1)
  13638. {
  13639. auto refNode = paramErrorRefNode;
  13640. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  13641. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  13642. Fail("Conversion operators must declare one parameter", refNode);
  13643. }
  13644. else
  13645. {
  13646. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13647. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  13648. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  13649. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  13650. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  13651. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  13652. // happened here
  13653. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  13654. {
  13655. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  13656. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  13657. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  13658. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  13659. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  13660. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  13661. }
  13662. }
  13663. }
  13664. }
  13665. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  13666. if (methodDef->mMethodType == BfMethodType_Mixin)
  13667. wantsDIData = false;
  13668. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  13669. wantsDIData = false;
  13670. bool wantsDIVariables = wantsDIData;
  13671. if (methodDef->mIsExtern)
  13672. wantsDIVariables = false;
  13673. SizedArray<BfIRMDNode, 8> diParams;
  13674. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  13675. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  13676. BfType* thisType = NULL;
  13677. if (!methodDef->mIsStatic)
  13678. {
  13679. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  13680. thisType = methodState.mClosureState->mClosureType;
  13681. else
  13682. thisType = mCurTypeInstance;
  13683. }
  13684. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  13685. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  13686. //////////////////////////////////////////////////////////////////////////
  13687. //
  13688. {
  13689. if (methodDeclaration != NULL)
  13690. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13691. else if (methodDef->mBody != NULL)
  13692. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13693. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13694. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13695. }
  13696. BfIRMDNode diFunction;
  13697. if (wantsDIData)
  13698. {
  13699. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  13700. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  13701. int defLine = mCurFilePosition.mCurLine;
  13702. if (mDICompileUnit)
  13703. {
  13704. int flags = 0;
  13705. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  13706. if (methodDef->mProtection == BfProtection_Public)
  13707. flags = llvm::DINode::FlagPublic;
  13708. else if (methodDef->mProtection == BfProtection_Protected)
  13709. flags = llvm::DINode::FlagProtected;
  13710. else
  13711. flags = llvm::DINode::FlagPrivate;
  13712. if (methodDef->mIsOverride)
  13713. {
  13714. //flags |= llvm::DINode::FlagVirtual;
  13715. }
  13716. else if (methodDef->mIsVirtual)
  13717. flags |= llvm::DINode::FlagIntroducedVirtual;
  13718. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  13719. flags |= llvm::DINode::FlagStaticMember;
  13720. else
  13721. {
  13722. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  13723. flags |= llvm::DINode::FlagStaticMember;
  13724. }
  13725. flags |= llvm::DINode::FlagPrototyped;
  13726. if (methodDef->mMethodType == BfMethodType_Ctor)
  13727. {
  13728. flags |= llvm::DINode::FlagArtificial;
  13729. }
  13730. auto llvmFunction = methodInstance->mIRFunction;
  13731. SizedArray<BfIRMDNode, 1> genericArgs;
  13732. SizedArray<BfIRValue, 1> genericConstValueArgs;
  13733. String methodName;
  13734. if (methodInstance->GetForeignType() != NULL)
  13735. {
  13736. methodName += TypeToString(methodInstance->GetForeignType());
  13737. methodName += ".";
  13738. }
  13739. if (methodInstance->GetExplicitInterface() != NULL)
  13740. {
  13741. methodName += TypeToString(methodInstance->GetExplicitInterface());
  13742. methodName += ".";
  13743. }
  13744. methodName += methodDef->mName;
  13745. if (methodInstance->GetNumGenericArguments() != 0)
  13746. {
  13747. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13748. {
  13749. if (genericArg->IsConstExprValue())
  13750. {
  13751. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  13752. while (genericConstValueArgs.size() < genericArgs.size())
  13753. genericConstValueArgs.push_back(BfIRValue());
  13754. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  13755. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  13756. }
  13757. else
  13758. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  13759. }
  13760. methodName += "<";
  13761. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  13762. {
  13763. if (i > 0)
  13764. methodName += ", ";
  13765. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  13766. methodName += TypeToString(type);
  13767. }
  13768. methodName += ">";
  13769. }
  13770. if ((methodName.empty()) && (methodDeclaration != NULL))
  13771. {
  13772. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  13773. {
  13774. methodName += "operator";
  13775. if (operatorDecl->mIsConvOperator)
  13776. {
  13777. methodName += " ";
  13778. methodName += TypeToString(methodInstance->mReturnType);
  13779. }
  13780. else if (operatorDecl->mOpTypeToken != NULL)
  13781. methodName += operatorDecl->mOpTypeToken->ToString();
  13782. }
  13783. }
  13784. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  13785. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13786. // defLine + 1, diFuncType, false, true,
  13787. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  13788. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  13789. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13790. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13791. defLine + 1, diFuncType, false, true,
  13792. llvm::dwarf::DW_VIRTUALITY_none,
  13793. 0,
  13794. nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13795. }
  13796. }
  13797. //////////////////////////////////////////////////////////////////////////
  13798. // Head and Init get rolled into Entry afterwards.
  13799. methodState.mIRFunction = methodInstance->mIRFunction;
  13800. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  13801. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  13802. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  13803. methodState.mCurScope->mDIScope = diFunction;
  13804. auto llvmEntryBlock = methodState.mIREntryBlock;
  13805. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  13806. if (methodDef->mBody != NULL)
  13807. {
  13808. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13809. }
  13810. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  13811. {
  13812. // We want to be able to step into delegate invokes -- we actually step over them
  13813. if (methodDef->mName != "Invoke")
  13814. {
  13815. UpdateSrcPos(typeDef->mTypeDeclaration);
  13816. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  13817. }
  13818. }
  13819. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  13820. mBfIRBuilder->ClearDebugLocation();
  13821. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  13822. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  13823. if (methodDef->mImportKind != BfImportKind_Dynamic)
  13824. {
  13825. int localIdx = 0;
  13826. int argIdx = 0;
  13827. if (methodInstance->HasStructRet())
  13828. argIdx++;
  13829. //
  13830. bool doDbgAgg = false;
  13831. Array<BfIRValue> splatAddrValues;
  13832. for ( ; argIdx < irParamCount; localIdx++)
  13833. {
  13834. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13835. if ((isThis) && (thisType->IsValuelessType()))
  13836. isThis = false;
  13837. BfLocalVariable* paramVar = NULL;
  13838. while (true)
  13839. {
  13840. BF_ASSERT(localIdx < methodState.mLocals.size());
  13841. paramVar = methodState.mLocals[localIdx];
  13842. if ((paramVar->mCompositeCount == -1) &&
  13843. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  13844. break;
  13845. localIdx++;
  13846. }
  13847. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  13848. {
  13849. paramVar->mIsReadOnly = true;
  13850. }
  13851. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType() != BfTypeCode_None);
  13852. if (paramVar->mResolvedType->IsMethodRef())
  13853. wantsAddr = false;
  13854. // if ((methodDef->mHasAppend) && (argIdx == 1))
  13855. // {
  13856. // BF_ASSERT(paramVar->mName == "appendIdx");
  13857. // wantsAddr = true;
  13858. // }
  13859. if ((!doDbgAgg) && (paramVar->mIsSplat))
  13860. {
  13861. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13862. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13863. BfTypeUtils::SplatIterate([&](BfType* checkType)
  13864. {
  13865. BfIRType splatIRType;
  13866. if (checkType->IsComposite())
  13867. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  13868. else
  13869. splatIRType = mBfIRBuilder->MapType(checkType);
  13870. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  13871. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  13872. if (!paramVar->mAddr)
  13873. paramVar->mAddr = allocaInst;
  13874. if (WantsLifetimes())
  13875. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13876. splatAddrValues.push_back(allocaInst);
  13877. }, paramVar->mResolvedType);
  13878. mBfIRBuilder->SetInsertPoint(prevInsert);
  13879. }
  13880. else if (isThis)
  13881. {
  13882. if (wantsAddr)
  13883. {
  13884. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13885. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13886. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  13887. if (paramVar->mIsSplat)
  13888. {
  13889. if (doDbgAgg)
  13890. {
  13891. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  13892. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13893. mBfIRBuilder->SetAllocaAlignment(allocaInst, thisType->mAlign);
  13894. paramVar->mAddr = allocaInst;
  13895. if (WantsLifetimes())
  13896. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13897. }
  13898. }
  13899. else
  13900. {
  13901. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  13902. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  13903. wantPtr = true;
  13904. if (wantPtr)
  13905. {
  13906. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  13907. }
  13908. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  13909. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13910. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  13911. paramVar->mAddr = allocaInst;
  13912. if (WantsLifetimes())
  13913. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13914. }
  13915. mBfIRBuilder->SetInsertPoint(prevInsert);
  13916. }
  13917. }
  13918. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  13919. {
  13920. // Address doesn't change so we don't have to alloca it
  13921. BfIRType allocType;
  13922. int alignSize = mSystem->mPtrSize;
  13923. if (paramVar->mResolvedType->IsRef())
  13924. {
  13925. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  13926. }
  13927. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  13928. {
  13929. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  13930. alignSize = paramVar->mResolvedType->mAlign;
  13931. }
  13932. else
  13933. {
  13934. paramVar->mHasLocalStructBacking = true;
  13935. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  13936. if (typeInst != NULL)
  13937. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  13938. else
  13939. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  13940. }
  13941. if (wantsAddr)
  13942. {
  13943. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13944. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13945. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  13946. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  13947. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13948. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  13949. paramVar->mAddr = allocaInst;
  13950. mBfIRBuilder->SetInsertPoint(prevInsert);
  13951. if (WantsLifetimes())
  13952. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13953. }
  13954. }
  13955. else if (wantsAddr)
  13956. {
  13957. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  13958. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13959. paramVar->mAddr = allocaInst;
  13960. }
  13961. if (paramVar->mIsSplat)
  13962. {
  13963. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  13964. }
  13965. else
  13966. {
  13967. argIdx++;
  13968. }
  13969. }
  13970. if (methodDef->mBody != NULL)
  13971. UpdateSrcPos(methodDef->mBody);
  13972. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13973. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  13974. int declArgIdx = 0;
  13975. localIdx = 0;
  13976. argIdx = 0;
  13977. if (methodInstance->HasStructRet())
  13978. argIdx++;
  13979. int splatAddrIdx = 0;
  13980. while (localIdx < (int)methodState.mLocals.size())
  13981. {
  13982. int curLocalIdx = localIdx++;
  13983. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  13984. if (!paramVar->IsParam())
  13985. continue;
  13986. if (paramVar->mCompositeCount != -1)
  13987. continue;
  13988. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13989. if ((isThis) && (thisType->IsValuelessType()))
  13990. isThis = false;
  13991. BfIRMDNode diVariable;
  13992. if (wantsDIData)
  13993. {
  13994. String paramName = paramVar->mName;
  13995. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13996. if (isThis)
  13997. {
  13998. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  13999. paramName = "__closure";
  14000. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14001. {
  14002. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14003. bool wantRef = paramVar->mResolvedType->IsComposite();
  14004. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  14005. wantRef = true;
  14006. if (wantRef)
  14007. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14008. }
  14009. else if (!paramVar->mResolvedType->IsValueType())
  14010. {
  14011. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  14012. }
  14013. }
  14014. else
  14015. {
  14016. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14017. {
  14018. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14019. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14020. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14021. }
  14022. }
  14023. if ((!paramVar->mIsSplat) || (doDbgAgg))
  14024. {
  14025. if (paramVar->mResolvedType->IsValuelessType())
  14026. {
  14027. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  14028. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14029. }
  14030. else if (paramVar->mIsImplicitParam)
  14031. {
  14032. // Annotate this specially?
  14033. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14034. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14035. }
  14036. else
  14037. {
  14038. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14039. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14040. }
  14041. paramVar->mDbgVarInst = diVariable;
  14042. }
  14043. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  14044. {
  14045. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14046. // {
  14047. // // Only add this placeholder if we don't have any values
  14048. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14049. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14050. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  14051. // }
  14052. }
  14053. }
  14054. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  14055. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  14056. {
  14057. // Write our argument value into the .addr
  14058. mBfIRBuilder->ClearDebugLocation();
  14059. if (paramVar->mIsSplat)
  14060. {
  14061. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14062. if (doDbgAgg)
  14063. {
  14064. auto curArgIdx = argIdx;
  14065. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curDestAddr)
  14066. {
  14067. if (checkType->IsStruct())
  14068. {
  14069. auto checkTypeInstance = checkType->ToTypeInstance();
  14070. if (checkTypeInstance->mBaseType != NULL)
  14071. {
  14072. auto baseDestAddr = mBfIRBuilder->CreateBitCast(curDestAddr, mBfIRBuilder->MapTypeInstPtr(checkTypeInstance->mBaseType));
  14073. checkTypeLambda(checkTypeInstance->mBaseType, baseDestAddr);
  14074. }
  14075. if (checkTypeInstance->mIsUnion)
  14076. {
  14077. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14078. if (!unionInnerType->IsValuelessType())
  14079. {
  14080. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 1);
  14081. checkTypeLambda(unionInnerType, newDestAddr);
  14082. }
  14083. if (checkTypeInstance->IsEnum())
  14084. {
  14085. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14086. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 2);
  14087. checkTypeLambda(dscrType, newDestAddr);
  14088. }
  14089. }
  14090. else
  14091. {
  14092. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14093. {
  14094. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14095. if (fieldInstance->mDataIdx >= 0)
  14096. {
  14097. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, fieldInstance->mDataIdx);
  14098. checkTypeLambda(fieldInstance->GetResolvedType(), newDestAddr);
  14099. }
  14100. }
  14101. }
  14102. }
  14103. else if (checkType->IsMethodRef())
  14104. {
  14105. BF_FATAL("Unimplemented");
  14106. // BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  14107. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14108. // {
  14109. // checkTypeLambda->
  14110. // }
  14111. }
  14112. else if (!checkType->IsValuelessType())
  14113. {
  14114. mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), curDestAddr, paramVar->mResolvedType->mAlign);
  14115. curArgIdx++;
  14116. }
  14117. };
  14118. checkTypeLambda(paramVar->mResolvedType, paramVar->mAddr);
  14119. }
  14120. }
  14121. else
  14122. {
  14123. bool handled = false;
  14124. //if ((!isThis) || (!methodDef->mIsMutating && !methodDef->mNoSplat))
  14125. if (paramVar->mIsLowered)
  14126. {
  14127. auto loweredTypeCode = paramVar->mResolvedType->GetLoweredType();
  14128. BF_ASSERT(loweredTypeCode != BfTypeCode_None);
  14129. if (loweredTypeCode != BfTypeCode_None)
  14130. {
  14131. // We have a lowered type coming in, so we have to cast the .addr before storing
  14132. auto primType = GetPrimitiveType(loweredTypeCode);
  14133. auto primPtrType = CreatePointerType(primType);
  14134. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, mBfIRBuilder->MapType(primPtrType));
  14135. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, paramVar->mResolvedType->mSize);
  14136. // We don't want to allow directly using value
  14137. paramVar->mValue = BfIRValue();
  14138. handled = true;
  14139. }
  14140. }
  14141. if (!handled)
  14142. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  14143. }
  14144. }
  14145. if (!isThis)
  14146. declArgIdx++;
  14147. if (methodDef->mBody != NULL)
  14148. UpdateSrcPos(methodDef->mBody);
  14149. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14150. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14151. else if (methodDeclaration == NULL)
  14152. UseDefaultSrcPos();
  14153. // Write our argument value into the .addr
  14154. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14155. {
  14156. int splatComponentIdx = 0;
  14157. auto curArgIdx = argIdx;
  14158. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  14159. {
  14160. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  14161. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  14162. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  14163. mBfIRBuilder->ClearDebugLocation(storeInst);
  14164. if (wantsDIData)
  14165. {
  14166. BfIRMDNode diType;
  14167. if (checkType->IsComposite())
  14168. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  14169. else
  14170. diType = mBfIRBuilder->DbgGetType(checkType);
  14171. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14172. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14173. if (wantsDIVariables)
  14174. {
  14175. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  14176. }
  14177. }
  14178. curArgIdx++;
  14179. splatComponentIdx++;
  14180. };
  14181. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  14182. {
  14183. if (checkType->IsStruct())
  14184. {
  14185. auto checkTypeInstance = checkType->ToTypeInstance();
  14186. if (checkTypeInstance->mBaseType != NULL)
  14187. {
  14188. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  14189. }
  14190. if (checkTypeInstance->mIsUnion)
  14191. {
  14192. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14193. if (!unionInnerType->IsValuelessType())
  14194. {
  14195. _FinishSplatsIterate(unionInnerType, name + "$u");
  14196. }
  14197. if (checkTypeInstance->IsEnum())
  14198. {
  14199. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14200. _FinishSplatsIterate(dscrType, name + "$d");
  14201. }
  14202. }
  14203. else
  14204. {
  14205. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14206. {
  14207. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14208. auto fieldDef = fieldInstance->GetFieldDef();
  14209. if (fieldInstance->mDataIdx >= 0)
  14210. {
  14211. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  14212. }
  14213. }
  14214. }
  14215. }
  14216. else if (checkType->IsMethodRef())
  14217. {
  14218. auto methodRefType = (BfMethodRefType*)checkType;
  14219. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  14220. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  14221. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  14222. // {
  14223. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  14224. // if (!paramType->IsValuelessType())
  14225. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  14226. // }
  14227. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14228. {
  14229. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  14230. String paramName = methodInstance->GetParamName(paramIdx);
  14231. if (paramName == "this")
  14232. paramName = "__this";
  14233. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  14234. {
  14235. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14236. }
  14237. else
  14238. {
  14239. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14240. }
  14241. }
  14242. }
  14243. else if (!checkType->IsValuelessType())
  14244. {
  14245. _FinishSplats(checkType, name);
  14246. }
  14247. };
  14248. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14249. if (!paramVar->mConstValue)
  14250. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  14251. }
  14252. BfIRValue declareCall;
  14253. if (diVariable)
  14254. {
  14255. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14256. {
  14257. if (!paramVar->mAddr)
  14258. {
  14259. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  14260. {
  14261. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14262. {
  14263. // We don't need to set the location for this
  14264. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14265. }
  14266. }
  14267. else
  14268. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  14269. }
  14270. else
  14271. {
  14272. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  14273. }
  14274. }
  14275. }
  14276. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  14277. {
  14278. // We don't allow actually assignment to "this", so we just do a single load
  14279. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  14280. // we need to store it in the stack frame for debugging purposes
  14281. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  14282. mBfIRBuilder->ClearDebugLocation(loadedThis);
  14283. paramVar->mValue = loadedThis;
  14284. }
  14285. if ((wantsDIData) && (declareCall))
  14286. mBfIRBuilder->UpdateDebugLocation(declareCall);
  14287. if (paramVar->mIsSplat)
  14288. {
  14289. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14290. }
  14291. else if (!paramVar->mResolvedType->IsValuelessType())
  14292. {
  14293. argIdx++;
  14294. }
  14295. }
  14296. if (wantsDIData)
  14297. {
  14298. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  14299. }
  14300. }
  14301. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  14302. {
  14303. auto paramVar = mCurMethodState->mLocals[varIdx];
  14304. // 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
  14305. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  14306. // if (paramVar->mIsSplat)
  14307. // {
  14308. // if (wantsDIVariables)
  14309. // {
  14310. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  14311. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  14312. // }
  14313. // }
  14314. if (paramVar->mResolvedType->IsValuelessType())
  14315. {
  14316. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14317. {
  14318. // Only add this placeholder if we don't have any values
  14319. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14320. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14321. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14322. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14323. }
  14324. }
  14325. }
  14326. if (IsTargetingBeefBackend())
  14327. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  14328. if (methodState.mClosureState != NULL)
  14329. {
  14330. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  14331. {
  14332. BfLocalVariable* localVar = new BfLocalVariable();
  14333. *localVar = constLocal;
  14334. AddLocalVariableDef(localVar, true);
  14335. }
  14336. }
  14337. bool wantsRemoveBody = false;
  14338. bool skipBody = false;
  14339. bool skipUpdateSrcPos = false;
  14340. bool skipEndChecks = false;
  14341. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodDef->mImportKind != BfImportKind_Dynamic);
  14342. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14343. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  14344. hasExternSpecifier = true;
  14345. // Allocate, clear, set classVData
  14346. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  14347. {
  14348. CreateStaticCtor();
  14349. }
  14350. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14351. {
  14352. skipBody = true;
  14353. skipEndChecks = true;
  14354. if (HasCompiledOutput())
  14355. {
  14356. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  14357. mBfIRBuilder->ClearDebugLocation();
  14358. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  14359. BfTypeInstance* innerType = boxedType->mElementType;
  14360. PopulateType(innerType, BfPopulateType_DataAndMethods);
  14361. mBfIRBuilder->PopulateType(mCurTypeInstance);
  14362. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14363. if (methodInstance->mIsForeignMethodDef)
  14364. {
  14365. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  14366. }
  14367. BfTypeVector methodGenericArguments;
  14368. if (methodInstance->mMethodInfoEx != NULL)
  14369. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  14370. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  14371. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  14372. {
  14373. if (!methodInstance->mReturnType->IsValuelessType())
  14374. {
  14375. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  14376. CreateReturn(retVal);
  14377. }
  14378. }
  14379. else
  14380. {
  14381. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  14382. SizedArray<BfIRValue, 8> innerParams;
  14383. BfExprEvaluator exprEvaluator(this);
  14384. if (!innerType->IsValuelessType())
  14385. {
  14386. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  14387. BfTypedValue innerVal(thisValue, innerType, true);
  14388. if (boxedType->IsBoxedStructPtr())
  14389. {
  14390. innerVal = LoadValue(innerVal);
  14391. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  14392. }
  14393. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  14394. }
  14395. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14396. {
  14397. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  14398. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  14399. exprEvaluator.PushArg(localVal, innerParams);
  14400. }
  14401. if (!innerMethodInstance.mFunc)
  14402. {
  14403. BF_ASSERT(innerType->IsUnspecializedType());
  14404. }
  14405. else if (methodInstance->HasStructRet())
  14406. {
  14407. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14408. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(0), methodInstance->mReturnType, true);
  14409. exprEvaluator.mReceivingValue = &returnType;
  14410. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14411. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  14412. mBfIRBuilder->CreateRetVoid();
  14413. }
  14414. else
  14415. {
  14416. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14417. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14418. if (mCurMethodInstance->mReturnType->IsValueType())
  14419. retVal = LoadValue(retVal);
  14420. CreateReturn(retVal.mValue);
  14421. }
  14422. }
  14423. }
  14424. mCurMethodState->SetHadReturn(true);
  14425. mCurMethodState->mLeftBlockUncond = true;
  14426. }
  14427. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  14428. {
  14429. SetIllegalSrcPos();
  14430. mBfIRBuilder->ClearDebugLocation();
  14431. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  14432. auto thisVal = GetThis();
  14433. int prevSize = mContext->mBfObjectType->mInstSize;
  14434. int curSize = mCurTypeInstance->mInstSize;
  14435. if (curSize > prevSize)
  14436. {
  14437. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  14438. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  14439. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  14440. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  14441. }
  14442. skipUpdateSrcPos = true;
  14443. }
  14444. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  14445. {
  14446. EmitCtorBody(skipBody);
  14447. }
  14448. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  14449. {
  14450. EmitDtorBody();
  14451. skipBody = true;
  14452. }
  14453. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  14454. {
  14455. EmitIteratorBlock(skipBody);
  14456. }
  14457. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  14458. {
  14459. // We need to be able to mark deleted objects
  14460. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14461. }
  14462. auto customAttributes = methodInstance->GetCustomAttributes();
  14463. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  14464. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14465. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  14466. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  14467. {
  14468. // We chain even non-default ctors to the default ctors
  14469. auto defaultCtor = methodInstance;
  14470. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  14471. CallChainedMethods(defaultCtor, false);
  14472. }
  14473. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14474. if (methodDef->mBody == NULL)
  14475. {
  14476. if (methodDeclaration != NULL)
  14477. {
  14478. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  14479. {
  14480. if (operatorDeclaration->mIsConvOperator)
  14481. wantsRemoveBody = true;
  14482. }
  14483. }
  14484. bool isDllImport = false;
  14485. if (methodDef->mImportKind == BfImportKind_Static)
  14486. {
  14487. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14488. {
  14489. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14490. {
  14491. if (customAttr.mCtorArgs.size() == 1)
  14492. {
  14493. auto fileNameArg = customAttr.mCtorArgs[0];
  14494. int strNum = 0;
  14495. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  14496. if (constant != NULL)
  14497. {
  14498. if (constant->IsNull())
  14499. continue; // Invalid
  14500. strNum = constant->mInt32;
  14501. }
  14502. else
  14503. {
  14504. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  14505. }
  14506. if (!mImportFileNames.Contains(strNum))
  14507. mImportFileNames.Add(strNum);
  14508. }
  14509. }
  14510. }
  14511. //mImportFileNames
  14512. }
  14513. else if (methodDef->mImportKind == BfImportKind_Dynamic)
  14514. {
  14515. CreateDllImportMethod();
  14516. }
  14517. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  14518. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  14519. {
  14520. if (mCurTypeInstance->mTypeDef->mIsFunction)
  14521. {
  14522. // Emit nothing
  14523. }
  14524. else
  14525. {
  14526. CreateDelegateInvokeMethod();
  14527. mCurMethodState->SetHadReturn(true);
  14528. mCurMethodState->mLeftBlockUncond = true;
  14529. }
  14530. }
  14531. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14532. {
  14533. if (mCurTypeInstance->IsObject())
  14534. {
  14535. CreateDynamicCastMethod();
  14536. }
  14537. else
  14538. {
  14539. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14540. mCurMethodState->mHadReturn = true;
  14541. }
  14542. }
  14543. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14544. {
  14545. BfIRValue ret;
  14546. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  14547. {
  14548. // This can happen if we provide an invalid name
  14549. AssertErrorState();
  14550. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  14551. }
  14552. else
  14553. {
  14554. // Unfortunate DebugLoc shenanigans-
  14555. // 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,
  14556. // so we only set the loc on the CreateRet which gets inlined out
  14557. mBfIRBuilder->SaveDebugLocation();
  14558. mBfIRBuilder->ClearDebugLocation();
  14559. BfIRValue fromBool;
  14560. if (!mCurTypeInstance->IsTypedPrimitive())
  14561. {
  14562. fromBool = GetDefaultValue(methodInstance->mReturnType);
  14563. }
  14564. else
  14565. {
  14566. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  14567. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  14568. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  14569. }
  14570. mBfIRBuilder->RestoreDebugLocation();
  14571. ret = mBfIRBuilder->CreateRet(fromBool);
  14572. //ExtendLocalLifetimes(0);
  14573. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14574. }
  14575. mCurMethodState->SetHadReturn(true);
  14576. mCurMethodState->mLeftBlockUncond = true;
  14577. }
  14578. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  14579. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14580. {
  14581. BfIRValue ret;
  14582. // Unfortunate DebugLoc shenanigans-
  14583. // 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,
  14584. // so we only set the loc on the CreateRet which gets inlined out
  14585. mBfIRBuilder->SaveDebugLocation();
  14586. mBfIRBuilder->ClearDebugLocation();
  14587. BfIRValue fromBool;
  14588. mBfIRBuilder->RestoreDebugLocation();
  14589. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  14590. //ExtendLocalLifetimes(0);
  14591. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14592. mCurMethodState->SetHadReturn(true);
  14593. mCurMethodState->mLeftBlockUncond = true;
  14594. }
  14595. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14596. {
  14597. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14598. if (HasCompiledOutput())
  14599. {
  14600. EmitEnumToStringBody();
  14601. }
  14602. mBfIRBuilder->CreateRetVoid();
  14603. mCurMethodState->SetHadReturn(true);
  14604. mCurMethodState->mLeftBlockUncond = true;
  14605. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14606. }
  14607. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14608. {
  14609. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14610. if (HasCompiledOutput())
  14611. {
  14612. EmitTupleToStringBody();
  14613. }
  14614. mBfIRBuilder->CreateRetVoid();
  14615. mCurMethodState->SetHadReturn(true);
  14616. mCurMethodState->mLeftBlockUncond = true;
  14617. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14618. }
  14619. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  14620. {
  14621. CreateValueTypeEqualsMethod();
  14622. skipBody = true;
  14623. skipEndChecks = true;
  14624. }
  14625. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  14626. {
  14627. CreateValueTypeEqualsMethod();
  14628. skipBody = true;
  14629. skipEndChecks = true;
  14630. }
  14631. else if (HasCompiledOutput())
  14632. {
  14633. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  14634. {
  14635. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14636. {
  14637. EmitGCMarkMembers();
  14638. }
  14639. else if (!mCurTypeInstance->IsObject())
  14640. {
  14641. }
  14642. }
  14643. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  14644. {
  14645. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14646. {
  14647. EmitGCFindTLSMembers();
  14648. }
  14649. }
  14650. }
  14651. }
  14652. else if (!skipBody)
  14653. {
  14654. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  14655. if (isEmptyBodied) // Generate autoProperty things
  14656. {
  14657. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14658. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  14659. {
  14660. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  14661. Fail("Body expected", methodDef->mBody);
  14662. }
  14663. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  14664. {
  14665. if (methodInstance->mReturnType->IsValuelessType())
  14666. {
  14667. mBfIRBuilder->CreateRetVoid();
  14668. }
  14669. else if (HasCompiledOutput())
  14670. {
  14671. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14672. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14673. BfFieldDef* fieldDef = NULL;
  14674. if (fieldInstance != NULL)
  14675. fieldDef = fieldInstance->GetFieldDef();
  14676. BfType* retType = methodInstance->mReturnType;
  14677. if (retType->IsRef())
  14678. retType = retType->GetUnderlyingType();
  14679. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  14680. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14681. {
  14682. BfTypedValue lookupValue;
  14683. if (fieldDef->IsNonConstStatic())
  14684. lookupValue = ReferenceStaticField(fieldInstance);
  14685. else if (mCurTypeInstance->IsObject())
  14686. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  14687. else
  14688. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mFieldIdx);
  14689. if (!methodInstance->mReturnType->IsRef())
  14690. lookupValue = LoadValue(lookupValue);
  14691. mBfIRBuilder->CreateRet(lookupValue.mValue);
  14692. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14693. }
  14694. else
  14695. {
  14696. // This can happen if we have two properties with the same name but different types
  14697. AssertErrorState();
  14698. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14699. }
  14700. }
  14701. else
  14702. {
  14703. // During autocomplete, the actual type may not have the proper field instance
  14704. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14705. }
  14706. mCurMethodState->SetHadReturn(true);
  14707. }
  14708. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  14709. {
  14710. if (!mCompiler->IsAutocomplete())
  14711. {
  14712. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14713. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14714. auto fieldDef = fieldInstance->GetFieldDef();
  14715. auto& lastParam = mCurMethodState->mLocals.back();
  14716. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  14717. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14718. {
  14719. BfIRValue lookupAddr;
  14720. if (fieldDef->IsNonConstStatic())
  14721. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  14722. else
  14723. {
  14724. auto thisValue = GetThis();
  14725. if (thisValue.IsSplat())
  14726. {
  14727. BF_FATAL("Should not happen");
  14728. }
  14729. if (mCurTypeInstance->IsObject())
  14730. thisValue = LoadValue(thisValue);
  14731. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  14732. }
  14733. mBfIRBuilder->CreateStore(lastParam->mValue, lookupAddr);
  14734. }
  14735. else if (!fieldInstance->mResolvedType->IsValuelessType())
  14736. {
  14737. // This can happen if we have two properties with the same name but different types
  14738. AssertErrorState();
  14739. }
  14740. }
  14741. }
  14742. }
  14743. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  14744. {
  14745. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  14746. if (mCurMethodInstance->HasStructRet())
  14747. {
  14748. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  14749. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  14750. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(0), allocaInst);
  14751. mBfIRBuilder->ClearDebugLocation(storeInst);
  14752. mCurMethodState->mRetValAddr = allocaInst;
  14753. }
  14754. else
  14755. {
  14756. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  14757. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  14758. }
  14759. }
  14760. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14761. {
  14762. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  14763. BfGetSymbolReferenceKind prevSymbolKind;
  14764. BfAutoComplete* prevAutoComplete;
  14765. if (mCompiler->mResolvePassData != NULL)
  14766. {
  14767. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  14768. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  14769. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  14770. }
  14771. EmitCtorCalcAppend();
  14772. if (mCompiler->mResolvePassData != NULL)
  14773. {
  14774. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  14775. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  14776. }
  14777. }
  14778. else if (!isEmptyBodied)
  14779. {
  14780. if (!mCurMethodState->mIRExitBlock)
  14781. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14782. bool isExpressionBody = false;
  14783. if (methodDeclaration != NULL)
  14784. {
  14785. if (methodDeclaration->mFatArrowToken != NULL)
  14786. isExpressionBody = true;
  14787. }
  14788. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  14789. {
  14790. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  14791. {
  14792. isExpressionBody = true;
  14793. }
  14794. }
  14795. else
  14796. {
  14797. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14798. {
  14799. if (!block->mChildArr.IsEmpty())
  14800. {
  14801. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  14802. {
  14803. if (exprStmt->mTrailingSemicolon == NULL)
  14804. isExpressionBody = true;
  14805. }
  14806. }
  14807. }
  14808. else
  14809. isExpressionBody = true;
  14810. }
  14811. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  14812. {
  14813. while (fieldDtorBody != NULL)
  14814. {
  14815. VisitEmbeddedStatement(fieldDtorBody->mBody);
  14816. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  14817. }
  14818. }
  14819. else if (!isExpressionBody)
  14820. {
  14821. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14822. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  14823. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  14824. VisitCodeBlock(bodyBlock);
  14825. }
  14826. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  14827. {
  14828. if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  14829. {
  14830. BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  14831. Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  14832. }
  14833. auto expectingType = mCurMethodInstance->mReturnType;
  14834. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  14835. // {
  14836. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  14837. // }
  14838. //TODO: Why did we have all this stuff for handling void?
  14839. // if (expectingType->IsVoid())
  14840. // {
  14841. // bool wasReturnGenericParam = false;
  14842. // if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  14843. // {
  14844. // wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  14845. // }
  14846. // else
  14847. // {
  14848. // auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  14849. // if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  14850. // wasReturnGenericParam = true;
  14851. // }
  14852. //
  14853. // // If we the void return was from a generic specialization, allow us to return a void result,
  14854. // // otherwise treat expression as though it must be a statement
  14855. // bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  14856. // if (isStatement)
  14857. // expectingType = NULL;
  14858. // }
  14859. UpdateSrcPos(expressionBody);
  14860. auto retVal = CreateValueFromExpression(expressionBody, expectingType);
  14861. if ((retVal) && (expectingType != NULL))
  14862. {
  14863. mCurMethodState->mHadReturn = true;
  14864. retVal = LoadValue(retVal);
  14865. EmitReturn(retVal.mValue);
  14866. }
  14867. }
  14868. }
  14869. }
  14870. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  14871. if (skipUpdateSrcPos)
  14872. {
  14873. // Skip
  14874. }
  14875. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  14876. UpdateSrcPos(bodyBlock->mCloseBrace);
  14877. else if (methodDef->mBody != NULL)
  14878. UpdateSrcPos(methodDef->mBody);
  14879. else if (methodDeclaration != NULL)
  14880. UpdateSrcPos(methodDeclaration);
  14881. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14882. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14883. else
  14884. UseDefaultSrcPos();
  14885. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14886. {
  14887. if (mCurMethodState->mRetVal)
  14888. {
  14889. mCurMethodState->SetHadReturn(true);
  14890. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  14891. mBfIRBuilder->CreateRet(retVal);
  14892. }
  14893. else
  14894. AssertErrorState();
  14895. }
  14896. if (!mCurMethodState->mHadReturn)
  14897. {
  14898. // Clear off the stackallocs that have occurred after a scopeData break
  14899. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  14900. }
  14901. if (mCurMethodState->mIRExitBlock)
  14902. {
  14903. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  14904. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  14905. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  14906. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  14907. if (!mCurMethodState->mDIRetVal)
  14908. CreateDIRetVal();
  14909. }
  14910. for (auto localVar : mCurMethodState->mLocals)
  14911. {
  14912. if ((skipEndChecks) || (bodyBlock == NULL))
  14913. break;
  14914. LocalVariableDone(localVar, true);
  14915. }
  14916. if (mCurMethodState->mIRExitBlock)
  14917. {
  14918. if ((mCurMethodState->mRetVal) && (!mCurMethodInstance->HasStructRet()))
  14919. {
  14920. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  14921. CreateReturn(loadedVal);
  14922. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14923. if (mCurMethodState->mDIRetVal)
  14924. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  14925. }
  14926. else
  14927. {
  14928. // Have something on the last line to step onto
  14929. if (mHasFullDebugInfo)
  14930. {
  14931. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  14932. UpdateSrcPos(bodyBlock->mCloseBrace);
  14933. EmitEnsureInstructionAt();
  14934. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  14935. {
  14936. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  14937. mBfIRBuilder->EnsureFunctionPatchable();
  14938. }
  14939. }
  14940. mBfIRBuilder->CreateRetVoid();
  14941. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14942. if (mCurMethodState->mDIRetVal)
  14943. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  14944. }
  14945. }
  14946. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  14947. {
  14948. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  14949. {
  14950. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  14951. {
  14952. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  14953. mBfIRBuilder->EnsureFunctionPatchable();
  14954. }
  14955. mBfIRBuilder->CreateRetVoid();
  14956. }
  14957. }
  14958. else
  14959. {
  14960. if (!mCurMethodState->mHadReturn)
  14961. {
  14962. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  14963. if (bodyBlock != NULL)
  14964. {
  14965. if (bodyBlock->mCloseBrace != NULL)
  14966. {
  14967. BfAstNode* target = bodyBlock->mCloseBrace;
  14968. Fail("Method must return value", target);
  14969. }
  14970. else
  14971. {
  14972. // It's possible to not have a closing brace if the method ends in an EOF
  14973. AssertErrorState();
  14974. }
  14975. }
  14976. }
  14977. }
  14978. // Move 'init' into 'entry'
  14979. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  14980. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  14981. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  14982. {
  14983. // Don't keep instructions for unspecialized types
  14984. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14985. }
  14986. if ((hasExternSpecifier) && (!skipBody))
  14987. {
  14988. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  14989. // incase it gets called later by some hot-loaded coded
  14990. if (mCompiler->mOptions.mAllowHotSwapping)
  14991. CreateFakeCallerMethod(mangledName);
  14992. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14993. }
  14994. else if ((methodDef->mImportKind == BfImportKind_Dynamic) && (!mCompiler->IsHotCompile()))
  14995. {
  14996. // We only need the DLL stub when we may be hot swapping
  14997. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14998. }
  14999. else if (wantsRemoveBody)
  15000. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15001. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  15002. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  15003. // unspecialized types
  15004. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  15005. {
  15006. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  15007. methodInstance->mIRFunction = BfIRFunction();
  15008. }
  15009. CheckAddFailType();
  15010. if (mHadBuildError)
  15011. prevHadBuildError.CancelRestore();
  15012. if (mHadBuildWarning)
  15013. prevHadWarning.CancelRestore();
  15014. if (!methodDef->mIsLocalMethod)
  15015. ProcessMethod_ProcessDeferredLocals();
  15016. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15017. if (methodState.mHotDataReferenceBuilder != NULL)
  15018. {
  15019. AddHotDataReferences(&hotDataReferenceBuilder);
  15020. }
  15021. else
  15022. {
  15023. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  15024. {
  15025. // Remove the hot method data
  15026. auto hotMethod = methodInstance->mHotMethod;
  15027. auto prevMethod = hotMethod->mPrevVersion;
  15028. if (prevMethod != NULL)
  15029. {
  15030. // If there's a prev method then pull its data into the main HotMethod.
  15031. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  15032. // over to the main HotMethod definition to keep the HotMethod address
  15033. // invariant
  15034. for (auto ref : hotMethod->mReferences)
  15035. ref->Deref();
  15036. hotMethod->mReferences.Clear();
  15037. BF_ASSERT(prevMethod->mRefCount == 1);
  15038. hotMethod->mReferences = prevMethod->mReferences;
  15039. if (hotMethod->mSrcTypeVersion != NULL)
  15040. hotMethod->mSrcTypeVersion->Deref();
  15041. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  15042. prevMethod->mSrcTypeVersion = NULL;
  15043. prevMethod->mReferences.Clear();
  15044. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  15045. prevMethod->mPrevVersion = NULL;
  15046. prevMethod->Deref();
  15047. }
  15048. hotMethod->Deref();
  15049. methodInstance->mHotMethod = NULL;
  15050. }
  15051. }
  15052. }
  15053. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  15054. {
  15055. String name;
  15056. bool found = false;
  15057. auto checkMethodState = mCurMethodState;
  15058. while (checkMethodState != NULL)
  15059. {
  15060. if (checkMethodState->mClosureState == NULL)
  15061. break;
  15062. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  15063. {
  15064. found = true;
  15065. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  15066. break;
  15067. }
  15068. checkMethodState = checkMethodState->mPrevMethodState;
  15069. }
  15070. if (!found)
  15071. name += mCurMethodInstance->mMethodDef->mName;
  15072. int prevSepPos = (int)name.LastIndexOf('$');
  15073. if (prevSepPos != -1)
  15074. {
  15075. name.RemoveToEnd(prevSepPos);
  15076. }
  15077. name += "@";
  15078. name += baseName;
  15079. HashContext hashCtx;
  15080. if (anchorNode != NULL)
  15081. {
  15082. hashCtx.Mixin(anchorNode->GetStartCharId());
  15083. }
  15084. //
  15085. {
  15086. auto checkMethodState = declMethodState;
  15087. auto checkMixinState = declMixinState;
  15088. while (checkMethodState != NULL)
  15089. {
  15090. if (checkMixinState != NULL)
  15091. {
  15092. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  15093. }
  15094. checkMethodState = checkMethodState->mPrevMethodState;
  15095. if (checkMethodState != NULL)
  15096. checkMixinState = checkMethodState->mMixinState;
  15097. }
  15098. }
  15099. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15100. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15101. {
  15102. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  15103. {
  15104. StringT<128> genericTypeName;
  15105. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  15106. hashCtx.MixinStr(genericTypeName);
  15107. }
  15108. }
  15109. uint64 hashVal = hashCtx.Finish64();
  15110. name += "$";
  15111. name += BfTypeUtils::HashEncode64(hashVal);
  15112. return name;
  15113. }
  15114. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  15115. {
  15116. if (localMethod->mMethodDef != NULL)
  15117. return localMethod->mMethodDef;
  15118. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15119. auto declMethodState = localMethod->mDeclMethodState;
  15120. auto declMixinState = localMethod->mDeclMixinState;
  15121. auto typeInst = mCurTypeInstance;
  15122. BfAstNode* body = NULL;
  15123. BfAstNode* anchorNode = NULL;
  15124. auto _AllocDirectTypeRef = [&](BfType* type)
  15125. {
  15126. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  15127. directTypeRef->Init(type);
  15128. return directTypeRef;
  15129. };
  15130. auto methodDeclaration = localMethod->mMethodDeclaration;
  15131. if (methodDeclaration != NULL)
  15132. {
  15133. body = methodDeclaration->mBody;
  15134. anchorNode = methodDeclaration->mOpenParen;
  15135. }
  15136. else
  15137. {
  15138. body = localMethod->mLambdaBindExpr->mBody;
  15139. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  15140. }
  15141. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  15142. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  15143. BfMethodDef* methodDef;
  15144. if (methodDeclaration != NULL)
  15145. {
  15146. BfDefBuilder defBuilder(mCompiler->mSystem);
  15147. defBuilder.mPassInstance = mCompiler->mPassInstance;
  15148. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  15149. BfMethodDef* outerMethodDef = NULL;
  15150. if (localMethod->mOuterLocalMethod != NULL)
  15151. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  15152. else
  15153. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  15154. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  15155. }
  15156. else
  15157. {
  15158. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  15159. methodDef = new BfMethodDef();
  15160. methodDef->mName = localMethod->mMethodName;
  15161. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  15162. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  15163. methodDef->mBody = body;
  15164. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  15165. {
  15166. auto paramType = invokeMethod->GetParamType(paramIdx);
  15167. String paramName;
  15168. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  15169. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  15170. else
  15171. paramName = invokeMethod->GetParamName(paramIdx);
  15172. auto paramDef = new BfParameterDef();
  15173. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  15174. paramDef->mName = paramName;
  15175. methodDef->mParams.Add(paramDef);
  15176. }
  15177. }
  15178. methodDef->mIdx = ~methodLocalIdx;
  15179. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  15180. methodDef->mName = localMethod->mExpectedFullName;
  15181. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  15182. //
  15183. // if (!localMethod->mExpectedFullName.IsEmpty())
  15184. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  15185. methodDef->mIsStatic = true;
  15186. methodDef->mIsLocalMethod = true;
  15187. methodDef->mIsVirtual = false;
  15188. localMethod->mMethodDef = methodDef;
  15189. auto methodInstanceGroup = new BfMethodInstanceGroup();
  15190. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  15191. methodInstanceGroup->mMethodIdx = -1;
  15192. methodInstanceGroup->mOwner = mCurTypeInstance;
  15193. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  15194. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  15195. {
  15196. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  15197. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  15198. }
  15199. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  15200. {
  15201. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  15202. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  15203. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  15204. {
  15205. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  15206. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  15207. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  15208. autoComplete->mDefType = typeInst->mTypeDef;
  15209. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  15210. autoComplete->mReplaceLocalId = methodLocalIdx;
  15211. }
  15212. }
  15213. return localMethod->mMethodDef;
  15214. }
  15215. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  15216. {
  15217. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  15218. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  15219. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15220. auto declMethodState = localMethod->mDeclMethodState;
  15221. auto declMixinState = localMethod->mDeclMixinState;
  15222. auto callerMethodState = mCurMethodState;
  15223. auto typeInst = mCurTypeInstance;
  15224. auto methodDef = GetLocalMethodDef(localMethod);
  15225. BfAstNode* body = NULL;
  15226. auto methodDeclaration = localMethod->mMethodDeclaration;
  15227. if (methodDeclaration != NULL)
  15228. {
  15229. body = methodDeclaration->mBody;
  15230. }
  15231. else
  15232. {
  15233. body = localMethod->mLambdaBindExpr->mBody;
  15234. }
  15235. bool hadConcreteInterfaceGenericArgument = false;
  15236. BfTypeVector sanitizedMethodGenericArguments;
  15237. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  15238. // version of this method for this pass through the outermost method
  15239. int dependentGenericStartIdx = 0;
  15240. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15241. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  15242. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  15243. if (methodGenericArguments.size() == 0)
  15244. {
  15245. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15246. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  15247. }
  15248. else
  15249. {
  15250. int genericArgIdx = 0;
  15251. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  15252. // {
  15253. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  15254. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  15255. // }
  15256. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15257. {
  15258. auto genericArgType = methodGenericArguments[genericArgIdx];
  15259. BF_ASSERT(!genericArgType->IsRef());
  15260. if (genericArgType->IsConcreteInterfaceType())
  15261. {
  15262. hadConcreteInterfaceGenericArgument = true;
  15263. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  15264. genericArgType = concreteInterfaceType->mInterface;
  15265. }
  15266. sanitizedMethodGenericArguments.push_back(genericArgType);
  15267. }
  15268. }
  15269. bool wantPrematureMethodInstance = false;
  15270. if (!force)
  15271. {
  15272. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  15273. }
  15274. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  15275. bool isDefaultPass = true;
  15276. BfTypeVector lookupMethodGenericArguments;
  15277. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15278. {
  15279. auto genericArgType = methodGenericArguments[genericArgIdx];
  15280. BF_ASSERT(!genericArgType->IsRef());
  15281. lookupMethodGenericArguments.Add(genericArgType);
  15282. if (genericArgType->IsGenericParam())
  15283. {
  15284. auto genericParam = (BfGenericParamType*)genericArgType;
  15285. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  15286. isDefaultPass = false;
  15287. }
  15288. else
  15289. {
  15290. isDefaultPass = false;
  15291. }
  15292. }
  15293. bool hadExistingMethodInstance = false;
  15294. if (methodInstance != NULL)
  15295. {
  15296. hadExistingMethodInstance = true;
  15297. }
  15298. else
  15299. {
  15300. if (isDefaultPass)
  15301. {
  15302. methodInstance = methodInstGroup->mDefault;
  15303. if (methodInstance != NULL)
  15304. {
  15305. hadExistingMethodInstance = true;
  15306. }
  15307. else
  15308. {
  15309. methodInstance = new BfMethodInstance();
  15310. methodInstGroup->mDefault = methodInstance;
  15311. }
  15312. }
  15313. else
  15314. {
  15315. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  15316. if (methodInstGroup->mMethodSpecializationMap == NULL)
  15317. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  15318. BfMethodInstance** methodInstancePtr = NULL;
  15319. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  15320. {
  15321. methodInstance = *methodInstancePtr;
  15322. hadExistingMethodInstance = true;
  15323. }
  15324. else
  15325. {
  15326. methodInstance = new BfMethodInstance();
  15327. *methodInstancePtr = methodInstance;
  15328. }
  15329. }
  15330. }
  15331. if (hadExistingMethodInstance)
  15332. {
  15333. if ((!methodInstance->mDisallowCalling) ||
  15334. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  15335. return BfModuleMethodInstance(methodInstance);
  15336. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  15337. }
  15338. else
  15339. {
  15340. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  15341. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  15342. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  15343. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  15344. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  15345. methodInstance->mMethodDef = methodDef;
  15346. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  15347. if (hadConcreteInterfaceGenericArgument)
  15348. methodInstance->mIgnoreBody = true;
  15349. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  15350. for (auto genericArg : sanitizedMethodGenericArguments)
  15351. {
  15352. if (genericArg->IsPrimitiveType())
  15353. genericArg = GetWrappedStructType(genericArg);
  15354. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  15355. }
  15356. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15357. {
  15358. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  15359. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  15360. }
  15361. SetupMethodIdHash(methodInstance);
  15362. }
  15363. auto _SetupMethodInstance = [&]()
  15364. {
  15365. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  15366. // Generic constraints
  15367. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15368. {
  15369. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  15370. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  15371. }
  15372. };
  15373. //////////////////////////////////////////////////////////////////////////
  15374. auto _VisitLambdaBody = [&]()
  15375. {
  15376. if (localMethod->mDeclOnly)
  15377. return;
  15378. if (mCompiler->mCanceling)
  15379. return;
  15380. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  15381. {
  15382. VisitCodeBlock(blockBody);
  15383. }
  15384. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  15385. CreateValueFromExpression(bodyExpr);
  15386. };
  15387. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  15388. {
  15389. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  15390. auto result = ResolveTypeRef(typeRef);
  15391. if (result == NULL)
  15392. result = mContext->mBfObjectType;
  15393. return result;
  15394. };
  15395. BfTypeInstance* outerClosure = NULL;
  15396. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  15397. outerClosure = declMethodState->mClosureState->mClosureType;
  15398. BfMethodState methodState;
  15399. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  15400. BfIRFunctionType funcType;
  15401. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15402. SizedArray<BfIRType, 0> paramTypes;
  15403. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, false);
  15404. mBfIRBuilder->SaveDebugLocation();
  15405. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  15406. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15407. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15408. BfDeferredLocalAssignData deferredLocalAssignData;
  15409. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  15410. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  15411. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  15412. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15413. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  15414. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  15415. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  15416. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  15417. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  15418. methodState.mIRFunction = declMethodState->mIRFunction;
  15419. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  15420. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  15421. BfClosureState closureState;
  15422. if (methodDef->mMethodType == BfMethodType_Mixin)
  15423. {
  15424. if (declMethodState != NULL)
  15425. {
  15426. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  15427. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  15428. else if (declMethodState->mMethodInstance != NULL)
  15429. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  15430. }
  15431. }
  15432. if (closureState.mReturnType == NULL)
  15433. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  15434. closureState.mCapturing = true;
  15435. closureState.mLocalMethod = localMethod;
  15436. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  15437. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  15438. methodState.mClosureState = &closureState;
  15439. closureState.mClosureType = outerClosure;
  15440. int outerLocalsCount = (int)methodState.mLocals.size();
  15441. if (!hadExistingMethodInstance)
  15442. {
  15443. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  15444. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  15445. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  15446. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  15447. auto declareModule = this;
  15448. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15449. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15450. BF_ASSERT(declareModule != NULL);
  15451. methodInstance->mDeclModule = declareModule;
  15452. _SetupMethodInstance();
  15453. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15454. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  15455. }
  15456. if (wantPrematureMethodInstance)
  15457. {
  15458. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  15459. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  15460. // its true method instance
  15461. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  15462. //BF_ASSERT(moduleMethodInstance);
  15463. return BfModuleMethodInstance(methodInstance);
  15464. }
  15465. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  15466. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  15467. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  15468. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  15469. closureState.mClosureMethodDef = methodDef;
  15470. bool wantsVisitBody = true;
  15471. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  15472. wantsVisitBody = false;
  15473. if (methodInstance->mIsUnspecializedVariation)
  15474. wantsVisitBody = false;
  15475. if (wantsVisitBody)
  15476. {
  15477. BP_ZONE("VisitLambdaBody");
  15478. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  15479. // this capture stage for each of those times
  15480. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  15481. /*
  15482. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  15483. // that will not occur during the actual lambda method generation, for example: returning a value
  15484. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  15485. // our AST nodes will still be visited
  15486. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  15487. */
  15488. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15489. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  15490. mBfIRBuilder->SaveDebugLocation();
  15491. closureState.mCaptureVisitingBody = true;
  15492. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  15493. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  15494. NewScopeState();
  15495. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  15496. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  15497. {
  15498. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  15499. for (auto localDef : methodState.mLocals)
  15500. {
  15501. if (localDef->mResolvedType->IsVar())
  15502. continue;
  15503. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  15504. }
  15505. }
  15506. _VisitLambdaBody();
  15507. RestoreScopeState();
  15508. //ProcessMethod(methodInstance);
  15509. closureState.mCaptureVisitingBody = false;
  15510. mBfIRBuilder->RestoreDebugLocation();
  15511. }
  15512. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  15513. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  15514. {
  15515. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  15516. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  15517. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  15518. }
  15519. //RestoreScopeState();
  15520. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  15521. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  15522. closureState.mClosureMethodDef = NULL;
  15523. for (auto methodInstance : closureState.mLocalMethodRefs)
  15524. {
  15525. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  15526. }
  15527. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  15528. prevIgnoreWrites.Restore();
  15529. std::multiset<BfClosureCapturedEntry> capturedEntries;
  15530. //
  15531. {
  15532. auto varMethodState = declMethodState;
  15533. while (varMethodState != NULL)
  15534. {
  15535. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  15536. {
  15537. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  15538. methodDef->mIsStatic = false;
  15539. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15540. methodDef->mIsMutating = true;
  15541. }
  15542. bool copyOuterCaptures = false;
  15543. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  15544. {
  15545. auto localVar = varMethodState->mLocals[localIdx];
  15546. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15547. {
  15548. if (localVar->mIsThis)
  15549. {
  15550. // We can only set mutating if our owning type is mutating
  15551. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  15552. {
  15553. if (mCurTypeInstance->IsValueType())
  15554. {
  15555. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15556. methodDef->mIsMutating = true;
  15557. }
  15558. }
  15559. methodDef->mIsStatic = false;
  15560. continue;
  15561. }
  15562. if ((localVar->mIsThis) && (outerClosure != NULL))
  15563. {
  15564. continue;
  15565. }
  15566. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  15567. {
  15568. closureState.mConstLocals.push_back(*localVar);
  15569. continue;
  15570. }
  15571. BfClosureCapturedEntry capturedEntry;
  15572. auto capturedType = localVar->mResolvedType;
  15573. bool captureByRef = false;
  15574. if (!capturedType->IsRef())
  15575. {
  15576. if (localVar->mIsThis)
  15577. {
  15578. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  15579. captureByRef = true;
  15580. }
  15581. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15582. captureByRef = true;
  15583. }
  15584. else
  15585. {
  15586. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  15587. {
  15588. capturedType = ((BfRefType*)capturedType)->mElementType;
  15589. }
  15590. }
  15591. if (captureByRef)
  15592. {
  15593. //capturedEntry.mIsByReference = true;
  15594. capturedType = CreateRefType(capturedType);
  15595. }
  15596. else
  15597. {
  15598. //capturedEntry.mIsByReference = false;
  15599. }
  15600. capturedEntry.mNameNode = localVar->mNameNode;
  15601. capturedEntry.mType = capturedType;
  15602. capturedEntry.mName = localVar->mName;
  15603. //capturedEntry.mLocalVarDef = localVar;
  15604. capturedEntries.insert(capturedEntry);
  15605. }
  15606. }
  15607. varMethodState = varMethodState->mPrevMethodState;
  15608. if ((varMethodState == NULL) ||
  15609. (varMethodState->mMixinState != NULL) ||
  15610. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  15611. break;
  15612. }
  15613. }
  15614. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  15615. {
  15616. auto fieldDef = copyField->GetFieldDef();
  15617. BfClosureCapturedEntry capturedEntry;
  15618. capturedEntry.mName = copyField->GetFieldDef()->mName;
  15619. capturedEntry.mType = copyField->mResolvedType;
  15620. if (capturedEntry.mType->IsRef())
  15621. {
  15622. // Keep by ref
  15623. }
  15624. else if (!fieldDef->mIsReadOnly)
  15625. {
  15626. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  15627. }
  15628. capturedEntries.insert(capturedEntry);
  15629. }
  15630. int captureIdx = 0;
  15631. for (auto& capturedEntry : capturedEntries)
  15632. {
  15633. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  15634. }
  15635. /*if (isDefaultPass)
  15636. {
  15637. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  15638. int captureIdx = 0;
  15639. for (auto& capturedEntry : capturedEntries)
  15640. {
  15641. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  15642. BfParameterDef* paramDef = new BfParameterDef();
  15643. paramDef->mName = capturedEntry.mName;
  15644. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  15645. directTypeRef->mType = capturedEntry.mType;
  15646. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  15647. paramDef->mTypeRef = directTypeRef;
  15648. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  15649. methodDef->mParams.Insert(captureIdx, paramDef);
  15650. captureIdx++;
  15651. }
  15652. }
  15653. else
  15654. {
  15655. auto defaultMethodInstance = methodInstGroup->mDefault;
  15656. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  15657. }*/
  15658. methodState.Reset();
  15659. closureState.mCapturing = false;
  15660. //////////////////////////////////////////////////////////////////////////
  15661. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  15662. if (methodInstance->mReturnType != NULL)
  15663. {
  15664. BF_ASSERT(methodInstance->mDisallowCalling);
  15665. // We did a premature declaration (without captures)
  15666. methodInstance->UndoDeclaration();
  15667. methodInstance->mDisallowCalling = false;
  15668. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  15669. }
  15670. auto declareModule = this;
  15671. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15672. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15673. BF_ASSERT(declareModule != NULL);
  15674. methodInstance->mDeclModule = declareModule;
  15675. _SetupMethodInstance();
  15676. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  15677. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15678. closureState.mReturnType = methodInstance->mReturnType;
  15679. mCompiler->mStats.mMethodsQueued++;
  15680. mCompiler->UpdateCompletion();
  15681. declareModule->mIncompleteMethodCount++;
  15682. mCompiler->mStats.mMethodsProcessed++;
  15683. if (!methodInstance->mIsReified)
  15684. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  15685. auto deferMethodState = rootMethodState;
  15686. // 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)
  15687. if ((!localMethod->mDeclOnly) && (!methodInstance->mIsUnspecializedVariation) &&
  15688. (!mWantsIRIgnoreWrites) && (methodDef->mMethodType != BfMethodType_Mixin))
  15689. {
  15690. BP_ZONE("BfDeferredLocalMethod:create");
  15691. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  15692. deferredLocalMethod->mLocalMethod = localMethod;
  15693. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  15694. deferredLocalMethod->mMethodInstance = methodInstance;
  15695. auto checkMethodState = declMethodState;
  15696. while (checkMethodState != NULL)
  15697. {
  15698. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  15699. {
  15700. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  15701. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15702. }
  15703. if (checkMethodState->mMixinState != NULL)
  15704. {
  15705. BfMixinRecord mixinRecord;
  15706. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  15707. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15708. }
  15709. checkMethodState = checkMethodState->mPrevMethodState;
  15710. }
  15711. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  15712. }
  15713. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15714. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  15715. mBfIRBuilder->RestoreDebugLocation();
  15716. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  15717. {
  15718. auto checkMethodState = mCurMethodState;
  15719. while (checkMethodState != NULL)
  15720. {
  15721. BfLocalMethod* nextLocalMethod = NULL;
  15722. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  15723. {
  15724. while (nextLocalMethod != NULL)
  15725. {
  15726. auto checkLocalMethod = nextLocalMethod;
  15727. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  15728. if (checkLocalMethod == localMethod)
  15729. continue;
  15730. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  15731. continue;
  15732. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  15733. if (checkMethodInstance == NULL)
  15734. continue; // Not generated yet
  15735. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  15736. {
  15737. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  15738. if (bfError != NULL)
  15739. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  15740. }
  15741. }
  15742. }
  15743. checkMethodState = checkMethodState->mPrevMethodState;
  15744. }
  15745. }
  15746. return BfModuleMethodInstance(methodInstance);
  15747. }
  15748. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  15749. {
  15750. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  15751. return 0;
  15752. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15753. int rootMethodGenericParamCount = 0;
  15754. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15755. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  15756. if (mCurMethodInstance == NULL)
  15757. return rootMethodGenericParamCount;
  15758. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  15759. return rootMethodGenericParamCount;
  15760. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  15761. if (callerLocalMethod == NULL)
  15762. return rootMethodGenericParamCount;
  15763. BfLocalMethod* calledLocalMethod = NULL;
  15764. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  15765. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  15766. {
  15767. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  15768. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  15769. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  15770. }
  15771. return rootMethodGenericParamCount;
  15772. }
  15773. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  15774. {
  15775. auto methodDef = methodInstance->mMethodDef;
  15776. if (methodInstance->GetCustomAttributes() != NULL)
  15777. return;
  15778. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15779. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  15780. auto typeInstance = methodInstance->GetOwner();
  15781. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  15782. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15783. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL))
  15784. {
  15785. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15786. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15787. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(methodDeclaration->mAttributes,
  15788. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method);
  15789. }
  15790. else if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mAttributes != NULL))
  15791. {
  15792. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15793. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15794. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mAttributes, BfAttributeTargets_Method);
  15795. }
  15796. }
  15797. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  15798. {
  15799. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  15800. {
  15801. // Don't create a func
  15802. return;
  15803. }
  15804. auto typeInstance = methodInstance->GetOwner();
  15805. auto methodDef = methodInstance->mMethodDef;
  15806. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  15807. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  15808. if (mCompiler->mResolvePassData == NULL)
  15809. {
  15810. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  15811. {
  15812. typeInstance->mHasStaticInitMethod = true;
  15813. }
  15814. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  15815. {
  15816. typeInstance->mHasStaticDtorMethod = true;
  15817. }
  15818. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  15819. {
  15820. typeInstance->mHasStaticMarkMethod = true;
  15821. }
  15822. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  15823. {
  15824. typeInstance->mHasTLSFindMethod = true;
  15825. }
  15826. }
  15827. if (isTemporaryFunc)
  15828. {
  15829. BF_ASSERT((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL));
  15830. mangledName = "autocomplete_tmp";
  15831. }
  15832. if (!mBfIRBuilder->mIgnoreWrites)
  15833. {
  15834. BfIRFunction prevFunc;
  15835. // Remove old version (if we have one)
  15836. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15837. if (prevFunc)
  15838. {
  15839. if (methodDef->mIsExtern)
  15840. {
  15841. // Allow this
  15842. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  15843. }
  15844. else if (typeInstance->IsIRFuncUsed(prevFunc))
  15845. {
  15846. // We can have a collision of names when we have generic methods that differ only in
  15847. // their constraints, but they should only collide in their unspecialized form
  15848. // since only one will be chosen for a given concrete type
  15849. mCurMethodInstance->mMangleWithIdx = true;
  15850. mangledName.Clear();
  15851. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  15852. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15853. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  15854. }
  15855. else
  15856. {
  15857. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  15858. mBfIRBuilder->Func_EraseFromParent(prevFunc);
  15859. }
  15860. }
  15861. }
  15862. if (typeInstance != mContext->mBfObjectType)
  15863. {
  15864. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  15865. GetMethodCustomAttributes(methodInstance);
  15866. }
  15867. // if (prevFunc)
  15868. // {
  15869. // if (methodDef->mIsExtern)
  15870. // {
  15871. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  15872. // methodInstance->mIRFunction = prevFunc;
  15873. // }
  15874. // else
  15875. // {
  15876. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  15877. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  15878. // {
  15879. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  15880. // BfLogSysM("Ignoring function name collision\n");
  15881. // }
  15882. // else
  15883. // {
  15884. // if (methodDef->mMethodDeclaration == NULL)
  15885. // {
  15886. // AssertErrorState();
  15887. // }
  15888. // else
  15889. // {
  15890. // BF_ASSERT(mIsSpecialModule);
  15891. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  15892. // {
  15893. // // We shouldn't have name collisions on the first run!
  15894. // AssertErrorState();
  15895. // }
  15896. // }
  15897. // }
  15898. // BfLogSysM("Before erase\n");
  15899. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  15900. // }
  15901. // }
  15902. bool isIntrinsic = false;
  15903. if (!methodInstance->mIRFunction)
  15904. {
  15905. BfIRFunction func;
  15906. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  15907. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  15908. {
  15909. if (!mIsReified)
  15910. wantsLLVMFunc = false;
  15911. }*/
  15912. if (wantsLLVMFunc)
  15913. {
  15914. func = GetIntrinsic(methodInstance, true);
  15915. if (func)
  15916. {
  15917. isIntrinsic = true;
  15918. }
  15919. else
  15920. {
  15921. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  15922. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  15923. if (methodInstance->mAlwaysInline)
  15924. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15925. // if (prevFunc)
  15926. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  15927. }
  15928. methodInstance->mIRFunction = func;
  15929. //if (!ignoreWrites)
  15930. //BF_ASSERT(!func.IsFake());
  15931. }
  15932. }
  15933. if (outIsIntrinsic != NULL)
  15934. *outIsIntrinsic = isIntrinsic;
  15935. if (!isIntrinsic)
  15936. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  15937. }
  15938. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  15939. {
  15940. if (methodInstance->mHotMethod != NULL)
  15941. return;
  15942. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  15943. {
  15944. auto srcTypeInst = methodInstance->GetOwner();
  15945. StringT<128> mangledName = inMangledName;
  15946. if (mangledName.IsEmpty())
  15947. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  15948. // We always keep the current primary method at the same address
  15949. BfHotMethod* hotMethod;
  15950. BfHotMethod** hotMethodPtr;
  15951. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  15952. {
  15953. hotMethod = new BfHotMethod();
  15954. *hotMethodPtr = hotMethod;
  15955. hotMethod->mRefCount = 1;
  15956. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15957. #ifdef BF_DBG_HOTMETHOD_IDX
  15958. static int sMethodIdx = 0;
  15959. hotMethod->mMethodIdx = sMethodIdx++;
  15960. #endif
  15961. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15962. }
  15963. else
  15964. {
  15965. hotMethod = *hotMethodPtr;
  15966. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  15967. {
  15968. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  15969. auto prevHotMethod = *hotMethodPtr;
  15970. hotMethod = new BfHotMethod();
  15971. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15972. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  15973. hotDupMethod->mRefCount++;
  15974. prevHotMethod->mReferences.Add(hotDupMethod);
  15975. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  15976. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15977. }
  15978. else if (mCompiler->IsHotCompile())
  15979. {
  15980. // Link the previous version into the mPrevVersion
  15981. BfHotMethod* prevMethod = new BfHotMethod();
  15982. prevMethod->mRefCount = 1;
  15983. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  15984. hotMethod->mPrevVersion = prevMethod;
  15985. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  15986. hotMethod->mSrcTypeVersion = NULL;
  15987. prevMethod->mFlags = hotMethod->mFlags;
  15988. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  15989. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  15990. #ifdef BF_DBG_HOTMETHOD_NAME
  15991. prevMethod->mMangledName = hotMethod->mMangledName;
  15992. #endif
  15993. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  15994. }
  15995. else
  15996. {
  15997. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15998. hotMethod->Clear(true);
  15999. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16000. }
  16001. }
  16002. if (methodInstance->mIsClosure)
  16003. {
  16004. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  16005. }
  16006. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  16007. hotMethod->mSrcTypeVersion->mRefCount++;
  16008. hotMethod->mRefCount++;
  16009. #ifdef BF_DBG_HOTMETHOD_NAME
  16010. hotMethod->mMangledName = mangledName;
  16011. #endif
  16012. methodInstance->mHotMethod = hotMethod;
  16013. }
  16014. }
  16015. // methodDeclaration is NULL for default constructors
  16016. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  16017. {
  16018. BP_ZONE("BfModule::BfMethodDeclaration");
  16019. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  16020. // to effectively make mIgnoreWrites method-scoped
  16021. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized);
  16022. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  16023. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  16024. if (mCompiler->IsAutocomplete())
  16025. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  16026. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  16027. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16028. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  16029. if (mAwaitingInitFinish)
  16030. FinishInit();
  16031. auto typeInstance = mCurTypeInstance;
  16032. auto typeDef = typeInstance->mTypeDef;
  16033. auto methodDef = mCurMethodInstance->mMethodDef;
  16034. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  16035. if (typeInstance->IsClosure())
  16036. {
  16037. if (methodDef->mName == "Invoke")
  16038. return;
  16039. }
  16040. auto methodInstance = mCurMethodInstance;
  16041. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  16042. addToWorkList = false;
  16043. bool hasNonGenericParams = false;
  16044. bool hasGenericParams = false;
  16045. int dependentGenericStartIdx = 0;
  16046. if (methodDef->mIsLocalMethod)
  16047. {
  16048. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  16049. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  16050. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  16051. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  16052. // over the local method each time
  16053. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  16054. dependentGenericStartIdx = 0;
  16055. if (rootMethodInstance->mMethodInfoEx != NULL)
  16056. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16057. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  16058. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  16059. }
  16060. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  16061. {
  16062. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  16063. if (genericArgType->IsGenericParam())
  16064. {
  16065. hasGenericParams = true;
  16066. auto genericParam = (BfGenericParamType*)genericArgType;
  16067. methodInstance->mIsUnspecialized = true;
  16068. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  16069. methodInstance->mIsUnspecializedVariation = true;
  16070. }
  16071. else
  16072. {
  16073. hasNonGenericParams = true;
  16074. if (genericArgType->IsUnspecializedType())
  16075. {
  16076. methodInstance->mIsUnspecialized = true;
  16077. methodInstance->mIsUnspecializedVariation = true;
  16078. }
  16079. }
  16080. }
  16081. if ((hasGenericParams) && (hasNonGenericParams))
  16082. {
  16083. methodInstance->mIsUnspecializedVariation = true;
  16084. }
  16085. if (typeInstance->IsUnspecializedType())
  16086. {
  16087. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  16088. // actually want to do method processing on it
  16089. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  16090. methodInstance->mIsUnspecializedVariation = true;
  16091. methodInstance->mIsUnspecialized = true;
  16092. }
  16093. methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  16094. for (auto genericParamDef : methodDef->mGenericParams)
  16095. {
  16096. if (mCompiler->IsAutocomplete())
  16097. {
  16098. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16099. //autoComplete->CheckTypeRef()
  16100. }
  16101. }
  16102. if (methodInstance->mIsUnspecializedVariation)
  16103. {
  16104. }
  16105. if (methodInstance->mIsUnspecializedVariation)
  16106. BF_ASSERT(methodInstance->mIsUnspecialized);
  16107. if (methodDef->mMethodType == BfMethodType_Mixin)
  16108. methodInstance->mIsUnspecialized = true;
  16109. BfAutoComplete* bfAutocomplete = NULL;
  16110. if (mCompiler->mResolvePassData != NULL)
  16111. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  16112. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->GetNumGenericArguments(); genericParamIdx++)
  16113. {
  16114. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  16115. ResolveGenericParamConstraints(methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx], methodDef->mGenericParams, genericParamIdx);
  16116. if (bfAutocomplete != NULL)
  16117. {
  16118. for (auto nameNode : genericParamDef->mNameNodes)
  16119. {
  16120. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  16121. }
  16122. }
  16123. }
  16124. if (methodInstance->mMethodInfoEx != NULL)
  16125. {
  16126. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  16127. {
  16128. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  16129. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16130. if (genericParam->mTypeConstraint != NULL)
  16131. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16132. }
  16133. }
  16134. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  16135. {
  16136. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16137. BfAstNode* nameNode = methodDeclaration->mNameNode;
  16138. if (nameNode == NULL)
  16139. {
  16140. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  16141. nameNode = ctorDeclaration->mThisToken;
  16142. }
  16143. if (autoComplete->IsAutocompleteNode(nameNode))
  16144. {
  16145. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  16146. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  16147. autoComplete->mDefType = typeDef;
  16148. autoComplete->mDefMethod = methodDef;
  16149. autoComplete->SetDefinitionLocation(nameNode);
  16150. if (methodDef->mIsOverride)
  16151. {
  16152. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  16153. {
  16154. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  16155. if (ventry.mDeclaringMethod.mMethodNum == -1)
  16156. continue;
  16157. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  16158. if (virtMethod != NULL)
  16159. {
  16160. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  16161. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  16162. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  16163. {
  16164. // Is matching method
  16165. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  16166. {
  16167. auto baseType = typeInstance->mBaseType;
  16168. if (baseType != NULL)
  16169. {
  16170. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  16171. baseType = baseType->mBaseType;
  16172. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  16173. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  16174. autoComplete->mDefType = baseType->mTypeDef;
  16175. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  16176. }
  16177. }
  16178. break;
  16179. }
  16180. }
  16181. }
  16182. }
  16183. }
  16184. }
  16185. bool reportErrors = true;
  16186. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16187. reportErrors = true;
  16188. // Only the defining contexts needs to report errors here
  16189. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  16190. if (methodDef->mMethodType == BfMethodType_Dtor)
  16191. {
  16192. if (methodDef->mIsStatic)
  16193. {
  16194. }
  16195. else
  16196. {
  16197. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  16198. {
  16199. BfAstNode* refNode = methodDeclaration;
  16200. if (refNode == NULL)
  16201. {
  16202. // Whatever caused this ctor to be generated should have caused another failure
  16203. // But that failure might not be generated until the ctor is generated
  16204. }
  16205. else
  16206. {
  16207. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  16208. if (dtorDecl != NULL)
  16209. refNode = dtorDecl->mThisToken;
  16210. Fail("Structs cannot have destructors", refNode);
  16211. }
  16212. }
  16213. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16214. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  16215. (mCurTypeInstance != mContext->mBfObjectType))
  16216. {
  16217. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  16218. }
  16219. }
  16220. }
  16221. BfType* resolvedReturnType = NULL;
  16222. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  16223. (methodDef->mReturnTypeRef != NULL))
  16224. {
  16225. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16226. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  16227. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  16228. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  16229. {
  16230. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  16231. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16232. }
  16233. if (resolvedReturnType == NULL)
  16234. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16235. }
  16236. else
  16237. {
  16238. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  16239. }
  16240. BF_ASSERT(resolvedReturnType != NULL);
  16241. mCurMethodInstance->mReturnType = resolvedReturnType;
  16242. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  16243. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  16244. //if (!methodInstance->IsSpecializedGenericMethod())
  16245. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16246. if (methodDef->mExplicitInterface != NULL)
  16247. {
  16248. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16249. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  16250. auto explicitInterface = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  16251. if (explicitInterface != NULL)
  16252. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  16253. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  16254. {
  16255. bool interfaceFound = false;
  16256. for (auto ifaceInst : typeInstance->mInterfaces)
  16257. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  16258. if (!interfaceFound)
  16259. {
  16260. if (methodDef->mMethodDeclaration != NULL)
  16261. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  16262. else
  16263. {
  16264. // For property decls, we should have already given the error during type population
  16265. if (mCompiler->mRevision == 1)
  16266. AssertErrorState();
  16267. }
  16268. }
  16269. }
  16270. }
  16271. bool isThisStruct = mCurTypeInstance->IsStruct();
  16272. BfType* thisType = NULL;
  16273. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  16274. {
  16275. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  16276. {
  16277. thisType = mCurTypeInstance;
  16278. if (thisType == NULL)
  16279. return;
  16280. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  16281. {
  16282. BfTypeUtils::SplatIterate([&](BfType* checkType)
  16283. {
  16284. PopulateType(checkType, BfPopulateType_Data);
  16285. }, thisType);
  16286. }
  16287. }
  16288. else
  16289. {
  16290. thisType = mCurTypeInstance;
  16291. PopulateType(thisType, BfPopulateType_Declaration);
  16292. }
  16293. }
  16294. int implicitParamCount = 0;
  16295. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  16296. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  16297. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  16298. bool hadDelegateParams = false;
  16299. bool hadParams = false;
  16300. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  16301. {
  16302. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  16303. BfParameterDef* paramDef = NULL;
  16304. int paramDefIdx = -1;
  16305. if (paramIdx < implicitParamCount)
  16306. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  16307. else
  16308. {
  16309. paramDefIdx = paramIdx - implicitParamCount;
  16310. paramDef = methodDef->mParams[paramDefIdx];
  16311. }
  16312. if (hadParams)
  16313. break;
  16314. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  16315. (paramDef->mParamKind != BfParamKind_AppendIdx))
  16316. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  16317. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  16318. {
  16319. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16320. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16321. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  16322. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  16323. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  16324. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  16325. }
  16326. BfType* resolvedParamType = NULL;
  16327. if (closureCaptureEntry != NULL)
  16328. resolvedParamType = closureCaptureEntry->mType;
  16329. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  16330. {
  16331. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  16332. resolvedParamType = mContext->mBfObjectType;
  16333. }
  16334. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  16335. {
  16336. if (methodDef->mMethodType != BfMethodType_Mixin)
  16337. {
  16338. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  16339. resolvedParamType = mContext->mBfObjectType;
  16340. }
  16341. else
  16342. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16343. }
  16344. BfType* unresolvedParamType = resolvedParamType;
  16345. bool wasGenericParam = false;
  16346. if (resolvedParamType == NULL)
  16347. {
  16348. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16349. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration,
  16350. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  16351. }
  16352. if (resolvedParamType == NULL)
  16353. {
  16354. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16355. unresolvedParamType = resolvedParamType;
  16356. if (mCurTypeInstance->IsBoxed())
  16357. {
  16358. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  16359. // If we failed a lookup here then we better have also failed it in the original type
  16360. BF_ASSERT(boxedType->mElementType->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType));
  16361. }
  16362. }
  16363. if (!methodInstance->IsSpecializedGenericMethod())
  16364. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16365. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  16366. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  16367. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  16368. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  16369. {
  16370. BfMethodState methodState;
  16371. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16372. methodState.mTempKind = BfMethodState::TempKind_Static;
  16373. BfTypedValue defaultValue;
  16374. if (resolvedParamType->IsConstExprValue())
  16375. {
  16376. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  16377. BfExprEvaluator exprEvaluator(this);
  16378. exprEvaluator.mExpectingType = constExprType->mType;
  16379. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  16380. defaultValue = exprEvaluator.GetResult();
  16381. }
  16382. else
  16383. {
  16384. BfConstResolver constResolver(this);
  16385. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, BfConstResolveFlag_NoCast);
  16386. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  16387. {
  16388. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  16389. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  16390. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  16391. {
  16392. defaultValue = castedDefaultValue; // Good!
  16393. }
  16394. else if (!CanImplicitlyCast(defaultValue, resolvedParamType))
  16395. {
  16396. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  16397. // a conversion operator.
  16398. // This should throw an error
  16399. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  16400. AssertErrorState();
  16401. if (!defaultValue.mValue.IsConst())
  16402. defaultValue = BfTypedValue();
  16403. }
  16404. }
  16405. }
  16406. if (!defaultValue)
  16407. {
  16408. defaultValue = GetDefaultTypedValue(resolvedParamType);
  16409. if (!defaultValue.mValue.IsConst())
  16410. defaultValue = BfTypedValue();
  16411. }
  16412. if (defaultValue)
  16413. {
  16414. BF_ASSERT(defaultValue.mValue.IsConst());
  16415. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  16416. mCurMethodInstance->mDefaultValues.Add(BfIRValue());
  16417. CurrentAddToConstHolder(defaultValue.mValue);
  16418. mCurMethodInstance->mDefaultValues.Add(defaultValue.mValue);
  16419. }
  16420. }
  16421. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  16422. {
  16423. bool addParams = true;
  16424. bool isValid = false;
  16425. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  16426. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  16427. {
  16428. // Span<T>
  16429. isValid = true;
  16430. }
  16431. else if (resolvedParamType->IsArray())
  16432. {
  16433. // Array is the 'normal' params type
  16434. isValid = true;
  16435. }
  16436. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  16437. {
  16438. hadDelegateParams = true;
  16439. // This means we copy the params from a delegate
  16440. BfMethodParam methodParam;
  16441. methodParam.mResolvedType = resolvedParamType;
  16442. methodParam.mParamDefIdx = paramDefIdx;
  16443. methodParam.mDelegateParamIdx = 0;
  16444. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16445. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  16446. {
  16447. methodParam.mDelegateParamIdx = delegateParamIdx;
  16448. mCurMethodInstance->mParams.Add(methodParam);
  16449. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  16450. if (!methodInstance->IsSpecializedGenericMethod())
  16451. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16452. }
  16453. isValid = true;
  16454. addParams = false;
  16455. }
  16456. else if (resolvedParamType->IsGenericParam())
  16457. {
  16458. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  16459. if (genericParamInstance->mTypeConstraint != NULL)
  16460. {
  16461. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16462. if (genericParamInstance->mTypeConstraint->IsArray())
  16463. {
  16464. BfMethodParam methodParam;
  16465. methodParam.mResolvedType = resolvedParamType;
  16466. methodParam.mParamDefIdx = paramDefIdx;
  16467. mCurMethodInstance->mParams.Add(methodParam);
  16468. isValid = true;
  16469. }
  16470. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16471. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  16472. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  16473. {
  16474. mCurMethodInstance->mHadGenericDelegateParams = true;
  16475. isValid = true;
  16476. addParams = false;
  16477. }
  16478. }
  16479. }
  16480. else
  16481. {
  16482. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  16483. if ((paramTypeInst != NULL) &&
  16484. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  16485. {
  16486. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  16487. isValid = true;
  16488. addParams = false;
  16489. }
  16490. }
  16491. if (!isValid)
  16492. {
  16493. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  16494. // Failure case, make it an Object[]
  16495. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  16496. }
  16497. if (addParams)
  16498. {
  16499. BfMethodParam methodParam;
  16500. methodParam.mResolvedType = resolvedParamType;
  16501. methodParam.mParamDefIdx = paramDefIdx;
  16502. mCurMethodInstance->mParams.push_back(methodParam);
  16503. }
  16504. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  16505. {
  16506. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  16507. }
  16508. }
  16509. else
  16510. {
  16511. BfMethodParam methodParam;
  16512. methodParam.mResolvedType = resolvedParamType;
  16513. methodParam.mParamDefIdx = paramDefIdx;
  16514. mCurMethodInstance->mParams.Add(methodParam);
  16515. }
  16516. }
  16517. if (hadDelegateParams)
  16518. {
  16519. HashSet<String> usedNames;
  16520. Dictionary<int, int> usedParamDefIdx;
  16521. for (auto methodParam : methodDef->mParams)
  16522. {
  16523. usedNames.Add(methodParam->mName);
  16524. }
  16525. for (auto& methodParam : mCurMethodInstance->mParams)
  16526. {
  16527. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  16528. {
  16529. int* refCount = NULL;
  16530. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  16531. (*refCount)++;
  16532. }
  16533. }
  16534. for (auto& methodParam : mCurMethodInstance->mParams)
  16535. {
  16536. if (methodParam.mDelegateParamIdx != -1)
  16537. {
  16538. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  16539. methodParam.mDelegateParamNameCombine = true;
  16540. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16541. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  16542. if (usedNames.Contains(paramName))
  16543. methodParam.mDelegateParamNameCombine = true;
  16544. }
  16545. }
  16546. }
  16547. int argIdx = 0;
  16548. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  16549. if (methodInstance->HasStructRet())
  16550. argIdx++;
  16551. if (!methodDef->mIsStatic)
  16552. {
  16553. if (methodInstance->GetParamIsSplat(-1))
  16554. argIdx += methodInstance->GetParamType(-1)->GetSplatCount();
  16555. else if (!methodInstance->GetOwner()->IsValuelessType())
  16556. argIdx++;
  16557. }
  16558. for (auto& methodParam : mCurMethodInstance->mParams)
  16559. {
  16560. if (methodParam.mResolvedType->IsMethodRef())
  16561. {
  16562. methodParam.mIsSplat = true;
  16563. }
  16564. else if (methodParam.mResolvedType->IsComposite())
  16565. {
  16566. PopulateType(methodParam.mResolvedType, BfPopulateType_Data);
  16567. if (methodParam.mResolvedType->IsSplattable())
  16568. {
  16569. int splatCount = methodParam.mResolvedType->GetSplatCount();
  16570. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16571. {
  16572. methodParam.mIsSplat = true;
  16573. argIdx += splatCount;
  16574. continue;
  16575. }
  16576. }
  16577. }
  16578. argIdx++;
  16579. }
  16580. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  16581. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  16582. {
  16583. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  16584. }
  16585. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  16586. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  16587. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  16588. (!methodDef->mIsSkipCall))
  16589. {
  16590. if (methodDeclaration->mEndSemicolon == NULL)
  16591. {
  16592. AssertParseErrorState();
  16593. }
  16594. else
  16595. {
  16596. bool isError = true;
  16597. if (typeInstance->IsTypedPrimitive())
  16598. {
  16599. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16600. {
  16601. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  16602. {
  16603. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  16604. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  16605. {
  16606. isError = false;
  16607. }
  16608. }
  16609. }
  16610. }
  16611. if (isError)
  16612. {
  16613. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  16614. MethodToString(methodInstance).c_str()),
  16615. methodDef->GetRefNode());
  16616. }
  16617. }
  16618. }
  16619. if (methodDef->IsEmptyPartial())
  16620. hasExternSpecifier = true;
  16621. if (!methodInstance->IsAutocompleteMethod())
  16622. {
  16623. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  16624. int implicitParamCount = methodInstance->GetImplicitParamCount();
  16625. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  16626. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  16627. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  16628. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  16629. int paramIdx = 0;
  16630. int defaultParamIdx = 0;
  16631. while (true)
  16632. {
  16633. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  16634. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  16635. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  16636. {
  16637. paramIdx++;
  16638. continue;
  16639. }
  16640. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  16641. {
  16642. defaultParamIdx++;
  16643. continue;
  16644. }
  16645. if ((isDone) || (isDefaultDone))
  16646. {
  16647. // 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
  16648. // to cause us to throw an assertion in the declaration here
  16649. if (!defaultMethodInstance->mHadGenericDelegateParams)
  16650. BF_ASSERT((isDone) && (isDefaultDone));
  16651. break;
  16652. }
  16653. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType->IsGenericParam();
  16654. paramIdx++;
  16655. defaultParamIdx++;
  16656. }
  16657. }
  16658. StringT<128> mangledName;
  16659. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16660. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16661. {
  16662. auto paramType = methodInstance->GetParamType(paramIdx);
  16663. if (paramType->IsComposite())
  16664. PopulateType(paramType, BfPopulateType_Data);
  16665. if (!methodInstance->IsParamSkipped(paramIdx))
  16666. {
  16667. if (paramType->IsStruct())
  16668. {
  16669. //
  16670. }
  16671. else
  16672. {
  16673. PopulateType(paramType, BfPopulateType_Declaration);
  16674. }
  16675. }
  16676. }
  16677. // Only process method in default unspecialized mode, not in variations
  16678. if (methodInstance->mIsUnspecializedVariation)
  16679. return;
  16680. PopulateType(resolvedReturnType, BfPopulateType_Data);
  16681. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  16682. if (resolvedReturnType->IsValuelessType())
  16683. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  16684. if (!mBfIRBuilder->mIgnoreWrites)
  16685. {
  16686. bool isIntrinsic = false;
  16687. if (!methodInstance->mIRFunction)
  16688. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  16689. if (isIntrinsic)
  16690. {
  16691. addToWorkList = false;
  16692. }
  16693. }
  16694. auto func = methodInstance->mIRFunction;
  16695. // if (methodInstance->mIsReified)
  16696. // CheckHotMethod(methodInstance, mangledName);
  16697. 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);
  16698. SizedArray<BfIRMDNode, 8> diParams;
  16699. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  16700. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  16701. {
  16702. //CS0708
  16703. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  16704. }
  16705. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  16706. {
  16707. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  16708. methodDef->mIsVirtual = false;
  16709. }
  16710. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  16711. {
  16712. if (methodDef->mIsStatic)
  16713. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  16714. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  16715. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  16716. else if (methodDef->mMethodType == BfMethodType_Ctor)
  16717. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16718. else if (methodDef->mMethodType == BfMethodType_Dtor)
  16719. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16720. }
  16721. if (isTemporaryFunc)
  16722. {
  16723. // This handles temporary methods for autocomplete types
  16724. BF_ASSERT(mIsScratchModule);
  16725. BF_ASSERT(mCompiler->IsAutocomplete());
  16726. BfLogSysM("DoMethodDeclaration autocomplete bailout\n");
  16727. return; // Bail out early for autocomplete pass
  16728. }
  16729. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  16730. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  16731. // autocompleter. Why did we have this check anyway?
  16732. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  16733. {
  16734. AddMethodReference(methodInstance);
  16735. mFuncReferences[methodInstance] = func;
  16736. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  16737. }*/
  16738. if (mParentModule != NULL)
  16739. {
  16740. // For extension modules we need to keep track of our own methods so we can know which methods
  16741. // we have defined ourselves and which are from the parent module or other extensions
  16742. if (!func.IsFake())
  16743. mFuncReferences[methodInstance] = func;
  16744. }
  16745. if (addToWorkList)
  16746. {
  16747. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  16748. if (wasAwaitingDecl)
  16749. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16750. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  16751. {
  16752. if (!wasAwaitingDecl)
  16753. AddMethodToWorkList(methodInstance);
  16754. }
  16755. else
  16756. {
  16757. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  16758. methodInstance->mIgnoreBody = true;
  16759. if (typeInstance->IsUnspecializedType())
  16760. {
  16761. // Don't hold on to actual Function for unspecialized types
  16762. methodInstance->mIRFunction = BfIRFunction();
  16763. }
  16764. }
  16765. }
  16766. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  16767. (!methodDef->mIsLocalMethod) &&
  16768. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)))
  16769. {
  16770. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  16771. {
  16772. //TODO:
  16773. //CS0053
  16774. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  16775. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16776. methodDef->mReturnTypeRef, true);
  16777. }
  16778. else
  16779. {
  16780. //CS0050
  16781. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  16782. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16783. methodDef->mReturnTypeRef, true);
  16784. }
  16785. }
  16786. if ((typeInstance->IsInterface()) && (methodDef->mMethodType == BfMethodType_Ctor))
  16787. {
  16788. Fail("Interfaces cannot contain constructors", methodDeclaration);
  16789. }
  16790. // Don't compare specialized generic methods against normal methods
  16791. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  16792. (!methodDef->mIsLocalMethod))
  16793. {
  16794. if (!methodInstance->mIsForeignMethodDef)
  16795. {
  16796. typeDef->PopulateMemberSets();
  16797. BfMethodDef* nextMethod = NULL;
  16798. BfMemberSetEntry* entry = NULL;
  16799. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16800. nextMethod = (BfMethodDef*)entry->mMemberDef;
  16801. while (nextMethod != NULL)
  16802. {
  16803. auto checkMethod = nextMethod;
  16804. nextMethod = nextMethod->mNextWithSameName;
  16805. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  16806. {
  16807. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  16808. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  16809. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16810. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16811. {
  16812. bool canChain = false;
  16813. if ((methodDef->mParams.empty()) &&
  16814. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  16815. {
  16816. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  16817. canChain = true;
  16818. else if (methodDef->mMethodType == BfMethodType_Normal)
  16819. {
  16820. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  16821. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  16822. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  16823. canChain = true;
  16824. }
  16825. }
  16826. if (canChain)
  16827. {
  16828. bool isBetter;
  16829. bool isWorse;
  16830. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  16831. if (isBetter && !isWorse)
  16832. {
  16833. methodInstance->mChainType = BfMethodChainType_ChainHead;
  16834. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  16835. }
  16836. else
  16837. {
  16838. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  16839. methodInstance->mChainType = BfMethodChainType_ChainMember;
  16840. }
  16841. }
  16842. else if ((checkMethod->mBody == NULL) && (methodDef->mBody != NULL) &&
  16843. (checkMethod->mDeclaringType != methodDef->mDeclaringType))
  16844. {
  16845. // We're allowed to override an empty-bodied method
  16846. checkMethodInstance->mChainType = BfMethodChainType_ChainSkip;
  16847. }
  16848. else
  16849. {
  16850. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  16851. continue;
  16852. bool silentlyAllow = false;
  16853. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  16854. {
  16855. if (typeInstance->IsInterface())
  16856. {
  16857. if (methodDef->mIsOverride)
  16858. silentlyAllow = true;
  16859. }
  16860. else
  16861. silentlyAllow = true;
  16862. }
  16863. if (!silentlyAllow)
  16864. {
  16865. if (!methodDef->mName.IsEmpty())
  16866. {
  16867. auto refNode = methodDef->GetRefNode();
  16868. auto bfError = Fail("Method already declared with the same parameter types", refNode, true);
  16869. if (bfError != NULL)
  16870. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  16871. }
  16872. }
  16873. }
  16874. }
  16875. }
  16876. }
  16877. }
  16878. // Virtual methods give their error while slotting
  16879. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  16880. (!methodDef->mIsLocalMethod) &&
  16881. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  16882. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  16883. {
  16884. bool foundHiddenMethod = false;
  16885. auto baseType = typeInstance->mBaseType;
  16886. while (baseType != NULL)
  16887. {
  16888. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  16889. auto baseTypeDef = baseType->mTypeDef;
  16890. baseTypeDef->PopulateMemberSets();
  16891. BfMethodDef* checkMethod = NULL;
  16892. BfMemberSetEntry* entry = NULL;
  16893. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16894. checkMethod = (BfMethodDef*)entry->mMemberDef;
  16895. while (checkMethod != NULL)
  16896. {
  16897. if (checkMethod->mMethodDeclaration == NULL)
  16898. continue;
  16899. if (baseType->mMethodInstanceGroups.size() == 0)
  16900. {
  16901. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  16902. break;
  16903. }
  16904. if (checkMethod == methodDef)
  16905. continue;
  16906. if (checkMethod->mName != methodDef->mName)
  16907. continue;
  16908. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  16909. if (checkMethodInstance != NULL)
  16910. {
  16911. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16912. (checkMethod->mProtection != BfProtection_Private) &&
  16913. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16914. {
  16915. if (!methodDef->mIsNew)
  16916. {
  16917. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  16918. if (refNode != NULL)
  16919. {
  16920. 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?
  16921. if (bfError != NULL)
  16922. bfError->mIsPersistent = true;
  16923. }
  16924. }
  16925. foundHiddenMethod = true;
  16926. break;
  16927. }
  16928. }
  16929. checkMethod = checkMethod->mNextWithSameName;
  16930. }
  16931. if (foundHiddenMethod)
  16932. break;
  16933. baseType = baseType->mBaseType;
  16934. }
  16935. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  16936. {
  16937. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  16938. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  16939. methodDeclaration->mNewSpecifier;
  16940. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  16941. }
  16942. }
  16943. }
  16944. mCompiler->mStats.mMethodDeclarations++;
  16945. mCompiler->UpdateCompletion();
  16946. }
  16947. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  16948. {
  16949. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  16950. auto typeInstance = mCurTypeInstance;
  16951. auto methodDef = methodInstance->mMethodDef;
  16952. int virtualMethodMatchIdx = -1;
  16953. if (typeInstance->mHotTypeData != NULL)
  16954. {
  16955. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  16956. {
  16957. BF_ASSERT(mCompiler->IsHotCompile());
  16958. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  16959. // may slot this override anyway (?)
  16960. int vTableStart = 0;
  16961. if (typeInstance->mBaseType != NULL)
  16962. vTableStart = typeInstance->mBaseType->mVirtualMethodTableSize;
  16963. StringT<128> mangledName;
  16964. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  16965. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  16966. {
  16967. // O(1) checking when virtual methods haven't changed
  16968. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  16969. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  16970. if (mangledName == entry.mFuncName)
  16971. {
  16972. virtualMethodMatchIdx = vTableStart + checkIdx;
  16973. break;
  16974. }
  16975. }
  16976. if (virtualMethodMatchIdx != -1)
  16977. {
  16978. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  16979. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  16980. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  16981. }
  16982. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  16983. }
  16984. }
  16985. if (virtualMethodMatchIdx == -1)
  16986. {
  16987. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  16988. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  16989. typeInstance->mVirtualMethodTable.push_back(entry);
  16990. }
  16991. }
  16992. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  16993. {
  16994. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  16995. {
  16996. // When we provide an extension override in the same project a root type override
  16997. isBetter = true;
  16998. isWorse = false;
  16999. }
  17000. else
  17001. {
  17002. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17003. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17004. }
  17005. }
  17006. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  17007. {
  17008. BP_ZONE("BfModule::SlotVirtualMethod");
  17009. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  17010. return false;
  17011. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  17012. {
  17013. if (!mCompiler->mOptions.mAllowHotSwapping)
  17014. return;
  17015. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  17016. return;
  17017. if (methodInstance->mHotMethod == NULL)
  17018. CheckHotMethod(methodInstance, "");
  17019. if (methodInstance->mHotMethod == NULL)
  17020. return;
  17021. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  17022. if (declMethodInstance->mHotMethod == NULL)
  17023. CheckHotMethod(declMethodInstance, "");
  17024. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  17025. virtualDecl->mRefCount++;
  17026. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  17027. };
  17028. auto typeInstance = mCurTypeInstance;
  17029. auto typeDef = typeInstance->mTypeDef;
  17030. auto methodDef = methodInstance->mMethodDef;
  17031. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17032. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17033. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  17034. BfAstNode* declaringNode = methodDeclaration;
  17035. if (propertyMethodDeclaration != NULL)
  17036. declaringNode = propertyMethodDeclaration->mNameNode;
  17037. BfMethodInstance* methodOverriden = NULL;
  17038. bool usedMethod = false;
  17039. BfTokenNode* virtualToken = NULL;
  17040. if (propertyDeclaration != NULL)
  17041. virtualToken = propertyDeclaration->mVirtualSpecifier;
  17042. else if (methodDeclaration != NULL)
  17043. virtualToken = methodDeclaration->mVirtualSpecifier;
  17044. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  17045. {
  17046. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  17047. }
  17048. else if (methodDef->mIsVirtual)
  17049. {
  17050. if (mCompiler->IsHotCompile())
  17051. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  17052. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  17053. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  17054. BfTypeInstance* checkBase = typeInstance;
  17055. // If we are in an extension, look in ourselves first
  17056. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  17057. checkBase = checkBase->mBaseType;
  17058. if (typeInstance->IsValueType())
  17059. {
  17060. if (typeInstance->mBaseType == NULL)
  17061. return false; // It's actually ValueType
  17062. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  17063. if (!methodDef->mIsOverride)
  17064. {
  17065. Fail("Structs cannot have virtual methods", virtualToken, true);
  17066. return false;
  17067. }
  17068. checkBase = mContext->mBfObjectType;
  17069. if (checkBase->mVirtualMethodTableSize == 0)
  17070. PopulateType(checkBase, BfPopulateType_Full);
  17071. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  17072. return false; // System circular ref, don't do struct checking on those
  17073. }
  17074. int virtualMethodMatchIdx = -1;
  17075. bool hadHidingError = false;
  17076. BfMethodInstance* bestOverrideMethodInstance = NULL;
  17077. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  17078. int bestOverrideMethodIdx = -1;
  17079. int ambiguousOverrideMethodIdx = -1;
  17080. if (checkBase != NULL)
  17081. {
  17082. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17083. auto lookupType = checkBase;
  17084. while (lookupType != NULL)
  17085. {
  17086. lookupType->mTypeDef->PopulateMemberSets();
  17087. BfMethodDef* nextMethodDef = NULL;
  17088. BfMemberSetEntry* entry;
  17089. if (lookupType->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17090. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  17091. while (nextMethodDef != NULL)
  17092. {
  17093. auto checkMethodDef = nextMethodDef;
  17094. nextMethodDef = nextMethodDef->mNextWithSameName;
  17095. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  17096. continue;
  17097. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  17098. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  17099. continue;
  17100. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  17101. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17102. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17103. {
  17104. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17105. continue;
  17106. }
  17107. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17108. if (baseMethodInstance == NULL)
  17109. {
  17110. AssertErrorState();
  17111. continue;
  17112. }
  17113. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17114. {
  17115. if (methodDef->mIsOverride)
  17116. {
  17117. BfMethodInstance* checkMethodInstance;
  17118. if (typeInstance->IsValueType())
  17119. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17120. else
  17121. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17122. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17123. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17124. continue;
  17125. if (bestOverrideMethodInstance != NULL)
  17126. {
  17127. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17128. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17129. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17130. if (isBetter == isWorse)
  17131. {
  17132. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17133. }
  17134. else
  17135. {
  17136. if (isWorse)
  17137. continue;
  17138. ambiguousOverrideMethodInstance = NULL;
  17139. }
  17140. }
  17141. bestOverrideMethodInstance = checkMethodInstance;
  17142. bestOverrideMethodIdx = checkMethodIdx;
  17143. }
  17144. else
  17145. {
  17146. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17147. {
  17148. if (!hadHidingError)
  17149. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17150. hadHidingError = true;
  17151. }
  17152. }
  17153. }
  17154. }
  17155. lookupType = lookupType->mBaseType;
  17156. }
  17157. }
  17158. //TODO:
  17159. if ((checkBase != NULL)
  17160. && (false)
  17161. )
  17162. {
  17163. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17164. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  17165. {
  17166. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17167. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17168. {
  17169. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17170. continue;
  17171. }
  17172. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17173. if (baseMethodInstance == NULL)
  17174. {
  17175. AssertErrorState();
  17176. continue;
  17177. }
  17178. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17179. {
  17180. if (methodDef->mIsOverride)
  17181. {
  17182. BfMethodInstance* checkMethodInstance;
  17183. if (typeInstance->IsValueType())
  17184. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17185. else
  17186. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17187. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17188. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17189. continue;
  17190. if (bestOverrideMethodInstance != NULL)
  17191. {
  17192. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17193. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17194. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17195. if (isBetter == isWorse)
  17196. {
  17197. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17198. }
  17199. else
  17200. {
  17201. if (isWorse)
  17202. continue;
  17203. ambiguousOverrideMethodInstance = NULL;
  17204. }
  17205. }
  17206. bestOverrideMethodInstance = checkMethodInstance;
  17207. bestOverrideMethodIdx = checkMethodIdx;
  17208. }
  17209. else
  17210. {
  17211. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17212. {
  17213. if (!hadHidingError)
  17214. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17215. hadHidingError = true;
  17216. }
  17217. }
  17218. }
  17219. }
  17220. }
  17221. if (bestOverrideMethodInstance != NULL)
  17222. {
  17223. if (ambiguousOverrideMethodInstance != NULL)
  17224. {
  17225. bool allow = false;
  17226. // 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.
  17227. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  17228. bool canSeeEachOther = false;
  17229. //
  17230. {
  17231. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  17232. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17233. canSeeEachOther = true;
  17234. }
  17235. //
  17236. {
  17237. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  17238. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17239. canSeeEachOther = true;
  17240. }
  17241. if (!canSeeEachOther)
  17242. {
  17243. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  17244. }
  17245. else
  17246. {
  17247. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  17248. if (error != NULL)
  17249. {
  17250. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  17251. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  17252. }
  17253. }
  17254. }
  17255. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17256. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  17257. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  17258. {
  17259. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  17260. {
  17261. BfTypeReference* returnTypeRef;
  17262. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17263. {
  17264. returnTypeRef = propertyDeclaration->mTypeRef;
  17265. Fail("Property differs from overridden property by type", returnTypeRef, true);
  17266. }
  17267. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17268. {
  17269. returnTypeRef = methodDeclaration->mReturnType;
  17270. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  17271. }
  17272. else
  17273. {
  17274. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  17275. }
  17276. return usedMethod;
  17277. }
  17278. }
  17279. if (methodDef->mIsOverride)
  17280. {
  17281. // We can have multiple matches when a virtual method is used to implement interface methods
  17282. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  17283. // vtable entries for this method signature
  17284. virtualMethodMatchIdx = bestOverrideMethodIdx;
  17285. if (!typeInstance->IsValueType())
  17286. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17287. if (typeInstance->IsValueType())
  17288. {
  17289. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17290. }
  17291. else
  17292. {
  17293. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17294. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17295. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  17296. {
  17297. methodOverriden = overridenRef;
  17298. BfMethodInstance* setMethodInstance = methodInstance;
  17299. bool doOverride = true;
  17300. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  17301. {
  17302. bool isBetter = false;
  17303. bool isWorse = false;
  17304. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  17305. if (isBetter == isWorse)
  17306. {
  17307. // We have to resolve later per-project
  17308. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  17309. {
  17310. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17311. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  17312. }
  17313. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  17314. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  17315. doOverride = false;
  17316. }
  17317. else
  17318. {
  17319. if ((isBetter) && (ambiguityContext != NULL))
  17320. {
  17321. ambiguityContext->Remove(virtualMethodMatchIdx);
  17322. }
  17323. doOverride = isBetter;
  17324. }
  17325. }
  17326. if (doOverride)
  17327. {
  17328. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17329. _AddVirtualDecl(declMethodInstance);
  17330. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  17331. }
  17332. }
  17333. }
  17334. if (methodOverriden != NULL)
  17335. {
  17336. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  17337. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  17338. {
  17339. const char* protectionNames[] = {"hidden", "private", "protected", "public"};
  17340. BfAstNode* protectionRefNode = NULL;
  17341. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17342. {
  17343. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  17344. if (protectionRefNode == NULL)
  17345. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  17346. if (protectionRefNode == NULL)
  17347. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  17348. }
  17349. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17350. {
  17351. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  17352. if (protectionRefNode == NULL)
  17353. protectionRefNode = methodDeclaration->mNameNode;
  17354. }
  17355. if (protectionRefNode != NULL)
  17356. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  17357. }
  17358. }
  17359. }
  17360. }
  17361. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  17362. {
  17363. if (methodDef->mIsOverride)
  17364. {
  17365. BfTokenNode* overrideToken = NULL;
  17366. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17367. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  17368. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17369. overrideToken = methodDeclaration->mVirtualSpecifier;
  17370. if (overrideToken != NULL)
  17371. {
  17372. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  17373. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  17374. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  17375. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  17376. else
  17377. Fail("No suitable method found to override", overrideToken, true);
  17378. }
  17379. return usedMethod;
  17380. }
  17381. UniqueSlotVirtualMethod(methodInstance);
  17382. }
  17383. else
  17384. usedMethod = true;
  17385. if (typeInstance->IsValueType())
  17386. return usedMethod;
  17387. }
  17388. bool foundInterface = false;
  17389. bool hadAnyMatch = false;
  17390. // See if this method matches interfaces
  17391. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17392. {
  17393. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17394. if (ifaceInst->IsIncomplete())
  17395. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  17396. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17397. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17398. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  17399. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  17400. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  17401. continue;
  17402. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  17403. continue;
  17404. bool hadMatch = false;
  17405. bool hadNameMatch = false;
  17406. BfType* expectedReturnType = NULL;
  17407. bool showedError = false;
  17408. // We go through our VTable looking for NULL entries within the interface sections
  17409. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  17410. // because a normal method declared in this type could have matched earlier
  17411. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  17412. ifaceInst->mTypeDef->PopulateMemberSets();
  17413. BfMethodDef* checkMethodDef = NULL;
  17414. BfMemberSetEntry* entry;
  17415. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17416. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  17417. while (checkMethodDef != NULL)
  17418. {
  17419. int iMethodIdx = checkMethodDef->mIdx;
  17420. int iTableIdx = iMethodIdx + startIdx;
  17421. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  17422. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  17423. bool storeIFaceMethod = false;
  17424. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  17425. continue;
  17426. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  17427. auto iMethodInst = iMethodGroup.mDefault;
  17428. if (iMethodInst == NULL)
  17429. {
  17430. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  17431. AssertErrorState();
  17432. continue;
  17433. }
  17434. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  17435. hadNameMatch = true;
  17436. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  17437. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  17438. {
  17439. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  17440. }
  17441. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  17442. {
  17443. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  17444. {
  17445. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  17446. {
  17447. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  17448. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  17449. if (error != NULL)
  17450. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  17451. showedError = true;
  17452. }
  17453. }
  17454. }
  17455. if (doesMethodSignatureMatch)
  17456. {
  17457. usedMethod = true;
  17458. hadMatch = true;
  17459. hadAnyMatch = true;
  17460. storeIFaceMethod = true;
  17461. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  17462. {
  17463. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  17464. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  17465. {
  17466. // When autocompletion regenerates a single method body but not the whole type then
  17467. // we will see ourselves in the vtable already
  17468. return usedMethod;
  17469. }
  17470. bool isBetter = false;
  17471. bool isWorse = false;
  17472. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  17473. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  17474. if (isBetter == isWorse)
  17475. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  17476. if (isBetter == isWorse)
  17477. {
  17478. if (ambiguityContext != NULL)
  17479. {
  17480. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  17481. }
  17482. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  17483. storeIFaceMethod = true;
  17484. }
  17485. else
  17486. {
  17487. if ((isBetter) && (ambiguityContext != NULL))
  17488. ambiguityContext->Remove(~iTableIdx);
  17489. storeIFaceMethod = isBetter;
  17490. }
  17491. }
  17492. }
  17493. if (storeIFaceMethod)
  17494. {
  17495. _AddVirtualDecl(iMethodInst);
  17496. *iMethodPtr = methodInstance;
  17497. }
  17498. checkMethodDef = checkMethodDef->mNextWithSameName;
  17499. }
  17500. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  17501. {
  17502. if (expectedReturnType != NULL)
  17503. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  17504. else if (hadNameMatch)
  17505. Fail("Method parameters don't match interface method", declaringNode, true);
  17506. else
  17507. Fail("Method name not found in interface", methodDef->GetRefNode(), true);
  17508. }
  17509. }
  17510. // Any overriden virtual methods that were used in interfaces also need to be replaced
  17511. if (methodOverriden != NULL)
  17512. {
  17513. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  17514. {
  17515. if (methodEntry.mMethodRef == methodOverriden)
  17516. methodEntry.mMethodRef = methodInstance;
  17517. }
  17518. }
  17519. return usedMethod;
  17520. }
  17521. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  17522. {
  17523. auto typeInstance = mCurTypeInstance;
  17524. auto methodDef = methodInstance->mMethodDef;
  17525. if (methodDef->mMethodType == BfMethodType_Ctor)
  17526. return true;
  17527. bool foundOverride = false;
  17528. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  17529. {
  17530. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  17531. }
  17532. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  17533. {
  17534. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  17535. }
  17536. BfAstNode* declaringNode = methodDef->GetRefNode();
  17537. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17538. {
  17539. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17540. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17541. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17542. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  17543. continue;
  17544. ifaceInst->mTypeDef->PopulateMemberSets();
  17545. BfMethodDef* nextMethod = NULL;
  17546. BfMemberSetEntry* entry = NULL;
  17547. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17548. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17549. while (nextMethod != NULL)
  17550. {
  17551. auto checkMethod = nextMethod;
  17552. nextMethod = nextMethod->mNextWithSameName;
  17553. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17554. if (ifaceMethod == NULL)
  17555. continue;
  17556. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17557. {
  17558. if (methodDef->mIsOverride)
  17559. {
  17560. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  17561. {
  17562. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  17563. if (error != NULL)
  17564. {
  17565. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  17566. }
  17567. }
  17568. foundOverride = true;
  17569. }
  17570. else if (!methodDef->mIsNew)
  17571. {
  17572. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  17573. }
  17574. }
  17575. }
  17576. }
  17577. if ((methodDef->mIsOverride) && (!foundOverride))
  17578. {
  17579. // This allows us to declare a method in the base definition or in an extension and then provide
  17580. // an implementation in a more-specific extension
  17581. typeInstance->mTypeDef->PopulateMemberSets();
  17582. BfMethodDef* nextMethod = NULL;
  17583. BfMemberSetEntry* entry = NULL;
  17584. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17585. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17586. while (nextMethod != NULL)
  17587. {
  17588. auto checkMethod = nextMethod;
  17589. nextMethod = nextMethod->mNextWithSameName;
  17590. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17591. if (ifaceMethod == NULL)
  17592. continue;
  17593. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17594. continue;
  17595. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17596. {
  17597. foundOverride = true;
  17598. }
  17599. }
  17600. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17601. // {
  17602. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  17603. // if (ifaceMethod == NULL)
  17604. // continue;
  17605. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17606. // continue;
  17607. //
  17608. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17609. // {
  17610. // foundOverride = true;
  17611. // }
  17612. // }
  17613. }
  17614. if (methodDef->mIsOverride)
  17615. {
  17616. if (!foundOverride)
  17617. {
  17618. BfTokenNode* overrideToken = NULL;
  17619. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17620. overrideToken = propertyDeclaration->mVirtualSpecifier;
  17621. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17622. overrideToken = methodDeclaration->mVirtualSpecifier;
  17623. if (overrideToken != NULL)
  17624. {
  17625. Fail("No suitable method found to override", overrideToken, true);
  17626. }
  17627. else
  17628. {
  17629. // Possible cause - DTOR with params
  17630. AssertErrorState();
  17631. }
  17632. }
  17633. return true;
  17634. }
  17635. // Generic methods can't be called virtually
  17636. if (methodInstance->GetNumGenericParams() != 0)
  17637. return true;
  17638. // Only public methods can be called virtually
  17639. if (methodDef->mProtection != BfProtection_Public)
  17640. return true;
  17641. UniqueSlotVirtualMethod(methodInstance);
  17642. return true;
  17643. }
  17644. void BfModule::DbgFinish()
  17645. {
  17646. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  17647. return;
  17648. if (mAwaitingInitFinish)
  17649. FinishInit();
  17650. if (mHasForceLinkMarker)
  17651. return;
  17652. String markerName;
  17653. BfIRValue linkMarker;
  17654. if (mBfIRBuilder->DbgHasInfo())
  17655. {
  17656. bool needForceLinking = false;
  17657. for (auto& ownedType : mOwnedTypeInstances)
  17658. {
  17659. bool hasConfirmedReference = false;
  17660. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  17661. {
  17662. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  17663. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) &&
  17664. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  17665. {
  17666. hasConfirmedReference = true;
  17667. }
  17668. }
  17669. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  17670. needForceLinking = true;
  17671. }
  17672. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  17673. {
  17674. BfMethodState methodState;
  17675. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17676. methodState.mTempKind = BfMethodState::TempKind_Static;
  17677. mHasForceLinkMarker = true;
  17678. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  17679. SizedArray<BfIRType, 0> paramTypes;
  17680. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  17681. String linkName = "FORCELINKMOD_" + mModuleName;
  17682. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  17683. mBfIRBuilder->SetActiveFunction(func);
  17684. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  17685. mBfIRBuilder->SetInsertPoint(entryBlock);
  17686. auto firstType = mOwnedTypeInstances[0];
  17687. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  17688. SizedArray<BfIRMDNode, 1> diParamTypes;
  17689. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  17690. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  17691. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  17692. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  17693. methodState.mCurScope->mDIScope = diScope;
  17694. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  17695. SizedArray<BfIRValue, 8> args;
  17696. BfExprEvaluator exprEvaluator(this);
  17697. for (auto& ownedType : mOwnedTypeInstances)
  17698. {
  17699. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  17700. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  17701. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  17702. }
  17703. mBfIRBuilder->CreateRetVoid();
  17704. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  17705. }
  17706. }
  17707. }
  17708. bool BfModule::Finish()
  17709. {
  17710. BP_ZONE("BfModule::Finish");
  17711. BfLogSysM("BfModule finish: %p\n", this);
  17712. if (mHadBuildError)
  17713. {
  17714. // Don't AssertErrorState here, this current pass may not have failed but
  17715. // the module was still queued in mFinishedModuleWorkList
  17716. ClearModule();
  17717. return true;
  17718. }
  17719. if (mUsedSlotCount != -1)
  17720. {
  17721. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  17722. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  17723. }
  17724. BF_ASSERT(mAddedToCount);
  17725. mAddedToCount = false;
  17726. mAwaitingFinish = false;
  17727. mCompiler->mStats.mModulesFinished++;
  17728. if (HasCompiledOutput())
  17729. {
  17730. DbgFinish();
  17731. if (mAwaitingInitFinish)
  17732. FinishInit();
  17733. for (auto ownedTypeInst : mOwnedTypeInstances)
  17734. {
  17735. // Generate dbg info and add global variables if we haven't already
  17736. mBfIRBuilder->PopulateType(ownedTypeInst);
  17737. }
  17738. if (mBfIRBuilder->DbgHasInfo())
  17739. {
  17740. mBfIRBuilder->DbgFinalize();
  17741. }
  17742. String objOutputPath;
  17743. String irOutputPath;
  17744. mIsModuleMutable = false;
  17745. //mOutFileNames.Clear();
  17746. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  17747. bool writeModule = mBfIRBuilder->HasExports();
  17748. String outputPath;
  17749. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  17750. auto& compilerOpts = mCompiler->mOptions;
  17751. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  17752. auto moduleOptions = GetModuleOptions();
  17753. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  17754. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  17755. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  17756. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  17757. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  17758. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  17759. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  17760. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  17761. bool allowWriteToLib = true;
  17762. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) && (mModuleName != "vdata"))
  17763. {
  17764. codeGenOptions.mWriteToLib = true;
  17765. mWroteToLib = true;
  17766. }
  17767. else
  17768. {
  17769. mWroteToLib = false;
  17770. }
  17771. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  17772. {
  17773. outputPath = mModuleName;
  17774. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  17775. BfModuleFileName moduleFileName;
  17776. if (mParentModule != NULL)
  17777. {
  17778. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  17779. {
  17780. if (checkPair.mValue == this)
  17781. moduleFileName.mProjects = checkPair.mKey;
  17782. }
  17783. }
  17784. moduleFileName.mProjects.Add(mProject);
  17785. if (fileIdx > 0)
  17786. outputPath += StrFormat("@%d", fileIdx + 1);
  17787. if (mCompiler->mOptions.mWriteIR)
  17788. irOutputPath = outputPath + ".ll";
  17789. if (mCompiler->mOptions.mGenerateObj)
  17790. {
  17791. objOutputPath = outputPath + BF_OBJ_EXT;
  17792. moduleFileName.mFileName = objOutputPath;
  17793. }
  17794. else if (mCompiler->mOptions.mWriteIR)
  17795. {
  17796. moduleFileName.mFileName = irOutputPath;
  17797. }
  17798. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mWriteIR))
  17799. {
  17800. BF_FATAL("Neither obj nor IR specified");
  17801. }
  17802. moduleFileName.mModuleWritten = writeModule;
  17803. moduleFileName.mWroteToLib = mWroteToLib;
  17804. if (!mOutFileNames.Contains(moduleFileName))
  17805. mOutFileNames.Add(moduleFileName);
  17806. }
  17807. if (mCompiler->IsHotCompile())
  17808. {
  17809. codeGenOptions.mIsHotCompile = true;
  17810. //TODO: Why did we have this 'mWroteToLib' check? 'vdata' didn't get this flag set, which
  17811. // is required for rebuilding vdata after we hot create a vdata
  17812. //if (mWroteToLib)
  17813. {
  17814. if (mParentModule != NULL)
  17815. mParentModule->mHadHotObjectWrites = true;
  17816. mHadHotObjectWrites = true;
  17817. }
  17818. }
  17819. //TODO: Testing VDATA
  17820. /*if (mModuleName == "vdata")
  17821. {
  17822. codeGenOptions.mOptLevel = 4;
  17823. }*/
  17824. codeGenOptions.GenerateHash();
  17825. BP_ZONE("BfModule::Finish.WriteObjectFile");
  17826. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  17827. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  17828. mLastModuleWrittenRevision = mCompiler->mRevision;
  17829. }
  17830. else
  17831. {
  17832. for (auto type : mOwnedTypeInstances)
  17833. {
  17834. BF_ASSERT(!type->IsIncomplete());
  17835. }
  17836. }
  17837. for (auto& specModulePair : mSpecializedMethodModules)
  17838. {
  17839. auto specModule = specModulePair.mValue;
  17840. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  17841. {
  17842. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  17843. }
  17844. }
  17845. CleanupFileInstances();
  17846. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  17847. return true;
  17848. }
  17849. void BfModule::ReportMemory(MemReporter* memReporter)
  17850. {
  17851. memReporter->Add(sizeof(BfModule));
  17852. if (mBfIRBuilder != NULL)
  17853. {
  17854. memReporter->BeginSection("IRBuilder_ConstData");
  17855. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  17856. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  17857. memReporter->EndSection();
  17858. memReporter->BeginSection("IRBuilder_BFIR");
  17859. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  17860. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  17861. memReporter->EndSection();
  17862. memReporter->Add(sizeof(BfIRBuilder));
  17863. }
  17864. memReporter->BeginSection("FileInstanceMap");
  17865. memReporter->AddMap(mFileInstanceMap);
  17866. memReporter->AddMap(mNamedFileInstanceMap);
  17867. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  17868. memReporter->EndSection();
  17869. memReporter->AddVec(mOwnedTypeInstances, false);
  17870. memReporter->AddVec(mSpecializedMethodModules, false);
  17871. memReporter->AddVec(mOutFileNames, false);
  17872. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  17873. memReporter->AddMap(mInterfaceSlotRefs, false);
  17874. memReporter->AddMap(mStaticFieldRefs, false);
  17875. memReporter->AddMap(mClassVDataRefs, false);
  17876. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  17877. memReporter->AddMap(mTypeDataRefs, false);
  17878. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  17879. memReporter->AddMap(mDeferredMethodCallData, false);
  17880. memReporter->AddHashSet(mDeferredMethodIds, false);
  17881. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  17882. }
  17883. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  17884. // be transient through the next compile
  17885. void BfModule::ClearModuleData()
  17886. {
  17887. BfLogSysM("ClearModuleData %p\n", this);
  17888. if (mAddedToCount)
  17889. {
  17890. mCompiler->mStats.mModulesFinished++;
  17891. mAddedToCount = false;
  17892. }
  17893. mDICompileUnit = BfIRMDNode();
  17894. mIsModuleMutable = false;
  17895. mIncompleteMethodCount = 0;
  17896. mHasGenericMethods = false;
  17897. // We don't want to clear these because we want it to persist through module extensions-
  17898. // otherwise we may think an extension succeeds even though the base module failed
  17899. //mHadBuildError = false;
  17900. //mHadBuildWarning = false;
  17901. mClassVDataRefs.Clear();
  17902. mClassVDataExtRefs.Clear();
  17903. for (auto& kv : mTypeDataRefs)
  17904. kv.mValue = BfIRValue();
  17905. mStringCharPtrPool.Clear();
  17906. mStringObjectPool.Clear();
  17907. mStaticFieldRefs.Clear();
  17908. BF_ASSERT(!mIgnoreErrors);
  17909. for (auto prevIRBuilder : mPrevIRBuilders)
  17910. delete prevIRBuilder;
  17911. mPrevIRBuilders.Clear();
  17912. for (auto& specPair : mSpecializedMethodModules)
  17913. {
  17914. auto specModule = specPair.mValue;
  17915. specModule->ClearModuleData();
  17916. }
  17917. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  17918. mBuiltInFuncs[i] = BfIRFunction();
  17919. if (mNextAltModule != NULL)
  17920. mNextAltModule->ClearModuleData();
  17921. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  17922. delete mBfIRBuilder;
  17923. mBfIRBuilder = NULL;
  17924. mWantsIRIgnoreWrites = false;
  17925. }
  17926. void BfModule::DisownMethods()
  17927. {
  17928. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  17929. mBuiltInFuncs[i] = BfIRFunction();
  17930. BfModule* methodModule = this;
  17931. if (mParentModule != NULL)
  17932. methodModule = mParentModule;
  17933. for (auto typeInst : methodModule->mOwnedTypeInstances)
  17934. {
  17935. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  17936. {
  17937. if (methodGroup.mDefault != NULL)
  17938. {
  17939. if (methodGroup.mDefault->mIRFunction)
  17940. {
  17941. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  17942. if (methodGroup.mDefault->mDeclModule == this)
  17943. {
  17944. methodGroup.mDefault->mIRFunction = BfIRFunction();
  17945. }
  17946. }
  17947. }
  17948. if (methodGroup.mMethodSpecializationMap != NULL)
  17949. {
  17950. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  17951. {
  17952. auto methodInstance = mapPair.mValue;
  17953. if (methodInstance->mDeclModule == this)
  17954. {
  17955. methodInstance->mIRFunction = BfIRFunction();
  17956. }
  17957. }
  17958. }
  17959. }
  17960. }
  17961. }
  17962. void BfModule::ClearModule()
  17963. {
  17964. ClearModuleData();
  17965. DisownMethods();
  17966. for (auto& specPair : mSpecializedMethodModules)
  17967. {
  17968. auto specModule = specPair.mValue;
  17969. specModule->ClearModule();
  17970. }
  17971. if (mNextAltModule != NULL)
  17972. mNextAltModule->ClearModule();
  17973. }